libmicrohttpd-1.0.10/0000775000175000017500000000000015235437006010205 5libmicrohttpd-1.0.10/src/0000775000175000017500000000000015235437006010774 5libmicrohttpd-1.0.10/src/fuzz/0000775000175000017500000000000015235437005011771 5libmicrohttpd-1.0.10/src/fuzz/corpus/0000775000175000017500000000000015232434352013303 5libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-41.bin0000664000175000017500000000005615232214516016707 @GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-33.bin0000664000175000017500000000011215232141452016674 @>GET / HTTP/1.1 Host: x Authorization: Basic dXNlcjpwYXNz libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-24.bin0000664000175000017500000000004715232141452016703 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-09.bin0000664000175000017500000000001515232214516017226 2`p`@p2libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-23.bin0000664000175000017500000000004715232414252016015 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-06.bin0000664000175000017500000000001315232214516017221 !01@libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-22.bin0000664000175000017500000000010115232214516016675 /GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-08.bin0000664000175000017500000000001415232103064016014 %41%42%%%0libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-20.bin0000664000175000017500000000000715232414252017217 2libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-20.bin0000664000175000017500000000005615232214516016704 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-06.bin0000664000175000017500000000001415232214516016011 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-12.bin0000664000175000017500000000004315232214516017410  libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-16.bin0000664000175000017500000000005615232214516016711 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-34.bin0000664000175000017500000000004715232141452016704 0GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-22.bin0000664000175000017500000000004715232414252016014 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-11.bin0000664000175000017500000000002315232141452017452 Basic dXNlcjpwYXNzlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-02.bin0000664000175000017500000000002215232103064017446 Digest algorithm=libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-02.bin0000664000175000017500000000000515232103064016006 abclibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-37.bin0000664000175000017500000000004715232414252016022 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-07.bin0000664000175000017500000000001615232103064016015 @/a%41%42%zz%libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-05.bin0000664000175000017500000000001415232214516017221 4859@<libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-13.bin0000664000175000017500000000001315232141452017453 Basic ====libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-01.bin0000664000175000017500000000001715232103064020125 a=1&b=%41&clibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-61.bin0000664000175000017500000000010615232214516016705 v?cE! -34POST /a HTTP/1.1 Host: x Content-Length: 4 abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-10.bin0000664000175000017500000000004715232214516016012  GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-21.bin0000664000175000017500000000005215232141452017455 Digest username="user", realm="TestRealm"libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-27.bin0000664000175000017500000000004715232414252016021 @GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-01.bin0000664000175000017500000000004215232103064016006 0123456789abcdef0123456789abcdeflibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-38.bin0000664000175000017500000000006415232214516016714 "GET /a?q=%41 HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-27.bin0000664000175000017500000000011015232141452016675 GET /a HTTP/1.1 Host: x GET /b HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-23.bin0000664000175000017500000000005615232214516016707 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-16.bin0000664000175000017500000000004715232214516016020 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-09.bin0000664000175000017500000000010115232214516016702 /GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-10.bin0000664000175000017500000000001115232103064016002 a\"b\\clibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-56.bin0000664000175000017500000000005615232214516016715 @GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-03.bin0000664000175000017500000000005615232214516016705 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-02.bin0000664000175000017500000000015215232141452016674 @ABCDEFHPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 3 ABC 3;x="y" DEF 0 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-15.bin0000664000175000017500000000002215232103064016011 fffffffffffffffflibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-62.bin0000664000175000017500000000010115232214516016701 r?F9 "/GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-04.bin0000664000175000017500000000002115232214516017405  !libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-24.bin0000664000175000017500000000004715232414252016016 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-38.bin0000664000175000017500000000014115232141452016703 UGET / HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm" libmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/0000775000175000017500000000000015232667545016252 5libmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K5-bare-cr-keep.bin0000664000175000017500000000005715232141452021360 #GET /a HTTP/1.1 Host: x X: y libmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K7-upgrade-after-must-close.bin0000664000175000017500000000021215232142356023741  |GET / HTTP/1.1 Host: x Connection: Upgrade Upgrade: fuzz-protocol Content-Length: 0 Transfer-Encoding: chunked 0 libmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K4a-wsp-first-header.bin0000664000175000017500000000005115232141452022441 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K4b-empty-header-name.bin0000664000175000017500000000006115232141452022561 %GET /a HTTP/1.1 : value Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K9-pp-nested-boundary-leak.bin0000664000175000017500000000141215232214516023557 --abcContent-Type: my=Q@"=c -- ef" ----abc ef" Content-Type: multipart/mixed;bomixed;bouboundary=Q@ultipart/mixed;boub--abc=c -- ef"-- ----abc ef" Content-Type: multipart/mixed;bouboundary=Q@ultipakt/mixed;b--ouboundary=Q@4"=;b--ouboundary=Q@#9"=c -- ef" ----abc oundary=Q@"=c -- ef" ----abc ef" C=ontent-Type: multipart/mixed;b Content-Type: multipart/mixedŖomixed;bouboundary=Q@ultipart/mixed;bouboundary=Q@"=c -- ef" ----abc ef" C=ontent-Type: multipart/mixed;bouboundary=Q@"=c -- ef"M BBBB%%%%%%D2%A2%%%%%DW%%%%%D2%%%%D2%A3%ssssssssssssssssssssssef" Conype: multipart/mdary=Q@"=c 1- ef"..............................-nt- TypabD c- - libmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K6-nonce-length-collision.bin0000664000175000017500000000031615232141452023474 GET /a HTTP/1.1 Host: x GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="00000000000000000000000000000000000000000000", uri="/a", response="e" libmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K14-fuzz_eventloop-force-close-not-closed.bin0000664000175000017500000000035415232214516026542 :P P7:jjjjjjjj9DDDbbbg-bbbbbbbbbbbbbbbbb(bbbbbbbbb26)2T0[zzzz&_libmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K2-chunkext-no-space.bin0000664000175000017500000000025015232141452022447 H-@ABCDEFGHIJKLMNOPQRSTUVWXHIJKLMNOPQRSTOPQRSTUVPOST (/a HTTP/1.1 Host: x Transfer-Encoding: chunked  18 MABCDEFGHIJKLMNOPQRSTUVWX 00d;ext=QRlibmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K15-stop-with-queued.bin0000664000175000017500000000001015232414252022416 2@libmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K3-chunkext-stop-with-error.bin0000664000175000017500000000021215232141452024026 ;POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked d;Aext="qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlibmicrohttpd-1.0.10/src/fuzz/corpus/known-findings/K1-digest-empty-realm.bin0000664000175000017500000000020015232141452022616 tGET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="", nonce="0000", uri="/a", response="00" libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-50.bin0000664000175000017500000000005615232214516016707 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-25.bin0000664000175000017500000000004715232414252016017 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-11.bin0000664000175000017500000000000715232103064016010 a"b\clibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-21.bin0000664000175000017500000000005615232214516016705 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-01.bin0000664000175000017500000000002415232214516017405 D\  libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-00.bin0000664000175000017500000000001515232214516017215 0@ 0libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-10.bin0000664000175000017500000000020615232141452016673  @a=1&b=%41&cmPOST /a HTTP/1.1 Host: x Content-Type: application/x-www-form-urlencoded Content-Length: 11 a=1&b=%41&clibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-07.bin0000664000175000017500000000022315232103064017456 Digest response="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-29.bin0000664000175000017500000000004715232414252016023 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/0000775000175000017500000000000015232434352015260 5libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d203.bin0000664000175000017500000000004715232434352021432 759275a4a $T=: HTTP/:.1 Ho3t: : Plibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d230.bin0000664000175000017500000000000515232414252020216 %Flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d296.bin0000664000175000017500000000001615232414252020234 %hunke, i libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d130.bin0000664000175000017500000000011715232434352020216 m0Gbte =1 HTTP/1.1 Host: x Cookie: a=b\eConne2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d016.bin0000664000175000017500000000003515232414252021103 ƌr: a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d193.bin0000664000175000017500000000004715232414252021117 0'GET /%41%443 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d241.bin0000664000175000017500000000000515232414252020220 0%8alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d153.bin0000664000175000017500000000000515232414252020222 abclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d084.bin0000664000175000017500000000005415232434352021437 7#275a4aQ ETQ0Gt: HTTP/1.2 H@s 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d366.bin0000664000175000017500000000031615232414252021115 POST /a HTTP/1.1 Host:ost x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Content-Dispositiwn: form-data; name="k" value -- .0 / libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d865.bin0000664000175000017500000000101115232414252021112 PWET /a HTTP /a HTTP/1.1 HCEContent-Type: applic Host: x AudXQlcjpwYXN1.1 HCEContent-T: x Authorization: Digest username="user", realm="TestRealm", nonc=e"%%NONCE%%", uri="/a", qop=auth-int Authorization: DigestPpe="uContent-Type: applic s: xotH Authorization: Digest useb rname="user", realm="TestRealm", nonc=e"%%NONCߊi=#/a", qop=auth-int Authorization: DigestPpe="user"upgraGETGET / HTT, realm=", realm="TestRealm", nonc=e"%%NONCE%%GE",est uselibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d314.bin0000664000175000017500000000003315232414252021105 =CONNECT Hlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d274.bin0000664000175000017500000000003615232414252021112 5 ET /a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d224.bin0000664000175000017500000000012115232414252021103 IAFHEAD /a HTTP/1.1 Host: x Transfer-Encoding: chunked 7libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d160.bin0000664000175000017500000000001415232434352021426 : P 7bBBlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d069.bin0000664000175000017500000000011515232434352021440 ,/022A22@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d467.bin0000664000175000017500000000007215232414252021121 GET /a HTTP/1.1 Ho555555555stEEEE: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d122.bin0000664000175000017500000000004115232414252021101 GET TT1 /HneT / HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d189.bin0000664000175000017500000000000315232414252020231 %Blibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d822.bin0000664000175000017500000000040115232414252021105 (GET / HTTP/1.1 Ho.t: GET /a HTTP/1.1 Hopt: x XGET /a HTTP/1.0 Host: x Authorization: Digest username="745096PATCH 0884aaafilenameaaaa", userhash=true, rea, n once="%%NONCE%%", u"deadbeef", algorith+=SHA-4 rs5e6,pabcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d740.bin0000664000175000017500000000022015232414252021103 ET0/??=00000002,cfonce="deadbeef", algorithm=S rNON`E%%tRealm"%", uri=/a?b, qop=auth, ncb HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d159.bin0000664000175000017500000000037215232434352020234 A,GT /a HT/1.0 Host:/GET /b HTTP/1.1 Host: x chunk: x /GET /b HTTP/1.1 Host: x Content-Length: 18446744073709551616 chunkost: x / /b HTTP/1 Hostost: x /GET /b HTTP/1.1 H: a=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d285.bin0000664000175000017500000000001015232414252020224 bedededlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d582.bin0000664000175000017500000000054215232414252021121 r5JGET$GET /a HTTP/1.1 Host: x /uGET /a HTTP/1.1 HGET / HoET /a HTTP/1.1 Host: x Cnonn o : sOPTIONStHo x G / tt:GE T /a HTTP/1.1 xost: x Cnonn oq%&0?q=%&9 HTTP/?q=%&q%&0?q=%&9 HTTP/?q=%&9 Hq%&0?q=%&9 HTTP/ :sOPTIONStHo x G / tHo x  t/1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d254.bin0000664000175000017500000000000515232414252020224 /6%Elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d004.bin0000664000175000017500000000001015232414252021603 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d268.bin0000664000175000017500000000003415232414252021113 T HTTP/1.1 Lolibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d270.bin0000664000175000017500000000002015232414252021102 @Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d094.bin0000664000175000017500000000007515232414252021115 ie: a=b GET /t:path?a31 HTTP/1.1 Host: x Cookie: a= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d225.bin0000664000175000017500000000006115232434352021432 7Aa592!4aONNECTQ ET%FQ5Gt: HTTP/1.1 oe0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d141.bin0000664000175000017500000000015515232414252021105 PpAFGEP /a HTTP/1.2 Host:a HTTP/1.1 HEAD X Authorization: Digest us00, algorithm="\SHA-512" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d575.bin0000664000175000017500000000006115232414252021114 :GET /a HTTP/1.1 Host: 1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d076.bin0000664000175000017500000000002015232434352021431 P$DELETE libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d472.bin0000664000175000017500000000004015232414252021105 %%NONCE%%T /%a=0&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d431.bin0000664000175000017500000000005715232414252021113 a=1&b=2GET "/a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d243.bin0000664000175000017500000000015415232434352021435 7a519#275a4~Q ETGt: HTTP/1.1 Hsot: x Cookie: Host: x Cookie: FFFFFFFFFFFFFFFFFFFFFFFFFAFF 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d531.bin0000664000175000017500000000004515232414252021106 t:'x ] HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d060.bin0000664000175000017500000000004315232414252021104 )ET /%29 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d084.bin0000664000175000017500000000004615232434352020227 @GET % HTTP/1.1 #fuolue" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d148.bin0000664000175000017500000000000515232414252020226 %%Allibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d234.bin0000664000175000017500000000021315232414252021103 U A  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d070.bin0000664000175000017500000000003415232434352020217 GET / HTTPo1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d163.bin0000664000175000017500000000004515232414252021107 dGET / HTTP/1.1 Host:l libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d465.bin0000664000175000017500000000003715232414252021115 aresponse="G=T %33a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d344.bin0000664000175000017500000000004515232414252021113 (/G72T / HTTP/1.1 C_nnelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d010.bin0000664000175000017500000000001115232414252021650 Digest mlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d011.bin0000664000175000017500000000002015232414252021651 Digest qop="\z"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d483.bin0000664000175000017500000000010115232414252021110 `0 /GET /a HTTP/1.1 Host: x ConPOSTShectio:se libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d777.bin0000664000175000017500000000030615232414252021122 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Content-Disposition: form-data; name="k, 1 value --- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d047.bin0000664000175000017500000000006615232434352020230 0GT /pth?=2+ HTTP/1.1 Host: x e: bba= ilibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d262.bin0000664000175000017500000000002115232414252021101  GE/ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d477.bin0000664000175000017500000000004015232414252021112 GET /%77 HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d229.bin0000664000175000017500000000007115232434352021437 7a54275a4aQ : HTTP/1.1 Host: Cookie: na=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d401.bin0000664000175000017500000000001515232414252021077 x*?libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d234.bin0000664000175000017500000000000515232414252020222 .%8?libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d299.bin0000664000175000017500000000005215232414252021117 %// GKTaCO%ECT HTTP/1.1 : GET libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d149.bin0000664000175000017500000000001315232434352021434 !'@D libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d154.bin0000664000175000017500000000000515232414252020223 @%F@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d024.bin0000664000175000017500000000010315232414252021101 T/aST1EAD ): libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d093.bin0000664000175000017500000000001015232414252022336 b%2C=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d426.bin0000664000175000017500000000002515232414252021107 E ,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d167.bin0000664000175000017500000000000315232414252020225 45libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d162.bin0000664000175000017500000000002215232414252021104 l14 aAlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d032.bin0000664000175000017500000000011115232434352020211 A<POST /a HTTP/1.1 Host: x Content-Length: 11 hello worldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d638.bin0000664000175000017500000000011415232414252021113  GEK /a HTTP/1.1 Hoste n="a Connection: close,,Uf" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d792.bin0000664000175000017500000000032615232414252021121 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Content-Disposition: form-data;name="k"filename a l ue J----abc*-- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d563.bin0000664000175000017500000000017515232414252021122 . FPOS>T /= HTTP/1.1 Ho HTTP/0.Con@ent-Length: 0 1 Los: x Cookie:=; POSHNNNNNNNNNNNN05 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d513.bin0000664000175000017500000000004315232414252021104 GET / HTTP/1.1 Hosv1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d300.bin0000664000175000017500000000005215232414252021076 GET / HTTP/1.1 GEHst: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d219.bin0000664000175000017500000000012415232414252021107 ;POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked D/A; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d450.bin0000664000175000017500000000006315232414252021111 GET /a HTTP/1.1 Cookie:"a=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d281.bin0000664000175000017500000000000615232414252020225 %=Yj==libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d144.bin0000664000175000017500000000021515232434352020222 AGET /a HTTP/1.1 Host: x /GET /b HTTP/1.1 Host: x Connection: clos"u;ext;ext="a\"b"ser", %4 HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d202.bin0000664000175000017500000000000415232414252020214 EEflibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d783.bin0000664000175000017500000000031715232414252021121 `Upgrade: GET /a HTTP/1.1 H.1 Host: x Authorization: Digest username="aaaaaaaaaaaaaaaaaaaa9999999999999999999999999999999999999999aaacaaaaTRACE ", userhash=true, r6, response="/0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d242.bin0000664000175000017500000000014515232434352021434 a59275a4aQ ETQ0Gt: HTTP/1.1 Host: x Cookie: cn=nce=2o@st:b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d000.bin0000664000175000017500000000000515232414252021603 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d527.bin0000664000175000017500000000004515232414252021113 GEt %a/ HTTP/1.0 Ho554libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d084.bin0000664000175000017500000000011515232414252021621 ?)libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d789.bin0000664000175000017500000000032315232414252021124 POST /a%%NONCE%% HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 4327 ----abc g2: chunkedclose Content-Type: multipart/mixed; boundary=b ---libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d090.bin0000664000175000017500000000003015232414252021661 Digest algorithm="\MD5"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d617.bin0000664000175000017500000000011115232414252021105 4%a=1;b=2;c=1 a=b0C HTTP/1.1 Host: x Cookie: a=b012345698;ab libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d385.bin0000664000175000017500000001371115232414252021121 POWET /a HTTP/1&1 Host XGET /a HTTP/1.1 H X(G0T /a HTTP/1.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1TX[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G2T /abcPATCH c=nnection: u HTTP/1.1 Host;a=1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiGET /a HTTP/1.1 HDiges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H]]]]]]]]]]]]]]]]]]]]]]]]]= X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 Haque=" X(G1T /a HTTP$1.2WET /a HTTP/1.1 Host  X(G1T -aG[ET$@a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRACE X(G1T /a HTTP$1.2WET /a HTTP/1.1 Host]&뫫t %a %aTRA;E aaaaaaP/1.%7/ HTTP/1nc=00000001QTTTt %aaaaaaaaaaaaaPt %anc%NO%CauE%%ET /a HTTP/1.1a Htsotcnonce="c6ff43b1b4f430d54f65083251884bda000000028ee3ent-Type: multipart/form-data; boundasy=--abc Transfer-Encodza/a?b&ction:aaonce="horizatiboundary=t ername="aa%%1 x3encTRAEC aa/1.%7/ HTTP/t %aaa%u%%NO.1 Hostcnonce="horization: Digest ername="aaa=1&(=%41&cmdary=t ername="aa%%1 x3enc TRAPATCH CE aaaaaaP/1.%$7/ HTTP/1.1 aaaaaaP/1.%TP/1.1 t aa%aaaaaaHostx* x Content-Type: application/x-www-form-urlenCoded Content-Length: 451 Cur)="t %aaaaaaaaaaaaa/1.%7/ HTTP/t %aaa%%000001, cPATCH %7/. H b %NONCE00600000"T /a H /a HTTP/1.1 HvvvvTRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G2T /abcPATCH c=nnection: u HTTP/1.1 Host;a=1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 H]]]]]]]]]]]]]]]]]]]]]]]]]WET /a HTTP/1&1 Host XGET /a HTTP/1.1 H X(G0T /a HTTP/1.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G2T /abcPATCH c=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 Haque=" X(G1T /a HTTP$1.2WET /a HTTP/1.1 Host 1T /a HTTP$1.2WET /a HTTP/1.1 HostAC~E X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 HET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H]]]]]]]]]]]]]]]]]]]]]%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&t %a %aTRACE aaaaaaP/1.'7/ HTTP/1nc=000001t %aaaaaaaaaaaaaPt %anc%NO%CauE%%ET /a HTTP/1.1 Hostcnonce="horization:aaonce="horizatiboundary=t ername="aa%%1 x3encTRACE aaaaaaP/1.%7bd17b7f0c814015a224725ec4ce46d010000000a163c/ HTTP/1.1 aaaaaaP/1.%7/ HTTP/1.1 t %aaaaaaaaaaaaa/1.%7/ HTTP/t %aaa%u%%NO.1 Hostcnonce="horization: ername="aaa=s/a HTTP/1.1 aaa/2.%7Content-Length: +5 NONCE%%000000, cnonc%NO%Ca POST /a HTTP/11. Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 522 ----abc gzip boundary= Host XGET /a  GET /boundaT 4ry=1 Host XGET /a H%%%%%%%%&t %a %aTRACE aaaaaaP/1.%7/ HTTP/1oded Co Hntent-Length: 450$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H]]]]]]]]]]]]]]]]]]]]]]]]] X(G1T abcPATCH c=nnection: u HTTP/1.1 Host XGET /a : u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HT0123456789abcdefTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTT~P/1.1 Host XGET /a HTTP/1.1 H X(G1T /abcPATCH c=nnnameection: u HTTP/1.1 Host;a=1;b=2;c TRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H]]]]]]]]]]]]]* X(G0T /abcPATCtion: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRACE X(G2T /a HTTP$1.2WET /a HT* GET /a HTTP/1.2 HospMD1 XGET /# HTTP/1. X(G1T /abcPATCH c=nneclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d162.bin0000664000175000017500000000040615232434352020224 !/ -/a?b&cGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d061.bin0000664000175000017500000000001015232414252021606 'alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d192.bin0000664000175000017500000000003315232434352021434 2$ 222$p2311#`libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d001.bin0000664000175000017500000000000215232414252021650 B:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d141.bin0000664000175000017500000000045115232414252022341 --abcContent-Type: my=Q@"=c -- ef" ----abc ef" Content-Type: multipart/mixed;bomixed;bouboundary=Q- Content-Disposition: attachment; filename="f" )bc=c -- ef"-- ----abc ef" Content-Type: multipart/mixed;bouboundary=Q@eltip-c=c -- ef"---a"=c c - libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d034.bin0000664000175000017500000000001715232434352021431 % D3234@2:2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d023.bin0000664000175000017500000000034615232434352020223 uff iGET /aaaa/a?brfc334Namaaaaaaaaaaaaaaaaaaaaaaaaa_aa HTTP/1.1 Host: aaaaaad aaaaaaaa aaaaaaaaET / libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d166.bin0000664000175000017500000000120415232434352020225 )&GET /  /a?b&c [ 99999999999999SHA-19999999999999962DELETE 999999999999---,-BEGIN Ptest-mhdserverencryptedprO 99999999999999999999xt PTIONSservcryptedpravt HTTP/1. 9-mhdserverencryptedprO PTIONSservcryptedpravt HTTP/1. 99999999999999999999999999999xt 9999999999999999999999999999xt HTTP/1.1 HosOPTIONS libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d090.bin0000664000175000017500000000004715232434352020225 UGET / HTTP/1.1 HqqqPRIlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d047.bin0000664000175000017500000000000515232414252021616 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d043.bin0000664000175000017500000000001015232414252022331 bb%31&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d031.bin0000664000175000017500000000001015232414252021603 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d056.bin0000664000175000017500000000001215232414252021663 Digest "libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d011.bin0000664000175000017500000000002015232414252021073  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d578.bin0000664000175000017500000000006415232414252021122 1GET / HTTP/1.1 Host: x Cookie: a=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d217.bin0000664000175000017500000000005515232434352021436 v?cG! 171HEAD / HTTP/1.[ BB libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d151.bin0000664000175000017500000000001315232434352021425 d11d@d||libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d031.bin0000664000175000017500000000001115232434352021420 < 02libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d068.bin0000664000175000017500000000002215232414252021111 r?Flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d267.bin0000664000175000017500000000002015232414252021110 Auth:rixaat(libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d359.bin0000664000175000017500000000027015232414252021116  @!tG[T /a HTTP/1.1 Hos+7ff@ET /a HTTNONCE%%T @'/aE%%@/a HTTP/1.1@/a HTTP/1.1 ||libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d080.bin0000664000175000017500000000003515232434352021432 4]OPTIONS OPT!@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d020.bin0000664000175000017500000000002015232414252021073 /a' TP/0.F libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d288.bin0000664000175000017500000000002315232414252021116 #5555 5555 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d003.bin0000664000175000017500000000000215232414252021652 slibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d352.bin0000664000175000017500000000004615232414252021113 l H4ST / HTTP/1.1 oo-t-libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d264.bin0000664000175000017500000000000515232414252020225 %5Clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d514.bin0000664000175000017500000000004315232414252021105  @1&\ /a HTTP/1.1 Ho41&clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d142.bin0000664000175000017500000000063615232414252022347 --abcCont@"=c -- ef" ----abc ef" Content-Type: multipart/mixed;bomixed;bouboundary=Q@ultipart/mixeoub--abc=c -- ef" ----P%zzbounda&b=%82&c.+!a=2&a=a=0&b=%41&c!a=1&a=0&b=%41&c2c.+!a=2&\"0&b=%41&a=1&aclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d257.bin0000664000175000017500000000000115232414252021106 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d249.bin0000664000175000017500000000046515232414252021125 v?cG! /PO)T / HTTP/1.1 Host: x nt: xLength:T 4 :POS17PO)T / HTTP/1.1 Host: ccccccccccccccctQ h:T 4 :POT /TT /PH1.1 x n: t: abcllibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d120.bin0000664000175000017500000000000515232414252020214 %95libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d136.bin0000664000175000017500000000000515232414252020223 %DBlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d167.bin0000664000175000017500000000001515232434352021436 ===eeeelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d811.bin0000664000175000017500000000037115232414252021111 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algoriNOmH52-%A6, response="012346913578abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d866.bin0000664000175000017500000000101115232414252021113 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 522 ----abc g2: chunked 5" c:2nkeqd 52 --RLT%ACEunked 522 ----abc g2: chunked 52 ----abc g2: cnkeqd 52 ----abc Conk%%NONCE%%d 53 ----abc gET /ath[[/1.1 TP/1.1 Content-Disposition: name="aG1T /a 52 ----abc Conk%%NONCE%%d 53 ----abc gET /ath[[/1.1 TP/1.1 Conte chunked, Connectiousername*=UTF-8''aaNsfer-EncodUUpodin8-fent-Dispo7e27122slibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d051.bin0000664000175000017500000000000515232414252020217 4%EDlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d242.bin0000664000175000017500000000000515232414252020221 %8libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d178.bin0000664000175000017500000000004315232414252021116  0ET /a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d047.bin0000664000175000017500000000003415232414252021106 T / HTTP/1.2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d818.bin0000664000175000017500000000037715232414252021126 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri=/"a", qop=auth, nc=00000040, cnonce="deadbeef", algorithm=SHA-256, response="012cdef0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d050.bin0000664000175000017500000000012115232414252021075 Upgrade: GET /a HTTP/1.1 Host: x Authorization: Digest username*=once="de libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d037.bin0000664000175000017500000000001315232414252021614 ----libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d386.bin0000664000175000017500000000005015232414252021115  GET / HTTP/1.0 iose libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d080.bin0000664000175000017500000000001015232414252022332 %42&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d036.bin0000664000175000017500000000003715232414252021107 ư: a HTTP/1.1 x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d018.bin0000664000175000017500000000012415232434352021432 7a59275a4a~Q ET)Q0Gt: HTTP/1.1 Host: x Cookie: cn=nce=2o@st;xnpab 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d308.bin0000664000175000017500000000010415232414252021104 QkGET /a HTTP/1.1 Host: XG?T /a HTTP/1.1 Host x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d321.bin0000664000175000017500000000003715232414252021107 d$AR]GPT / HTTP/1. libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d525.bin0000664000175000017500000000004515232414252021111 chunkedtGET %2A%2A HTTP/1.1 oamelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d279.bin0000664000175000017500000000002015232414252021113 ;y/a,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d147.bin0000664000175000017500000000001315232434352021432 #3@ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d290.bin0000664000175000017500000000002315232414252021107 42P libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d412.bin0000664000175000017500000000002115232414252021076 /CONON libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d071.bin0000664000175000017500000000001715232414252021665 Basic QQ==QQ==libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d082.bin0000664000175000017500000000003715232434352021436 `mCONNECT 15Pp2E`["0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d580.bin0000664000175000017500000000006515232414252021114 : @>GET / HTTP/1.1 Host: x iozan: wYXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d067.bin0000664000175000017500000000000515232414252020226 f&%0Alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d721.bin0000664000175000017500000000017215232414252021110 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data-ab Transfer-Encoding: chunked 52 - .0 / libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d627.bin0000664000175000017500000000011215232414252021107 @>GET / HTTP/1.1 Host: x Authorization: Basic dXNlcjpwYXN= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d091.bin0000664000175000017500000000001015232414252022334 'q--alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d702.bin0000664000175000017500000000015515232414252021110 P?ST /#a HTTP/1.1 Host: x Content yTpe: mipart/fo Transfer-Encoding: chunked 52 --nameTPGflibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d709.bin0000664000175000017500000000016015232414252021113 dGET / HTTP/1.1 Host: x Authorization: Digest userhash=true, username="cabb", realm="TetRealm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d588.bin0000664000175000017500000000007115232414252021121 Q /path?a=1G HTTP/1.1 H Cookie: ;"""""""" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d595.bin0000664000175000017500000000007715232414252021125 GET /a HTTP/1.1 Host: x Authorizat'on: Diges" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d007.bin0000664000175000017500000000001615232414252022337 coab-- as libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d067.bin0000664000175000017500000000003315232434352020224 )GET / HTT/2.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d178.bin0000664000175000017500000000001715232434352021442 :jjjj:jjj8qblibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d476.bin0000664000175000017500000000007715232414252021126 /GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d286.bin0000664000175000017500000000001015232414252020225 ?L\T\c\libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d231.bin0000664000175000017500000000000515232414252020217 %/dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d088.bin0000664000175000017500000000001015232414252022342 $b%f libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d054.bin0000664000175000017500000000013115232434352020217 0GET /path?a=1 HTTP/1.1 H: x Cookie: a=b  vvvvvvvvvvvvvv libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d833.bin0000664000175000017500000000042315232414252021113 GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaa\aaaaaaaa", us/a?b&c=true, realm="TestRealm", nonce="%%NONCE", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response="0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d435.bin0000664000175000017500000000005715232414252021117 /HE/aGT ?%87 HTTP/1.0 t: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d027.bin0000664000175000017500000000015215232414252021110 /f34(PT /aPOST HTTP/1.1 x@GET / HTTP/4.11 T /a HTTP/1.1 Ho t߇ H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d373.bin0000664000175000017500000000034515232414252021115 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri=*/a", qop=auth, nc=00000001, cnonce="de", algorithm=SHA-256, response="0123" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d274.bin0000664000175000017500000000000615232414252020227 C#%,%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d553.bin0000664000175000017500000000005015232414252021106  HTTP/0 /;a HTTP/1.1 : v Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d101.bin0000664000175000017500000000001015232414252022324 }%8&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d757.bin0000664000175000017500000000024515232414252021122 namePOST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----aT / HTTP/1.1 Ha- ----abc 1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d000.bin0000664000175000017500000000002015232414252021071 *libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d082.bin0000664000175000017500000000002415232414252021665 Digest qop=00000002libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d213.bin0000664000175000017500000000000415232414252020216 a)libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d701.bin0000664000175000017500000000015415232414252021106 COzFET /a HTTP/1.1 Host: x Authorization: DigeSt username="user", realm="Teal(", nse="" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d095.bin0000664000175000017500000000003415232414252021672 Digest algorithm="\SHA-256"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d048.bin0000664000175000017500000000001015232414252022336 %5f&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d041.bin0000664000175000017500000000000515232414252021610 @ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d086.bin0000664000175000017500000000004615232434352020231  GET /b HTTP/(.0 -x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d091.bin0000664000175000017500000000003115232414252021663 Digest algorithm=sha-256libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d760.bin0000664000175000017500000000025415232414252021114 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundboundary= Tran%%NONCE%%sfer-Encoding: chunked 26bc ent-Dksposn: form- value libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d283.bin0000664000175000017500000000000715232414252020230 O "libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d090.bin0000664000175000017500000000000415232414252020221 LD5libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d162.bin0000664000175000017500000000004515232414252021106 3 / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d259.bin0000664000175000017500000000000515232414252020231 Y1%elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d114.bin0000664000175000017500000000002015232414252021077 @ost:t: xlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d110.bin0000664000175000017500000000000115232414252021072 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d232.bin0000664000175000017500000000013615232414252021110 ;q  FPOST /a HTTP/1.1 Host Transfer-Encoding: chunked 3 ;[HEAD Co1.libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d013.bin0000664000175000017500000000001015232414252021603  =5libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d550.bin0000664000175000017500000000004715232414252021111 j GET / HTTP/1.3 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d112.bin0000664000175000017500000000007215232434352020216 AiGET /aaa@aaaa%-8Xaaaaaa HTTP/1.1 Hist: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d167.bin0000664000175000017500000000011415232414252021110 T ;POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked d(;qlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d273.bin0000664000175000017500000000002015232414252021105 P H Nlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d113.bin0000664000175000017500000000016215232434352021430 7a59#275a4~Q ETGt: HTTP/1.1 Hsot: x Cookie: cnonce="o:!TP/0.1 Host: x Cookie: cnp5d!t:5xnpab= 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d463.bin0000664000175000017500000000007015232414252021113 E'GET= /?%40+%+a=&%43 HTTP/1.1 Hos%4 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d103.bin0000664000175000017500000000005615232434352020220 0 GET /realm?%A02 HTTP/1.1 Ha=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d448.bin0000664000175000017500000000003515232414252021114 ;exGET HTTP/1.0 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d130.bin0000664000175000017500000000020015232414252022327 --abcCon}en- ef" ----abc ef" Content-Type: multipart/mixedGT / HTTP/1.1 Host: x Authorization: Basic dXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d522.bin0000664000175000017500000000004515232414252021106 &T +dX%lcjp HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d009.bin0000664000175000017500000000040615232434352020224 !--GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGPRIVATElibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d012.bin0000664000175000017500000000000215232414252021652 "alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d360.bin0000664000175000017500000000004615232414252021112 @GET / HTTP/1.0 HZZZ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d020.bin0000664000175000017500000000011515232434352020212 uiGET /aaaaaaaaaaaaaaaa_aa HTTP/1.1 H33333333iPAddre3333iPAddre3P libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d077.bin0000664000175000017500000000000315232414252020225 clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d036.bin0000664000175000017500000000001315232414252021613  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d179.bin0000664000175000017500000000031515232414252021116 FGET0/?=00000002, cnonce="deadbeef", alg f4a7614a6bf87ffd2d99212efa8f48880000000094e4 ", uri="/a", qop=auth, ncb HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d190.bin0000664000175000017500000000003215232434352021431 q(0 212libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d351.bin0000664000175000017500000000021315232414252021103 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 26 ----a chunketa;libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d007.bin0000664000175000017500000000015415232434352020222 Arealm=""OST /a HTTP/1.1 ot: x Content-Length: 5 Content-Length: 6 ContenTGEength: 11 hello worldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d097.bin0000664000175000017500000000007615232414252021124  /GET /a HTTP/1.1 Host: Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d119.bin0000664000175000017500000000003015232414252021105 /GET libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d096.bin0000664000175000017500000000003515232414252021674 Digest algorithm="MD\5-sess"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d161.bin0000664000175000017500000000000615232414252020222 )1234libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d175.bin0000664000175000017500000000004015232414252021110 TAGET / HTTP/2.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d374.bin0000664000175000017500000000004715232414252021120 r?F9 "/GE /a HTTP/1.1 H9 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d824.bin0000664000175000017500000000040215232414252021110 GET /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest useUpgrade: rname-"user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8''a%001%756089m=SH52-A6, response="0123456789abcd89abadeff0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d086.bin0000664000175000017500000000007515232434352021444 !!>>>> >>>>>.>3rrrr=rrDDz6Dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d176.bin0000664000175000017500000000021615232414252021113 XGET /a HTTP/2.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", qop=auth, nc=51615&b=%1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d076.bin0000664000175000017500000000005215232414252021113 'HGET / HTTP/1.1 Howt: zzlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d133.bin0000664000175000017500000000001215232434352021424 ف 128libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d820.bin0000664000175000017500000000037715232414252021117 (GET / HTTP/1.1 Ho.t:a HTTP/1.0 Host: x Authorization: Digest username=e48af00fc018ffe7e271223a9b4fb1e884aaafilenameaaaa", userhash=true, rea, n once="%%NONCE%%", "d&adbeef", algorith+=SHA-4 56, respe="0123489a_delibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d035.bin0000664000175000017500000000005615232434352021435 DD2OETET!HAD1!EEEEEE30@1!1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d007.bin0000664000175000017500000000002015232414252021100 /1.-.{libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d155.bin0000664000175000017500000000003715232414252021111  P HTTP/1.1 ywW libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d036.bin0000664000175000017500000000002315232414252021105 4 @ : x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d178.bin0000664000175000017500000000000315232414252020227 4Elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d402.bin0000664000175000017500000000005215232414252021104 B'0'GET /%41%4a= HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d205.bin0000664000175000017500000000005215232414252021105 P0POS) GET /a%xF8: HTTP/1.1 Kdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d071.bin0000664000175000017500000000004515232414252021110 GET %a HTTP/1.1 :libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d468.bin0000664000175000017500000000007215232414252021122 3PQGET /a HTTP/1.1 Cookie:; a=!&&&!!x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d073.bin0000664000175000017500000000000115232414252020217 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d404.bin0000664000175000017500000000005215232414252021106 C'r>&/ETgET %%c83% HTTP/1.1 Hrlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d265.bin0000664000175000017500000000002015232414252021106 Upgradd: fuzz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d150.bin0000664000175000017500000000000515232414252020217 %FFlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d061.bin0000664000175000017500000000000315232414252020216 zlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d253.bin0000664000175000017500000000000515232414252020223 Y%fclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d237.bin0000664000175000017500000000022715232414252021113 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----vue ----abc-- ; 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d091.bin0000664000175000017500000000001315232434352021430 1< libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d020.bin0000664000175000017500000000001015232414252022324 ^`=44libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d143.bin0000664000175000017500000000020315232434352020216 AGET /a HTTP/1.1 Host: x/1.1 Host: x /GET /b HTTP/1.1 Host: x Connection: clos /GET /b HTTP/1.1 Host: xo libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d039.bin0000664000175000017500000000001015232414252022336 <<:=%Dc=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d100.bin0000664000175000017500000000005515232434352020214 :GET /aaaaaaaaa%aaa HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d252.bin0000664000175000017500000000062115232414252021106 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="de&dbeef", algorithm=SHA-256, response="0123456789aTE3456789.bcdef0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d015.bin0000664000175000017500000000001215232414252021075 /TD*lerlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d006.bin0000664000175000017500000000002015232414252021077 gUp: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d570.bin0000664000175000017500000000005415232414252021111 .#%E /` HTTP/1.1 X:/1 .1 c libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d829.bin0000664000175000017500000000040515232414252021120 Upgrade: GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest usernamAut, username*=UTF-8''a62TRACEBnonce="BBBB%BBBBe47abK+gDigest%BCCCC%BCCCC%BCCCCintCC%CC libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d140.bin0000664000175000017500000000011015232414252021076  HH/a H2a HTTP/1.1 Cookie:Aa= Hi 7 :a= 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d312.bin0000664000175000017500000000003215232414252021102 1d#0/?0bAutXNjH libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d041.bin0000664000175000017500000000002015232414252021076 `0 }.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d196.bin0000664000175000017500000000005015232414252021114 @=GET /a% HTTP/1.1 Hrlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d243.bin0000664000175000017500000000021715232414252021112 , /GET /a HTTP/1.1 H$ LETEtcek a/ HTTP/1.1 Expect: 100-continue Ho Transfer-Encoding: chunked =MMM c ose libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d614.bin0000664000175000017500000000011015232414252021101  |GET /T; HTTP/1.1 Host: x Connection: de Upgrade:: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d006.bin0000664000175000017500000000001015232414252021654 Basic Ylibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d104.bin0000664000175000017500000000201215232414252021076 9 GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 HochunkedAuthorizatioaaaaaaaaaaaaaaaaaarealm="aa=aaaaaost:GET /a HTTP/1.1 Host x XGT /a HTTP/1.1 Transfer-Encoding: org/aHo x XGET /a HTTP/1.1 HoGET ʞ HTTP/1.1 Host x XGET /a HTTP/1.1 Host2 x Gauth(T / HTTP/1.1 XGET /a HTTP/1.1 Hoauth,auth-intGET /a HTTP/2.1 Host x XGET /a HTTP/1.1 Ho x XGET /a HTTP/1.1 HoGET ʞ HTTP/1.1 Host x XGET t:GET /a HTTP/1.1 Host x XGT /a HTTP/1.1 TransfET t:GET /a HTTP/1.1 Host x XTTP/2. Host2 x Gauth(T HTTP/1.1 Host x XGET /a HTTP/1.1 Host2 x Gauth(T / HTTP/1.1 alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d064.bin0000664000175000017500000000000515232414252020223 )%%dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d246.bin0000664000175000017500000000023115232434352021434 #!23` p4@_@2pc`3`p`3`libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d115.bin0000664000175000017500000000003415232414252022337 --abc ----abc ve #-- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d304.bin0000664000175000017500000000007515232414252021107 )UGT / HTTP/1.1 Host: x Authorization: Digest libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d599.bin0000664000175000017500000000007015232414252021125 Q=X/1X R 'libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d116.bin0000664000175000017500000000030315232414252021102 &GET /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest username-"user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8''a%!ef0126789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d029.bin0000664000175000017500000000002215232414252021103 Connection:HEAD libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d108.bin0000664000175000017500000000011015232434352021425 7a5927a4aQt EQ0Gt: HTTP/1.1 Host: x Cookie: cnon: xnpa=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d562.bin0000664000175000017500000000017315232414252021117 ?/GETZOST /a HTTP/1.1 Content-Length: 1048576 9991.1 Content-Length: 1048576 999999999999::ose $libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d407.bin0000664000175000017500000000005315232414252021112 B' 0'GET 42?a=%3C HTTP/1.1 Hlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d213.bin0000664000175000017500000000010115232414252021077 'ET /T/1. HTTP/1.1 Connection: close x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d161.bin0000664000175000017500000000037515232434352020230 AiGET /aaaaaaaaaaaaaaqaaaaaaaaaaaa?aaaaaa%35aaaa HTTP/1.1 Host: x X-Lo;aaaaaaaaaaaaaaa libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d090.bin0000664000175000017500000000001015232414252022333 %a&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d276.bin0000664000175000017500000000000615232414252020231   libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d113.bin0000664000175000017500000000027715232414252021672 0"21nec=3456789acdef", uri="/a" qot0"21nec=3456789acdef", uri="/a" qotlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d050.bin0000664000175000017500000000010715232434352020216 A<POST /a HTTP/1.1 Host: x Content-Length: 12 heo 11 ldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d052.bin0000664000175000017500000000012215232434352020215 qqqdGET / HTTP/1.1 HoJJJqHtso: x Cookie: ;ext="quoted"a= HTTP/2.0b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d069.bin0000664000175000017500000000003415232434352020227 ^= @TTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d290.bin0000664000175000017500000000004215232414252021105 .}%#T /` HTTP/1.1 X: clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d104.bin0000664000175000017500000000001115232414252022330 .; =%29libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d066.bin0000664000175000017500000000001015232414252021613 A}libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d021.bin0000664000175000017500000000012715232434352020216 AiGET /aaaaaaaaaaaa443aaaaaa HTTP/1.1 H$ost: xn: Upgrade 4444444444444gz4 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d234.bin0000664000175000017500000000011215232434352021427 ,0022A22@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d037.bin0000664000175000017500000000000515232414252020223 %E7libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d042.bin0000664000175000017500000000001015232414252022330 %99&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d497.bin0000664000175000017500000000004215232414252021116  | / HTTP/1.1 Hos^^2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d874.bin0000664000175000017500000000174715232414252021132 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/.%9FFFFFFFFFFFFFFFFFFFFFF%98 HTT.%9FFFFFFFFFFFFFFFFFFFFFF%98 HTT@@@@@@@@@@@@@@@@@@@@%17 H%99 H.%9FFFFFFFFFF\FFFFFFFFFFF.%9FFFFFFFFFFFFFFFFFFFFFF%98 HTT.%9FFFFFFFFFFFFFFFFFFFFFF%98 HTT@@@@@@@@@@@@@@@@@@@@%17 H%99 H.%9FFFFFFFFFFFFFFFFFFFFFF%98 HTT@@@@@@@@@@@@@@@@@@@@%17 H%99 HFFFFFFFFFFFFFFFFFF%98 HTT.%8FFFFFFFFFFFFFFF.%9FFFFFFFF~FFFFFFFFFFFFFFa", qop=auth, nc=00000001, cnonce="deadbef", algorithm=SHA-256, response="0481472191af01HTTR6783456789deadef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d227.bin0000664000175000017500000000012315232414252021110 FT .a HTTP/1.1 Host: Transfer-Encoding: chunked 2 ab1c libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d108.bin0000664000175000017500000000002015232414252021102 Contt-/AD B'libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d293.bin0000664000175000017500000000002315232414252021112 ?/ap/0.1 = libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d123.bin0000664000175000017500000000001215232434352021423 1;j0=0julibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d257.bin0000664000175000017500000000000515232414252020227 /b1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d021.bin0000664000175000017500000000001415232414252022331 XY--XY -libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d153.bin0000664000175000017500000000003615232414252021106 U G /%MD5 HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d528.bin0000664000175000017500000000012515232414252021116 YY FPOST .a HTTP/1.1 Host: x Transfer-Encoding: chunked 1 ab1cc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d575.bin0000664000175000017500000000027615232414252021127 v?cE!GET-34POST /a HTTP/1.1 Host: x Content-Length: 4nect abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d014.bin0000664000175000017500000000000315232414252020214 "a"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d523.bin0000664000175000017500000000012315232414252021107 FP HTTP/1.1 Host: x Transfer-Encoding: chunked 6 abc 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d035.bin0000664000175000017500000000000415232414252020220 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d103.bin0000664000175000017500000000001115232414252022327 \-=99libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d231.bin0000664000175000017500000000020215232414252021076 GE%@;ext="quoted@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%NONCE%%1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d283.bin0000664000175000017500000000004115232414252021106 @>GET  HTTP/1.1 Qasrtlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d000.bin0000664000175000017500000000010215232434352020204 !0GNegotiate =1 HTTP/1.1 Host: x Cookie: a=-174 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d056.bin0000664000175000017500000000001015232414252021612 ǧlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d328.bin0000664000175000017500000000012015232414252021104 ;POS/aT HTTP/1.1 Host: x Transfer-Encoding: chunked d;Alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d672.bin0000664000175000017500000000013115232414252021110 Pp&FGET /a HTTP/1.1 Ho (  Authorization: Digest username*="us\r", l libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d411.bin0000664000175000017500000000005315232414252021105 ; GET /a0%b7 HTTP/1.1 KK libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d264.bin0000664000175000017500000000002015232414252021105  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d099.bin0000664000175000017500000000003615232414252021700 Digest algorithm=Mvponse=&ef"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d810.bin0000664000175000017500000000037015232414252021107 GET /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest useUpgrade: rname-"user", rerealm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8''a%001%-A6, response="0123456789abcd89abadeff0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d115.bin0000664000175000017500000000000715232434352021430 Pp4@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d114.bin0000664000175000017500000000007415232434352020222 A<POST /a HTTP/1.1 HSHA-256-s2essost: 1 hello libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d033.bin0000664000175000017500000000001415232414252021660 Digest , libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d157.bin0000664000175000017500000000001415232434352021434 #0`wwlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d172.bin0000664000175000017500000000020015232414252021100 c3333333333PUT3-3333CODCT 333333Authorization: Basic 333333333333333333333z333POlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d551.bin0000664000175000017500000000014315232414252021112 4POST /a HTTP/1.1 Hos%:2.1 Host: Content-Length: 3 x Content-Length: 2 abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d197.bin0000664000175000017500000000004315232434352021442 7A92a4Q E%Q HTTP/1.1 Ce0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d034.bin0000664000175000017500000000000515232414252022335 nnllibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d036.bin0000664000175000017500000000010115232434352021425 T/1@?$!0??w62B==========libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d302.bin0000664000175000017500000000002715232414252021105 @Exp hlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d185.bin0000664000175000017500000000000315232414252020225 fFlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d129.bin0000664000175000017500000000004615232414252021112 'GET HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d149.bin0000664000175000017500000000000515232414252020227 ^%D5libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d140.bin0000664000175000017500000000015615232434352020222 Arealm=""OST /a HTTP/1.1 Hsot: x Content-Length: 5 Content-Length: 5 ContenTGEength: 11 hello worldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d890.bin0000664000175000017500000000162115232414252021117  GET /a HTTP/1.1 Host XGET /a HTTP/1.1 Host: x Authorizatio1 Host: x Authorization: Dige{t usopaque="erst x9d2aaa32418653ost: y =G;T /a HTTP/1.1 Host: xDiname=: y =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri=/a", qop=auth, nc=00000001, cnonce="deadbeef", algoritm=hSHA-9dd4486210af algorithm=SHA-256, response="0123<56789abcdef" alm" response 23456788ab="00" @ cd Uf" /a ges/1.1 H GET /a Herst x8d2aaa32418653ost: y =G;T /a HTTP/1.1 Host: xDiname=: y =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri=/a", qop=auth, nc=00000001, cnonce="deadeef", algoritm=hSHA-9dd4486210af algobithm=SHA-256, response="0123<56789abcdef" alm" response 23456788ab="00" @ cd Uf" /aHTTP e0tent-.en0", uri="/a", algoritgtlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d319.bin0000664000175000017500000000011115232414252021104 T=G"m E/ HTTP/1.1 Host: x Connection: Upgrade Upgrade: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d238.bin0000664000175000017500000000024015232414252021107 * 8GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaaaaaaaaaaaaaaaa", userhash=true,e rhm=on: upgrade libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d120.bin0000664000175000017500000000001215232434352021420 dd0dvlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d278.bin0000664000175000017500000000004015232414252021111  /a HTTP/1.1 nc00libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d274.bin0000664000175000017500000000002015232414252021106   libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d131.bin0000664000175000017500000000005515232414252021103  @>GET / HTTP/1.1 Host: x Aat:ic libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d056.bin0000664000175000017500000000001215232434352021430 ????O? libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d096.bin0000664000175000017500000000003715232434352021443 ,02A22@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d137.bin0000664000175000017500000000011415232414252021105 T;POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked d '*libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d166.bin0000664000175000017500000000010715232414252021111  HTTP/.0 GKT ;/a HTTP/1.1 Cookie:a=b; HTTP/2nfgr- H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d539.bin0000664000175000017500000000004615232414252021117 aresotC %ent- HTTP/1.1 Hjst%4libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d347.bin0000664000175000017500000000004515232414252021116 %<IONS * HTTP/1.1 s~x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d234.bin0000664000175000017500000000013715232414252021113 -v?cE! ST /a=1 HTTP/1.1 Host: x Content-Length: 2222222222222222222228 a#bcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d460.bin0000664000175000017500000000006715232414252021116 0 Gt: lPOST / HTTP/1.1 HContst:$libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d141.bin0000664000175000017500000000016315232434352020221 uiG/TGET /aaaaaaaaaaaaaaaaaaB!sic QQ=5aa HTTP/1.0aaaaaaaaa_aa HTTP/1.1 HoPPPPPPPPPPP(P QU@A=Xst xlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d084.bin0000664000175000017500000000002515232414252021670 Digest algorithm=MD1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d392.bin0000664000175000017500000000001215232414252021105 op =uon libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d384.bin0000664000175000017500000000005015232414252021113 GuuuET /a%2A8b HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d236.bin0000664000175000017500000000021715232414252021111 8GET oa P/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest userham=true,username*=UTF-7''a, nAuthorization56 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d056.bin0000664000175000017500000000006615232414252022350 --abc ----abc Content-Disposition: ffilename*- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d116.bin0000664000175000017500000000057715232414252021700 Bsu[r3TesyBasic QQ==QQ=UUUUUUUUDigest OUUEUBearer UUUUUUUUu[U'asiA QQ==QQ=UUUUUUUUNJDigest OUUEUBearer UUUUUUUU=Digest =Digest libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d406.bin0000664000175000017500000000001715232414252021106  8 Hܻ߷ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d588.bin0000664000175000017500000001020215232414252021121 ;q   =OT SP/a HTTP/1.1 Hostd: x= Transfer-Encong: NlcjpwYXNz x= Transfer-Encong: =OT SP/a HT =OT S=OT std: x= Transfer-Encoing: ch  =OT SP/a HTTP/1.1 Hostd: x= Transfer-Encong: NlcjpwYXNz x= Transfer-Encong: =OT SP/a HT =OT S=OT std: x= Transfer-Encoing: chu Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing: chu =OT SP/a HT =OT S=OT std: x= Transfer-Encoing: chu Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing: chun 1u Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing:RR HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%$12'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%41'2+a=&%8TP/ET /?%4P/ET /?%41&%RRRRRRRRRRRRRRa=& HTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%R HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?A2?a=& P?%412'+a=&%86 HTTRRRRRRRRRRRRRRRRRRR HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRA2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?A2?a=& P?%412'+a=&%86 HTTRRRRRRRRRRRRRRRRRRR HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%41'2+a=&%8TP/ET /?%4P/ET /?%41&%RRRRRRRRRRRRRa=&TTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412%412'+a=&%RRRRRRRRRRRHTTP/1=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%41'2+a=&%8TP/ET /?%4P/ET /?%41&%RRRRRRRRRRRRRRa=& HTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%R HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%+a=?%412'+a=&%RRRTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'RRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%41'2+a=&%8TP/ET /?%4P/ET /?%41&%RRRRRRRRRRRRRa=& HTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%R HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%%412'+a1 A2?a=& P?%412'+a=&%8ET /?%4 HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%+a=?%412'+a=&%RRRTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2 chu =OT SP/a HT =OT S=OT std: x= Transfer-Encoing: chu Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing: chun 1 &libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d266.bin0000664000175000017500000000002015232414252021107 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d224.bin0000664000175000017500000000015015232414252021102 dGET / HTTP/1.1 Host: Authorization: Digest userhash=true, username="aAbb", realm="/alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d311.bin0000664000175000017500000000010615232414252021100 DTS th?a=1C HTTP/1.1 Host: x Cookie: a30=b412 /clef libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d171.bin0000664000175000017500000000000315232414252020220 4libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d804.bin0000664000175000017500000000036115232414252021112 Upgrade: GET MD5/a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest usernae="aaa----------a-a-aaaaaaaaaa", username*=UTF-8''auCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCf8e6%d9e" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d320.bin0000664000175000017500000000003715232414252021106 +a=%RT %4a4T 8 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d120.bin0000664000175000017500000000010415232434352020211 A<POST /a HTTP/1.1 Host: x Content-Length:; ext11 hellibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d769.bin0000664000175000017500000000027115232414252021124 namePOST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc osi#tion: for-data; value --- ----abc 1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d723.bin0000664000175000017500000000017415232414252021114 GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm",e=T"0000", uri=orionse00" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d186.bin0000664000175000017500000000000315232414252020226 elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d142.bin0000664000175000017500000000016615232434352020225 A&iGET /aaaaaaaaaaaaaaaaaaaaaa[aaa HTTP/1.1 Hchunkedost: x X-Long: aaaaaaaaaAuthorization: Digest aaaaa libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d525.bin0000664000175000017500000000012415232414252021112   GEOPTIONS * HTTP/1.1 POSHE@ / HTTP/1.1 T: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d086.bin0000664000175000017500000000031515232414252021113 GET /aHTTP/1.1 Host: x GET / HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="00000000000000000000000018446744073709551615", uri="/a", response="e" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d527.bin0000664000175000017500000000012515232414252021115 2~ =OT POST HTTP/1.1 Host:d x= Transfer-Encoding: chunked 3 abc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d254.bin0000664000175000017500000000162515232414252021115 WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /a HT[P/1.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 HGET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qožnc=0*000001, cnonce="deadbeef", algorithm=SHA-256, response=/1.1 HTRA/1.1 HostT / GET /a%4TTP/1.1 Host: x =GET /GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri=nc=00000000, cnonce="deadbeef", algorithm=SHA-256, response=/1.1 HTRA/1.1 HostT T /a HTTP/1. Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="%%NONCE%%auth, nc=00000001, cnonce=dbeef", algorithm=SHA-256, response=1 Host XGET /a HTT%GET /aP/1.1 H TTP/1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d010.bin0000664000175000017500000000000515232414252022327 alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d228.bin0000664000175000017500000000007015232434352021435 7a59275aQ 0Gt: HTTP/1.1 Cookie:;cn0 Cookie:;=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d181.bin0000664000175000017500000000002215232434352021430 dOt1 >libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d796.bin0000664000175000017500000000034115232414252021122 8GET /a HTTP/2.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaaaaaaaaaaFaaa,aaaaaaaaa", userhash=true, ree="%%NONCE%%", uri="/a", qop=uth, nc=00000001, /a HTTP/1.tion: upgrade libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d678.bin0000664000175000017500000000013615232414252021123  0GET /p?1= HTTP/1.1 Host: x Cookie: a= t=alTP/; T/: a=f/a HTTP/1.1HJQQa; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d299.bin0000664000175000017500000000002615232414252020240 18446744073709551615libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d747.bin0000664000175000017500000000023715232414252021122 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest use="deadbeef", algorithm=SHA-656, response="0123def016789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d571.bin0000664000175000017500000000005515232414252021113 HEAD a HTTP/1.1 Host:#d9b12" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d083.bin0000664000175000017500000000001015232414252022335 %%en=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d211.bin0000664000175000017500000000005315232434352021426 7Aa592a4aQ ET%7QGt: HTTP/1.1 Coe0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d019.bin0000664000175000017500000000001215232434352021427 32libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d710.bin0000664000175000017500000000016115232414252021104 GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TetRealm", username*=UTF% libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d050.bin0000664000175000017500000000001015232414252022327 a%C5 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d354.bin0000664000175000017500000000024615232414252021114 XGETGET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username=i="/a", qop=auth, nc=0 =GET /a HTTP/1.1 Host: nce="deadbe9a libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d240.bin0000664000175000017500000000015415232414252021107 FAFHEAD HHGHHHH/a HTTP/1.1 Host: x Transfer-Encoding: chunked 0200000000000fffffffffff libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d213.bin0000664000175000017500000000005415232434352021431 7Aa59275a4aQ ET%Q0Gt: HTTP/1.1 C 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d081.bin0000664000175000017500000000004515232434352020223 GET / HTTP/1.1 CoSHA-.14libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d093.bin0000664000175000017500000000005115232434352020223  dGET / HTTP/1.1 HoJJJJ$J libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d597.bin0000664000175000017500000000010015232414252021112 nameCONNECT / HTTP/1.1 Host: x Authization:& Bas N libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d564.bin0000664000175000017500000000020115232414252021111 v?cE(POS FAFHEAD HHGHHHH/a HTTP/1.1 Host: xz Transfer-Encoding: chunked 6 fbc 0 TSTlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d176.bin0000664000175000017500000000000315232414252020225 Clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d547.bin0000664000175000017500000000013715232414252021122 pP FPOST /a HTTP/a HTTP/1.1 Hos^t: x Transfer-Encoding: chunked fer. libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d149.bin0000664000175000017500000000024515232434352020232 A!<POST /a.14 HTTP/1.1 Hsot: x ContenGETength:: x Cono 03 hello wroldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d128.bin0000664000175000017500000000004215232414252021105 lenameGET / HTTP/1.1 Ho libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d321.bin0000664000175000017500000000011215232414252021076  |GET / HTTP/1.1 Host: x Connection: Upgrade Upgrade:he libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d175.bin0000664000175000017500000000000315232414252020224 9Dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d017.bin0000664000175000017500000000000515232414252021613 blibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d562.bin0000664000175000017500000000005215232414252021110 dXlYjwc.N)ET / HTTP/1.1 Host: x* libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d136.bin0000664000175000017500000000014615232434352020226 0&GlEr/eT m=%nt0cionuade0t`?%++++++++0 HTTP/1.1 Ha=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d207.bin0000664000175000017500000000005315232414252021110 ET /a HTTP/1.1 Hos: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d132.bin0000664000175000017500000000000515232414252020217 /%@9libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d183.bin0000664000175000017500000000001515232414252021106 0A: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d888.bin0000664000175000017500000000045215232414252021127 LGET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 H'ooaaaaaaaaaaaaost: x XGET /a HTTP/1.9 Host: x Autheaaaaost: x XGET /a HTTP/1.2 Hoct:1bәd80eforizatioaaaaaaaaaaaaaost: x XGET /a HTTP/1.9 Host: x Auhritoon: Digest useaaaaost: xM XGET /a HTTP/1.2 Host:1b" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d296.bin0000664000175000017500000000002515232414252021117 Pp H1.1/ Ex libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d258.bin0000664000175000017500000000001615232414252021112 srha~s-h! libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d097.bin0000664000175000017500000000000515232414252020231 S%33libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d133.bin0000664000175000017500000000021015232414252022333 --abc *----abc Content-Transfer-Encoding: bi f" Content-Type: multipart/mixed;bomixedŧouboundary=Q@ultiparec -- e libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d680.bin0000664000175000017500000000013715232414252021115 @ABCDE]POST /a HTTP/1.0 Host: x Transfer-Encoding: chunked 2;ext AB 3; HTlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d120.bin0000664000175000017500000000003215232414252021077 [(GElibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d045.bin0000664000175000017500000000004715232434352020225 AGET a HTTP/1.1 HostdNSNamelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d179.bin0000664000175000017500000000002115232434352021436 @30666Dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d746.bin0000664000175000017500000000023715232414252021121 GET /a HTTP(1.1 HosQ;D^=GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="Telm", nonce="%%NONCE%%", uri=0019abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d211.bin0000664000175000017500000000007415232414252021106 [?cE! -88POST / HTTP/1.1 Hosp: x+ Ct-Lh:8 &Elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d166.bin0000664000175000017500000000002415232414252021112 =) w w libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d346.bin0000664000175000017500000000004515232414252021115 =O =OT HTTP/1.1 HoRR libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d349.bin0000664000175000017500000000020515232414252021113 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 TRACE -- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d555.bin0000664000175000017500000000005015232414252021110 GET /a HTTP/1.1 HoSt:l libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d339.bin0000664000175000017500000000004415232414252021116 (GET /a HTTP/1.1 X"olibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d420.bin0000664000175000017500000000002415232414252021100 ?TRACE ?libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d294.bin0000664000175000017500000000002415232414252021114  P libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d664.bin0000664000175000017500000000012515232414252021114 T ;POST a HTTP/1.1 Host: x Transfer-Encoding: chunked d;Aqqqqqqq qlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d881.bin0000664000175000017500000001406215232414252021122 #$G$GET /a`HTT HTTP/1.1 Ho : X x : yPTP/1.1 Ho : X x : yP/2.1 Host: / X x : yx X: y Host: x AX: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.#$G$GET /a`HTT HTTP/1.1 Ho X x : yPTP/1.1 Ho : X x : yP/2.1 Host: / X x : yx X: y Host: x AX: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.1 Ho : X x : .1 Ht: x yP/2.1 Host: /1.1 Ho : X x.1 Ht: x yP/2.1 Host: /1.1 Ho : X x : yP/2.1--b #$GET /a`HTT Hy : X x 8 yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : X x : yPyP/2.1 Host: /1.1 Ho : X x : yP/2.1#$GET /a`HTT Hy : X x : yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : o : X x : yP/4.1 Host: x X: y Host: x X: y : X x :o : X x : yP/2.1--b #$GET /a`HTT Hy : X x 8 yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : X x : yPyP/2.1 Host: /1.1 Ho : X x : yP/2.1#$GET /a`HTT Hy : X x : yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : o : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.#$G$GET /a`HTT HTTP/1.1 Ho X x : yPTP/1.1 Ho : X x : yP/2.1 Host: / X x : yx X: y Host: x AX: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X xo X x : yPTP/1 : yP/2.1--b #$GET /a`HTT Hy : X x 8 yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : X x : yPyP/2.1 Host: /1.1 Ho : X x : yP/2.1#$GET /a`HTT Hy : X x : yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : o : X x : yP/4.1 Host: x X: y Host: x X: y : X x :o : X x : yP/2.1--b #$GET /a`HTT Hy : X x 8 yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : X x : yPyP/2.1 Host: /1.1 Ho : X x : yP/2.1#$GET /a`HTT Hy : X x : yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : o : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.#$G$GET /a`HTT HTTP/1.1 Ho X x : yPTP/1.1 Ho x : X : yP/2.1 Host: / X x : yx X: y Host: x AX: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X xo X x : yPTP/1.1 Ho : X x : yP/2.1 Host: / X x : yx X: y Host: x AX: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.1 Ho : X x : .1 Ht: x yP/2.1 Host: /1.1 Ho : X x : yP/2.1--b #$GET /a`HTT Hy : X x 8 yPTP/1.1 Ho : yPTP/1.#$G$GET /a`HTT HHo : X x : yP/2.1--b #$GET /a`HTT Hy : X x 8 yPTP/1.1 GET /a HTTost: x GET /a oamEaHo : X x : yP/2.1 Host: /1.1 Ho : X x : yPyP/2.1 Host: /1.1 Ho : X x : yP/2.1#$GET /a`HTT Hy : X x : yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : o : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.#$G$GET /a`HTT HTTP/1.1 Ho X x : yPTP/1.1 Ho : X x : yP/2.1 Host: /: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.#$G$GET /a`HTT HTTP/1.1 Ho X x : yPTP/1.1 Ho : X x : yP/2.1 Host: / X x : yx X: y Host: x AX: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.1 Ho : X x : .1 Ht: x yP/2.1 Host: /1.1 Ho : X x : yP/2.1--b #$GET /a`HTT Hy : X x 8 yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : X x : yPyP/2.1 Host: /1.1 Ho : X x : yP/2.1#$GET /a`HTT Hy : X x : yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : o : X x : yP/4.1 Host: x X: y Host: x X: y : X x :o : X x : yP/2.1--b #$GET /a`HTT Hy : X x 8 yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : X x : yPyP/2.1 Host: /1.1 Ho : X x : yP/2.1#$GET /a`HTT Hy : X x : yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : o : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.#$G$GET /a`HTT HTTP/1.1 Ho X x : yPTP/1.1 Ho : X x : yP/2.1 Host: / X x : yx X: y Host: x AX: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/2.1 Host: x X: y Host: x X: y : X xo X x : yPTP/1.1 H-- : X x : yP/2.0 Host: / X x : yx X: y Host: x AX: y ET /a` /a`HTT%HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.1 Ho : X x : .1 Ht: x yP/2.1 Host: /1.1 Ho : X x : yP/2.1--b #$GET /a`HTT Hy : X x 8 yPTP/1.1 Ho : yPTP/1.#$G$GET /a`HTT HHo : X x : yP/2.1--b #$GET /a`HTT Hy : X x 8 yPTP/1.1 Ho : X x : yP/2.1 Host: 1.1 : X x : yPyP/2.1 Host: /1.1 Ho : X x : yP/2.1HPTP/2. @@@@%@6@9 HTTP/1.1 #$GET /a`HTT Hy : X x : yPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho : o : X x : yP/4.1 Host: x X: y Host: x X: y GET /a HTT: X x : yPTP/1.#$G$GET /a`HTT HTTP/1.1 Ho X x : yPTP/1.1 Ho : X x : yP/2.1 Host: / X x : yx X: y Host: x AX: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X x :TTP/0.1 Ho  x : yPTP/1.1 Ho : X x : yP/2.1 Host: / X x : yx X: y Host: x AX: y ET /a` /a`X x : yPTP/1.1 Ho : X x : yP/2.1 Host: / X x : yx X: y Host: x AX: yHTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP X x : yx X: y Host: x AX: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X x :TTP/0.1 Ho X x : yPTP/1.1 Ho : X x : yP/2.1 Host: / X x : yx X: y Host: x AX: y ET /a` /a`HTT HTTP// .1 Ho : X x : yP/2.1do : X x : yP/4.1 Host: x X: y Host: x X: y : X x : yPTP/1.1 Ho : X x : .1 Ht: st: /1.1 Ho : o : X x PTP/2. @@@@%@6@9: yP/4.1 Host: x X: y Host: x X: y : X x : GET, / Ho : X xPTP/1.1 Ho : X x : yP/2.1 Host: /1.1 Ho ost: x GET /a oamEa: X x : yPyP/2.1 Host: /1.1 Ho : X x : yP/2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d040.bin0000664000175000017500000000004315232434352020214 dGET ? HTTP/1.1 loc|||libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d235.bin0000664000175000017500000000014115232414252021107 /34(PT /aPST HTTP/1.1 x@GET / HTTP/1.11 T /a.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d201.bin0000664000175000017500000000004015232414252021073 HTTP/1.0G / HTTP/1.1 Ht libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d118.bin0000664000175000017500000000004115232414252022340 --abcp----abc Content-Dispo libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d469.bin0000664000175000017500000000003715232414252021121  @;>GT / HTTP/1.1 H^^^libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d097.bin0000664000175000017500000000004115232434352021437 :::libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d291.bin0000664000175000017500000000002315232414252021110 =clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d331.bin0000664000175000017500000000004315232414252021105 /GET /a HTTP/1.d libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d563.bin0000664000175000017500000000005215232414252021111 a HPTP/11 X: y %41 HT y %41 HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d809.bin0000664000175000017500000000037015232414252021117 GET /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest useUpgrade: rname-"user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8''a%001%52-A6, response="0123456789abcd89abadeff0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d051.bin0000664000175000017500000000001315232414252022333 =A libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d819.bin0000664000175000017500000000037715232414252021127 GET TP/1.T /a HTTP/1T/a HTTP/1.1 Hi: x Authorization: Digest usernaem-"user", realm="TestRealm", nonce="%۱", uri="/a(", username*=UTF-8''aFFFFFFFF/aE%FFF%$F=ef", aOm=SH52-AY6, response="01234567012345d6789abcdef" RONCE%%", qolibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d383.bin0000664000175000017500000000005015232414252021112 `0 '/GET /a HTTP/1.1 HELETElibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d589.bin0000664000175000017500000001410215232414252021125 ;q   =OT SP/a HTTP/1.1 Hostd: x= Transfer-Encong: NlcjpwYXNz x= Transfer-Encong: =OT SP/a HT =OT S=OT std: x= Transfer-Encoing: ch  =OT SP/a HTTP/1.1 Hostd: x= Transfer-Encong: NlcjpwYXNz x= Transfer-Encong: =OT SP/a HT =OT S=OT std: x= Tra=& HTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%R HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?A2?a=& P?%412'+a=&%86 HTTRRRRRRRRRRRRRRRRRRR HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRA2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?A2?a=& P?%412'+a=&%86 HTTRRRRRRRRRRRRRRRRRRR HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%41'2+a=&%8TP/ET /?%4P/ET /?%41&%RRRRRRRRRRRRRa=&TTP?%412'+a=?%412'+a1 A2?a=& Pnsfer-Encoing: chu Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing: chu =OT SP/a HT =OT S=OT std: x= Transfer-Encoing: chu Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing: chun 1u Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing:RR HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%$12'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%41'2+a=&%8TP/ET /?%4P/ET /?%41&%RRRRRRRRRRRRRRa=& HTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%R HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?A2?a=& P?%412'+a=&%86 HTTRRRRRRRRRRRRRRRRRRR HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRA2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?A2?a=& P?%412'+a=&%86 HTTRRRRRRRRRRRRRRRRRRR HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%41'2+a=&%8TP/ET /?%4P/ET /?%41&%RRRRRRRRRRR2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%41'2+a=&%8TP/ET /?%4P/ET /?%41&%RRRRRRRRRRRRRa=&TTP?%412'+a=?%412'+a1 A2?a=& Pnsfer-Encoing: chu Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing: chu =OT SP/a HT =OT S=OT std: x= Transfer-Encoing: chu Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing: chun 1u Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing:RR HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%$12'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HTRRa=&TTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%+a=?%411'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412%412'+a=&%RRRRRRRRRRRHTTP/1=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%41'2+a=&%8TP/ET /?%4P/ET /?%41&%RRRRRRRRRRRRRRa=& HTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%R HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%+a=?%412'+a=&%RRRTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'RRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+aa=&%R HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412%412'+a=&%RRRRRRRRRRRHTTP/1=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HT412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%41'2+a=&%8TP/ET /?%4P/ET /?%41&%RRRRRRRRRRRRRRa=& HTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%R HTTP/1.1 A2?a=& HTTP?%412'+a=?%412'+a=&%RRRRRRRRRRRHTTP/1.1 A2?a=& HTTP?%412'+a=&%86 HTTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa=& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTTP/ET /?%+a=?%412'+a=&%RRRTP/ET /?%412'+a=&%RRRRRRRRRRRRRRa& HT>P?%471'+a=?%412'+a1 A2?a=& P?%412'+a=&%8ET /?%412'+RRRRRRRHTTP?%412'+a=?%412'+a1 A2?a=& P?%412'+a=&%86 HTa=& HT>P?%471'+a=?%412'+a1 A2 chu =OT SP/a HT =OT S=OT std: x= Transfer-Encoing: chu Hostd: x= Transfer-Encoing: cIONShunked Transfer-Encoing: chun 1 &libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d024.bin0000664000175000017500000000001315232414252021610 D:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d358.bin0000664000175000017500000000004615232414252021121 GET / HTTP/1.1 HbbbA libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d454.bin0000664000175000017500000000003615232414252021112 GEt %7 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d490.bin0000664000175000017500000000010315232414252021110 r0'GET /%2?a=%4@ +++++++++++++G1.1 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d102.bin0000664000175000017500000000042215232414252021077 \GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00%", uri="/a", qop=auth, nc=00000002, cnonce="deadbeef", algalgorithm=orithm=SHA-256, response="ef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d255.bin0000664000175000017500000000001415232414252021105 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d014.bin0000664000175000017500000000010115232414252021076 ?/GETZOST /a HTTP/1.1 Content-Length: 1048576 $libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d092.bin0000664000175000017500000000005015232434352020221 G*ET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d306.bin0000664000175000017500000000010315232414252021101 56-sessmm0GET /pa HTTP/1.1 Hostx Cookie: po libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d379.bin0000664000175000017500000000042715232414252021124 8GET oa P/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest userhame="aaaaaaaaaaaaaaaaaaaaaboundary=aaaaaaaaaaaaaaaaaaaaaa", userhash=true,username*=UTF-7''a, nAuthorization: Digest "/a", op=auth, nc=00000001, cnonce="deadeef", algorithm=SHA56 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d024.bin0000664000175000017500000000000615232414252022335 nobgulibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d137.bin0000664000175000017500000000010315232414252021106 v?cGHEAD17PO)T /a HTTP/1.1 :? n:  :? n:  .E\llibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d501.bin0000664000175000017500000000004215232414252021100 b910302G=T / HTTP/1.1 ^u^de^0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d498.bin0000664000175000017500000000004215232414252021117 +Upg GET /Y HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d404.bin0000664000175000017500000000001615232414252021103 #GET: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d168.bin0000664000175000017500000000014215232414252021112 namePOST /a HTTP/1.1 Host: x Content-Type: Transfer-Encoding: chunked c Cont flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d817.bin0000664000175000017500000000037615232414252021124 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="a/",h, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response="012346789abcdef0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d113.bin0000664000175000017500000000000515232414252020216 %cAlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d312.bin0000664000175000017500000000010615232414252021101 t: x GET / HTTP/1.1 Host: x Authorization: Digest use0" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d718.bin0000664000175000017500000000017215232414252021116 a HPT/P1. 1XqJ: y&c%20 HTTP/1.2 Host: xa HPT0" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d261.bin0000664000175000017500000000002015232414252021077 <%%NO libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d122.bin0000664000175000017500000000000515232414252020216 Y%b1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d208.bin0000664000175000017500000000005015232434352021431 7A92a4aQ E%Q3Gt HTTP/1.1 Ce0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d476.bin0000664000175000017500000000004015232414252021111 ET / HTTP/TTP Host libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d085.bin0000664000175000017500000000004615232434352020230 GET / HTTP/1.1 Hnsy: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d498.bin0000664000175000017500000000010515232414252021122 Q gGET /a HTTP/1.1 Cookie: a=b GGG&&&Q&&\ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d227.bin0000664000175000017500000000015415232414252021111 XPOST /a HT'TP/T /a HTTP/1.1 Host: x Transfer-Encoding: chunked 0;ePOSTx1.1 Host:0b7 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d187.bin0000664000175000017500000000001715232414252021114 GET 512P libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d080.bin0000664000175000017500000000010415232414252021104 W0 Qon:.libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d206.bin0000664000175000017500000000005015232434352021427 7A924` E%Q6Gt: HTTP/1.1 Ce0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d041.bin0000664000175000017500000000010015232414252021072 ET / HTTP/1.1 Host: Authorization: Basic dXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d315.bin0000664000175000017500000000010715232414252021105 ?G HTTP/1.1 Host: x Authorization: Basic dXuserhash=z libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d028.bin0000664000175000017500000000003115232434352020217 OPTIONS rea- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d847.bin0000664000175000017500000000052115232414252021117 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest c=00000000, username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000000, cnonce="deadbeef", algorihtm=SHA-256, response="0123$56789abcdef0123452789D456789abcdef01234560123456790abcdef0123456789abcdef0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d309.bin0000664000175000017500000000003115232414252021107 GPS T / libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d524.bin0000664000175000017500000000004515232414252021110 .#GET /a HTTP/1.1 X: y libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d510.bin0000664000175000017500000000004315232414252021101 GET / HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d367.bin0000664000175000017500000000004715232414252021122 *GET /a HTTP/1.1 H7776libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d058.bin0000664000175000017500000000003015232414252021107 0G<"T /HEAD libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d758.bin0000664000175000017500000000025015232414252021117 ԾPOST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Contentohuntnke d -- 0 .libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d596.bin0000664000175000017500000000002515232414252021122 ???GETG0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d141.bin0000664000175000017500000000012415232414252021104 Hosa= a=1&b=2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d210.bin0000664000175000017500000000000415232414252020213 %MDlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d052.bin0000664000175000017500000000001015232414252021606 &`libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d218.bin0000664000175000017500000000000515232414252020224 %41,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d076.bin0000664000175000017500000000004215232434352020224 GE / HTTP/1.1 Hed9bo libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d231.bin0000664000175000017500000000010215232434352021423 7Aa595aCOENNCTQ ET%Q7Aa595aCOF5Gt: HTTP/1.1 Coe0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d415.bin0000664000175000017500000000005315232414252021111 v0GET'T %1a?+4=&%43 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d044.bin0000664000175000017500000000000515232414252020221 Y%3libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d043.bin0000664000175000017500000000005015232414252021103 GE'GET 5?a:&%43 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d629.bin0000664000175000017500000000011215232414252021111 @>GET / HTTP/1.1 Host: x Authorization: Basic dXNljcXYpw== libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d645.bin0000664000175000017500000000011615232414252021113 d HPTP/1.1 X: y %69 HTTP/1.1 Host: xa HPTP/0.1 X libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d003.bin0000664000175000017500000000001015232434352021416 :?22libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d087.bin0000664000175000017500000000010615232434352021440 7a59275a4aQ ETQ"0Gt: HTTP/1.1 H: x Cookie:e=o"stest: 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d480.bin0000664000175000017500000000010015232414252021104  YGET /a HTTP/1.1 Cookie: a=" HCnnectAon: k libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d641.bin0000664000175000017500000000011515232414252021106 @ABCDEFHPOST /a HTTP/1.1 Host: x Transfer-Encoding: tchu libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d268.bin0000664000175000017500000000000515232414252020231 ajJ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d058.bin0000664000175000017500000000013415232414252021111 dGET / HTTP/1.1 Host: x Authorization: Digest userhash=true, username="alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d024.bin0000664000175000017500000000001215232434352021423 ف=3!libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d178.bin0000664000175000017500000000027515232414252021122 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Content Content-Transfer-Encoding: identity - 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d048.bin0000664000175000017500000000000515232414252021617 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d134.bin0000664000175000017500000000013315232434352020220 AiGET /aaaaaaaaaaaaaaaaaaa/a?ba HTTP/1.1 Hkqt: x X-Long:aaaa/1.5 aaaaaaaaaaa libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d831.bin0000664000175000017500000000042015232414252021106 GET / HTTP/1.1 Hv4GET /a HTTP/1.1 Host: x XGET /nonce="a HTTP/1.0 Host: x Authorization: Digest username=91upgrade0491af9528c8a8e9d553c070bf28e4f8b00fcCE%%", uri="/a", qop=au$th, nc=,00000,0cno= 0nce="deadbf", algoHA-4 56, reelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d766.bin0000664000175000017500000000026215232414252021121 upgradee=bbbbbbbbbbbbbbbbbbbbbbbbbbbbT / HTTP/1.1 Host: alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d347.bin0000664000175000017500000000020215232414252021106  @a=1=%41&nameOST /+a HTTP/1.1 Host: x Content-Type: application/x-www-form-urlencoded Content-Length: 11 a=1d Contclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d425.bin0000664000175000017500000000002515232414252021106 enngth: nlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d210.bin0000664000175000017500000000006315232414252021103  @ ]GET /a HTTP/1.1 Cookie: ;=b:T libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d003.bin0000664000175000017500000000003415232414252021076 @2+T @%a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d060.bin0000664000175000017500000000041615232414252022342 ContCont name P Q name P Qnt-Type: text/plain &&&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d102.bin0000664000175000017500000000001015232414252022325 %77&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d306.bin0000664000175000017500000000003015232414252021103 GET s libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d447.bin0000664000175000017500000000006215232414252021116 iP'GET /%8+2?a=%|+43 HTTP/1.0 Hlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d815.bin0000664000175000017500000000037515232414252021121 GET /a HTTP/1.1 Host: x GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="000000000000000000000000000000000up00000000000", uri="/a", response="e" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d017.bin0000664000175000017500000000032315232414252021104 PpFGET /a HTTP/1.1 Host: x =GET /a?b%c/a HTTP/1.1 = Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", nce="deef", algorithm=SHA-256, response=ef" 2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d423.bin0000664000175000017500000000002415232414252021103 sc R)/a Olibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d199.bin0000664000175000017500000000004415232434352021445 7c59275a4aQ $t HTTP/!.1 HoClibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d836.bin0000664000175000017500000000043015232414252021114 PpFGET /a HTTP/1.1 Host: x =GET ?a=0 @ T /a HTTP/1 HTTP/1.1 = Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="?a", 0000001, cnonce="deef", algorithm=SHA-256, response="012345\6789a\decdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d316.bin0000664000175000017500000000010715232414252021106 ?GET /a HTTP/1.1 Host: x Authorization: Basic XNlcpNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d013.bin0000664000175000017500000000004015232414252021077 ,P SHT / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d537.bin0000664000175000017500000000004515232414252021114 XGET /a %4En%4e HTTP/1.1 HoRqlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d097.bin0000664000175000017500000000013615232414252021116 GET /a HTTP/1.1 Host: x Authorization: Digest "Tetm", username*=UTF-6''anse=" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d131.bin0000664000175000017500000000001215232434352021422 $$F=Flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d657.bin0000664000175000017500000000012215232414252021113 UGET / HTTP/1.1 Host: x Authorization: Digest username="use""alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d101.bin0000664000175000017500000000006315232434352021425 7a5TRACE4aQ ETQ%1At: HTTP/1.1 Cookiecnb libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d149.bin0000664000175000017500000000001615232414252021111 2?1 qlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d350.bin0000664000175000017500000000004515232414252021110 v?aE! -34ST >+ HTTP/1.1 oFFlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d112.bin0000664000175000017500000000002015232414252021075  Bonlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d113.bin0000664000175000017500000000007215232434352020217 UGET HTTP/1.1 HOst: x Authorization: Dige libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d076.bin0000664000175000017500000000004115232414252021106 T 1?%/A&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d336.bin0000664000175000017500000000004415232414252021113 & GT /a%b HTTP/1.1 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d206.bin0000664000175000017500000000004715232414252021107 (GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d333.bin0000664000175000017500000000012415232414252021104 BCDEFHPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked ABCDEFuserhlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d058.bin0000664000175000017500000000000315232414252020224 ::libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d099.bin0000664000175000017500000000017515232414252021123 GET /a HTTP/1.1 Host: x Authorization: Digest usearmne"=user", realm="TetRealm", username*=UTF-8''anse="00" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d040.bin0000664000175000017500000000000515232414252020215 X%%6dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d039.bin0000664000175000017500000000000515232414252020225 %13libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d180.bin0000664000175000017500000000000115232414252021076 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d016.bin0000664000175000017500000000000515232414252022335 ;&=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d130.bin0000664000175000017500000000000515232414252020215 @%%6libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d069.bin0000664000175000017500000000000615232414252020231 %C7556libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d280.bin0000664000175000017500000000004015232414252021102 TE: Ga HTTP/1.1 Holibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d134.bin0000664000175000017500000000001215232434352021425 2423ablibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d323.bin0000664000175000017500000000011315232414252021101  /h?a=1Gt: HTTP/1.1 Host: x Cookie: cnonce="%%ET /a HTTx 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d001.bin0000664000175000017500000000003215232414252021072 %%NONCE%%T HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d196.bin0000664000175000017500000000003715232414252021116 GEa/ HTTP/1.1 GGGupglibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d399.bin0000664000175000017500000000001515232414252021117 fz= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d503.bin0000664000175000017500000000004215232414252021102 --b--) +'GEt %fi HTTP/1.1 # libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d032.bin0000664000175000017500000000011215232414252022332 -abc ----abc Content-Disposition: f2ok"; filename="f" t/plain v]libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d408.bin0000664000175000017500000000002015232414252021102 $e= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d117.bin0000664000175000017500000000003715232414252022344 --abc ----abc Contenta=i libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d666.bin0000664000175000017500000000012515232414252021116 Host: x XGE+ /a HTTP/1.0 Host: xAu Connection: keep-alive, ade nonce="dea libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d177.bin0000664000175000017500000000000315232414252020226 18libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d113.bin0000664000175000017500000000011115232414252021074 @>GET / HTTP/1.1 Host: x Authorization: Basic dXNlcjpwYXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d006.bin0000664000175000017500000000051615232434352020223 uiGET]*’ HTTP/4.1 /aaaa libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d020.bin0000664000175000017500000000001215232414252021652 Digest ,,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d828.bin0000664000175000017500000000040515232414252021117 W(GET / HTTP/1.1 Ho.t: GET/a HTTP/1.1 Host HTTP/1.GET /a HTTP/1.0 Host: x Authorization: Digest username="BBBBBBBB,BBBBBBBilenameaaaa", userhash=true, rea, n once="%%NONCE%%",ansfer-Encoding: chunked 52 ----abc Conten%%N 89abcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d834.bin0000664000175000017500000000042515232414252021116 uugbcdef" HEAD GET / HTTP/1.1 H @a=1&(=%TP/1.1 41&cmPOST /a HTzTPOST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Contg: chunked, ch0.1 Huqqalibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d524.bin0000664000175000017500000000012315232414252021110 FPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 6 abc 0 :libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d221.bin0000664000175000017500000000000515232414252020216 Y%08libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d003.bin0000664000175000017500000000001015232414252021602 !libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d069.bin0000664000175000017500000000012115232414252021107 GET /a HTTP/1.1 Hos Authorization: Digest uSername=r", r libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d005.bin0000664000175000017500000000001415232414252021657 Digest qop=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d151.bin0000664000175000017500000000000515232414252020220 )%1Flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d445.bin0000664000175000017500000000003515232414252021111  GT / HTTP/0.1 6 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d722.bin0000664000175000017500000000017415232414252021113 PpAFGEP /a HTTP/1.1 Host: EADHx X Authorization: Host: xHE Authorization: Digest us0, algorithm="\SHA-256-" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d067.bin0000664000175000017500000000002015232414252021106 rF/a0=2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d157.bin0000664000175000017500000000000615232414252020227 A4A8Alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d039.bin0000664000175000017500000000001715232414252021671 Digest nc="\f"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d094.bin0000664000175000017500000000000415232414252020225 a%%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d271.bin0000664000175000017500000000002015232414252021103 XNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d029.bin0000664000175000017500000000005515232414252022346 --abc\" ----abc Content-Type: texv lai libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d479.bin0000664000175000017500000000004015232414252021114 %%NONCE%%T /%aF0&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d041.bin0000664000175000017500000000000515232414252020216 P" "libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d364.bin0000664000175000017500000000030715232414252021113 PpAFGEP /a HTTP/1.1 Host: xHEAD X Authorization: Digest us00, algorithm="\sd9O9a" 1.1 / HTTP /a HTTP/1.1 Host: xHEAD X Authorization: Digest us00, algorithm="\SHA-256" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d209.bin0000664000175000017500000000000415232414252020223 588libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d148.bin0000664000175000017500000000001315232434352021433 p6 p libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d082.bin0000664000175000017500000000004515232434352020224 Host: x /GET /b HTTP/1.1 Docc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d137.bin0000664000175000017500000000000515232414252020224 0%39libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d813.bin0000664000175000017500000000037215232414252021114 PpFGET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 = Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", 0000001, cnonce="deef", algorithm=SHA-256, response="676357\6789a\cd89abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d039.bin0000664000175000017500000000001315232434352021432 &&u222libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d240.bin0000664000175000017500000000014015232434352021425 @P$H DEAgb HTTP!P$H DEAgb HTTP !44libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d230.bin0000664000175000017500000000012715232414252021106 FPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 3 acb a HT libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d073.bin0000664000175000017500000000002015232414252021661 digest qop=AUtHlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d277.bin0000664000175000017500000000003715232414252021116 PTR#u.1~ %99 HTTP/1.1 Holibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d328.bin0000664000175000017500000000004215232414252021112  GET /a H,TP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d493.bin0000664000175000017500000000010415232414252021114 GET /a HTTP/1.1 Cookie:= bTRACE,|| libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d238.bin0000664000175000017500000000013315232434352021436 7a592754aQ ETQ0Gt: HTTP/1.1 okie:;cnonP0.1 Cookie:;cnon,eA4o@snx! t:pa=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d583.bin0000664000175000017500000000054515232414252021125 $3(SOT y34=(POGET'GET /%/%24zT /%45FF%FFF HTT59?`/%49%59?`a=43/1.145T /%45%FF HTTP/1.1 45T /%45 /1.14/1.0 45T /%45ST /a HTTP/1.1 Host; x *@T 11'+R HTTP/2.1 1.1 Host8a HTT< st: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d174.bin0000664000175000017500000000000315232414252020223 7libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d083.bin0000664000175000017500000000021515232414252021107 close |GET / HTT24ab170b5b97e454f1P/1closeosContent-LTTP/SHA-256-sessx d libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d035.bin0000664000175000017500000000001315232414252021612 %P libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d449.bin0000664000175000017500000000003515232414252021115  % / HTTP/1.9 ** libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d037.bin0000664000175000017500000000001715232414252021667 Basic dXNcjNzlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d043.bin0000664000175000017500000000002015232434352021423 22_@H @@2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d879.bin0000664000175000017500000000643515232414252021136 POWET /a HTTP/1&1 Host XGET /a HTTP/1.1 H X(G0T /a HTTP/1.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Dige X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G2T /abcPATCH c=nnection: u HTTP/1.1 Host;a=1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 HDiges 3256787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H]]]]]]]]]]]]]]]]]]]]]]]]]= X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRopaque=" X(G1T /a HTTP$1.2WET /a HTTP/1.1 Host  X(G1T -aG[ET$@a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRACE X(G1T /a HTTP$1.2WET /a HTTP/1.1 Host]&t %a %aTRA;E aaaaaaP/1.%7/ HTTP/1nc=00000001QTTTt %aaaaaaaaaaaaaPt %anc%NO%CauE%%ET /a HTTP/1.1 Htsotcnonce="c6ff43b1b4f430d54f65083251884bda000000028ee3ent-Type: multipart/form-data; boundasy=--abc Transfer-Encodza/a?b&ction:aaonce="horizatiboundary=t ername="aa%%1 x3encTRAEC aa/1.%7/ HTTP/t %aaa%u%%NO.1 Hostcnonce="horization: Digest ername="aaa=1&(=%41&cmdary=t ername="aa%%1 x3encTRAPATCH CE aaaaaaP/1.%$7/ HTTP/1.1 aaaaaaP/1.%TP/1.1 t aa%aaaaaaHostx* x Content-Type: application/x-www-form-urlenCoded Content-Length: 451 Cur)="t %aaaaaaaaaaaaa/1upgradeTTP/t %aaa%%000001, c%7/. H b %NONCE00600000"T /a H /a HTTP/1.1 HvvvvTRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host;a=1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787bcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T$/aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H]]]]]]]]]]]]]]]]]]]]]]]]]WET /a HTTP/1&1 Host XGET /a HTTP/1.1 H X(G0T /a HTTP/1.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H1;b=2;c X(G2T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H=  Pst OSClibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d055.bin0000664000175000017500000000001215232434352021427 ?Alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d022.bin0000664000175000017500000000001315232414252021606 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d135.bin0000664000175000017500000000024515232414252022345 --abcCixe@ultipa----abc e Content-Type: multipart/mixed;boundary=Q@- Content-Disposition: attachment; filename="--f" bc=c -- ef"--  oundary= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d068.bin0000664000175000017500000000000515232414252020227 0%56libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d016.bin0000664000175000017500000000002015232414252021100 rAu1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d223.bin0000664000175000017500000000000515232414252020220 3%Flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d072.bin0000664000175000017500000000003615232434352020223 EGET /a HTTP/1.x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d027.bin0000664000175000017500000000000515232414252021614 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d694.bin0000664000175000017500000000014715232414252021123 GET /a HTTP/1.1 Host: x J XGET /a HTTP/1.1 Host: x Authorization: Digest usernam,= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d114.bin0000664000175000017500000000020615232414252021102 GET /a BTTP/1.1 Host: x XG /a HTTP/1.1 Host:x Authorization: Digest username="aaaaaaaa\\L\\\\\\\\+\89abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d889.bin0000664000175000017500000000153115232414252021127  (GET /a HTTP/1.1 Host XGET /a HTTP/1.1 Host: x Authorizatio1 Host: x Authorization: Dige{t usopaque="erst x7d2aaa64837306ost: y =G;T /a HTTP/1.1 Host: xDiname=: y =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="4a", qop=auth, nc=00000001, cnonce="deadbeef", algoritm=hSHA-9dd4486210af algorithm=SHA-256, response="0123<56789abcdef" alm" response 23456788ab="00" @ cd Uf" /aHGET /a HTTP/1.1 Host XGET /a HTTP/1.1 Host: x Authorizatio1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/c", qop=auth, nc=00000001, cnonce="deadbeef", algoritm=hSHA-9dd4486210af# algorithm=SHA-256, response="0123<56789abcdef" alm" response 23456788ary=--abc Transfer-TRACEing: chunked 95 ------abc1Q%Ulibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d138.bin0000664000175000017500000000000515232414252020225 a%41libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d077.bin0000664000175000017500000000002215232434352021434 236; Plibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d489.bin0000664000175000017500000000010315232414252021120 v?cE! -3POST /a HTTP/1.1 Host:x Content7Length: 4 abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d044.bin0000664000175000017500000000001015232414252022332 0%40 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d073.bin0000664000175000017500000000031615232414252021110 GET /a HTTP/0.1 Host: x GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="00000000000000000000000000000000000000000000", uri="/a", response="e" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d293.bin0000664000175000017500000000004315232414252021111 GET /a HTTP/1.1 Ho789"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d478.bin0000664000175000017500000000007715232414252021130 $ET0 /%43-%41%fddddddddddddd= HTTP/1.1 alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d123.bin0000664000175000017500000000007215232414252022340 -abc ----abc Content-Disposition: fta; 0name="name= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d333.bin0000664000175000017500000000004315232414252021107 ET / HTTP2: H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d553.bin0000664000175000017500000000014515232414252021116 04POST /a HTTP/1.1 Hos%:2.1 Host: Content-Length: 3 x Content-Length:`2 abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d225.bin0000664000175000017500000000015215232414252021105 GET /a HTTP/1.1 Host: xs+: x Authorization: Digest user="%%NNC%%E", uri=, qop=auth, n libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d041.bin0000664000175000017500000000001615232434352021426 %2222libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d491.bin0000664000175000017500000000004115232414252021107 ConnectGE / HTTP/1.1 HjjjHElibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d455.bin0000664000175000017500000000006415232414252021117 B'GET / HTTP/1.1 GET /%dddH HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d682.bin0000664000175000017500000000014215232414252021113 GET /a HTTP/1.1 Host: x Authorization: Digest use"usr", realm="Te1615", uri lg libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d095.bin0000664000175000017500000000005215232414252021114 @E(GET /q HTTP/1.1 Hosl: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d005.bin0000664000175000017500000000000515232414252021610 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d157.bin0000664000175000017500000000002015232414252021106 C-Śkoo=alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d221.bin0000664000175000017500000000011215232414252021100 (ST34( /a HTTP/1.1 Host: x GET / HTTP/1.0 a0bcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d088.bin0000664000175000017500000000001215232434352021435  s22libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d056.bin0000664000175000017500000000027615232414252021116 Upgrade: GET /a HTTP/1.1 Host: x XET /a HTTP/1.1 Host: x Authorization: Digest username="01DDDD3abec1229876c4a85ec7aaaAaaaAaaaaTRACa", userhash=true, realm=uu"0123456789abclef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d014.bin0000664000175000017500000000001015232414252021653 Basic libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d052.bin0000664000175000017500000000005215232414252021105 ET /aHEAD / HTTP/1.1 : !x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d443.bin0000664000175000017500000000006115232414252021111 r.1 ?GHEAD / HTTP/1.1 d on:o:ste libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d446.bin0000664000175000017500000000003515232414252021112 2 @>G %E/T HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d038.bin0000664000175000017500000000000515232414252020224 %eElibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d184.bin0000664000175000017500000000004515232414252021115  /GET /a HTTP/1.1 Honelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d129.bin0000664000175000017500000000000515232414252020225 C%A4libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d188.bin0000664000175000017500000000000315232414252020230 6libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d277.bin0000664000175000017500000000002015232414252021111 G.ETlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d233.bin0000664000175000017500000000021015232414252021077 U  X a HTTP/1.5 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d070.bin0000664000175000017500000000004315232414252021105 (GET % HTTP/1.1 tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d272.bin0000664000175000017500000000002015232414252021104 POSs T libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d210.bin0000664000175000017500000000007315232414252021101  |G / HTTP/1.1 Host: x Connection: Hx& libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d109.bin0000664000175000017500000000002215232414252021105 +/+E libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d215.bin0000664000175000017500000000010415232414252021104 a=1OST /a HTTP/1.2 Host: x Content-Length:3 4 abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d456.bin0000664000175000017500000000006515232414252021121 90 b'GET /?%995'+a=&%43 HTTP/1.1 HE: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d279.bin0000664000175000017500000000000615232414252020234 UJA==libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d776.bin0000664000175000017500000000030115232414252021114 8GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaBBBBBBaaaaaaaaaaaaaa", userhash=true, realm="TestReam", nonce="%%NONCE%%", uri="/a", libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d576.bin0000664000175000017500000000006115232414252021115 Q /path?a=ength+1&tq : HTTP/1.1 s:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d615.bin0000664000175000017500000000011115232414252021103 @>GET / HTTP/1.1 Host: x Authorization: Basic dXclosewYXN{ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d152.bin0000664000175000017500000000003615232414252021105 ߂ GET / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d059.bin0000664000175000017500000000001315232414252021667 Basic QQ==libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d871.bin0000664000175000017500000000114715232414252021121 WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /a HT[P/1.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H nonce=" (1XG T/a HTTP/1.1ONCE%%", uri="/a", qop=auth, nc=00000st: yx =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="\TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response=/1.1 HTRA/1.1upgrad HTTP/1.e / JQo1OST / .1 Hgggggggggggggggggggggggggggggggggggggggggggt XggggYggggggYlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d017.bin0000664000175000017500000000000515232414252022336 /libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d311.bin0000664000175000017500000000003215232414252021101 , GET /a DELETE /libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d802.bin0000664000175000017500000000036015232414252021107 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000002, cnonce="deadbeef", algorithm=SHA-256, response="089abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d127.bin0000664000175000017500000000004615232414252021113 r?9 &/GET /a HTTP/1.1 IONlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d168.bin0000664000175000017500000000000315232414252020226 z45libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d490.bin0000664000175000017500000000004115232414252021106 GEt %6/ HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d738.bin0000664000175000017500000000021615232414252021117 close |GDELETE TTT / HT!T916afea4ba3e74361696b95702" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d251.bin0000664000175000017500000000000515232414252020221 2%bclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d032.bin0000664000175000017500000000001415232434352021424 7;libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d078.bin0000664000175000017500000000001615232414252021624 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d087.bin0000664000175000017500000000001015232414252022341 wD%E libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d204.bin0000664000175000017500000000005215232414252021104 B'r0'GET /%5 HTTP/1.1 Hh libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d005.bin0000664000175000017500000000000315232414252020214 @2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d050.bin0000664000175000017500000000001415232434352021424 13 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d081.bin0000664000175000017500000000001015232414252022333 =%06&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d202.bin0000664000175000017500000000004615232434352021430 ?????$libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d235.bin0000664000175000017500000000011315232434352021431 7a59#275a4~Q TGt: HTTP/1.1 Host: x Cookie:e="ost:5xnpa=b 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d109.bin0000664000175000017500000000011515232434352021433 7a59275a4aQ $TGt: HTTP/1.1 Host:!x# Cookie: cn=!/12o a=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d025.bin0000664000175000017500000000002015232414252021100  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d124.bin0000664000175000017500000000003515232414252021103 %3/ HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d004.bin0000664000175000017500000000000715232414252021660 Digestlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d009.bin0000664000175000017500000000000515232414252021614 *libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d117.bin0000664000175000017500000000057715232414252021701 fBsu[r3TesyǂǂBasic QQ==QQ=UUUUUUUUUUUEUBearer UU삂ȂBasic QQ=UUUUUBasic QQ==QQ=UUUUUUUUUUEUBearer UUUUUrealm="TestRealm"UUlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d188.bin0000664000175000017500000000002015232414252021107 chunked/G libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d070.bin0000664000175000017500000000013115232414252021100 PpFGET /a HTTP/1.1 Ho (  Authorization: Digest username*="us\r", l libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d072.bin0000664000175000017500000000004515232414252021111 /lE/GT "q%4! HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d313.bin0000664000175000017500000000003315232414252021104 +TP/0.1 Hot: x T libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d459.bin0000664000175000017500000000006715232414252021126 B'r0 /%+20T /%+f0%42?a&&&&ET / HTTP/1.0 h libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d111.bin0000664000175000017500000000002015232414252021074 1 Ho libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d158.bin0000664000175000017500000000002015232414252021107 ?F libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d242.bin0000664000175000017500000000021415232414252021106 E/a)Zr GET /a%06b HTTP/1.1 KKKKKKKKKKKKKKKKKKKKKKKKKKKKzzzzzzzzzzzzzzzz Transfer-Encoding: chunked 0 KKKKKB libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d228.bin0000664000175000017500000000012415232414252021112 r?F9JL /GET /a HTTP/1.1 G Transfer-Encoding: chunked 9 ;abc 0x) libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d542.bin0000664000175000017500000000004615232414252021111 H%4T (/e HTTP/1.1 &&P####libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d417.bin0000664000175000017500000000002215232414252021104 GEk 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d222.bin0000664000175000017500000000005615232434352021433 7a59275a4aQ ETQG"0 HTTP/1.7 H: 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d076.bin0000664000175000017500000000000315232414252020224 Y%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d504.bin0000664000175000017500000000004215232414252021103 t %7/ HTTP/1.1  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d151.bin0000664000175000017500000000021615232414252021107 E/a)Zr GET /a%06b HTTP/1.1 KKKKKKKKKKKKKKK KKKKKKKKKKKKKKzzzzzzzTzz~zzz Transfer-Encoding: chunked 0 KKKKKBx libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d376.bin0000664000175000017500000000005015232414252021114 a=1&b=2E/aGT "?q=%5! HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d018.bin0000664000175000017500000000002715232414252021111 %4a=%iT/4 a libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d122.bin0000664000175000017500000000001215232434352021422 ,@j.=d~libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d499.bin0000664000175000017500000000010615232414252021124 @osa= GET / HTTP/1.0 iolibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d327.bin0000664000175000017500000000004115232414252021110 "@GM! H PaTT/.11 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d034.bin0000664000175000017500000000001615232414252021663 Digest nc=f libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d555.bin0000664000175000017500000000014715232414252021122 BET /a HTTP/1.1 Expect: 1ntinue :: x Transfer-Encoding: chunked libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d675.bin0000664000175000017500000000013515232414252021117 GET /a HTTP/1.1 Host: x Authorization: Digest useae"=user", username*=="00 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d209.bin0000664000175000017500000000006715232414252021114 0GET /pat HTTP/1.1 Host: x Cookie: ab= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d197.bin0000664000175000017500000000000315232414252020230 ,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d421.bin0000664000175000017500000000002415232414252021101 GETPAT /libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d122.bin0000664000175000017500000000105315232414252021102  GET /a HTTP/1.1 Host XGET /a HTTP/1.1 Host: x AuthorizatiR : x Authorization: Dige{t usopaque="erst x3d2aaa32418653ost: y ='G;T /a HTTP/1.1 Host: xDiname=: y =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algoritm=hSHA-9dd486210af algorithM=SHA-25=SHA-256, response="0123<56789abcdeef", algoritm=hSHA-9dd684 st: x Authorizatio1 Host: x Aut2aaa32418653ost: y =Authorization: Digest "/a", algoritgtlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d020.bin0000664000175000017500000000000315232414252020211 olibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d124.bin0000664000175000017500000000000515232414252020220 /=%84libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d088.bin0000664000175000017500000000002615232414252021675 Digest algOrithm="\s"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d061.bin0000664000175000017500000000001315232414252021660 Basic dXN{libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d365.bin0000664000175000017500000000031615232414252021114 &x =GET a HTTP/1.1 Host: x Authorization: Digest ame-"user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8''0!%adXNlcjpwusername*=UTF-8''0!%adXNlcjpwYXUTF-8''0!%adXNlNzdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d182.bin0000664000175000017500000000000315232414252020222 dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d208.bin0000664000175000017500000000006415232414252021110 /1.0v x a HTTP/1.1 :>&jQ Cookie: b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d066.bin0000664000175000017500000000027015232414252021114  OEGT ;a HTT Ha HTTP/1.1 $H ;e_o OST / HTTP/1.1 T /a HTTP/1.1 H T /aT /a HTTP/1.1 Hos t߇ H T /a HTTP/1oHEA.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d557.bin0000664000175000017500000000005015232414252021112 .1 Hlxt:x X /a HTTP/1.5 Host:m libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d023.bin0000664000175000017500000000000515232414252020216 %%delibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d543.bin0000664000175000017500000000004615232414252021112 GETa HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d171.bin0000664000175000017500000000001515232434352021431 +$1:?? ???libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d284.bin0000664000175000017500000000002315232414252021112 @f##### libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d124.bin0000664000175000017500000000004315232414252021105 v?!cE -? / HTTP/1.1 ECTlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d068.bin0000664000175000017500000000010515232414252021110 ?GET HTTP/1.1 Host: x Authorization: Basic dXNlfXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d334.bin0000664000175000017500000000004415232414252021111 ConteGE oa HTTP/1.1 &&olibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d034.bin0000664000175000017500000000017715232434352020227 aaaaa{AGET /a HTTP/1.1 Host: x /GET /b HTTP/1.1 /GET /b HTTP/1.1 Ho@yyyyyyyyy$e POST e % libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d289.bin0000664000175000017500000000004215232414252021115 ET %AC HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d080.bin0000664000175000017500000000007615232414252021111  GET /a HTTP/1.1 Host XGET /a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d021.bin0000664000175000017500000000005515232414252021101 GETQ me?: HTTP/1.1 Cookie: a=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d236.bin0000664000175000017500000000014115232414252021110 a=1&b=2ST34( /a HTTP/1.1 Host: x GET / HTTP/1.0 a0bcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d596.bin0000664000175000017500000000010015232414252021111 ; ex = val GET / HTTP/1.1 Host: x val T / HTTP/1.1 Ho",libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d085.bin0000664000175000017500000000011515232414252021622 1555z0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d144.bin0000664000175000017500000000032415232414252021106 GET /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest useUpgrade: rname-"user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8''a%001%!756, response="01ef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d602.bin0000664000175000017500000000010115232414252021076  GET /a HTTP/1.1 Host: x 0T /a HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d644.bin0000664000175000017500000000011615232414252021112 |GET / HTTP/1.0 HCo.nection: close Transfer-Encoding: chpnke 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d083.bin0000664000175000017500000000004515232434352020225  !AGET / HTTP/1.1 Hvst2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d250.bin0000664000175000017500000000060415232414252021110 . Pp~T 1/ Ta=1&b=2Expect: 100-continue ,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,/0. 1. Pp~T 2/ H.Ta=1&b=2,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,/1. 1. Pp,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1/. POST1. ,,,,E e#P/aeocti@ZEE libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d369.bin0000664000175000017500000000004715232414252021124 R EGET /a HTTP/1.1 Ho54libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d006.bin0000664000175000017500000000001015232414252021605 66libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d409.bin0000664000175000017500000000002015232414252021103 ET"/ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d251.bin0000664000175000017500000000042115232414252021103 WET /a HTTP/1.1 Host XGET /a HTTP/1.1 HtET /a HTTP/1.1 zationx Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri=/a?b, 000001, cnonce="deadbeef", algorithm=SHA-256, response=/1 TggggTTP/1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d745.bin0000664000175000017500000000023315232414252021114  GET /a HTTP/1.1 P/1.1 Hos t: x Authorization: Digest username=FFFFFFFF t: x 197abcdUf" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d095.bin0000664000175000017500000000007615232414252021117 GET /a HTTP/1.1 Authorization: Digest e="00" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d057.bin0000664000175000017500000000001215232414252021664 Digest "xlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d073.bin0000664000175000017500000000001315232434352021430 *23of<libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d093.bin0000664000175000017500000000004315232414252021107 T /?a&=0f HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d393.bin0000664000175000017500000000005115232414252021114  GET /a HTTP/1.1 N% libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d035.bin0000664000175000017500000000022215232434352020217  GET /44444444444444444444444444444444444444444444444444444444444444444444444444444444444%444444444444444444444444=#HTTP/044444 x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d031.bin0000664000175000017500000000000315232414252020213 [\libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d319.bin0000664000175000017500000000003715232414252021116 < T / HTTP?1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d174.bin0000664000175000017500000000001515232434352021434 :j3MB$ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d259.bin0000664000175000017500000000001615232414252021113 @~ x nlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d838.bin0000664000175000017500000000043415232414252021122 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="\estRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response="0123456789abcd0f0123456789abcdef01234567c89abdfe01def" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d778.bin0000664000175000017500000000031015232414252021116 (GET / HTTP/1.1 Ho.t: GET /a HTTP/0.1 Host: x XGEzT /a HTTP/1.0 Host: x Authorization: Digest username=filenameaaaa", userhash=true, rea:oef 56, respbcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d049.bin0000664000175000017500000000000715232414252021671 d008dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d024.bin0000664000175000017500000000042515232434352020222 A,GT /a HT/1.1 Host: x /GET /b HTTP/1.1 Host: x chunk: x /GET /b HTTP/1.1 Host: x Content-Length: 18446744073709551615 chunkost: x //GET /b HGET /b Glibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d019.bin0000664000175000017500000000000515232414252021615 @libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d566.bin0000664000175000017500000000021015232414252021113   <GET POSHEAD / HTTP/1.1 T: x onte/AE=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d271.bin0000664000175000017500000000003515232414252021106   / / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d039.bin0000664000175000017500000000011715232414252021114 FHEAD /a HTTP/1.1 Host: x Transfer-Encoding: chunked 1 alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d050.bin0000664000175000017500000000000515232414252021610 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d136.bin0000664000175000017500000000025615232414252022350 --abc ----abc Cforme="feTypeabc Content-Disposition: form-data; name="k"; filename ef" Content-Type: multipart/mixed;bomixed;bouboundary=namec -- ra xtey libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d533.bin0000664000175000017500000000012715232414252021114 FPOSP /a HTTP/1.1 Host: x Transfer-Encoding: chunked 3 abc 0  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d075.bin0000664000175000017500000000002015232414252021663 Digest qop="\D"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d014.bin0000664000175000017500000000002615232434352021427 !652libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d598.bin0000664000175000017500000000010015232414252021113 ie: a=b GET /t:path?a31 HTTP/1.1 Host: x Cookie: a==b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d387.bin0000664000175000017500000000250215232414252021117  GET /a HTTP/1.1 Host XGET /a HTTP/1.1 Host: =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000002, cnonce="deadbeef", algoritm=hSHA-9dd4486210af algorithm=SHA-256, response="0123<56789abcdef" alm" response 23456788ab="00" @ cd Uf" /aHTTP/1.1 ges/1.1 H ?GET /a HTTP/1.1 Host:uthoriza418653ost: y =G:T /a HTTP/1.1 Host: xDiname-: y =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algoritm=hSHA-9dd4486210af algorithm=SHA-256, response="0123<56789abcdef" alm" response 23456788ab="00" @ cd =G;T /a HTTP/1.1 Host: xDiname=: y =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algoritm=hSHA-9dd4486210af algorithm=SHA-256, response="0123<56789abcdef" alm* onse 23456788ab="00" @ cd Uf" /aHTTP/1.1 ge's/1.1 H GET /a HTTP/1.1 Host:1.1 Host: xDiname=: y =GET /a HT^P/1.1 Host: x Authorization: Digest username="user", realm="TestRlm", nauth="%%NONCE%%", uri="/a", qopnc=0000Len0", uri="/a", algoritgtlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d022.bin0000664000175000017500000000002015232414252021075 C nt-Lengt libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d519.bin0000664000175000017500000000012015232414252021111 R/GET /a HTTP/1.0 st: ~se x Connection: ookie:close libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d464.bin0000664000175000017500000000003715232414252021114 GET /a HTTP/1.1 HZlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d526.bin0000664000175000017500000000004515232414252021112 ' p=N%eba HTTP/1.1 H&A%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d077.bin0000664000175000017500000000001315232414252021620 (libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d121.bin0000664000175000017500000000003315232414252021101 r5͞:GET RACElibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d087.bin0000664000175000017500000000011715232414252021626 bbbbbbbbbalibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d092.bin0000664000175000017500000000004015232414252021103 fuzz-GETl?T/ 0%&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d192.bin0000664000175000017500000000003615232414252021111 a HPTP/1.1 X: yN%d0 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d145.bin0000664000175000017500000000000515232414252020223 [%50libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d237.bin0000664000175000017500000000000515232414252020225 %14libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d233.bin0000664000175000017500000000010315232434352021426 P2vvvS22 21222222 :2J222222222'1 45!11QS@ 222libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d823.bin0000664000175000017500000000040215232414252021107 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response=4def0ET123456789abcdfe0&df" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d019.bin0000664000175000017500000000000515232414252020223 @%78libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d496.bin0000664000175000017500000000010515232414252021120 r?F9 ont-tenTypePOS/a T HTTP/1.1 Host:a HTTPtlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d035.bin0000664000175000017500000000001615232414252021664 Digest uri= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d292.bin0000664000175000017500000000004315232414252021110 username="T / HTTP/1.1 POSC libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d026.bin0000664000175000017500000000001015232414252022332 n3%_A=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d126.bin0000664000175000017500000000011115232434352020215 0&G/Tr e`l%E?mm`?PO0 HTTP/1.1 Ha=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d081.bin0000664000175000017500000000002415232414252021664 @Digest qop="auth\"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d160.bin0000664000175000017500000000000615232414252020221 0123libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d025.bin0000664000175000017500000000001315232434352021425 p222libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d207.bin0000664000175000017500000000005015232434352021430 11_ 2222:222222&2202>>224GETa5_libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d028.bin0000664000175000017500000000022115232414252021103 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-databoundary=--abc Transfer-Encoding: chunked 52 ----abc value oa;libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d625.bin0000664000175000017500000000011215232414252021105 ET / HTTP/1.1 Host: x Authorization: Basic dX^lcj0wYXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d047.bin0000664000175000017500000000001115232434352021427 @ z2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d217.bin0000664000175000017500000000010515232414252021107 ~B'r &+++++++++ a? & +++++++++&b=2 HTTP/1.1 Hx & libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d198.bin0000664000175000017500000000004415232434352021444 !>bPhTE Hos:[Q ; @@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d030.bin0000664000175000017500000000000515232414252020214 e%5ulibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d023.bin0000664000175000017500000000011415232414252021102 FPOST /a HTTP/1.0 Host:x Transfer-Encoding: chunked 8 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d392.bin0000664000175000017500000000005115232414252021113 GET /a%07b HTTP/1.1 KKKKlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d157.bin0000664000175000017500000000033715232434352020233 AiGET /aaaaaaaaaaaaaaqaaaaaaaaaaaa?%35aaaa HTTP/1.1 HX-Lo;aaaaaaaaaaaa libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d126.bin0000664000175000017500000000004115232414252021102  HTTP/0.lo / HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d022.bin0000664000175000017500000000003415232434352021425 1f#w[@1 $@1 `libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d105.bin0000664000175000017500000000010015232434352021421  36&2;#R0@;#*R!26!@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d034.bin0000664000175000017500000000001515232414252021101 TTP/1.1. libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d546.bin0000664000175000017500000000013515232414252021117 ;q  FEPOST /a HTTP/1.1 H Transfer-Encoding: chunked 6;[ abc 5 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d011.bin0000664000175000017500000000000515232414252021605 ! libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d139.bin0000664000175000017500000000010615232414252021113 FPOST /a= HTTP/1.0 Host:d x Transfer-Encoding: bGab libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d529.bin0000664000175000017500000000004515232414252021115 ߷٫/1.1 X: e%b HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d360.bin0000664000175000017500000000027515232414252021113 8GET oa P/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaaaaaaaaaaaaboundary=aaaaaaaaaaaaaaaaaaaaaa", userhash=true,username*=UTFSHA56 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d366.bin0000664000175000017500000000004715232414252021121 p"GET /%eqx HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d621.bin0000664000175000017500000000011215232414252021101 PO HTTRP/1. /a HTTP/1.1 Host:st: x XGET /a HTTP/1.1 n libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d619.bin0000664000175000017500000000011115232414252021107 T /a HTTP/1.1 Host: x GET /a HTTP/1.1 Host: xCon libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d159.bin0000664000175000017500000000000615232414252020231 ;; ;libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d013.bin0000664000175000017500000000002215232414252021655 Digest algorithm=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d116.bin0000664000175000017500000000000515232414252020221 %%66libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d095.bin0000664000175000017500000000002315232434352021435 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d863.bin0000664000175000017500000000073615232414252021125 Upgrade: GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaa-----------------------------------------------------aaaaaaaaaaaa", username*=UTF-8''aut:%f3e6%f9e62TRACEe47baa%zzaaaacaaaaaaaaaa", u0 response="+0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d226.bin0000664000175000017500000000000515232414252020223 %d2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d413.bin0000664000175000017500000000002115232414252021077 G / libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d223.bin0000664000175000017500000000006015232434352021427 7a59275a4aQ TzQ0Gt: HTTP/11. H&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d590.bin0000664000175000017500000000007215232414252021113 &T /?++&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d127.bin0000664000175000017500000000011215232434352020217 A<POST ?a HTTP/1.1 Host: x Content-Length: 11 helflo worldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d200.bin0000664000175000017500000000005015232414252021076  G /%00b HTTP/1.1 os 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d288.bin0000664000175000017500000000001015232414252020227  c%C,@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d154.bin0000664000175000017500000000001315232434352021430 %,4llibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d250.bin0000664000175000017500000000000515232414252020220 ?%B?libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d117.bin0000664000175000017500000000001115232434352021425 !` 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d548.bin0000664000175000017500000000014015232414252021115 !rPOSTACE "2GET /atyyyyy HTTP/1.1 Host: / libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d214.bin0000664000175000017500000000010215232414252021101 &GE /a HTTP/1.1 Cookie: =+b ;NEx libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d295.bin0000664000175000017500000000002415232414252021115 r F9 " libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d161.bin0000664000175000017500000000001415232434352021427 dT$$$libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d020.bin0000664000175000017500000000001015232414252021601 E`libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d019.bin0000664000175000017500000000001015232414252022334 %4a libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d592.bin0000664000175000017500000000002015232414252021111 r 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d066.bin0000664000175000017500000000004115232434352021433 3 ] PUT ܈ O:::2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d042.bin0000664000175000017500000000010715232414252021102 %41;POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked dAlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d421.bin0000664000175000017500000000005415232414252021107 GET'GET /%28%2a+?=%23 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d542.bin0000664000175000017500000000013315232414252021111 Pp F POST DELETE/a HTTP/1.1 Host: s Transfer-Encoding: chunked 3 F1BFFFFlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d095.bin0000664000175000017500000000001015232414252022340 V%V%1F=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d049.bin0000664000175000017500000000011615232414252021111  x OET /a HTTP/1.1 Host: x Authorization: Digest response="e" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d283.bin0000664000175000017500000000002215232414252021110 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d580.bin0000664000175000017500000000045015232414252021115 15555=/GEGET / HTTP/1.1 1.1 x Conqqqqqqqqqq =OT SP/a HTTP/1.1 Host:d x Transfer-Encoding: chunked 0 T =/GEGET / HTTP/1.1 1.1 x Conqqqqqq5555=O)Tabc 0 0 Content-Type: applrm-urlencoded libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d026.bin0000664000175000017500000000006315232414252021105  |GET / HTTP/1.1 Ho Connection:!d 2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d144.bin0000664000175000017500000000001315232434352021427 #+3.libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d606.bin0000664000175000017500000000010415232414252021105 FET /?+++ +%+++++++++++++++++0=&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d132.bin0000664000175000017500000000006315232414252021106 tent-LeqContent-LeContent libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d361.bin0000664000175000017500000000004615232414252021113 , /GET / HTTP/1.1 :tsH Tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d569.bin0000664000175000017500000000021615232414252021124 /ST34(POST /a HTTP/1.0 Host:UUUUUUUUUUUUUUUJJJJJJJJJJJJJJJJJJJJJJJU x Content-Length: 5 Content-Length: 0 GET abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d704.bin0000664000175000017500000000015615232414252021113 J |GET / HTTP/1.1 Host: x Connon: GTUcol Content-Length: 0 Transfer-Encoding: chunked 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d263.bin0000664000175000017500000000000515232414252020224 Y%%Elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d135.bin0000664000175000017500000000000515232414252020222 Y%alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d121.bin0000664000175000017500000000143215232414252021102 upgrade2GET /a HTT]/1.1 Host: x GET /a HTTP/1.1 host: x Authoriza HTTP/1f4344f26c138f66201f"255aa cnonce="deadbeef", XGET /a HTTP/1.1 host: x Authorizatiation XGET /a HTTP/2f4344c263f18f66201f"f26c138f66201f"255af", XGET /a HTTP/1.1 host: x Authorizatiati1 XGET /a HTTP/1.1 Host2 x Gauth(T / HTTPA-25 AuthoriadbeePOST f4 algPOSThm=SHA-256, recpo XGET /a HTTP/1.1 host: x Authorizatiation XGET /a HTTP/1f4344c263f18f66201f"f26c138f66201f"255af", 5aa cnonce="deadbeef", XGET /a HTTP/1.1 host: x Authorizatiation XGET /a HTTP/1f4344c263f18f66201f"f26c138f66201f"255af", XGET /a HTTP/1.1 host: x Authorizatit x XGET /a HTTP/1.1 T /0 a HTTP/1.1 Host: x XGET /a HTTP/1.1th(T / HTTPA-256, recpolibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d091.bin0000664000175000017500000000004615232414252021113 rAutn: DuseET / HTTP/1.1 selibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d008.bin0000664000175000017500000000002015232414252021101 5$R0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d841.bin0000664000175000017500000000044215232414252021113 Upgrade: GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaa-------------------------------aaaaaaaaaaaa", username*=UTF-8''aut:%f4t:%f4e6t:%f4e6123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d536.bin0000664000175000017500000000013115232414252021112 YY FPOST .a HTTP/1.1 Host: x Transfer-Encoding: chunked 1 ab1cC libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d191.bin0000664000175000017500000000000315232414252020222 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d779.bin0000664000175000017500000000031515232414252021124 POST /a%%NONCE%% HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 437 ----abc g2: chunked Content-Type: multipart/mixed; boundary=b ---libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d128.bin0000664000175000017500000000015415232414252022346 --abc ----abc Content-Disposition: form-data; name="k"; l Content-Disposition: for na]]]]]"b v -libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d886.bin0000664000175000017500000000014215232414252021121  HPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 3 ABC 7;x="y"  OHglibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d059.bin0000664000175000017500000000021315232434352020225 AiGET ̞aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa HTTP/1.1 Hoqt: x X-Long:MD5-sessaaaaaaaaaaaaaaaaaa HTTP/1.1 Hoqt: x X-aaaaa libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d007.bin0000664000175000017500000000001015232434352021422 P(5libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d122.bin0000664000175000017500000000007215232414252022337 --abc ----abc Content-Disposition: forata; name="k libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d138.bin0000664000175000017500000000010415232414252021110 B'r0. 1Cokie:# a=b HTTP/1.1 Cookie: a=%5@ abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d556.bin0000664000175000017500000000015015232414252021115 =OT P/a HTTP/1.1 Host:d x Transfer-Encoding: chunked 00 ng: chunked 00 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d743.bin0000664000175000017500000000022515232414252021113 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary="us00000 Transfer-Encoding: chunked 52 ----abc spositio/1ta;libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d244.bin0000664000175000017500000000023215232414252021110 O1(1GE /a HTTP/1.1 /1. ch/g:nN1.1 /1.1 1. ch/nkd CONNECT * HTTP/1.1 xUUUUUng:onNS * HTTP/ ch-nked 8 Ko/anNS `Plibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d719.bin0000664000175000017500000000017215232414252021117 upgrade@ABCDE]POST /a HTTP/1.0 Host: x Transfer-Encoding: chunked 2;ext=val AB 3;a="b;c" CDE 5CDE]POSTTT libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d057.bin0000664000175000017500000000001015232414252021613 !libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d279.bin0000664000175000017500000000004015232414252021112 GET %09/a HTTP/1.1 tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d015.bin0000664000175000017500000000002015232434352020211 0612te3cde libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d158.bin0000664000175000017500000000000615232414252020230 %C756libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d401.bin0000664000175000017500000000005215232414252021103 GET'GET /%2BBHT HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d805.bin0000664000175000017500000000036215232414252021114 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadeef", algorithm=SHA-256, response="0123456789f" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d400.bin0000664000175000017500000000001515232414252021076 1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d009.bin0000664000175000017500000000003515232434352021433 X)XX ? 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d072.bin0000664000175000017500000000001715232414252021666 Basic =QQ==QQ=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d077.bin0000664000175000017500000000006615232414252021121  YGET /a HTTP/1.1 Cookie: a="Aon: k libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d188.bin0000664000175000017500000000004615232414252021122 GET /a%15b HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d163.bin0000664000175000017500000000001215232414252020221 QUJDRA==libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d643.bin0000664000175000017500000000011615232414252021111 0GET /patah?1= HTTP/1.1 upgradeHoit: x Cookie: a=t/form-data; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d887.bin0000664000175000017500000000044015232414252021123 LGET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 H'ooaaaaaaaaaaaaost: x XGET /a HTTP/1.9 Host: x Autheaaaaost: x XGET /a HTTP/1.2 HocoaaaaaaaaaaaaaosRe6t: x XGET /a HTTP/1.9 Host: x Auhritoon: Digest useaaaaost: xM XGET /a HTTP/1.2 Host:1b" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d023.bin0000664000175000017500000000001515232414252021660 Digest nc="libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d652.bin0000664000175000017500000000012015232414252021104 666666666666666666666666666666666]6666666666666G]T /?a0&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d469.bin0000664000175000017500000000007215232414252021123 P0`S'GET /%75.?a+GEa+GE HTTP/1.0 Y RT / libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d468.bin0000664000175000017500000000003715232414252021120 a=b GET %16 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d081.bin0000664000175000017500000000000415232414252020221 Bflibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d212.bin0000664000175000017500000000005315232434352021427 7a59275a4aQ $TGt:% HTTP/1.1 065libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d799.bin0000664000175000017500000000034415232414252021130 /a;ext=val1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm=CE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response="0123456789abcdcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d038.bin0000664000175000017500000000001715232414252021670 Basic QQas(c$Qlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d647.bin0000664000175000017500000000011715232414252021116 T;POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked dElibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d425.bin0000664000175000017500000000005615232414252021115 /BET /0=2q"%e HTTP/1.1 H!libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d119.bin0000664000175000017500000000010115232434352020216 0GET /path?a HTTP/1.1 H: x Cookie: a=,,********* libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d133.bin0000664000175000017500000000013115232434352020215 AGET /a HTTP/1.1 Host: x /GET /b HTTP/1.1 Host: x C!nnection: close libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d258.bin0000664000175000017500000000000515232414252020230 -%15libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d083.bin0000664000175000017500000000002015232414252021104 @]libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d071.bin0000664000175000017500000000001215232434352021425 bb25]libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d577.bin0000664000175000017500000000033115232414252021121 ! FAFHEAD HHHHHH/a HTTP/1.1 Host:YoGie: 1P/1.1 KKKKKKKKKKKKKHEADKKzzzzzzzzzzz Transfer-Encoding: chunked 0 KKR>st: ncCookie: a=Host: HHHHHnked 7 ab/?Colibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d297.bin0000664000175000017500000000004615232414252021120  3GE / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d093.bin0000664000175000017500000000005115232414252021111 POST / HTTP/1.1 s:ox libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d098.bin0000664000175000017500000000003515232414252021676 Digest algorithm=SHA-512-256libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d116.bin0000664000175000017500000000000715232434352021431 Fj1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d494.bin0000664000175000017500000000004215232414252021113  |GET HTTP/1.1 HkkkG libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d202.bin0000664000175000017500000000004115232414252021075 T;P /a HTTP/1.1 nFFzilibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d493.bin0000664000175000017500000000004215232414252021112 GET / HTTP/.1 kst: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d105.bin0000664000175000017500000000003515232414252021102 8POST /% HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d798.bin0000664000175000017500000000034215232414252021125 GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TestRecdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d075.bin0000664000175000017500000000000315232414252020223 H,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d114.bin0000664000175000017500000000016515232434352021434 79a5#275a4~Q ETGt: HTTP/1.1 Hsot: x Cookie: cnonce=":!H\TP/0.1 Host: x Cookie: cnonce=s!t:5xnpa=b 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d111.bin0000664000175000017500000000010015232414252021070 %GET /a HTTP/1.1 Cookie:nonce="0000"osta= b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d191.bin0000664000175000017500000000003615232414252021110 Healm=" / HTTP/1.1 WWWWlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d795.bin0000664000175000017500000000034015232414252021120 GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaaaa", userhash="TesaRe\lm", nonceuth, nc=00001, cnonce="deadbeef", algorithm=SHA-256, response="0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d053.bin0000664000175000017500000000012615232434352021433 7a59275a4aVQ ETQ0Gt: HTTP/1.1 Host: x Cookie: cnonce=;"ost: xnpa=b !10libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d182.bin0000664000175000017500000000004515232414252021113 'GeT %63 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d101.bin0000664000175000017500000000004015232414252021653 Digest algoritHm="SHA-512-2\56"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d759.bin0000664000175000017500000000025015232414252021120 H-@ABCDEFGHIJKLMNOPQRSTUVWXHIJKLMNOPQRSTOPQRSTUVPOST (/a HTTP/1.1 Host: x Transfer-Encoding: chunked  18 MABCDEFGHIJKLMNOPQRSTUVWX 00d;ext=QRlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d004.bin0000664000175000017500000000000315232414252020213 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d364.bin0000664000175000017500000000004615232414252021116 / G /a HTTP/1.1 2222 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d159.bin0000664000175000017500000000002015232414252021110 npGET(/ TP/.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d180.bin0000664000175000017500000000004515232414252021111 /E/aGT q=%20 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d584.bin0000664000175000017500000000065715232414252021132 $3(SOT y34(POST /a HTTP/1.1 Host; x *@ FPOS*T /a HTTP/1.9 Host: y Transfer-EncoDing: chunked 3 abc 00000000000000ffvffff 01P/.T 1 HHTTP/1.1 : x GET / HTDP/1.GGET / HTTP/1.1 DP/1.GET / HT01P/.T 1 HHTTP/1.1 : x GET / HTDP/GET / HTTP/1.1 DP/1.GET / HT01P/.T 1 Ho!bbbbbbbbbbbbbbbbbbbbbbbbbbP/1.1 Host; x .1 : x HT2P/2.1 Host8a HTT<GET / HTTP/1.1 Hri^^^^^^^^^Pii^^^^^^^libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d200.bin0000664000175000017500000000000415232414252020212 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d530.bin0000664000175000017500000000004515232414252021105 GET /a HTTP/1.1 dXNlcYX)libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d046.bin0000664000175000017500000000006515232434352021437 EE3030@6666%E1036:[7`7p7772GElibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d205.bin0000664000175000017500000000004615232414252021105  / : xHEAD GET /a HTTP/1.1 ; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d215.bin0000664000175000017500000000011015232414252021076 dGET / HTTP/1.1 Host: x Authorization: Digest uss="est\ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d835.bin0000664000175000017500000000042615232414252021120 GET /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest usernae-"user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8''a0002%%DO , algConteNOm=SH13- HT0A6, response="0123456789abcd89abad123456789abcdebcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d074.bin0000664000175000017500000000001215232414252021102  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d015.bin0000664000175000017500000000001015232414252022330 `aa=%%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d532.bin0000664000175000017500000000012715232414252021113 FPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 0 abc 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d733.bin0000664000175000017500000000021115232414252021105 77777777777777ST /a HTTP/1.1 Host: x Content-Type: application/x-www-form-urlencoded Content-Length: 42 a=77777777775555542&clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d303.bin0000664000175000017500000000002715232414252021106 vGr?OPT!ET / .libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d193.bin0000664000175000017500000000003615232434352021440 75QT # HTTP/1.1 p 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d002.bin0000664000175000017500000000044315232434352020216 uiGET?*’ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d186.bin0000664000175000017500000000001615232414252021112 a x? libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d034.bin0000664000175000017500000000023315232414252021106 E/a)Zr GET /a%06b HTTP/1.1 KKKKKKKKKKKKKKKKKKKKKKKKKKKK KKKKKKKKKKKKKKzzzzzzzzzzzzzzzz Transfer-Encoding: chunked 0a=1&b=2x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d371.bin0000664000175000017500000000032115232414252021105 0 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRelm", non,e="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbea", q:op=a6t libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d132.bin0000664000175000017500000000001215232434352021423 62_libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d129.bin0000664000175000017500000000001215232434352021431 ##-3pRlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d356.bin0000664000175000017500000000025415232414252021115 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Ceitionk" value ----abc-- 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d065.bin0000664000175000017500000000015315232414252021113 2rTRACE "2GET /a HTTP/1.1 rPR@ACE  "0GET /aHT`/ Ho HEAD / HTTP/1.1 Holibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d275.bin0000664000175000017500000000002015232414252021107 .&:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d857.bin0000664000175000017500000000062315232414252021123 GET /a HTTP/1.1 Host: x XGET a HTTP/1.1 Host: xaaaa#aaaaaXaHost: Authorizatx XGET a HTTP/1.1 Host: xaaaa#aaaaaXaHost: Authorization: D)i,%qop=authion: D)i,%qop=auth, ncx XGET /a HTTP/1.1 Host: xaaaa#aaaaa\aHost uth, ncx XP[89abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d060.bin0000664000175000017500000000022015232414252021076 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Ca libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d864.bin0000664000175000017500000000101015232414252021110 GET T!/1.T /a HTTP/1.1 Host: x Aut6666i="/a(", username*=UTF-6''a0001%%N; = aETG HTTP/1.1 HostW: x Authorization: Digest username-"user", realm="TestRealm", nonce="%۱", uri="/a(", username*=UTF-8''a0001%%boundary=agloriNOm=SH52-A6, response="0123456789abcd9daab8ef01234cdef0123456789abcdef" RONCE%%", qop=au]%20 HT%%", urRONCE%%", uri="/a", qop=auth%"%21 HT%% /a", qop=auth%00, nc=,000 cnoce="dea libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d640.bin0000664000175000017500000000011415232414252021104 n`me+GET 8` HTTP/1.1 Host: x Connection: close  res" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d192.bin0000664000175000017500000000004715232414252021116  G /a HTTP/1.1 H77pPlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d771.bin0000664000175000017500000000027515232414252021121 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm=uWET"/a", qop=auth, nc=00000002, cnonce= Content-Type: applica56e01def" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d764.bin0000664000175000017500000000025715232414252021123 nonce=||||||||||||||||||||||||||||||||||||||||||||"ET / HTTP/1.1 Host: alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d559.bin0000664000175000017500000000005115232414252021115 %1'GEt %fz-pGIONS/ HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d411.bin0000664000175000017500000000002115232414252021075  %*ontentt i libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d444.bin0000664000175000017500000000006115232414252021112 ETP???POST / HTTP/1.1 /1.1 HEAD libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d135.bin0000664000175000017500000000007015232414252021107 FPOST /a HTTP/1.1 Hos: x Cookie: ao11 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d387.bin0000664000175000017500000000005015232414252021116 pgrade: HT$:GET / HTTP/1.0 %%%-pc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d444.bin0000664000175000017500000000003515232414252021110  realm=""CT ET / HTTP/1.7 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d247.bin0000664000175000017500000000035315232414252021114 Upgrade: GETGET /a HTTP/1.1 Host: x Authorization: Digest username="aaa-------------------aaaaaaaaaaaa", username*=UTF-8''aui=""%DEL%DELE%150username="%f9e6%f9e"%DEL%DELf9ef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d219.bin0000664000175000017500000000010615232414252021112 v?cE! -34POST /a HTTP/1.1 Host: x Content-Length: 4 abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d508.bin0000664000175000017500000000011315232414252021111  ]VGET /a HTTP/1.1 Co Cookie: ; Author libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d475.bin0000664000175000017500000000004015232414252021110 GET / HTTP/1.2 oMs libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d752.bin0000664000175000017500000000024115232414252021111 GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="0000", uri="/a", algoupgraderithmMD5GUS, response="00" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d209.bin0000664000175000017500000000005215232434352021434 7Aa592a4aQ ET%2QGt: HTTP/1.1 Clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d177.bin0000664000175000017500000000027415232414252021120 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Content-Type: it form-data; name-="k" vallibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d591.bin0000664000175000017500000000007315232414252021115 %41GET /?+***+**nonce=""Tb HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d221.bin0000664000175000017500000000013515232414252021102 dGET / HTTP/1.1 Host: Authorization: Digest userhash=true, username=%zz"aalm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d278.bin0000664000175000017500000000002015232414252021112 ,; Rlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d541.bin0000664000175000017500000000004615232414252021110 GET / H HTTP/1.1 Ho:*  \libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d572.bin0000664000175000017500000000025415232414252021120 E/a)Zr GET /a%06b HTTP/1.1 KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKzzzzzzzzzz Transfer-Encoding: chunked FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d121.bin0000664000175000017500000000000515232414252020215 %63libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d285.bin0000664000175000017500000000002315232414252021113 C-Śkab0 ab libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d526.bin0000664000175000017500000000012415232414252021113 FPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 3 a libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d449.bin0000664000175000017500000000006315232414252021121 GET'GoC 9T%E/28%2a+?=%23 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d153.bin0000664000175000017500000000031215232434352020220 uff iGET /aaaaa/?b&;ext="a\"b"fa/?b&caaaaa]aaa HTTP/1.1 Host: x X-ong: aaaaaTransf+ -ET libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d066.bin0000664000175000017500000000000515232414252020225 =%%I7libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d096.bin0000664000175000017500000000000515232414252020230 %4flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d628.bin0000664000175000017500000000011215232414252021110  GET /a H HTTP/1.1 a H *Host:x Authorization: Digest  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d518.bin0000664000175000017500000000004415232414252021112 GE$ /%546&b HTTP/1.0 $ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d138.bin0000664000175000017500000000014715232434352020231 B0$GNegotiate =1 HTTP/1.1 Host: x Cookie: a=b,HntTE: 4 HHHwHHH*libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d848.bin0000664000175000017500000000052515232414252021124 GGT TP/1.T /a HTTP/1.1 Hostut666666666666666 HTTP/1.1 Host: x Authorization: Digest username- realm="Testlm", non_e="%", realm="TestRealm", nonce="%۱", uri="/a(", username*=UTF-8''a0001%bdea%ef", agloriNOm=SH53-A6, response="0123456789abcd9daab8ef01234cdef01789abcdef" RONa", qp=,000 cnoce="dea libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d560.bin0000664000175000017500000000016115232414252021112 ` F|OST.1 /a HTTP/1.1 Host: x Transfer-Encoding: chunked Transfer-Encoding: hunked a libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d017.bin0000664000175000017500000000004315232414252021106 Hosa=2sb&0 oGET / HTTP/1.0 Plibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d787.bin0000664000175000017500000000032215232414252021121 ( x XGET /a HTTP/1.0 Host: x Authorization: Digest usernaMe="aaaaaaaaaaaaaaaaaaaaeaaaaaaa85191088̞filenameaaaa", userhash=true, rea, n`once="%%NONCE%%", uri="/a", qop=auth, nc=0c-- 0123489abcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d108.bin0000664000175000017500000000006215232434352020222 :0GTE HTTP/1.0 H: x Cookie: ;a=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d488.bin0000664000175000017500000000004115232414252021115 UET / HTTP/1.1 HoKKKKlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d351.bin0000664000175000017500000000004615232414252021112 `0 /GET /a HTTP/1.1 TK libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d152.bin0000664000175000017500000000000515232414252020221 ec%bclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d558.bin0000664000175000017500000000015115232414252021120 &ET /a HTTP/1.1 Expect:/1ntinue Transfer-Encoding: chunked libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d564.bin0000664000175000017500000000005215232414252021112 a .= %bouny=I4 HTTP/1.1 Hostlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d479.bin0000664000175000017500000000010015232414252021114 %412#+a=&%86 HT4T2 /?1=+'%&a3 HTTP/1.1 A2?a=&%4P1/E: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d552.bin0000664000175000017500000000014315232414252021113 'Br0HEAD / HTTP/1.1 tent-Lengt41 =ba HTT1.1 Cookie: a="=" s :x bcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d067.bin0000664000175000017500000000004415232434352021437 7a575Q E: HTTP/0.1 Hospa=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d467.bin0000664000175000017500000000003715232414252021117 GEt %1/ HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d461.bin0000664000175000017500000000003715232414252021111 , %Ij %5fol HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d139.bin0000664000175000017500000000032015232414252022343 --abcContent-Type: my=Q@"=c ef" ----abc ef" Content-Type: multipart/mixed;ixed;bouboundary=Q@"=c ef" ----abc e=c -- ef"-- ----abc ef" "=c -- ef" ----abc oulibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d140.bin0000664000175000017500000000000515232414252020216 /%0blibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d191.bin0000664000175000017500000000003215232434352021432 #"11@_  Vlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d055.bin0000664000175000017500000000000515232414252020223 e"%calibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d429.bin0000664000175000017500000000002615232414252021113 DELETE POSlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d139.bin0000664000175000017500000000001315232434352021433 3ala.HADlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d238.bin0000664000175000017500000000014215232414252021113 04POST /a HTTP/1.1 Hos%:2.1 Host: Content-Length: 3 x Content-Length: 2 dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d855.bin0000664000175000017500000000056015232414252021121 ncone=algorithm=U['"ET / HTTP/1.1 Host: alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d324.bin0000664000175000017500000000004015232414252021104 p-alive GET a HTTP/0@3 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d087.bin0000664000175000017500000000004615232434352020232 0T /rem=%0A0 HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d885.bin0000664000175000017500000000012715232414252021123 FGET /a HTTP/1.1 Host: x GET /a HTTP/1.1 Host: 0 response="e" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d172.bin0000664000175000017500000000003015232414252021104 TP/1.1 nߜos st libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d108.bin0000664000175000017500000000004215232414252021103 r ealm=""C / HTTP/1.1 ̜07 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d036.bin0000664000175000017500000000000715232414252022341 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d031.bin0000664000175000017500000000033615232414252021104 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a",!qop=auth,, algorithm=SHA-256, response="0123456724356789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d373.bin0000664000175000017500000000004715232414252021117 RGET / HTTP/1.1 OTPIONSlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d245.bin0000664000175000017500000000022115232434352021432 ;@ PQQQQQQQQQbB;7bbB:!1Q*EURFbbBB :::::EbbBBB# ::::Q:::::::::::::!::::::4 :::::::::4@;:04libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d378.bin0000664000175000017500000000005015232414252021116 /E/aGT "?q=%41 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d134.bin0000664000175000017500000000007615232414252021111 )UGET / HTTP/1.1 Host: x Authorization: Digest libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d180.bin0000664000175000017500000000000315232414252020220 Alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d100.bin0000664000175000017500000000012215232414252021075 FPOST /a HTTP/1.0 Host: x Transfer-Encoding: chunked 3 abc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d474.bin0000664000175000017500000000004015232414252021107 GET / HTTP/1.1 I libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d438.bin0000664000175000017500000000003215232414252021110 @j GT HP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d181.bin0000664000175000017500000000000315232414252020221 3libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d437.bin0000664000175000017500000000006015232414252021113 =GETd'GET /%dddddd%74 HTTP/1.1 Hos libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d009.bin0000664000175000017500000000003715232414252021107 GE;T / HTTP/1.1 : libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d568.bin0000664000175000017500000000021615232414252021123 ?/GETZOST /a HTTP/1.1 Content-Length: 1048576 99990.1 Content-Length: 10948576 990 99999/1.1 Hlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d249.bin0000664000175000017500000000000515232414252020230 1%%alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d419.bin0000664000175000017500000000005415232414252021116 HTTP"GEt /a?q=%A64 HTTP/1.1 222 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d163.bin0000664000175000017500000000002215232414252021105 Gto:nnGtt3on: Ulibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d045.bin0000664000175000017500000000007615232414252021115 3PQGET /a HTTP/1.1 Cookie: a=!&&&'&Ho!!!!x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d128.bin0000664000175000017500000000004715232414252021115  GT /a%.b HTTP/1.1 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d021.bin0000664000175000017500000000001315232434352021421 D:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d164.bin0000664000175000017500000000006415232414252021111 conETe / HTTP/1.1 / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d132.bin0000664000175000017500000000006215232414252021102 A5: G= HTTP/1.1 Hot: x Cookie: aAb libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d473.bin0000664000175000017500000000004015232414252021106 pET / HTTP/1.1 Ho|:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d456.bin0000664000175000017500000000003615232414252021114 ET %3/ HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d225.bin0000664000175000017500000000000515232414252020222 %5Dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d015.bin0000664000175000017500000000010415232414252021102 r?F9 Content-Typ /a He:Authorization: Basic dXNlcjpwYXNzlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d273.bin0000664000175000017500000000003615232414252021111  #GE HTTP/1.1 TTP/libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d107.bin0000664000175000017500000000001315232414252022335 !r=bo----elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d605.bin0000664000175000017500000000010315232414252021103 0GETQ /path?a=1Gt: HTTP/1.1 Host: x Cookie: a=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d775.bin0000664000175000017500000000030115232414252021113 Upgrade: GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="Cookie: 0123456789abcab234cDDEa", userhash=true, realm="%serhash=trueAuthorizatioHA-2def" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d725.bin0000664000175000017500000000017615232414252021120 : @>http://example.org/aET /ࠠ HTTP/1.1 Host: x Auhtriozation: Basic libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d237.bin0000664000175000017500000000012515232434352021436 7a59275a4a~Q ETQ0Gt: HTTP/1.1 Host: x Cookie: kn=nnpaeeeeeeeeeeeeeeeeeb, 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d594.bin0000664000175000017500000000004115232414252021116 r?F9J "/G /a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d014.bin0000664000175000017500000000001315232414252021607 @libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d446.bin0000664000175000017500000000006215232414252021115 "GFT /a?q=%92 HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d105.bin0000664000175000017500000000001115232414252022331 %1=%dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d027.bin0000664000175000017500000000001115232414252022334 ]--- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d165.bin0000664000175000017500000000001415232434352021433 211 2XXlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d782.bin0000664000175000017500000000031715232414252021120 JGET /a HTTP/1.1 Host: x %%NONCE%%XGET /a HTTP/1.1 Host XGET / HTTP/1.1 HceGET /a HTTP/1.1 Host XETGET /a HTTP/1.1 Host: x Authorization: Digest" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d272.bin0000664000175000017500000000003615232414252021110 j GET / HTTP/1.1 o1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d358.bin0000664000175000017500000000026115232414252021115 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Content-Disposition: form-data; name= k" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d118.bin0000664000175000017500000000010115232434352020215 uiGET /aaaaaaaa%95aaaa_aa HTTP/1.1 HoPPPPPP3aaaa aE/ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d168.bin0000664000175000017500000000002615232414252021116 @P/1PUT libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d598.bin0000664000175000017500000000041315232414252021125 'ET /T / HTTP/1.1 HTTP/1.1 ox: t sG /ectionaT / HTTP/1.1 HTTP/1.1 ox: t sG /ecti:n:POST GET/T / HTTP/1.1 HTTP/1.1 ox: t sG /ectionaT / HTTP/1.1 HTTP/1.1 ox: t sG /ecti:n:POST GE / HTTP/1.0 / HTTP+1.1 x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d199.bin0000664000175000017500000000005015232414252021117 2fGET[ %1A8b HTTP/1.0 .libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d049.bin0000664000175000017500000000000515232414252021620 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d098.bin0000664000175000017500000000000515232414252020232 T%Clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d102.bin0000664000175000017500000000000515232414252020214 '%Clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d111.bin0000664000175000017500000000000515232414252020214 %%elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d057.bin0000664000175000017500000000016115232434352020225 m0GNegotibte =1 HTTP/1.1 Host: x Cookie: a=b Connection: close \eConntiCONNECT uth2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d017.bin0000664000175000017500000000005015232434352020216 MET /a HTTP/1.2 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d256.bin0000664000175000017500000000032615232414252021117  +EFT ;a HTT H/ HTTP/1.1 T/ a HTTP/1.1 T /a HTTP/1.1 H T /aT /a HTTP/1.1 Hos{ H TTP/1.1 T :a HTTP/1A.3 Hos tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d027.bin0000664000175000017500000000005215232434352021432 ;!!0?BB):::0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d233.bin0000664000175000017500000000013615232414252021111 pP FPOST /a HTTP/a HTTP/1.1 Host: x Transfer-Encoding: chunked 5;  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d049.bin0000664000175000017500000000001315232434352021433 ::2 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d826.bin0000664000175000017500000000040215232414252021112 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000100, cnonce="deadbeef", algorithm=SHA-256, response="0123456789abcd8956789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d098.bin0000664000175000017500000000004215232434352021441 b(1V!-`5libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d142.bin0000664000175000017500000000012515232414252021106 =OT SP/a HTTP/1.1 Host:d x Transfer-Encoding: chunked 0 abc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d107.bin0000664000175000017500000000045115232414252021111 v?cG! -17POTS /a HTTP/1.1 Host: x n: t: xLent: xLength:T$ 3 OPTIONS * HTTP/1.1 gth:T))))))))))))))))))) 4 :gth:T 4 : x n:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d143.bin0000664000175000017500000000000515232414252020221 B%B=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d851.bin0000664000175000017500000000053415232414252021116 aTS PO/%%NONCE%% HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 4327 ----abc g2: chunkedclose Content-Type: multipart/mixed; boundary=b --  }-Ty b = -- 1.1 undary=b --  GET /Trailer: a 2TTP/1-.1 : valu, n libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d105.bin0000664000175000017500000000004515232414252021664 Digest algorithm="\SHA-512-256-sess"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d276.bin0000664000175000017500000000002015232414252021110 :sOPTIONStHo libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d037.bin0000664000175000017500000000001015232434352021425 9?libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d145.bin0000664000175000017500000000001315232434352021430 ::jjjlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d051.bin0000664000175000017500000000004615232414252021107 "GET, /a?q=& HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d202.bin0000664000175000017500000000005115232414252021101  GT /a%0b HTTP/1.1 Host2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d737.bin0000664000175000017500000000021415232414252021114  |GET / HTTP/1.1 Host: x ConnecTtion: Upgra:de Upgrade: fuzz-protocol Content-Length: 1 Transfer-Encoding: chunked 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d080.bin0000664000175000017500000000000415232414252020220 /2%Zlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d705.bin0000664000175000017500000000015715232414252021115  |GET / HTTP/1.1 Host: x Connection: Cont-Length: 0 Transfer-Encoding: chunked 0 HTTP/1. libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d100.bin0000664000175000017500000000001015232414252022323 3&%F&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d155.bin0000664000175000017500000000001315232434352021431 2F+libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d046.bin0000664000175000017500000000001015232414252022334 0b%-=8 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d310.bin0000664000175000017500000000010515232414252021076 GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: 4 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d049.bin0000664000175000017500000000000515232414252020226 e4%0blibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d066.bin0000664000175000017500000000000615232414252022343 &libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d075.bin0000664000175000017500000000005015232414252021110 Up~n gr KKKExpectlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d076.bin0000664000175000017500000000001315232414252021617 @libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d754.bin0000664000175000017500000000024115232414252021113 POST /a# HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding:chunked 08 ----abc Contentporm---abc-) 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d294.bin0000664000175000017500000000004415232414252021113 ?ET / HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d072.bin0000664000175000017500000000002615232414252020225 X18446744073709551617libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d051.bin0000664000175000017500000000001015232414252021654 Basic ;libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d061.bin0000664000175000017500000000032215232434352020217 =GET /= HTTP/1.1 TE: : }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}%00}}}}}}}}}}}}}}}X libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d661.bin0000664000175000017500000000012415232414252021110 ncone=T / HTTP/1.1 Host: alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d173.bin0000664000175000017500000000003115232414252021106 # . ??? libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d416.bin0000664000175000017500000000002215232414252021103 c1 , libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d181.bin0000664000175000017500000000001215232414252021101 $ulibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d396.bin0000664000175000017500000000001515232414252021114 " libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d192.bin0000664000175000017500000000000315232414252020223 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d019.bin0000664000175000017500000000006115232414252021110 FPOST /a HTTP/1.1 Cookie: a=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d290.bin0000664000175000017500000000001015232414252020220 1234702libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d140.bin0000664000175000017500000000001315232434352021423 #)p5JJlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d576.bin0000664000175000017500000000030015232414252021114 ( FPST /a HTTP/1.1 Expect: 100-continue F.1 Host: x^stFPOST /a HTTP/1.1 Host:݇^ Tsansx^Au Transfer-Encoding: chunked 4 ab1c 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d054.bin0000664000175000017500000000001015232414252021610 }) libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d217.bin0000664000175000017500000000000515232414252020223 :%Wflibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d200.bin0000664000175000017500000000004015232414252021072 *GE / HTTP/1.1 Ha libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d025.bin0000664000175000017500000000001315232414252021611 #!libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d474.bin0000664000175000017500000000007515232414252021122 G.T /a HTTP/1.1 Cookie: a&&Host; x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d125.bin0000664000175000017500000000001215232434352021425 1@2**libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d684.bin0000664000175000017500000000014315232414252021116 POST /a HTTP/1.1 Host: x C-onTe: nryabc Transfer-Encoding: chunked 045f72f450 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d007.bin0000664000175000017500000000000515232414252020220 9%zalibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d014.bin0000664000175000017500000000001015232414252022327 --- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d053.bin0000664000175000017500000000003215232414252022336 a"b--a"b -- -- vlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d099.bin0000664000175000017500000000001015232414252022344 @%1d=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d538.bin0000664000175000017500000000013215232414252021115 pP FPxOSpT /a HTTP/1.1 Transfer-Encoding: chunked 9  .libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d574.bin0000664000175000017500000000026415232414252021123 0 /%+42ET /%+20%42?a&&&&&&&&%+20%4%ET /%+20%42?a&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&/%&&&&&&&&&&&&"&&&&&&&&&!&&&4@&HTͿ TTP 4@?a=%4@. HT%%Ϳ HP HTTP/1.1 NHx h  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d013.bin0000664000175000017500000000000515232414252020215 %!8libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d632.bin0000664000175000017500000000011215232414252021103 LT / HTTP/1.1 Host: Connection: Upgrade Upgrade:c 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d803.bin0000664000175000017500000000036115232414252021111 (GET / HTTP/1.1 Ho.t: GET /a HTTP/1.1 Host: x XTGE /a HTTP/1.0 Host: x Authorization: Digest username="5̞filenameaaaa", userhash=true, rea, n oncri=#"/a", qop=auth, 56, respose="0123489abcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d046.bin0000664000175000017500000000003315232414252021104 j G / HTTP/1.1 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d033.bin0000664000175000017500000000000315232414252020215 -1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d355.bin0000664000175000017500000000004615232414252021116 P@)PO / HTTP/1.1 ww G libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d216.bin0000664000175000017500000000010515232414252021106 Cont=ents-S @apXPosXXXXXXpQQl"""""""tion/xww-@EGTlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d380.bin0000664000175000017500000000005015232414252021107 '/GET /a HTTP/1.1 HOqqqq libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d053.bin0000664000175000017500000000012115232414252021100 POST /a HTTP/1.1 Host: ibc Transfer-Encoding: chunked 26 --libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d300.bin0000664000175000017500000000002615232414252021102 uuuEPOSTTT libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d079.bin0000664000175000017500000000001015232414252022342 o libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d868.bin0000664000175000017500000000103515232414252021123 Upgrade: GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaa-----------------------------------------------------aaaaaaaaaaaa", username*=UTF-8''auupgradet:%f8e6%f9e62TRACEe47ba"%DEL%DELE%15t:%f9e6%f9e62TRACEe47caaaaaaaaaa", u0 response="+0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d098.bin0000664000175000017500000000005515232434352020234 Ai=GET /aaaa%11aaaa HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d108.bin0000664000175000017500000000000515232414252020222 *%dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d471.bin0000664000175000017500000000004015232414252021104 G %clos HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d633.bin0000664000175000017500000000011315232414252021105 ?GET /a HTTP/1.1 Host: x Authorization: Basic dXNlcjpwYX?z libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d078.bin0000664000175000017500000000000315232414252020226 [6%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d297.bin0000664000175000017500000000002615232414252021121 0GET /a HPP/1.: ~libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d437.bin0000664000175000017500000000003215232414252021107 //1.1 H  / HTT//11 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d509.bin0000664000175000017500000000011515232414252021114 FPOST /a HTTP/1.0 Host: x Transfer-Encoding: chunked 3 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d232.bin0000664000175000017500000000010215232434352021424 !1###>>> >0p@)!::::::"p":D_libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d361.bin0000664000175000017500000000027615232414252021115 8GET oa P/2.1 Host: x XGET /a HTTP/1.1 Host: x AuthorizationHost: x Authorization: Digest usernam1="aue,username*: Digest usernam1="aue,username*=UT`F-7, nm9SHA56 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d085.bin0000664000175000017500000000002015232414252021106 100-continue libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d065.bin0000664000175000017500000000004415232414252021107 /1.1 HosGET / HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d530.bin0000664000175000017500000000012615232414252021110 &GE /c HTTP/1.1 Cookie: kie: ==;  ;NEEx libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d153.bin0000664000175000017500000000051515232414252021113 $3(SOT y34(POST /a HTTP/1.1 Host; x *@GET /a HTTP/1.1 Host: x GAT / HET /a HTTP/1.1 : x GET / HTDP/1.GGET / HTTP/1.1 DP/1.GET / HT01P/.T 1 HHTTP/1.1 2 : x HTTP/2.1 Host8a HTT<T /ᠠ HTTP/1.1 Host: x Auhtozozat/Nz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d856.bin0000664000175000017500000000057015232414252021123 Upgrade: FET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaa-----------------------------------------------------aaaaaaaaaaaa", username*=UTF-8''aut:%EETf9baaaGET /%%4 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d341.bin0000664000175000017500000000015515232414252021107 Upgrade: GET /a HTTP/1.1 Host: a\aaacaaaaaa23 Authorization: Digest username*="aaaaaaaaaaaaaaa\aaaef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d136.bin0000664000175000017500000000007715232414252021117 FOT SP/a HTTP/1.1 t:d x Content-Length:0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d182.bin0000664000175000017500000000001215232414252021102 rEcCoot libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d660.bin0000664000175000017500000000012415232414252021107 ` H/PTP/1.1 X: y tgrad%@6@9 HTTP/1.0 JPUQ+TT Connection: close000000" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d727.bin0000664000175000017500000000017715232414252021123 Hclose5eb4c46dc818417d37bdbf85dc89c016aae27a17a6d043e42a9a61fba07 /a HTTP/1.1 Hfaa019e /a HTTP/1.1 Host: x Glibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d251.bin0000664000175000017500000000076715232414252021123 1. Pp~T 1/ H.Tauthorization: Digest(username=&user" ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,/0  GPOST / HTTP/1.1 osGPOST / HTTP/2.1 `osGPOSGPOST / HTTP/1.1 oskGPOST / H`osGPOSGPOST / HTTP/1.1 oGPOST / HTT/P1.1 osGPOST / HTTP/1.1 `os ET /a HTTP/1.1 HosT:/x   ET /a H,,,,,E?E OST / HTst߇t߇ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d106.bin0000664000175000017500000000020515232414252021105 rP POSp5T /a HTTP/1.1 Expect: 100-continue Ho: chub c0  Transfer-Encoding: chunked :  3 ab c0  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d154.bin0000664000175000017500000000031615232434352020225 uff iGET /aaaaaaaaaaaaaaaaaaaaaaaaaaaaa_aa HTTP/1.1 Host: x X-Lhunke libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d517.bin0000664000175000017500000000011615232414252021114 GET /a HTTP/1.1 Cookie: a=b GG,& libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d123.bin0000664000175000017500000000011015232434352020211 AiGET aaaaa%afbbbbbbbbbbbbbbaaaaaaa%4aaaaa HTTP/1.1 Host:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d510.bin0000664000175000017500000000011515232414252021104 FPOST /a HTTP/1.0 Iost: x Transfer-Encoding: chunked 2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d082.bin0000664000175000017500000000002015232414252021103 GETlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d043.bin0000664000175000017500000000000515232414252020220 \%delibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d601.bin0000664000175000017500000000010115232414252021075 @ealm=+ @/aE%FFF%FFFFFޞ%T @/a HTTP/1.1 xong: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d026.bin0000664000175000017500000000001715232434352021432 EE@E203 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d765.bin0000664000175000017500000000026215232414252021120 6GAT /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest username\-"user", realm="TestRealm", nonce="%%KONCE%%", uri="/a", username*=WTF-8'' libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d227.bin0000664000175000017500000000007015232434352021434 bP$ HDEADELETE HTTRCE222libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d080.bin0000664000175000017500000000002415232414252021663 Digest qop=auth-intlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d198.bin0000664000175000017500000000004015232414252021112 :1t0 /%8a HTTP/1.1 Ho libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d294.bin0000664000175000017500000000001215232414252020226 UYWjQJJDlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d084.bin0000664000175000017500000000002015232414252021105  &libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d287.bin0000664000175000017500000000001015232414252020226 89aba8aflibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d046.bin0000664000175000017500000000014415232414252021112 8POST /a HTTP/1.1 Hostst: z Content-Length: 1048 Expect:GET / HTTinue abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d087.bin0000664000175000017500000000000415232414252020227 790libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d162.bin0000664000175000017500000000001215232414252020220 QUJ~RA==libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d038.bin0000664000175000017500000000010415232414252021107 r?F9 ntent{-TypePOST /a HTTP/1.1 Host: L?c nlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d255.bin0000664000175000017500000000030515232414252021113  OEGT ;a HTT Ha HTTP/1.1 $HoeFst ;e_o OST / HTTP/1.1 T /a HTTP/1.1 H T /aT /a HTTP/1.1 Hos t߇ H T /a HTTP/1oHEA.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d673.bin0000664000175000017500000000013415232414252021114 dGET / HTTP/1.1 Host: x Authorization: Digest userhash=true, username="Alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d338.bin0000664000175000017500000000014115232414252021110 POST /a HTTP/1.0 Host: ba Transfer-Encoding: chunked 5AAAAAAAAAAAAAAAAAA`FAAnlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d403.bin0000664000175000017500000000001615232414252021102  tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d329.bin0000664000175000017500000000004215232414252021113 G a HTT@/0.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d453.bin0000664000175000017500000000003615232414252021111 %GE1/ HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d207.bin0000664000175000017500000000005515232414252021107  @>GET / HTTP/1.1 HVst: x Auhchun libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d072.bin0000664000175000017500000000001215232434352021426 10?2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d005.bin0000664000175000017500000000002015232414252021076 F0H_Rmlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d082.bin0000664000175000017500000000001015232414252022334 %=%r7&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d405.bin0000664000175000017500000000005315232414252021110  GET HTTP/1.1 HosT: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d049.bin0000664000175000017500000000002015232414252021106 Mozt&Glibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d117.bin0000664000175000017500000000000515232414252020222 %79libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d163.bin0000664000175000017500000000042315232434352020224 !--0000000000007173733806442603406Cookie: 4440123789abcdef7173733userhash=806442603406CookiČ HTTP/1.1 HosCCCCCCCzCCCCC!!!CCC!!!!CCCCCCCCCCCzat libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d634.bin0000664000175000017500000000011315232414252021106 ?GET /a HTTP/1.1 Host: x Authorization: Basic ,XNlcpjwYXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d088.bin0000664000175000017500000000030515232414252021626 ((((((((((]((((((((((( 6((((((((((( 6((((((((((((((((((((((((((((((((((((((((((((((]((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((3libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d669.bin0000664000175000017500000000012715232414252021123 dGET HTTP/1.1 Host: x Authorization: Digest userhash=t CONNECT libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d471.bin0000664000175000017500000000007415232414252021116 !ob GETGET /?%41/?%412'+a=&%43 HTTP/1.1 AE0vv libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d382.bin0000664000175000017500000000005015232414252021111 IONS HTTP/1.1 xUU] libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d008.bin0000664000175000017500000000000515232414252021613  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d502.bin0000664000175000017500000000010615232414252021105 v?cE! -01POST /a HTTP/1.1 Host: x Content-Length: 4 s0Blibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d877.bin0000664000175000017500000000245315232414252021130 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 522 ----abc g2: chunked 52 ----abc g2: chunkeTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: ch=++++upgE /?T=++++upg)*/՜/&GE /?.GE /?T,=++++upg HTTP/0.9pg/&,=++++TP/0.9pg/&GE /?T,=++++upg HTTP/0.9pg/&=++=++++upg HTTP/0.9pg/&,=++++upg HTTP/0.9pg/&GE /? HTTP/0.9pg/&GE /?T,=++++upg HTTP/0.9pg/&=++++upg՜ܜ& HTTP/0.9Q0N/&,=++++upnameg-abc Conk#d 53 ----anked 52 ---- pgrada HTTPlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d025.bin0000664000175000017500000000002215232434352020214 @uri=TRACE libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d121.bin0000664000175000017500000000001215232434352021421 jj:5/wlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d844.bin0000664000175000017500000000047015232414252021117 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response="0123456789abcdef01234556789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d604.bin0000664000175000017500000000010315232414252021102  HGET / HTTP/1.1 Host: Connection:de: fuz,htple.l libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d062.bin0000664000175000017500000000000415232414252020220 99libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d073.bin0000664000175000017500000000003715232434352020225  ?ET / HTTP/1.1 Hos_Tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d040.bin0000664000175000017500000000000515232414252021607 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d046.bin0000664000175000017500000000000515232414252021615 @libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d280.bin0000664000175000017500000000000615232414252020224 QA=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d389.bin0000664000175000017500000000005115232414252021121 /E/aGT "rrrrr=%19 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d241.bin0000664000175000017500000000017215232414252021110 [6a=;&b =2>00000000000000000002434804libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d179.bin0000664000175000017500000000000315232414252020230 TAlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d478.bin0000664000175000017500000000004015232414252021113 .0 P/ =0&b HTTP/1.0 $ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d763.bin0000664000175000017500000000025615232414252021121 7GAT /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest username-"user", realm="TestRealm", username*= , nce="deadbe" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d035.bin0000664000175000017500000000007015232414252021106 `0/G/a HT HTTP/1.1 H Connection: clo libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d292.bin0000664000175000017500000000001215232414252020224 9A9ADAdA3libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d052.bin0000664000175000017500000000001615232414252021102  HTTP/1.0T libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d069.bin0000664000175000017500000000004315232414252021115 //aGT "%4! HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d515.bin0000664000175000017500000000004315232414252021106 @>GET / HTTP/1.1 lllllalibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d011.bin0000664000175000017500000000010515232434352020211 A<POST /a HTTP/1.1 Host:c x Content-Length: 11 he: rldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d120.bin0000664000175000017500000000005515232414252022336 _\"=%=b60&clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d048.bin0000664000175000017500000000010415232434352020222 0GET /pat(+?=1 HTTP/1.1 H: x Cookie: realm="******; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d686.bin0000664000175000017500000000014315232414252021120 n]"ET / HTTP/1.1 Host: alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d502.bin0000664000175000017500000000004215232414252021101 T; /a HTTP/1.1 oxxxxqlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d801.bin0000664000175000017500000000035615232414252021113 (GET / HTTP/1.1 Ho.t: GET /a HTTP/1.1 Host: x XTGE /a HTTP/1.0 Host: x Authorization: Digest username="3̞filenameaaaa", userhash=true 0 cnonce="d&eddbeef", a 56, respose="0123489abcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d038.bin0000664000175000017500000000001015232414252022335 a%13&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d448.bin0000664000175000017500000000006215232414252021117 r2?驩GHost: / HTTP/1.0 Host: / os`Tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d078.bin0000664000175000017500000000000715232414252022347 `> ay=3libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d442.bin0000664000175000017500000000006115232414252021110 [T /a HTTP/1.1 Host2UUUUUUUUUUUlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d122.bin0000664000175000017500000000010615232434352020215 A ''''/GETGET1GET =",1 HTTP/1.1 Cookie: T =Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d631.bin0000664000175000017500000000011215232414252021102 GET / HTTP/1.1 Host: x Authorization: Digest uuepose="e" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d083.bin0000664000175000017500000000002515232414252021667 Digest userhash="\g"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d055.bin0000664000175000017500000000015215232414252021106 PpAF/ HTTP /a HTTP/1.1 Host: xHE/0 Authorization: Digest ts00, algorits00, algorithm="\s" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d161.bin0000664000175000017500000000004415232414252021104  G / HTTP/1.1 Host:x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d028.bin0000664000175000017500000000002315232414252021106 GET / H= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d146.bin0000664000175000017500000000040215232414252021105 PpFGET /a HTTP/1.1 Host: x =GET ?a HTTP/1.1 = Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="?a", 0000001, cnonce="deef", algorithm=SHA-256, response="012345\6789a\cd89abcdecdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d353.bin0000664000175000017500000000024015232414252021105 tGET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="", nonce="0000", uri="/a", response="00" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d422.bin0000664000175000017500000000005515232414252021111 B'0'GET /%4F HTTP/1.1 Hx libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d499.bin0000664000175000017500000000004215232414252021120 @++GE%ET %CN@ HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d100.bin0000664000175000017500000000020115232414252021070 &b=%41&cmPOST /a HTTP/1.1 Host: x Content-Type: application/x-www-form-urlencoded Content-Length: 11 a8=1&b= %41&clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d002.bin0000664000175000017500000000000215232414252021651 slibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d045.bin0000664000175000017500000000001015232414252022333 =66libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d007.bin0000664000175000017500000000000515232414252021612 Plibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d092.bin0000664000175000017500000000001315232434352021431 #;3 p#libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d252.bin0000664000175000017500000000346115232414252021116 $3SOT y35(POST /a HTTP/1.1 Host; x *@ GET/a HTTP/1.1 Host: x GAT / HET /a HTTP/1.1 : GET / HTDP/1.GGET / HTTP/1.1 DP/1.GET / Host; x *@GET /a HTTP/0.1 Host: x GAT / HET /a HTTP/1.1 : x :'GET H HTTP/2.1 /%24%59?`a=4/%49%59?`a=4/%49%59?`a=43/%24%59?`a=4/%49%59?`a=4/%49%59?`a=433/%24%599?`a=4/%49%59?`a=439%HEAD / HTTP/1.1 TPOS/%49%59?`a=43233# 3M/%2433/%24%59?`/%49%59?`aT' / HET /a HTTP/1.1 : GETHTDP/1.GGET / HTTP/1.1 D EGT ;a HTTP/1.1 Ha TTP/1.1 Fst xPOST / HTTP/1.1 T /a HTTP/1.1 Hos t߇1 HoFst xPOST / HTTP/1.1 T /a HTTP/1.1 H Host xPOST / HTTP/1.1 T /a HTTP/1.1 Hos t xPOST / HTTP/1.1 P/1.GET / H  x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d001.bin0000664000175000017500000000002015232414252021072 `<[=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d026.bin0000664000175000017500000000002215232434352020215 0PUT = libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d424.bin0000664000175000017500000000002415232414252021104 .CONNECT libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d094.bin0000664000175000017500000000005215232414252021113 @GET /a HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d036.bin0000664000175000017500000000001615232414252021665 Digest nc="""libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d208.bin0000664000175000017500000000005615232414252021114 Pp'GET /%58%3CNECT HTTP/1.0 Holibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d566.bin0000664000175000017500000000005315232414252021115 /l a HTTP/1.1 : v Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d030.bin0000664000175000017500000000001115232414252021652 Digest libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d739.bin0000664000175000017500000000021615232414252021120 GE cnonce="deadbeeT / 2 tion:CE%gesta cnonce="deaT /a HTTP/1.1 Ho libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d018.bin0000664000175000017500000000001415232414252021663 Digest nc=Dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d162.bin0000664000175000017500000000001415232434352021430 26Alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d793.bin0000664000175000017500000000032715232414252021123 (GET / HTTP/1.1 Ho.t: GET /a HTTP/0.1 Host: x XGEzT /a HTTP/1.0 Host: x Authorization: Digest username="aaaaafile6851911088̞filenameaaaa", userhash=true, rea:oef 56, respcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d126.bin0000664000175000017500000000000515232414252020222 %flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d342.bin0000664000175000017500000000015715232414252021112 nonce=,U"ET / HTTP/1.1 Host: alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d398.bin0000664000175000017500000000005215232414252021122 'GET /%C242?a=%2 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d017.bin0000664000175000017500000000001315232414252021661 Digest nc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d055.bin0000664000175000017500000000001115232414252021661 Digest libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d119.bin0000664000175000017500000000000515232414252020224 u%D1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d030.bin0000664000175000017500000000005315232434352020214 0G HTTP/1.0 / HTTP/1.1 Ho libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d370.bin0000664000175000017500000000031715232414252021111 Upgrade: GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaaCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaa", userhash=true libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d240.bin0000664000175000017500000000000515232414252020217 ~%C6libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d546.bin0000664000175000017500000000004615232414252021115  R&5 0194%3d05 HTTP/1.1 jjjlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d097.bin0000664000175000017500000000001015232414252022342 H=1&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d064.bin0000664000175000017500000000001315232414252021663 Basic sh==libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d772.bin0000664000175000017500000000027515232414252021122 GET /a;ext=val1 ot :sx =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="Test|m",qop=auth, nc=0def0123456789abcddef0123456789ab789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d487.bin0000664000175000017500000000010215232414252021115 r?F9 "/GE a HTTP/1.1 Host: x Connection:sgth, 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d226.bin0000664000175000017500000000015315232414252021107 ( / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d111.bin0000664000175000017500000000007215232434352020215 1&GlEr/eP m=%dt0cionuade5 HTTP/1.1 Ha=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d292.bin0000664000175000017500000000002315232414252021111 C-Śkooa=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d136.bin0000664000175000017500000000011215232414252021102  XGET /a HTTP/1.1 Host: x Authorization: Digest 01, c libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d038.bin0000664000175000017500000000015515232414252021112 ﹹ / HTlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d113.bin0000664000175000017500000000002015232414252021076 vlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d069.bin0000664000175000017500000000001315232414252021621 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d812.bin0000664000175000017500000000037215232414252021113 Upgrade: GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa99999999aaaaaaaaaaaaaaaaaaaaacaaaaaaaaaa", userhash=true, re0000002, cnesponse="0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d052.bin0000664000175000017500000000001615232414252022337 XY--XY-- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d074.bin0000664000175000017500000000002015232414252021662 Digest qop=a?"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d346.bin0000664000175000017500000000017615232414252021117 GET /a HTTP/1.1 Hos xt: XGET /a HTTP/1.1 Host: Authorization: Digest ef uri="/a", qop=aut^, nc=000000 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d025.bin0000664000175000017500000000003515232414252021103 GET / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d517.bin0000664000175000017500000000004415232414252021111 POS 1/%0b HTTP/1.1 oT_libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d529.bin0000664000175000017500000000012615232414252021120 =OT SP/a HTTP/1.1 Host:d x Transfer-Encoding: chunked 0 a libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d330.bin0000664000175000017500000000004315232414252021104  /GE /a HTTP/1.1 *libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d537.bin0000664000175000017500000000013115232414252021113 FPOST /aETKGET HTTP/1.1 Host: x Transfer-Encoding: chunked 3A bc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d002.bin0000664000175000017500000000001015232414252021601 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d571.bin0000664000175000017500000000024315232414252021115 |?F0 576 loloF?0bT  ET HEAD / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d317.bin0000664000175000017500000000003615232414252021113 -OPTIONS * O libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d245.bin0000664000175000017500000000000515232414252020224 /a%9alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d216.bin0000664000175000017500000000000515232414252020222 %25libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d076.bin0000664000175000017500000000000715232414252022345 2&a=2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d428.bin0000664000175000017500000000002615232414252021112 (%GET/ HPlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d044.bin0000664000175000017500000000007415232414252021112 &GE /a HTTP/1.1 Cookie: =; NEx libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d065.bin0000664000175000017500000000000615232414252022342 c libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d453.bin0000664000175000017500000000006415232414252021115  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d486.bin0000664000175000017500000000004115232414252021113 userhash=#~/ "[%c%15 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d165.bin0000664000175000017500000000000315232414252020223 bclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d303.bin0000664000175000017500000000006415232414252021104 GET /a HTTP/1.1 Cookie:; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d135.bin0000664000175000017500000000010615232414252021104 nonce="ET / HTTP/1.1 Host: x Authorization: Digest Username libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d112.bin0000664000175000017500000000000515232414252020215 %3%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d224.bin0000664000175000017500000000000515232414252020221 _%4&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d027.bin0000664000175000017500000000012415232414252021104 dGET / HTTP/1.1 Host: x Authorization: Digest userhue, username=*m" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d011.bin0000664000175000017500000000004115232414252021073 ff $>G / HTTP/1.1 HoX libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d106.bin0000664000175000017500000000000515232414252020220 %4flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d267.bin0000664000175000017500000000002515232414252021112 Gx OPTIONS `libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d096.bin0000664000175000017500000000005315232434352020230 0GET %00t`?&a&=1 HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d200.bin0000664000175000017500000000004415232434352021424 7Aa592ONQ ET%QF0Gt: HTTP/1.1 Coe0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d512.bin0000664000175000017500000000004315232414252021103 %t /a HTTP/1.1 : v libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d501.bin0000664000175000017500000000010615232414252021104 PpRET / HTTP/1.1 Cookie: KN K a libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d107.bin0000664000175000017500000000006115232434352020220 AiG-ET %62aaaa HTTP/1.1 HoPOstlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d182.bin0000664000175000017500000000002215232434352021431 06% Dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d609.bin0000664000175000017500000000010515232414252021111 auth?GET /a HTTP/1.1 Host: x Authorization: BasicN libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d120.bin0000664000175000017500000000051515232414252021102 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", cnonce="deadbeef", algorithm=SHA-256, nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response="012347248f0846855de2eeeee282bc3a5fb03b0001234000003000089abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d786.bin0000664000175000017500000000032115232414252021117 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRelm", non,e="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbea", q:op=aut libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d168.bin0000664000175000017500000000001515232434352021437  0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d104.bin0000664000175000017500000000007415232434352021432 ;2Fz:::libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d144.bin0000664000175000017500000000000515232414252020222 (%A8libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d063.bin0000664000175000017500000000003715232414252021107 oundarA 0%&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d724.bin0000664000175000017500000000017515232414252021116 POST /a HTTP/1.1 H6666666="%%NONCE%%" Content-Length: 18446744073709551616 4T / 5 ; 4 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d010.bin0000664000175000017500000000000315232414252020210 @clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d112.bin0000664000175000017500000000010215232414252021073 %GKT 092345678abcdef/a HTTP/1.1 : v.&1 Host: ! libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d009.bin0000664000175000017500000000014015232414252022337 --abcComf"-- -----abc ef" Content-Type: multipart/mixed;b%uboundary=Q@uc -- =c elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d131.bin0000664000175000017500000000006115232414252021103  `/1.1 HoT /a HTTP/1.1 Cookie: a libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d445.bin0000664000175000017500000000006215232414252021114 (&:%4%?12%+Da=&%43 HT%fDa%+Da=&%50 HTTP/1.2 Hlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d103.bin0000664000175000017500000000012415232414252021102 l4POST )/a HTTP/1.2 Transfer-Encoding: chunked Host: x C: abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d016.bin0000664000175000017500000000004315232434352020217 AGET / HTTP/1.0 C&D libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d021.bin0000664000175000017500000000001015232414252021602 r:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d891.bin0000664000175000017500000000174015232414252021122  GET /a H1P/T.T1 Host XGET /a HTTP/1.1 Host: x Authorizatio1 Host: x Authorization: Dige{t usopaque="TP/1.1 Host: xDiname=: y =GET /a HTTP/1.1 Hh, n=00000001, cnonce="deadbeef", algoritm=hSHA-9dd4486210af algorithm6$ response="0123<56789abcdef" alm" response32 4 56788ab="00" @ cd Uf" /aHTTP/1.1y =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000002, cnonce="deadbeef", algoritm=hSHA-9dd4486210af algorithm=SHA-256, response="0123<56789abcdef" alm" response 23456788ab="00" @ cd Uf" /aRealm", nonce="%%NONCE%%", 9fame=: y =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algoritm=hSHA-9dd4486210af algorithm=SHA-256, response="0123<56789abcdef" alm" response 2345$$6788ab="00" Uost: xDiname=: y =GET /a se>libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d254.bin0000664000175000017500000000002315232414252021107 Authorizazio&! libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d033.bin0000664000175000017500000000011415232414252021100 d HPTP/ x:HEAD y 1%69 HTTP/1.0 HTTP/1.1 t-Lngth: 0x5 " ,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d143.bin0000664000175000017500000000026315232414252021107  !tG[ET /a HTTP/1.1 Hos+7ff@++GE%% |GET / HTTP/cnonce="NONCE%%T @/a HT.0@/a HTTP/1.1 go golibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d089.bin0000664000175000017500000000000415232414252020231 2Celibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d381.bin0000664000175000017500000000005015232414252021110 EE1T + HTTP/1.1 HosEAAD libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d492.bin0000664000175000017500000000004115232414252021110 G / HTTP/1.1 Hxot s:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d668.bin0000664000175000017500000000012715232414252021122  GET /a HTTP/1.1 Hos/a HTTP/1. Content-Length: 5 Content-Length: 6 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d372.bin0000664000175000017500000000004715232414252021116 @GET / HTTP/1.1 Hojjj libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d554.bin0000664000175000017500000000014615232414252021120 . FPOS>1T /= HTTP/1.1 Ho~O Cookie: /= HTTP/2.; Hos: x ookie:HEANN`N2 ao10 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d088.bin0000664000175000017500000000011315232414252021111 POST / HTTP/1.1 Host: Transfer-Encoding: chunked 2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d418.bin0000664000175000017500000000005415232414252021115 Conneocti GET0 /a HTTP/1.1 Hst : x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d059.bin0000664000175000017500000000001015232414252021615 `libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d036.bin0000664000175000017500000000000415232414252020221 zzlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d147.bin0000664000175000017500000000047715232414252021122 GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorith.m=SHA-256, response="0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d164.bin0000664000175000017500000000043215232434352020225 uff iGET /aaaaaaaaaaaaaaaaaaaaaaaaaaaaa_aa ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, =QQ=BQlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d367.bin0000664000175000017500000000031615232414252021116 GET /a HTTP/1.1 Host: x GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="000000000000000000000000000000000000000000", uri="/a", response="e" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d135.bin0000664000175000017500000000013515232434352020223  GET /Cff HoTTP1.1 HEAD :Ma_aa HTTP/1.1 Host: x X-Long: aaaD libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d246.bin0000664000175000017500000000034115232414252021110 &GET /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest usernam=-"user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8''0!%1aa0 ,lgoriNOm=SH52-A6, response=126789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d016.bin0000664000175000017500000000000315232414252020216 Rlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d001.bin0000664000175000017500000000000315232414252020210  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d118.bin0000664000175000017500000000000515232414252020223 %aClibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d452.bin0000664000175000017500000000003615232414252021110 uri="~A// 0%&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d070.bin0000664000175000017500000000000615232414252022336 "+=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d870.bin0000664000175000017500000000107515232414252021120 aTS PO/%%NONCE%% HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 4327 ----abc g2: chunkedclose Content-Type: multipart/mixed; boundary=b --  GET /Trailer: a HTTP/1-.1 : valueGETSHA-256 /a HTTP/1~: x =GET iiiiiiiiiii}-Type: multipart/mixed; boundary=b --  GET /Trailer: a HTTP/1-.1 : valueGETSHA-256 /a HTTP/1~: x =GET /a HTTP/1.1 Host: x Aiii"/a", qop=auth, n libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d435.bin0000664000175000017500000000003215232414252021105  a Tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d368.bin0000664000175000017500000000004715232414252021123 iE / HTTP/1.1 OQTJlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d029.bin0000664000175000017500000000001015232414252021661 Basic libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d436.bin0000664000175000017500000000003215232414252021106 t / HTTP/1.I libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d010.bin0000664000175000017500000000003415232414252021074 T . HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d003.bin0000664000175000017500000000000315232414252020212 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d671.bin0000664000175000017500000000013115232414252021107 Y0GET /pafuzz-protocolth?a=/a HTTP/1.1 X: 1 HTTP/1.! Host: x Cookie:a=+b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d245.bin0000664000175000017500000000034115232414252021107 GET /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest usernc=000000once="%%NO/a", username*=UTF-8''a%0010%5F-8''a%0010%56789m=SH52-''a%0010%56789m=SH52-A6, response="0123456789ababcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d042.bin0000664000175000017500000000004415232434352020217 A,iET /Aaaaa%7aaa HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d397.bin0000664000175000017500000000005215232414252021121 HET / HTTP/1.1 uzz-closelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d141.bin0000664000175000017500000000000515232414252020217 a%Elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d376.bin0000664000175000017500000000037215232414252021120 ,4ST / HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 95 ----abc Content1 Content-Disposition: fo-data; name="a"; filename="f" Hos--/1.1 Host: x Con*alue ----abc-- ncodilibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d301.bin0000664000175000017500000000002715232414252021104 r[1r qqlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d210.bin0000664000175000017500000000005215232434352021424 7Aa592a4aQ ET%4QGt: HTTP/1.1 Coe0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d756.bin0000664000175000017500000000024215232414252021116 GET /a HTTP/1.1 Host: x ZGET /a HTTP/1.1 Host: x Authorization: Digest use5rname="aaaaaaaaaaaaaaaaaef", algorithm=boundary=SHA-256, respons libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d057.bin0000664000175000017500000000001615232434352021435 P 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d103.bin0000664000175000017500000000004215232414252021657 Digest algorithm=SHA-512-256-sesslibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d022.bin0000664000175000017500000000001215232414252021073 HTTP/sHTlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d062.bin0000664000175000017500000000004715232414252021112 v?cE! -72P ?a HTTP/1.1 a#bcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d417.bin0000664000175000017500000000005315232414252021113 .uuuuuET /a8%A2b HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d174.bin0000664000175000017500000000003415232414252021112 1d#R0/AutXNjH libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d536.bin0000664000175000017500000000004515232414252021113  HT / HTTP/1.1 Host%u~~~libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d298.bin0000664000175000017500000000002615232414252021122 ?GSlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d216.bin0000664000175000017500000000005515232434352021435 7Aa592a4aQ ET%Q5Gt: HTTP/1.1 Coe0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d075.bin0000664000175000017500000000001615232434352021435 `>TRACE libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d247.bin0000664000175000017500000000031715232414252021117  AD HHTRACEa HTTP/1.1 Cookie: a= "2: a= "; coPT / HTTP/1.1 dchunked+ 6 abgc 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d103.bin0000664000175000017500000000000515232414252020215 %0Dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d067.bin0000664000175000017500000000000615232414252022344 --libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d459.bin0000664000175000017500000000003715232414252021120 HT / HTTP/1.1 HoJBAlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d840.bin0000664000175000017500000000043715232414252021116 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 HOst:"user", realm="Tes="%%NONCE%%a", uri"/a", qop=auth, nc=00000001, cnonce="deadbeGET /a H&TP/1%00.1 Host: x Authorization: Dighst name="user", zealm="SeslosetRealm","ef", algorithm=SHA-256, respone="%%NONCE%%", uri=f" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d218.bin0000664000175000017500000000005515232434352021437 7Aa592a4aQ ET%5QGt: HTTP/1.1 Coe0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d281.bin0000664000175000017500000000002215232414252021106 '/Tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d030.bin0000664000175000017500000000017115232414252021100 &b=%41&cmPOST /a HTTP/1.1 Host: x Content-Type: application/x-www-form-urlencoded Content-Length: 11 a=1&b=%41$clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d106.bin0000664000175000017500000000005115232414252021662 Digest username=,algorithm=MD5,response=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d152.bin0000664000175000017500000000024315232414252021110 r?F0 576 loloF?0bT  ET HEAD / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d004.bin0000664000175000017500000000005415232434352020216 *0GET /upg`?&a=&2 HTTP/1.1 Ha=b %libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d011.bin0000664000175000017500000000000415232414252020212 {GET / HTTP/1.1 Host: x A:::::::::::XNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d260.bin0000664000175000017500000000002015232414252021101 Host: x Blibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d045.bin0000664000175000017500000000000515232414252020222 a%41libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d181.bin0000664000175000017500000000004515232414252021112 <GET /a HTTP/1.1 Huxslibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d713.bin0000664000175000017500000000016315232414252021111 @ABCDE]POST /a HTTP/1.0 Host: 00@0000, ce="deax Transfer-Encoding: chunked ffffffffffffffff libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d078.bin0000664000175000017500000000002115232414252021667 Digest qop="a\!"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d023.bin0000664000175000017500000000000615232414252022334 200alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d269.bin0000664000175000017500000000000615232414252020233 37777libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d002.bin0000664000175000017500000000001015232434352021415  22libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d102.bin0000664000175000017500000000005615232434352020217 AiGE\ /aaaaaaaaaaa%8Caaaaa HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d152.bin0000664000175000017500000000031115232434352020216 uiGET0- /aaaaaaaaaaaaaaaaaaaaaaaPUT aa_aa HTTP/1.1 Host: x X-Long: aaaaaaaaaaaaa / libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d033.bin0000664000175000017500000000000115232414252022330 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d008.bin0000664000175000017500000000000415232414252020220 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d458.bin0000664000175000017500000000003715232414252021117 @>GE /%4 HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d118.bin0000664000175000017500000000002615232414252021111 4acdb ETGET libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d590.bin0000664000175000017500000000002015232414252021107 {raTnunked libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d057.bin0000664000175000017500000000002115232414252021106 a=10 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d009.bin0000664000175000017500000000000515232414252020222 %2Flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d080.bin0000664000175000017500000000001615232414252021615 LLLL`libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d028.bin0000664000175000017500000000002215232414252022337 XY--XY a=1-&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d431.bin0000664000175000017500000000003115232414252021100 T filenam00 HTTP/1; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d487.bin0000664000175000017500000000004115232414252021114 tGET /%Aa HTTP/1.1 Holibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d032.bin0000664000175000017500000000004115232414252021076 T /?A0&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d029.bin0000664000175000017500000000000415232414252020223 a\ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d630.bin0000664000175000017500000000011215232414252021101 @>GET / HTTP/1.1 Host: x Authorization: Basic dXNlcjpwYX== libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d433.bin0000664000175000017500000000003115232414252021102 .realm=""CONNECT a Hglibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d193.bin0000664000175000017500000000003615232414252021112 5%45 %#7/ HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d184.bin0000664000175000017500000000002315232434352021434 QQ2b;bR libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d204.bin0000664000175000017500000000000415232414252020216 4566libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d430.bin0000664000175000017500000000003115232414252021077 r------T HTTP'.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d078.bin0000664000175000017500000000002415232434352021437  #3:BBBlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d554.bin0000664000175000017500000000005015232414252021107 GET /a t %%TT%MD500/ HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d842.bin0000664000175000017500000000045115232414252021114 aTS PO/%%NONCE%% HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 4327 ----abc g2: chunkedclose Content-Type: multipart/mixed; boundary=b Content-Disposition: form-data; name="a" --  GET /Trailer, response="libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d142.bin0000664000175000017500000000022015232414252021077 namePOST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Cont libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d073.bin0000664000175000017500000000001315232414252021614 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d578.bin0000664000175000017500000000036715232414252021133 w4 abcd GETOPTIS * HTTP/1.5 xUUUUU DEG'GET /%CON HTTP/1.1 HP/0st xPOSTOST / HTF+st xP&/ETOST / HTTP/1.1  OP T libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d662.bin0000664000175000017500000000012415232414252021111 @ABCDE]POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 1;ext= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d337.bin0000664000175000017500000000004415232414252021114 GET /a HTTP/1.1 slibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d061.bin0000664000175000017500000000001215232414252021076 ZZZZZZ00libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d451.bin0000664000175000017500000000003515232414252021106 GE / HTTP/1.1 slibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d316.bin0000664000175000017500000000003515232414252021111 '=1&b=2GET "/a x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d086.bin0000664000175000017500000000011515232414252021623   libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d343.bin0000664000175000017500000000016615232414252021113 PRGET /a HTTP/1.1 tho Authorization: Digest usernam, cnonce="deef", algorithm=SHA-512-256-sess, real libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d859.bin0000664000175000017500000000065615232414252021133 WET /a HTTP/1.1 Host XGET /a?b/a HTTP/1.1 H1.1 HGET /a HTTP/2.1 Host: x Authorizationx Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri=/a?b, qop=auth, nc=00000001, cnonce="deadbeef", algorithm=op=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response=/1.1 HTRA/1.1 c89abdfe01def"JU TTP/1.2WET /a HTTP/1.1 Hos//HTT%GEt H TTP/1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d320.bin0000664000175000017500000000011215232414252021075 ET / HTTP/1.1 Host: x Connection: Upgrade Upgrade:c libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d171.bin0000664000175000017500000000003015232414252021103 >F9 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d125.bin0000664000175000017500000000000515232414252020221 %33libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d424.bin0000664000175000017500000000005515232414252021113 ?`./GE / HTTP/1.1 BBBBB#B##1.libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d033.bin0000664000175000017500000000001015232414252021605 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d070.bin0000664000175000017500000000000615232414252020221 XW,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d837.bin0000664000175000017500000000043315232414252021120 GET /a HTTP/1.1 Host: x) =GET a HTTP/1.1 Host: x Authorization: Digest useUpgrade: rname-"user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8'', realm="TestRealm", nonce="%%NONCE%%", a%001%378044m=SH52-A6, response="0123456789ab456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d484.bin0000664000175000017500000000004115232414252021111 =GEt %2n HTTP/1.1 Ht:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d173.bin0000664000175000017500000000000315232414252020222 alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d036.bin0000664000175000017500000000024615232434352020226 1&GlEr/eT m=%net0cionuade0t`?%++nonce;ext="qqqqqqqqqqqqqqqq="0000"m=%net0cionuade0t`?%++b&cet0cionua5 HTTP/1.1 Ha=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d875.bin0000664000175000017500000000177215232414252021131  GET /a HTTP/1.1 Host XGET /a HTTP/1.1 Host: Ax uthorContent-Length: 18446744073709551615 t usopaque="erst x7d2aaa32CE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algoritm=hSHA-9dd4486210af 777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777gost:7777777777777777rithm=SHA-256, response="0123<56789abcdef" alm" responoe 23456788ab=: y =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000202, cnonce="deadbeef", algoritm=h777777777777777777777777777gost:7777777777777777rithm=SHA-256, response="0123<56789abcdef" alm" responoe 23456788ab=: y =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", q4486210af algorithm=SHA-256, response="012close89abcde" alm" response 1 Host: x Authorization: Basic dXNlcj0wXNz GET /a HTTP/1on: Basic dXNlcj0wXNz GET23456788ab="00" =e>libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d504.bin0000664000175000017500000000011015232414252021102 B'r/%+20%42ET /%+20%42?a&&&&&&&&&&&&&&&&&&&&&&&&0P HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d482.bin0000664000175000017500000000010115232414252021107 /GET /a HTTP/1.1 Host: x Connection: c se libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d269.bin0000664000175000017500000000002015232414252021112 Coec|ionc|r libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d538.bin0000664000175000017500000000004615232414252021116 0 GEt %3A? HT% HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d318.bin0000664000175000017500000000003615232414252021114 @GET HTTP/0.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d067.bin0000664000175000017500000000001015232414252021614 CCClibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d350.bin0000664000175000017500000000021215232414252021101  |GET / HTTP/1.1 Host: x Connection: Upgrade Upgrade: fuzz-protocol Content-Length: 0 Transfer-Encoding: chunked 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d133.bin0000664000175000017500000000000515232414252020220 #%0Dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d330.bin0000664000175000017500000000012215232414252021077 @ABCDE]POST /a HTTP/1.0 Transfer-Encoding: chunked 2;ext AB 3;a= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d357.bin0000664000175000017500000000004615232414252021120 GET /a% 5b HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d565.bin0000664000175000017500000000005315232414252021114 0GET /path?+a=[1C HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d548.bin0000664000175000017500000000004715232414252021120 GET /?++* HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d284.bin0000664000175000017500000000004115232414252021107 T %41/bt&T %41/ HTTP/1.1 TTPlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d113.bin0000664000175000017500000000002415232414252022334 ~ -- e libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d047.bin0000664000175000017500000000001015232414252022335 -%2b&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d676.bin0000664000175000017500000000013515232414252021120 POST /a HTTP/1.1 Hlst: uri="t-Type: m;cabc Transfe-r--coding: chunke? 42 - libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d151.bin0000664000175000017500000000030315232434352020216 uiGET-2.5.29opaque="Bearer /aaaaaaaaaaaaaaaaaaaaaaaaaaaaa_aa HTTP/1.1 Host: x Xype: aaaaaa libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d005.bin0000664000175000017500000000001615232434352021426 ;#::libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d087.bin0000664000175000017500000000002615232414252021674 Digest algorithm="\"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d117.bin0000664000175000017500000000002615232414252021110  R - T libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d115.bin0000664000175000017500000000007515232434352020224 EuiGET /aaaaaaaaaaaaaaa%MD297aaaa_aa HTTP/1.1 iE/, libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d019.bin0000664000175000017500000000006015232434352020221 )GETp1 =b HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d253.bin0000664000175000017500000000014215232414252021105  GET /a HTTP/1.1 Host GET /a HTTP/1.1 Host XGET /a HTTP/1.1 X libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d247.bin0000664000175000017500000000024315232434352021440 "1Q :@22$@1::::::::::::::::::::::::::::::::::8:>::::::::::::::$1@:::::Q :@22$@1:::::::::::::::::::::::::::::::8:>::>:::::::::::::::1@:: :::212libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d111.bin0000664000175000017500000000002115232414252022327 a"b--a"b f libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d176.bin0000664000175000017500000000004115232414252021112 vc! -34ST /a HTTP/1.4 vlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d422.bin0000664000175000017500000000002415232414252021102 ?LQwx libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d078.bin0000664000175000017500000000007215232414252021117 GET /a HTTP/1.1 Cookie: a= t: $ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d111.bin0000664000175000017500000000015715232414252021665 BMD5-sessue*r:r:KKKKKKKKKUKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKSHA-512-256 R"alm:passlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d523.bin0000664000175000017500000000004515232414252021107 T%d0 %d0 HTTP/1.1 00de:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d849.bin0000664000175000017500000000052615232414252021126 POST /a%%NONCE%% HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 4327 ----abc g2: chunkedclose Content-Type: multipart/mixed; boundary=b -- =iiiiiiiiiiiiii&t: x iiiiiiiiiiiiiiiiiii=auth, n libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d146.bin0000664000175000017500000000022015232434352020220 AiGET /aaaaaaaaaaaaaaaaaaaaaaaaaa HTTP/1.1 H$ost: x X'Long: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 444444444444444444a 44444444444444 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d029.bin0000664000175000017500000000003715232434352020226 (GET / HTTP/0.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d544.bin0000664000175000017500000000004615232414252021113  HTTP/2.T /%BBBBBBB HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d339.bin0000664000175000017500000000014315232414252021113 D0:TQ /closepath?a=1C HTTP/1.1 Host: x Content-Length: 18446774043709551615f libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d118.bin0000664000175000017500000000001115232434352021426 AO libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d239.bin0000664000175000017500000000013615232434352021442 bP$bP$ 0~ HTNRCE222bP$bP$ 0~ HTNRCE222libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d042.bin0000664000175000017500000000002115232414252021656 Digest qop="a\u"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d397.bin0000664000175000017500000000001515232414252021115 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d000.bin0000664000175000017500000000001215232414252021067 Tdra xlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d114.bin0000664000175000017500000000003215232414252022334 XY --XY nohe -- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d491.bin0000664000175000017500000000010315232414252021111 ET /a HTTP/1.1 Host: Host: x Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d116.bin0000664000175000017500000000002415232414252021105 [E/a)Zr8M libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d414.bin0000664000175000017500000000005315232414252021110 ~}E/aGT -rrr=%86 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d412.bin0000664000175000017500000000005315232414252021106 <T /a HTTP/1.1 Htxs:o libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d219.bin0000664000175000017500000000000515232414252020225 7355libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d191.bin0000664000175000017500000000004715232414252021115 uuuET /a8%A2b HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d001.bin0000664000175000017500000000000515232414252021604 slibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d288.bin0000664000175000017500000000004215232414252021114 ?+T /a HTTP/1.1 a b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d235.bin0000664000175000017500000000021615232414252021107 t: x GET / HTTP/1.1 Host: x Authorization: Digest username="userstRealm", uri= /a?~b!HTT0onse="00A,opaque=" uri= /a?bn0" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d022.bin0000664000175000017500000000000315232414252020213 D=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d085.bin0000664000175000017500000000002515232414252021671 Digest algorithm=MDlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d284.bin0000664000175000017500000000000715232414252020231 ,2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d032.bin0000664000175000017500000000001315232414252021656 Digest nc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d696.bin0000664000175000017500000000015115232414252021120 ncone=;;;;;;;;;;;"ET / HTTP/1.1 Host: alm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d516.bin0000664000175000017500000000011515232414252021112 FPOST /a HTTP/1.0 Host: x Transfer-Encoding: chunked 6 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d170.bin0000664000175000017500000000001515232434352021430 1C20libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d561.bin0000664000175000017500000000005115232414252021106 ff @>G / HTTP/1.1 Ung: chlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d413.bin0000664000175000017500000000005315232414252021107  <GET SBD / HTTP/1.1 T libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d650.bin0000664000175000017500000000012015232414252021102 d HPTP/1.1 X: y %69 HTTP/1.1 Host: xa HPTP/0.1 X libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d573.bin0000664000175000017500000000005715232414252021117 ion: Basic % E546&b HTTP/1.0 $ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d570.bin0000664000175000017500000000023115232414252021111 B7r0GET /a HTTP/1.1 Cۦ&?e=%4@&HT%4@? =HTTP/1.1 Cookie: a=" @xp;GGR9e=%4@AuthmrTP/1.1 CoQD s :x @bcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d126.bin0000664000175000017500000000004615232414252021112 R/T /a HTTP/1.2 Ho libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d062.bin0000664000175000017500000000003315232414252021102 0 HTTP/1.1 & libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d761.bin0000664000175000017500000000025515232414252021116 GET /a HTTP/1.1 Hostost: xtho|izatiaaaaa0aaaaaaupgradeaaaaaaaaaaaost Authorization: Digest usame="aaaaaaaaaaaaaaaa?a"0, cnonce="deadbeef", algori= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d785.bin0000664000175000017500000000032115232414252021116 ( XGET /a HTTP/1.0 Host: x Authorization: Digest username="aaFa/E1aTaailenameaaaaaaaaaaaLETE 555555aaafilenameaaaa", userhash=true, rea, nc"%e%NON"nclgorith+=SHA-4x 56, resp/1.0="0123489abcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d750.bin0000664000175000017500000000024115232414252021107 GET /a HTTP/1.1 Hgst: x XGET /a HTTP/1.1 Host: x Authorization: Digest username=adeadbeef", algorithm=SHA-12cr ,e8splose"0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d003.bin0000664000175000017500000000001115232414252022326 6 -- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d135.bin0000664000175000017500000000001215232434352021426 #^3 Mlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d062.bin0000664000175000017500000000001315232414252021661 Basic 1QQ=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d059.bin0000664000175000017500000000012415232434352021437 ,-40[02222@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d127.bin0000664000175000017500000000015215232414252022343 --abcConype:  ----abc ef" Content-Type: multipart/mixed;bouboundary==c -- M e;f" -- mlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d520.bin0000664000175000017500000000004415232414252021103 a H/1 X: @@@@'%68 HTTP/1.1 HHlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d767.bin0000664000175000017500000000026315232414252021123 namePOST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Coosi#t value --- ----ab1 1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d272.bin0000664000175000017500000000000615232414252020225 %C755-libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d195.bin0000664000175000017500000000000315232414252020226 4libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d001.bin0000664000175000017500000000023215232434352020211 AiGET /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa HTTP/1.1 H$ost: x X'Long: aaaaaaaaaaaaaaaaaaaaaaaaaa 5864589%4aaaaa44444444444444444444444444444 POST libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d087.bin0000664000175000017500000000037715232414252021124 /GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", a\lgorithm=SHA-256, response="0123456789abcd89aabcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d119.bin0000664000175000017500000000046115232414252021112 GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaaaaa\aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TestRealm", nonce="%%%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response="012" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d305.bin0000664000175000017500000000010215232414252021077 ET / HTTP/1.1 Host: x Authorization: Basic z libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d129.bin0000664000175000017500000000011515232434352020224 AiGET /aaaaaaaa?aaaaaa HTTP/1.1 Hot: x X-Long:aaaaaaaaat-Type: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d697.bin0000664000175000017500000000015115232414252021121 @ABCDE]P_ST0 /a HTTP/1.1 Expect:POST /aonue Host: x Transfer-Encoding: chunked 2;ext= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d045.bin0000664000175000017500000000000515232414252021614 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d440.bin0000664000175000017500000000006115232414252021106   P0 ! /a HTTP/1.1 nectio close libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d295.bin0000664000175000017500000000001215232414252020227 a\hDR, ==libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d060.bin0000664000175000017500000000024115232434352020216 .A ET /aaaaaaaaaaaaaaqaaaaaaaaaaaaaaaaa HTTP/1.1 Host:Conteaaaaaaaaaa%aaaaaaaaaaaaa HTTP/1.1 Host: x X-Lobount/form-dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d056.bin0000664000175000017500000000014615232434352020227 0GET /path?a=1 HTTP/1.1 H: x Cookie: a=b ; ****** libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d427.bin0000664000175000017500000000002615232414252021111 GET . 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d038.bin0000664000175000017500000000001215232434352021430 : 55 $libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d253.bin0000664000175000017500000000002015232414252021103 ,;HTTP/1.1 /libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d081.bin0000664000175000017500000000010215232414252021100 0GET /patah?1= HTTP/1.1 Host: Cookie: a=; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d075.bin0000664000175000017500000000004215232434352020223 UGET / HTTP/1.1 grM  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d646.bin0000664000175000017500000000011715232414252021115 T / HTTP/1.1 Host:: 0 Transfer-Encoding: chunked 0 name libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d125.bin0000664000175000017500000000004615232414252021111 0HEAD HTTP/1.2 mkib libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d236.bin0000664000175000017500000000012415232434352021434 7a5927a4aQ Q%0888888888888888888888888818Gt: HTTP/1.1 Cookie:;cnonpa=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d173.bin0000664000175000017500000000001515232434352021433 26 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d227.bin0000664000175000017500000000000515232414252020224 %c\libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d160.bin0000664000175000017500000000002015232414252021100 [n߿ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d011.bin0000664000175000017500000000006115232434352021423 7a592754U ETQ0Gt: HTTP/1.1 Cookie:;a=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d751.bin0000664000175000017500000000024115232414252021110 GET /a HTTP/1.1 Hgst: x XGET /a HTTP/1.1 Host: x Authorization: Digest username=adeadbeef", algorithm=MD5-sess ,e8splose"0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d150.bin0000664000175000017500000000002015232414252021074  HTTP1.1 ilibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d592.bin0000664000175000017500000000007715232414252021122 %GMT /a HTTP/1.1 : value % Hostvalue % Host:: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d457.bin0000664000175000017500000000006615232414252021123 1.1 0b H0/GET /a HTTP/1.1 Host: x Connecti0.1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d048.bin0000664000175000017500000000000215232414252021663 eglibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d447.bin0000664000175000017500000000003515232414252021113 900/Gt %9X HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d551.bin0000664000175000017500000000004715232414252021112  /g HTTP/1.1 MD5 &libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d133.bin0000664000175000017500000000006615232414252021112 v?cG! 171HEAD / HTTP/1.1 st: P: t: nba llibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d384.bin0000664000175000017500000000630715232414252021123 upgradeGET POST2222222222222GET /a HTTP/1.1 Host: x %=POST2222222222222222222222222222&22222222222222222 &/ETgET /%c82% HTTP/1.1 HHostPplibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d170.bin0000664000175000017500000000017115232414252021105 41&cmPOST /a HTTP/1.1 Host: t Content-Type: application/x-www-form-urlencoded Content-Length: 02 =1a~=b1%4&clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d030.bin0000664000175000017500000000006215232414252022334 --abc ----abc Content-Disposition: forbc-- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d143.bin0000664000175000017500000000012615232414252021110  * F-EAD /a HTTP/1.1 Host: x Transfer-Encoding: chunked 6 GET / libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d521.bin0000664000175000017500000000012215232414252021104 pPFPOSpT /a HTTP/1.1 Host: x Transfer ncoding: chu libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d263.bin0000664000175000017500000000002015232414252021104 +Uon:Tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d547.bin0000664000175000017500000000004615232414252021116 ]0t:GET %08/a HTTP/1.1 TT libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d068.bin0000664000175000017500000000003415232434352020226 AGT /a HTTP/1. libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d285.bin0000664000175000017500000000004215232414252021111  G / HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d125.bin0000664000175000017500000000011115232434352020214 A<POST /a HTTP/1.1 Host: x Content-Length: 11 hello worldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d332.bin0000664000175000017500000000004315232414252021106 [?cE!6 -14POST /a ?cE!-1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d455.bin0000664000175000017500000000003615232414252021113 UGET / HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d220.bin0000664000175000017500000000005515232434352021430 7Aa592a4aQ ET%Q9Gt: HTTP/1.1 Coe0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d023.bin0000664000175000017500000000004315232414252021100 RGET / HTTP/1.0 e=" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d000.bin0000664000175000017500000000000315232414252020207 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d204.bin0000664000175000017500000000004415232414252021102 GET HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d000.bin0000664000175000017500000000000515232414252022326 -rmlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d385.bin0000664000175000017500000000005015232414252021114 GT /a%b00 HTTP/1.1 Holibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d533.bin0000664000175000017500000000004515232414252021110 [U GET /%92 HTTP/1.0 $ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d089.bin0000664000175000017500000000001015232414252022343 %%-D&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d116.bin0000664000175000017500000000003615232414252022342 a"b --a"b v --a"b-- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d024.bin0000664000175000017500000000010015232414252021073 UT /a HTTP/1.1 Host: x Content-Length: 8 hellolibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d102.bin0000664000175000017500000000006415232434352021427 7a59275a4a2@_@2Q ETQ%0Et: HTTP/1.1 pa=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d194.bin0000664000175000017500000000004215232434352021436  TRACE 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d012.bin0000664000175000017500000000031715232434352020217 =GET /= HTTP/1.1 Host: }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d185.bin0000664000175000017500000000001515232414252021110 H>>>>> libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d679.bin0000664000175000017500000000013615232414252021124 ET / HTTP/1.1 Host: x Connection:closeadupgrade Upgrade: chunked 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d097.bin0000664000175000017500000000003515232414252021675 Digest algorithm=MD2urr=alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d022.bin0000664000175000017500000000014015232434352020212 A<POST /a HTTP/1.1 Host: -----BEGIN PKCS12x Content-Length: 12 TP/1.1 Husv:sldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d164.bin0000664000175000017500000000000315232414252020222 cblibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d731.bin0000664000175000017500000000020615232414252021107  GET /a] HTTP/1.1 Host: x Authorization: Digest username="user", realm=ce="000000000008POT00", uri=," a"e/rsponse="e" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d770.bin0000664000175000017500000000027415232414252021117  |GET / HTTP/1.1 Host: x Connection: UCCFFFFFFFFFFFFCCCCCFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d880.bin0000664000175000017500000000745515232414252021131 POWET /a HTTP/1&1 Host XGET /a HTTP/1.1 H X(G1T /a HTTP/1.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host;a=1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H]]]]]]]]]]]]]]]]]]]]]]]]] X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRACE X(G1T /a HTTP$1.2WET /a HTTP/1.1 Host XGET /a HTTP/1.a HTTP/1.1 Host: x Auth Diges 32456787abcPATCH c=nnection: u HTTP/1.1 Host XGET /a : u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRACE X(G1T /a HTTP$1.2WET /a HTTP/1.1 Host XGET /a HTTP/1.a HTTP/1.1 Host: x Auth Diges 32456787abcPATCH c=nnetion: u HTTP/1.1 Host XGET /a HTTP/CH c=nnection: u HTTP/1.1 Host;a=1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRACE X(G1T /a HTTP/1.2WET /a HTTP/1.1 Host XGET @HTTP/CH c=nnection: u HTTP/1.1 Host;a=1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456774abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HvvvvTRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host;a=1;b=2;c X(G1T /a HTTP/1.1 Host: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H]]]]]]]]]]]]]]]]]]]]]]]]] X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 H#TRACE X(G1T /a HTTP$1.2WET /a HTTP/1.1 Host XGET /a HTTP/1.a HTTP/1.1 Host: x Auth Diges 32456787abcPATCH c=nnection: u HTTP/1.1 Host XGET /a : u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 Ht: x Auth Diges 32456787abcc=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRATRACE X(G1T /aG[ET$/a.2WET /a HTTP/1.1 HoaG[ET$/a.2WET /a HTTP/1.1 Host XGET /a HTTP/1.1 H X(G1T /abcPATCH c=nnection: u HTTP/1.1 Host XGET /a HTTP/1.1 HTRACE X(G1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d157.bin0000664000175000017500000000003715232414252021113 #GET /Q HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d021.bin0000664000175000017500000000000315232414252020212 \libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d098.bin0000664000175000017500000000001015232414252022343 %E4&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d053.bin0000664000175000017500000000001015232414252021607 ''libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d492.bin0000664000175000017500000000010315232414252021112 v?cE! -35POST /a HTTP/1.1 Host: Content-Length: 8 abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d062.bin0000664000175000017500000000001215232434352021425 b$ (Xlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d301.bin0000664000175000017500000000005315232414252021100 GET /a HTTP/1.1 Cookie: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d323.bin0000664000175000017500000000004015232414252021103 /AET / HCONNECT / T/a libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d077.bin0000664000175000017500000000002115232414252021666 Digest userhash=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d073.bin0000664000175000017500000000004515232414252021112 ETP/OST / HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d094.bin0000664000175000017500000000001015232414252022337 &b=%&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d773.bin0000664000175000017500000000027615232414252021124 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Content-Disposition: form-data; name="k" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d247.bin0000664000175000017500000000000515232414252020226 !%4Alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d032.bin0000664000175000017500000000001015232414252021604 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d196.bin0000664000175000017500000000004315232434352021441 7Ac592Q ET%Q1Gt: HTTP/1.1 C0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d579.bin0000664000175000017500000000006515232414252021124 +GET /a HTTP/1.1 Hos X-Fold: a b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d091.bin0000664000175000017500000000000415232414252020222 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d572.bin0000664000175000017500000000005715232414252021116   XGET /a HTTP/1.1 s1 1 XGlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d032.bin0000664000175000017500000000000315232414252020214 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d781.bin0000664000175000017500000000031615232414252021116 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Ca THTP/1.1 Host: x Content-Type: multipar"/form ----abc-- / libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d159.bin0000664000175000017500000000004215232414252021111 pOST /a HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d081.bin0000664000175000017500000000003615232434352021434 _$>> >>>?;1@ ? Z 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d059.bin0000664000175000017500000000004315232414252021114 0GET /a H0ST / HTTP/1.1 xlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d155.bin0000664000175000017500000000002015232414252021104 CoCon-Ln;:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d058.bin0000664000175000017500000000001315232414252021666 Basic ====libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d057.bin0000664000175000017500000000000315232414252020223 %libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d375.bin0000664000175000017500000000035715232414252021122 7 XGET /a HTTP/1.1 Host: x Authorization: Digest usernam1="aaaaa", userhash=true,username*=UTF-3''a, nA=SHA XGET /a HTTP/1.1 Host: x Authorization: Digest usernam1="aaaaa", userhash=true,username*=UTF-3''a, nA=SHA56 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d033.bin0000664000175000017500000000007315232414252021107 r?F9 "/GET -a HTTP/1.0 Connection:sgth,E0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d243.bin0000664000175000017500000000000515232414252020222 "%%%Clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d022.bin0000664000175000017500000000001315232414252021655 Digest nc,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d229.bin0000664000175000017500000000017215232414252021113 mOST /a HTTP/1.1 Host: x Content-Type: application/x-www-form-urlencoded Content-Length: 11 %1&clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d220.bin0000664000175000017500000000013515232414252021101 @ABCDE]Pqop=OT /a HTTP/1.1 Host: x Transfer-Encoding: chunked 3;eP AB 4;a Rlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d508.bin0000664000175000017500000000004315232414252021110 Upgrade: GET /a HTTP/1.1 UcWWHlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d065.bin0000664000175000017500000000004015232434352021431 ,  5libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d348.bin0000664000175000017500000000004515232414252021117 ~`G`T /a HTTP/p.1 Hostlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d062.bin0000664000175000017500000000033215232434352020221 !-----BEGIN DH PAEETMAS㌌PPPPPPPPPPPPPPPPPPPPPPPPPPPPP#PPPP Co,telibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d131.bin0000664000175000017500000000012015232434352020211 AGET /a HTTP/1.1 Host:Host: x Connection: cl0ose libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d028.bin0000664000175000017500000000000515232414252021615 *libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d226.bin0000664000175000017500000000012215232414252021106  F*O]T /a HTTP/1.0 Host: x Transfer-Encoding: chunked 0o libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d068.bin0000664000175000017500000000006415232434352021442 8a592754Q ET0G:: HTTP/5.1 Host: x Cookieb 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d145.bin0000664000175000017500000000014015232414252021106 B'r0/%+20ET / HTTP/1.1 t a2os: x ]#HT0.1 Cookie: a=;b GA ajcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d603.bin0000664000175000017500000000010215232414252021100  @>GET / HTTP/1.1 Host: x htriozation: Basic dNlcjp libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d040.bin0000664000175000017500000000002015232414252021653 Digest nc =,nc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d175.bin0000664000175000017500000000021115232414252021105 GET / HTTP/1.1 Host: GET /aResp/0.0="0123489abcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d148.bin0000664000175000017500000000001215232414252021104   1tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d098.bin0000664000175000017500000000007715232414252021126 [?cE! -34POST /a HTTP/1.1 Host: x+ Co: 4 abcdE!libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d383.bin0000664000175000017500000000240315232414252021113 aTS PO/%%NONCE%% HTTP/1.3 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 4327 ----abc g2: chunkedclose Content-Type: multipart/mixed; boundary=b -- GET /Trailer: a෫.1 : value85ec20000000002e010123456789abcab234cbdec9d3abec1229876c4a85ec799cab234cbdec9d3abec1229876c4e4fe9d1c76c4a85ec799aeb95c4bb970e9f456789a44444444444444444444444444444444444444444444444444444444ec1229876c4a85ec20000000002e010123456789abcab234cbdec9d3abec1229876c4a85ec799aeb95c4bb970e9f456789abcab234cbdec9d3abec1229876c4e4fe9dba0d420000000002e010123456789abcab234cbdec9d3ab44444444444444444444444444444444444444444444444470e9f456789abcab234cbdec9d3abec1229876c4e4fe9d1c76c4a85ec799aeb95c4bb970e9f456789abcab234cbdec9d3abec1229876c4e4fe9d1c5ad8a5e1c76c4a85ec799aeb95c4bb970e9f456789abcab234cbdec9d3abec1229876c4e4fe9d1c5ada85ec799aeb95cdf6794df335671de8c1dee59e333dc1458895ada85ec799aeb95cdf6794df335671de8c1799aeb95c4bb970e9f456789abcab234cbdec9d3abec1229876c4e4fe9d1c76c4a85ec799aeb95c4bb970e9f456789abcab234cbdec9d3abec1229876c4e4fe9d1c5ada85e1c76c4a85ec799aeb95c4bb970e9f1dee59e333dc1458895ada85ec799aeb95cdf6794df335671de8c1dee59e3338a522824d426019c4e30b58b1fd0c4d2688eea9f8f0fb3b67bbb10528-8''a%001%378044m=A6, response="libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d396.bin0000664000175000017500000000005215232414252021120 0'GET /%41%a=;43 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d140.bin0000664000175000017500000000041015232414252022333 boundary=--abc --&%41&&W%41e="k"; filename&&="f" Content-Type: tex)/plain &c ?value ----abc-abc --&%41&&W%41-- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d034.bin0000664000175000017500000000000415232414252020217 Ulibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d315.bin0000664000175000017500000000003315232414252021106 GPOST - T / : libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d543.bin0000664000175000017500000000013315232414252021112 F*O-ST /a= HTTP/1.1 Host:d x Transfer-Encoding: chunked 3 abc 0e libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d395.bin0000664000175000017500000000005215232414252021117 & @/G / HTTP/1.0 Hgggggggg libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d152.bin0000664000175000017500000000001315232434352021426 !&!F2FrFlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d112.bin0000664000175000017500000000002315232414252022332 --abc----abc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d341.bin0000664000175000017500000000004415232414252021107 GET /a HTP/1POST / HTTP/1.1 .1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d211.bin0000664000175000017500000000000415232414252020214 a%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d734.bin0000664000175000017500000000021215232414252021107 56-sessmm0GET /patah?1= HTTP/1.1 Host: x C x Cookie:-a=b; %  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d033.bin0000664000175000017500000000015215232434352020217 1&GlEr/eT m=%net0cionuade0t`?%++nonce="0000/a?b&c5 HTTP/1.1 Ha=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d126.bin0000664000175000017500000000001215232434352021426 .3<libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d322.bin0000664000175000017500000000004015232414252021102 <<GET / HTTP/1.1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d187.bin0000664000175000017500000000002615232434352021442 $EA303::(((libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d061.bin0000664000175000017500000000004515232414252021107 oR 3lGET / HTTP/1.1 P libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d695.bin0000664000175000017500000000015015232414252021116 nameGET /a HTTP/0.1 Host: xX GET /a HTTP/1.1 Host: x Authorization: Digest Digestn: ea libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d064.bin0000664000175000017500000000001615232434352021433  3libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d078.bin0000664000175000017500000000004315232434352020227 AGET /a HTTP/1.1 HoY libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d711.bin0000664000175000017500000000016215232414252021106  |GET / HTTP/1.1 Host: x Coicnnteon: Content-Length: 0 Transfer-Encoding: chunked 0 - HTTP/1. libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d156.bin0000664000175000017500000000001415232434352021433 ''Q2 ''''libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d114.bin0000664000175000017500000000027715232414252021673 fffus@\"bfrononce="0 SHA-512-256-sess\"bfrononce="0000"bnicate=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d539.bin0000664000175000017500000000013215232414252021116 PpPOST G2ET HTTP/1.1 Host: x Transfer-Encoding: chunked 3 ab11FFFFc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d389.bin0000664000175000017500000000011015232414252021112 $GET /a HTTP/1.1 Host: x GET /a HTTP/1.1 Host:, non libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d846.bin0000664000175000017500000000050315232414252021116 Upgrade: GET /ae50e445b9f5e6edb1e74bce79c6cc974668bab022497626ae771c43cd9e01927 HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE0000000000a167aaaaaACEa", userhash=true, realm="TmstRealm", nAuthorizatioHA-971,POST response="0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d088.bin0000664000175000017500000000004315232414252021116 B'rGET T%4D HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d179.bin0000664000175000017500000000004515232414252021121 @GET /a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d655.bin0000664000175000017500000000012115232414252021110 ]GET /?a=1&bb48517d384214f6964c047b44fb5a7d0b9aeaa539997c HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d623.bin0000664000175000017500000000011215232414252021103 T;POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked dExqqlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d093.bin0000664000175000017500000000000415232414252020224 ndElibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d231.bin0000664000175000017500000000013215232414252021103 =E/a)Zr ? TEa /G%03b HTTP/1.1 KKKK Transfer-Encoding: chunked FFFFFFFFFFFFFFFFlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d115.bin0000664000175000017500000000030215232414252021661 چ1auth,auth-intesehauser n="srrealm=stR""RRRRRRRRRRRRRR'RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR"Rlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d549.bin0000664000175000017500000000004715232414252021121 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d132.bin0000664000175000017500000000012715232434352020221 AiGET /aaa`aaaaaaa-----BEGIN DH PARAMETERSaaaaaaaaaaaa[aaa HTTP/1.1 Host: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d112.bin0000664000175000017500000000015015232434352021424 7a59275a4aQ EQ0tTG: HTTP/1.1 Ht: x Cookie: cno= LL2+ L 2] & $~ b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d040.bin0000664000175000017500000000002015232414252021075 Hs: x o s olibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d593.bin0000664000175000017500000000002015232414252021112 H`PEE0TQA;libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d072.bin0000664000175000017500000000001315232414252021613 ,,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d506.bin0000664000175000017500000000004215232414252021105 T 1?%/B&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d511.bin0000664000175000017500000000011515232414252021105 F POST /a HTTP/1.0 Host: x Transfer-Encoding: chunked 9 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d093.bin0000664000175000017500000000001615232434352021435 #0*06 @2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d688.bin0000664000175000017500000000014415232414252021123 +GT /a HTTP/1.1 Host: x %+GT //2.1 Hos b Content-Length: 5 Content-Length: 3 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d355.bin0000664000175000017500000000024715232414252021116 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 --t-Dis>posk" value ----abc-0- 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d515.bin0000664000175000017500000000011515232414252021111 FPOST /a HTTP/1.0 Host: x Transfer-Encoding: chunked 7 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d489.bin0000664000175000017500000000004115232414252021116 AGE /+AGET /%5a HTTP/1.1 Holibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d144.bin0000664000175000017500000000013015232414252021104 FPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 3 abc 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d218.bin0000664000175000017500000000010615232414252021111 v?cE! -34POST /a HTTP/1.1 Host: x Content-Length: 3 abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d065.bin0000664000175000017500000000000515232414252020224 @%90libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d816.bin0000664000175000017500000000037515232414252021122 Upgrade: GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aa1----------------------------------------------aaaaaaaaaaaa", username*=UTF-8''auaaaaaaaacaaaaaaaaaa", us56, response="01012345aaaacdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d063.bin0000664000175000017500000000001615232434352021432 A1A3libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d774.bin0000664000175000017500000000030115232414252021112 ;POST /a TTHPnam close qqqqqqqqlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d219.bin0000664000175000017500000000005515232434352021440 7A[92a4a ET%8Q6Gt: HTTP/1.1 Ce0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d216.bin0000664000175000017500000000011115232414252021100 @hello5POST /a HTTP/1.1 Host: x Content-Length: 5 hellolibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d069.bin0000664000175000017500000000001615232414252021673 Digest nonce;libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d217.bin0000664000175000017500000000011415232414252021104 t: x GET / HTTP/1.1 Host: x Authorization: Digest uri,="ne0 r libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d419.bin0000664000175000017500000000002315232414252021107 2PUT libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d117.bin0000664000175000017500000000030415232414252021104 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 437 ----abc g2: chunked Content-Type: multipart/mixed; boundary=b ---libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d070.bin0000664000175000017500000000001715232414252021664 basic QDigestlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d085.bin0000664000175000017500000000030715232414252021113 PpFGET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 = Authorization: Digest username="us\r", realm="TestRealm", nonce="%NONCE%%", uri="/a", m=SHA-256, response="01234cdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d685.bin0000664000175000017500000000014315232414252021117 %;_POST /a HTTP/1.1 Content-Length: 5 Content-Length: 6 ww-forgta: 22 a=& a=&9/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d511.bin0000664000175000017500000000004315232414252021102 bc&1=ST HTTP/1.1 tte6t-Riclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d488.bin0000664000175000017500000000010315232414252021117 QET /a HTTP/1.1 Cookie: a=b G&&&&H; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d056.bin0000664000175000017500000000000515232414252020224 /%D2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d282.bin0000664000175000017500000000000615232414252020226 bCeClibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d700.bin0000664000175000017500000000015415232414252021105 dGET / HTTP/1.1 Host: x Authorization: Digest userhash=true, username="aqbb", realm="Tealm" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d068.bin0000664000175000017500000000001315232414252021620 YVVVV^zVVlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d352.bin0000664000175000017500000000022515232414252021107 ,POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 51 ----abc Contentӻ ncodilibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d138.bin0000664000175000017500000000030015232414252022340 --abcCoQ@ultipaf "-- ----abc " Content-Type: multipart/mixed;bouboundary=Q@- Content-Disposition: attachment; filename="f" tnamPpp -- ef -"k" va -- libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d121.bin0000664000175000017500000000010615232434352020214 A<POST /a HTTP/1.1 Hsot: x ContenTGEength:1 hello worldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d485.bin0000664000175000017500000000004115232414252021112 G /a HTTP/1.1 DDD libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d335.bin0000664000175000017500000000004415232414252021112 GET /a HTTP/1.1 Ho4libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d193.bin0000664000175000017500000000000315232414252020224 Rulibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d535.bin0000664000175000017500000000004515232414252021112 HTT1.P T//%C%% HTTP/1.1 Hoslibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d049.bin0000664000175000017500000000010415232434352020223 qqqdGET / HTTP/1.1 HoJJJHtso: x Cookie: a= HTTP/2.0b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d197.bin0000664000175000017500000000005015232414252021115 GGE /%83;%43 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d839.bin0000664000175000017500000000043515232414252021124 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000000, cnonce="deadbeef", algorithm=SHA-256, response="0123456789abcd89abcdef0123456789abcdef0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d018.bin0000664000175000017500000000003515232434352020222 :GE/ HTTP/1.1 glibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d707.bin0000664000175000017500000000015715232414252021117 2222222222222222222222222 EAD / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d084.bin0000664000175000017500000000022015232414252021104 close |GET / HTT--Connection: close 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d852.bin0000664000175000017500000000054315232414252021117 !GET /a HTTP/1.1 ash=true, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaast: x Authorization: %4 XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NONCE%%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqaaaaaaost: x Xtioaaaaaaaa Digest us libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d221.bin0000664000175000017500000000005515232434352021431 7Aa592a4aQ ET%3QGt: HTTP/1.1 Coe0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d729.bin0000664000175000017500000000020015232414252021110 G@AJCDE]POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 0;ext=val AB 3b;c"/a?bE 07 % 0 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d194.bin0000664000175000017500000000004715232414252021120 `GET /a H NS * HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d074.bin0000664000175000017500000000000715232414252022343 f?ime=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d486.bin0000664000175000017500000000010215232414252021114 THEAD / HTTP/1.1 -Length: 4 [ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d265.bin0000664000175000017500000000002215232414252021105 nonce="00 / TVlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d158.bin0000664000175000017500000000004015232414252021106 QkGET /a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d591.bin0000664000175000017500000000002015232414252021110 ,,,,,,,,,0?,,,,libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d074.bin0000664000175000017500000000004615232414252021114 1 GT %c00 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d559.bin0000664000175000017500000000015715232414252021127 ` FPOS3T ./a HTTP/1.1 Host: x Transfer-EncodinG: chunked 3;1.1 @ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d015.bin0000664000175000017500000000000315232414252020215 %Flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d784.bin0000664000175000017500000000032015232414252021114 T;POST /a'+userhash=true HTTP/1.1 Co.tent-Disrosition: for" qqqqqqqqqqqqlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d139.bin0000664000175000017500000000014415232414252021112 BCDE]P_ST0 /a HTTP/1.1 Expect: 100-continue Host: x Transfer-Encoding: chunked %%NONCE%% libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d240.bin0000664000175000017500000000027015232414252021103  @!tG[ET /a HTTP/1.1 Hos+7ff@++G*%%T / HTTPopa /aE%%@/a HTTP/1.1@/a HTTP/1.1 go golibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d065.bin0000664000175000017500000000002315232434352020221  us- us libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d021.bin0000664000175000017500000000001215232414252021653 Digest nclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d012.bin0000664000175000017500000000000515232414252021606  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d535.bin0000664000175000017500000000013015232414252021110 ` FP|OST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 3 abc 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d209.bin0000664000175000017500000000005715232414252021116 =GETdGET /%dcddd%74 HTTP/1.1 Ho libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d079.bin0000664000175000017500000000004415232434352020231 UGET / HTTP/1.1 HosZTestlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d624.bin0000664000175000017500000000011215232414252021104 name+GET 8` HTTP/1.1 Host: x Connection: close T /)HTTP/e ng:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d138.bin0000664000175000017500000000011515232414252021107 ET / HTTP/1.1 Host:: 0 Transfer-Encoding: chunked 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d105.bin0000664000175000017500000000006015232434352020215 iGET /aaaaaaaaaaaa%eaa HTTP/1.1 Hoaalibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d256.bin0000664000175000017500000000001515232414252021107  ? libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d257.bin0000664000175000017500000000001615232414252021111 nv20 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d062.bin0000664000175000017500000000102415232414252022340 bbbb=1444444s4f4'''''''%0FFFF''''''''''''''VVVVVVVVVVVVV%0VVVVV%1FFFFFFFF'''''''''''''''''''''''VVVVVVVVVVVV%1aVVVVVVVVVVVVVWVVVVVV%1FFFFFFFF'''''''#'''''''VVVVVVVVVVVVVVVV%1aVWVVVVVVVVVVVWVVVOVV%2FFFFX#'''''''VVVVVVVVVVVVVVVV%1aVWVVVVVVVVVVVWVVVOVV%1FFFFFFFFFFFVVV%1aVVVVVVVVVVVVVVWVVVVV%1FFFFFFFFFFFFVV%0FFFF''''''''''''''''''''VVVVVVVVVVVV%1aVVVVVVVVVVVVVWVVVVVV%1FFFFFFFF'''''''#'''''''VVVVVVVVVVVVVVVV%1aVWVVVVVVVVVVVWVVVOVV%2FFFFFFFFFFF libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d407.bin0000664000175000017500000000001715232414252021107 1P x  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d337.bin0000664000175000017500000000013615232414252021113 @ABCDEFHPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked .1 F 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d070.bin0000664000175000017500000000012415232434352021430 a59275a4aQ ETQ0Gt: HTTP/1.1 Host: x Cookie: cn=nce=2o@st:xnpab 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d023.bin0000664000175000017500000000001315232414252021607 8libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d104.bin0000664000175000017500000000005715232434352020222 AiGET aaaab%bbaafbbaa HTTP/1.1 Host:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d077.bin0000664000175000017500000000000715232414252022346 &b=7libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d071.bin0000664000175000017500000000001315232414252021612  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d078.bin0000664000175000017500000000004415232414252021113 GET /?a0&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d275.bin0000664000175000017500000000003715232414252021114 nametGET /%1a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d131.bin0000664000175000017500000000000515232414252020216 %9hlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d239.bin0000664000175000017500000000024115232414252021111 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Content-Disposition: 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d201.bin0000664000175000017500000000005015232414252021077 E/1.S * HTTP/1.1 ! M libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d026.bin0000664000175000017500000000000615232414252020222 R===libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d183.bin0000664000175000017500000000002315232434352021433 ,11p2$1'zE1"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d390.bin0000664000175000017500000000013515232414252021111 aaaaaa XGET /` HTTP/1.1 0a XGET /` HTTP/1.1 XOET /a HTTP/1.1 Hos~:aaaa" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d245.bin0000664000175000017500000000023415232414252021113 $0(SOc34(POST /a HTTP/1.1 Host; GET /a HTTP/AD1 /a HTTP/1.1 Host: x Transfer-EncodinG: chunked 4;P|O$T.1_Host8a HTT<GET999999999999999999999999999DELETE 99username="9999999999-----BEG ?iPAddress/ HTTP/1.1 Lost: . ; elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d040.bin0000664000175000017500000000004115232414252021075  / : xGET /a HTTP/1.1 ; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d556.bin0000664000175000017500000000005015232414252021111 1.1 0 1%DM051/ HTTP/1.1 %%NE%%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d130.bin0000664000175000017500000000005215232414252021077 TrailerG: tET /a HTTP/1.1 Host:n: D libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d129.bin0000664000175000017500000000005215232414252021112 1 GT /a%b00 HTTP/1.1 H 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d058.bin0000664000175000017500000000011615232434352021437 ,00!4-0222@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d065.bin0000664000175000017500000000001315232414252021664 Basic E(=Jlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d104.bin0000664000175000017500000000004215232414252021660 Digest algorithm=123456729abcdef"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d242.bin0000664000175000017500000000030015232414252021077 Upgrade: GET /a HTTP/1.1 Host:+x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaa0000013db1aaaaaaAAAAAAAAAAa", userhash=true, re0200002,response="0123<56789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d814.bin0000664000175000017500000000037315232414252021116 GET /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest useUpgrade: rname-"user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8''a%e00%1756089m=SH52-A6, response="012bcd89abadeff0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d051.bin0000664000175000017500000000012315232414252021100 T;POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked d;Aqqqqqqqqqlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d155.bin0000664000175000017500000000032415232434352020225 AiGET /aaaaaaaaaaaaaaaaaaaaaaaaaaaX-Loaaaa HTTP/1.1 Host: x X-Long: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d031.bin0000664000175000017500000000007215232414252022336 u--abc ----abc Content-Transfer-Encoding: bi  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d326.bin0000664000175000017500000000004115232414252021107 @GET /a HTTP/(.2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d460.bin0000664000175000017500000000003715232414252021110  @> GET / HTTP/1.1 HV libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d052.bin0000664000175000017500000000010615232434352021430 7a52975a4aE QTQGt: HTTP/1.2 Host:kie:b Qlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d031.bin0000664000175000017500000000004615232414252021105 %%%%%%%%%%EaGT "?q=%5! HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d212.bin0000664000175000017500000000000415232414252020215 d\clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d032.bin0000664000175000017500000000005715232414252021110 @8GET /a HTTP/1.1 Cookie:: k libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d427.bin0000664000175000017500000000005615232414252021117 GET /%B63 HTTP/1.1 I libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d883.bin0000664000175000017500000001560115232414252021124 GET /a HTTP/1.1 aaupgradeaaaarhash=true, realm="TfstRe\lm", nonce="%%NONCE%%"n: %4 XE TG/a HT@TP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NONCE%%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGE[T/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorization: %#4 XGET /a HTTP/1.1 Host: x Authorization: Digest usernam,=S+HA-257s ,reonpse="aaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorizati: x Authorization: %4e, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqorization: %4 XE TG/a HT@TP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NONCE%%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorizati: x Authorization: %4 XE TG/a HT@TP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NOCN%E%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="",paque="", qoqqqqqqqrealm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqathm=S+HA256s ,reonpse="aaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorization: %4 XE TG/a HT@TP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NONCE%%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: realm="TfstRe\lm", nonce="%%NONCE%%"n: %4 XE TG/a HT@TP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NONCE%%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGE[T/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorization: %#4 XGET /a HTTP/1.1 Host: x Authorization: Digest usernam,=S+HA-257s ,reonpse="aaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorizati: x Authorization: %4e, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqorization: %4 XE TG/a HT@TP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NONCE%%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorizati: x Authorization: %4 XE TG/a HT@TP/1.1 Host: x Authorizat)GE& /a HTTP/1.1 -# Host U(gra :GdeET /a HTTP/0.1 Host: TTP/1.1 HosR~~~~~Ea", use /a HTTP/rhash=true, realm="TmstRealm", nAuphorizatioHA-971,POSst: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="4418e2cf84f83204abf08adb26127a2e8c1bc95612e9a7e29858a1ec7d6682610000000000000000000000aaaaaaaaaaaPATCH aaaaaa5f018d0d8a75c3cf6ea3760a02e9fa167aaaaaACEa", userhash=true, realm="TmstRealm",ܑAuphorizatioHA-971,POSst: xorization: Digest username="75c3calm=, use /a HTTP/rhash=true, realm="TmstRealm", nAuphorizatioHA-971,POSst: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="4418e2cf84f83204abf08adb26127a2e8c1bc95612e9a7e29858a1ec7d6682610000000000000000000000aaaaaaaaaaaPATCHda0d875c3cf6ea3760a02604bb970e9fa167aaaaaACEa", userhash=true, re1,POSst: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="EEEEEEEEEEEEEEEEEEEEEEEEEEEEHTTP/rhash=true, realm="TmstRealm", nAuphorizatioHA-971,POSst: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="4418e2cf84f612e9a7e29858a1ec7d6682610000000000000000000000aaaaaaaaaaaPATCH aaaaaa5f018da0d875c3cf6ea3760a02604bb970e9fa167aaaAEaaCa", userhash=true, re1,POSst: x XGET /a HTTP/1.1 Host: x Authorization: Digest usernaauth, nc="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorization: %#4 XGET /a HTTP/1.1 Host: x /1.1 Host: x Au Host: x Authorization: Digest usernam,=S+HA-257s ,reonpse="aaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorizati: x Authorization: %4e, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqorization: %4 XE TG/a HT@TP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NONCE%%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorizati: x Authorization: %4 XE TG/a HT@TP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NOCN%E%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="",paque="", qoqqqqqqqrealm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqathm=S+HA256s ,reonpse="aaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Auth, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqorization: %4 XE TG/a HT@TP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NONCE%%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorizati: x Authorization: %4 XE TG/a HT@TP/1.1 Host: x Authorization: Digest username="aaaaaaaa%NOCN%E%", uri="/a", qop="TfstRe\lm", nonce="%%NONCE%%",opaque="",paque="", qoqqqqqqqrealm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqqqqqqaT /a HTTP/1.NONCE%%",opaque="", qoqqqqqqqqqqqqqqqqaaaaaaaaaGET/aaaaaaaaaaaaaost: x XGET /a HTTP/1.1 Host: x Authorization: %#4 XGET /a HTTP/1.1 Host: x Authorization: Digest usernam,=S+HA-257s ,reonpse="aaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TfstRe\lm", nonce="%%NONCE%%",opaque="", qoqqqqqq GET / HTTP/1.7 Host: 7GAT /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Dige, QkGET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 HoAuthorization: Basicasic TP/1.1 Host:: x R ^4WET /a HTTP/1&1 Host XGET /a HTTP/1.1 H X(Gst murnaseion: u Hlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d495.bin0000664000175000017500000000010515232414252021117 3PQGET /a HTTP/1.1 Cookie: a=b !!!!!&&&'&Ho!!!!x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d030.bin0000664000175000017500000000010115232434352021417 7a59275a4aQ ETQ0G_t: HTTP/1.1 Cookie: cnofce=4o@st: xb# 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d147.bin0000664000175000017500000000014615232414252021116  FPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked Expect: 100-coP/1.1inue libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d086.bin0000664000175000017500000000001015232414252022340 %6 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d042.bin0000664000175000017500000000001715232434352021430 .02@`_libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d203.bin0000664000175000017500000000000415232414252020215 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d063.bin0000664000175000017500000000001015232414252021610 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d013.bin0000664000175000017500000000001715232434352021426 @2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d698.bin0000664000175000017500000000015315232414252021124 @ABCDE]P_ST0 /a HTTP/1.1 Expect: 100-continue Host: x Transfer-Encoding: chunked 1;ext= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d075.bin0000664000175000017500000000000715232414252022344 u*E=6libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d239.bin0000664000175000017500000000015315232414252021116 2rTRACE " 2GET /a HTTP/1.1 rPR@ACE  "0GET /aHT`/ Ho HEAD / HTTP/1.1 Holibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d116.bin0000664000175000017500000000010015232434352020212 ----E\ /pat(+?a=1 HTTP/1.1 H: x Cookie: reilm="**** libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d124.bin0000664000175000017500000000001215232434352021424 #0#3 2Zlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d670.bin0000664000175000017500000000013015232414252021105 dfWe4eLET / HTTP/1.1 Host: x Connection: Upgrade Upgrade:c 1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d161.bin0000664000175000017500000000002115232414252021102 =libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d439.bin0000664000175000017500000000006115232414252021116 PѰGET /%04Γ=%a43 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d408.bin0000664000175000017500000000005315232414252021113 HTTP"GEt /a?q=%B82 HTTP/1.1 22 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d169.bin0000664000175000017500000000016615232414252021121 PRGET /a HTTP/1.1 tho Authorization: Digest usernam, cnonce="deef", algorithm=SHA-512-256, css, real libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d194.bin0000664000175000017500000000003715232414252021114  GT / HTTP/1.1 Host#libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d099.bin0000664000175000017500000000005115232434352021442 779a524aQ E HTTP/1.1 Hm3t:b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d100.bin0000664000175000017500000000000515232414252020212 +%1Flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d020.bin0000664000175000017500000000001215232434352021417 7 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d687.bin0000664000175000017500000000014315232414252021121  04,GET /patah?1= HTTP/1.1 Host: x Cookie: a=t/form-dost: x Cookie:; ext = vQ"b"QQa; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d416.bin0000664000175000017500000000005315232414252021112 GET / HTTP/1.1 zost: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d540.bin0000664000175000017500000000013315232414252021107 Cookie: a=b =OT SP/a HTTP/1.1 Host:d x Transfer-Encoding: chunked 0 abc 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d012.bin0000664000175000017500000000003115232414252021073 T / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d282.bin0000664000175000017500000000002215232414252021107 `on:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d307.bin0000664000175000017500000000010315232414252021102 GET / HTTP/1.1 Host: x GET / HTTP/1.1 Host:e= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d229.bin0000664000175000017500000000000515232414252020226 /a%cjlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d359.bin0000664000175000017500000000004615232414252021122 #@) GET /a HTTP/1.2 HoWW-libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d080.bin0000664000175000017500000000004415232434352020221 @>GET / HTTP/1.1 HobrF libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d365.bin0000664000175000017500000000004615232414252021117 `0 /G a HTTP/1.1 Ho0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d049.bin0000664000175000017500000000001015232414252022337 D=%6libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d432.bin0000664000175000017500000000005715232414252021114 hGET'GET /%45%FF HTTP/1.1 H:x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d335.bin0000664000175000017500000000013015232414252021103 @ABCDE]POT /a HTTP/1.1 Host: x Transfer-Encoding: chunked 0;Sxt=val ?? ????D libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d286.bin0000664000175000017500000000004215232414252021112 ;JT / HTTP/1.1 HoYYY.Hlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d138.bin0000664000175000017500000000001315232434352021432 G1dcclibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d438.bin0000664000175000017500000000006015232414252021114 B fET %4D HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d005.bin0000664000175000017500000000000615232414252022334 w!%=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d166.bin0000664000175000017500000000000315232414252020224 dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d107.bin0000664000175000017500000000006715232414252021672 fraa%20wwwwwh-xyzUzU00blibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d434.bin0000664000175000017500000000003215232414252021104 C x,= 0ET / HTPP libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d271.bin0000664000175000017500000000000615232414252020224 tity=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d708.bin0000664000175000017500000000015715232414252021120 41&mPOST /a HTTP/1.1 Content-Length: 5 Content-Length: 6 ww-forgh: 22 a=&92 a=&9/1.1 Cb=%41&clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d042.bin0000664000175000017500000000000515232414252021611 ?libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d096.bin0000664000175000017500000000005315232414252021116 ??? POST / HTTP/1.1 clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d237.bin0000664000175000017500000000014215232414252021112 B'r0: =b/a HTTP/1.1 Cookie: =ba HTTP/0.1 Cookie:; cdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d558.bin0000664000175000017500000000005115232414252021114 GEt T%6%DD500 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d224.bin0000664000175000017500000000006015232434352021430 $DELETE G!2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d110.bin0000664000175000017500000000007215232414252021077 ?ET /a HTTP/1.1 Host: Authorization: Basic libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d127.bin0000664000175000017500000000001215232434352021427 **L_20Ulibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d223.bin0000664000175000017500000000012015232414252021101 zFPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 7 abc libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d054.bin0000664000175000017500000000005715232414252022346 --abc----abc Content-Type: t"=c 0- elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d426.bin0000664000175000017500000000005615232414252021116 GHost: x 'GET /%`?+272%a HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d125.bin0000664000175000017500000000003715232414252021106 %76 HT%76 HTTP/1.1 Plibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d130.bin0000664000175000017500000000005615232414252021106 P0`S'GET /%75.?a+GET / HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d430.bin0000664000175000017500000000005715232414252021112 "]GET /a?q=%70 HTTP/1.1 HHHHHlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d006.bin0000664000175000017500000000003415232414252021101 'G / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d394.bin0000664000175000017500000000001415232414252021111   1Hostlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d074.bin0000664000175000017500000000001315232414252021615 @Rlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d109.bin0000664000175000017500000000002015232414252022335 XY --XY nlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d520.bin0000664000175000017500000000012115232414252021102 oR 3lGETR 3lGET / HTTP/1.1 P%5ETGoundary=] / HTTP/1.0 PUT libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d004.bin0000664000175000017500000000006015232434352021424 a59;550a4aQ ETQ0Gt? HTTP/1.1 Hs 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d699.bin0000664000175000017500000000015315232414252021125 @ABCDE]P_ST0 /a HTTP/1.1 Expect: 140-continue Host: x Transfer-Encoding: chunked 1;ext= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d058.bin0000664000175000017500000000001015232414252021614 Glibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d735.bin0000664000175000017500000000021215232414252021110  x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", reaorithm=SHA-256, response="012345\ =GET /a89.b" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d063.bin0000664000175000017500000000000515232414252022337 &&&&libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d054.bin0000664000175000017500000000012715232414252021107 dGET / HTTP/1.1 Host: x Authorization: Digest userhash=true, username= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d006.bin0000664000175000017500000000000315232414252020215 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d196.bin0000664000175000017500000000000315232414252020227 %Elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d260.bin0000664000175000017500000000000515232414252020221 "1%a%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d008.bin0000664000175000017500000000000715232414252021664 Basic libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d656.bin0000664000175000017500000000012115232414252021111  %NONCE%%T dh-int?a&-int?a&=0b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d215.bin0000664000175000017500000000000415232414252020220 *alibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d091.bin0000664000175000017500000000003515232414252021106   /c HTTP/1.0 xlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d318.bin0000664000175000017500000000011115232414252021103 `5Q /path?a=1Gt: HTTP/1.1 Host; x ost: x Cookie:ithm=  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d146.bin0000664000175000017500000000014115232414252021110 a=1&b=2ST34(Expect: 100-continue GET / HTTP/2.0 a0bcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d440.bin0000664000175000017500000000003315232414252021102 0GET / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d198.bin0000664000175000017500000000000415232414252020232 ^8bblibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d002.bin0000664000175000017500000000002115232414252021071 HoS libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d252.bin0000664000175000017500000000000515232414252020222 %bblibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d400.bin0000664000175000017500000000005215232414252021102 Q '[e;BE/ /04=q"%e HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d379.bin0000664000175000017500000000005015232414252021117 P0(PGET / HTTP/1.0 onTPfffflibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d063.bin0000664000175000017500000000000415232414252020221 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d579.bin0000664000175000017500000000043515232414252021130 v?cG! /PO)T  HTTP/1.1 Host:nxLe,gth: :POS/PO)T / HTTP/1.1 Host: x n: th:T 4 OQ abcllibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d104.bin0000664000175000017500000000013115232414252021101 ` FPOST.1 /a HTTP/1.1 Host:x Transfer-EncodinG: chunked 3; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d007.bin0000664000175000017500000000000615232414252021662 SHA5 2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d481.bin0000664000175000017500000000010015232414252021105 `0 /GET /a HTTP/1.1 Host: xHTTP/1.1 Host:lose libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d206.bin0000664000175000017500000000005215232414252021106 GQoPET Ac HTTP/1.1 HQot:x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d055.bin0000664000175000017500000000001015232414252021611 h0}Dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d317.bin0000664000175000017500000000010715232414252021107 ?GET /a HTTP/1.1 Host: x Authorization: Basic cjpwYXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d008.bin0000664000175000017500000000003515232414252021104 h: b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d780.bin0000664000175000017500000000031515232414252021114 (GETGT/E a HTTP/1.0 Host: x Authorization: Digest username=2aaEDELETETaaaaaaaaa", userhash=true, realm="TestRealm", n once="%%NONCE%%",Cookie: a=bCo uri="/a",SHA-4x 5, respot="0123489abcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d845.bin0000664000175000017500000000050215232414252021114 GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response="0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d002.bin0000664000175000017500000000000515232414252022330  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d505.bin0000664000175000017500000000004215232414252021104 0GETQ /b?q& HTTP/1.1 H libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d086.bin0000664000175000017500000000000415232414252020226 /%%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d044.bin0000664000175000017500000000000515232414252021613 Blibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d393.bin0000664000175000017500000000001415232414252021110 GE HTTP/@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d728.bin0000664000175000017500000000020015232414252021107 tGET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="", nonce="0000", uri="/a", response="00" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d059.bin0000664000175000017500000000021415232414252021111 Upgrade: GET /a HTTP/1.1 Host: x Authorization: Digest username="21e758a3a8cc1aa", userhash=true, realm="eef", algorithm=SHAabcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d043.bin0000664000175000017500000000002315232414252021661 @Digest qop="a\uth"libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d414.bin0000664000175000017500000000002115232414252021100 IdGET libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d139.bin0000664000175000017500000000015615232434352020232 Arealm=""OST /a HTTP/1.1 Hsot: x Content-Length: 5 Content-Length: 5 ContenTGEength: 11 hello worldlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d119.bin0000664000175000017500000000004415232414252022344 --abc ----abc u=b ----abc elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d010.bin0000664000175000017500000000000515232414252021604 "libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d762.bin0000664000175000017500000000025515232414252021117 Upgrad x XGET /a HTTP/1.1 Host: x Authorization: Digest username="9aaTRACEa", userhash=true, realm="TmstReam", nAuthorizatioHA-512, response="0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d600.bin0000664000175000017500000000010115232414252021074 ?T /a HTTP/1.1 Host: x Authorization: Basic XNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d402.bin0000664000175000017500000000001615232414252021101 GET /st: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d015.bin0000664000175000017500000000000515232414252021611  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d574.bin0000664000175000017500000000006015232414252021112 @AE%%T @/aE%BeaE%Be HTTP/1.1 + +++libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d027.bin0000664000175000017500000000002315232434352020217 DELETE libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d302.bin0000664000175000017500000000005615232414252021104 0.1 Xclose: y ?b&m=u++ HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d659.bin0000664000175000017500000000012315232414252021116 @E R;POST /` HTTP/1.1 Host: x Transfer-Encoding: chunked d%Pqq  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d046.bin0000664000175000017500000000017715232414252021676 BstReamm:peeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ' slibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d092.bin0000664000175000017500000000000415232414252020223 aflibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d197.bin0000664000175000017500000000003715232414252021117 POST /% HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d189.bin0000664000175000017500000000003415232414252021115 %%NO/1.1 T /a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d343.bin0000664000175000017500000000004515232414252021112 a5ST /a HTTP/1.1 C Cdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d481.bin0000664000175000017500000000004115232414252021106 d @a=1&T HTTP/1.1 '7''libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d025.bin0000664000175000017500000000001615232414252021663 Digest nc="f5libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d369.bin0000664000175000017500000000031715232414252021121 Upgrade: GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="dddd11111aaaaaaaaaaaAaaaAaaaaTRACEa", userhash=true, realm="TmstRealm", nAuthorponse="0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d145.bin0000664000175000017500000000033315232414252021107 POST /a%%NONCE%% HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 4327 ----abc g2: chunkedclose Content-Type: multipart/mixed; boundary=b -- -libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d299.bin0000664000175000017500000000002615232414252021123 P/x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d690.bin0000664000175000017500000000014515232414252021115 OPTIONS GET % HTTP/1.1 H=st: x0Gth?a=TTP/:x Cookie: a=;ext="a\"b"def libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d693.bin0000664000175000017500000000014715232414252021122 @ABCDE]POST 1/a HTTP/1.1 Host: T x Transfer-Encoding: chunked 0;ext=val :c" CDE libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d021.bin0000664000175000017500000000002015232414252021074 rF$libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d005.bin0000664000175000017500000000004515232434352020217 !=%O /a?b&c/a HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d068.bin0000664000175000017500000000000615232414252022345 3-"Tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d458.bin0000664000175000017500000000006615232414252021124 ' /aT / HTTP/1.1 /cteo T T libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d024.bin0000664000175000017500000000001615232414252021662 Digest uri=c libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d230.bin0000664000175000017500000000017215232414252021103  @ libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d055.bin0000664000175000017500000000013515232434352020224 0GET /path?a=1 HTTP/1.1 H: x Cookie: a=b*********AC*R*ST ; 'Te: a=b*opaque=" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d143.bin0000664000175000017500000000001315232434352021426 E 36dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d107.bin0000664000175000017500000000000515232414252020221 ff%80libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d882.bin0000664000175000017500000001546615232414252021134 upgradeGET POST2222222222222GET /a HTTP/1.1 Host: x %=MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMPOST22222222222222222222222222222222222222222222G / HTTP/1.1 Hos: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d497.bin0000664000175000017500000000010515232414252021121 GET /a HTTP/1.1 Cookie: a=b GGG&&&"&&&&: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d470.bin0000664000175000017500000000003715232414252021111 T /a HTTP/1.1 3Elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d150.bin0000664000175000017500000000020115232414252021100 4POST /a HTTP/1.1 Host:1.1 Host: Content-Length: 1048576 CR dengtjGET Expect: 100-continue abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d115.bin0000664000175000017500000000000515232414252020220 %B2libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d850.bin0000664000175000017500000000053015232414252021111 (GET/a HTTP/1.1 Host HTTP/1.GET /a HTTP/1.0 Host: x Authorization: Digest username="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000028771231906filenameaaaa", userhash=true, rea, n once="%%NONCE%%",uu ralgorith+=SHA-2 56, respose="0123489abcdelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d230.bin0000664000175000017500000000007115232434352021427 , +CONNECTos*:sXo+CONost:sXoXt:$2 `libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d085.bin0000664000175000017500000000006315232434352021440 7a592754aQ ETQ0Gt: HTTP/1.1 Cookie:;nce 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d105.bin0000664000175000017500000000000515232414252020217 9%,7libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d281.bin0000664000175000017500000000004015232414252021103 000001 cG /a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d147.bin0000664000175000017500000000022115232434352020222 0&G/Tr Eelm=%net0cionuade0t`?%a=b+P###+##0 HTTP/1.1 Ha=b libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d099.bin0000664000175000017500000000010215232414252021114 *@GET /a HTTP/1.1 Hosx GEGET / HTTP/1.1 .1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d475.bin0000664000175000017500000000007615232414252021124  ]G / HTTP/1.1 Cookie: ;34(POST libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d649.bin0000664000175000017500000000012015232414252021112 ;HOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked d libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d450.bin0000664000175000017500000000003515232414252021105 #T /a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d500.bin0000664000175000017500000000010615232414252021103 ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]GET / HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d322.bin0000664000175000017500000000011215232414252021077 ET / HTTP/1.1 Host: x Authorization: Basic dXNlcj0wYXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d616.bin0000664000175000017500000000011115232414252021104 ET / HTTP/1.1 Host: x Authorization: Basic dXNlcjpYXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d064.bin0000664000175000017500000000000615232414252022341 4e %libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d296.bin0000664000175000017500000000004515232414252021116 e / HTTP/1.1 Hust: libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d703.bin0000664000175000017500000000015615232414252021112  Z+GT /a HTTP/1.1 Host: x TTP/1.1 HosTP Content-Length: 5 Co--b R b Content-Length: 5 Co libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d068.bin0000664000175000017500000000001515232414252021671 Digest nc=elibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d183.bin0000664000175000017500000000000315232414252020223 8%Clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d198.bin0000664000175000017500000000005015232414252021116  PpѰ'GET /%843 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d005.bin0000664000175000017500000000003415232414252021100 upgrade GET / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d241.bin0000664000175000017500000000014515232434352021433 7a59#275a4~Q ET]Gt: HTTP/1.1 Hsot: x:cnene"o=co:!HTTP/1.1 Host: x Cookie: cxnpab=; 1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d569.bin0000664000175000017500000000005415232414252021121  GET rai%ler: a HTTP/1.1 : libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d470.bin0000664000175000017500000000007315232414252021114 v?cE! -34OST /a>>>>>>>> HTTP/1.1 Host: x abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d013.bin0000664000175000017500000000056615232434352020226 AiGET ]aaaaaaaaaaaaaaaa!--0000000000007173733806442603406Cookie:Upgrade: h2c 4440123789abcdef7173733 D\UCUUCCzat UaaaaUlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d010.bin0000664000175000017500000000002015232414252021072 )libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d310.bin0000664000175000017500000000003215232414252021100 CoContentent-L2ngTRACE 50libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d016.bin0000664000175000017500000000001315232414252021660 Basic 45]flibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d742.bin0000664000175000017500000000022415232414252021111 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username=000/0+, realm="Te", uri="/a", qop=auth, nc=f" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d388.bin0000664000175000017500000000005115232414252021120 @ET /a HTTP/1.1 &!&&!! libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d584.bin0000664000175000017500000000007015232414252021114 --b T /?+?a&=0b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d788.bin0000664000175000017500000000032215232414252021122 6GET oa P/2.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest usernam1="aaaaaaaaaaaaaaaaaaaaboundray=aaaaaaaaaaaaaaaaaaaaaa", userhash=true,username*=UTF-7,0000, cnoncehm=SHA56 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d753.bin0000664000175000017500000000024115232414252021112 0PATCH =GET / HTTP/1.0 Hosth=false: x , %+re":ժ00258489 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d314.bin0000664000175000017500000000010715232414252021104 0GET /patah?1= HTTP/1.1 Host: x Cookie: a=t/form-data; libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d110.bin0000664000175000017500000000000515232414252020213 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d010.bin0000664000175000017500000000001015232434352021414 >1libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d573.bin0000664000175000017500000000025515232414252021122 'OS / HTTP/1.1 1.1 HdTTP/1.1 Connection: close ,TTPP/POST o TWGET /1.1 ox: t sG / ection:POST GET / HTTP333x30 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d031.bin0000664000175000017500000000001215232414252021654 Basic Q Qlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d593.bin0000664000175000017500000000007715232414252021123 =Bearer %4ce49106702c HTTP/1.1 Hot: x  libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d380.bin0000664000175000017500000000047215232414252021114 upgbcdef" GET / HTTP/1.1 HhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhGET / HTTP/0.1 Host: xname ding: chuqqalibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d827.bin0000664000175000017500000000040215232414252021113 POTS /a%%NONCE%% HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 4327 ----abc g1: chunkedclose Content-Type: multipart/mixed; boundary=b --  t:iii"/a", qop=auth, n libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d033.bin0000664000175000017500000000001315232434352021424 _K>>> libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d263.bin0000664000175000017500000000002115232414252021102 T libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d403.bin0000664000175000017500000000005215232414252021105 +0:jET /a HTTP/1.1 UUpgrarlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_memorypool-d018.bin0000664000175000017500000000000515232414252021614 6libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d123.bin0000664000175000017500000000000515232414252020217 2%delibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d105.bin0000664000175000017500000000014415232414252021106 K(/GEGET / HTTP/1.0 ost: xST Connection: keep-alive C_POST a=b : x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d291.bin0000664000175000017500000000001015232414252020221 56BABBBlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d133.bin0000664000175000017500000000006315232414252021104 ff f@,ET /a HTTP/1.1 x ' /a HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d057.bin0000664000175000017500000000004215232414252021106 %%NONCE%%T /?a=0&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d156.bin0000664000175000017500000000002015232414252021105 ,a.a.1 U libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d035.bin0000664000175000017500000000000715232414252022340  -%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d473.bin0000664000175000017500000000007415232414252021120 R/GT /a HTTP/1.0 Connon: we libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d108.bin0000664000175000017500000000006715232414252021673 tlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d088.bin0000664000175000017500000000000415232414252020230 Olibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d079.bin0000664000175000017500000000002215232414252021671 Digest username*'libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d100.bin0000664000175000017500000000005615232434352021426 D!0>>>><> >>libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d156.bin0000664000175000017500000000033315232434352020226 A!<POST /akjjj HTTP/1.1 Hsot:ntenGETength:2 x ContenGETengthdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d003.bin0000664000175000017500000000041215232434352020213 uiGET* HTTP/4.1 /aaaa libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d825.bin0000664000175000017500000000040215232414252021111 PpFGET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 = Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", 0000001, cnonce="deef", algorithm=SHA-256, response="838178\6789a\cd89abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d123.bin0000664000175000017500000000003415232414252021101 ET / HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d357.bin0000664000175000017500000000026115232414252021114 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Content-Disposition: fm-data; name libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d667.bin0000664000175000017500000000012615232414252021120  HGET / HTTP/1.1 Host: x Connection: Upgrade Upgrade: fuzz-protocol libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d100.bin0000664000175000017500000000003615232414252021657 Digest algorithm=SHA-256-sesslibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d720.bin0000664000175000017500000000017215232414252021107 @ @a=1 /a HTTP/1.1 Host: x Content-Type: application/x-www-form-urlencoded Content-Length: 12 a~=/ 000,$clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d423.bin0000664000175000017500000000005515232414252021112  HTTP/1.1 ET ?q=%4ETGET0 HTTP/1.1 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d463.bin0000664000175000017500000000003715232414252021113 TRACE a HTTP/1.1 o Ht libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d368.bin0000664000175000017500000000031615232414252021117 GET /a HTTP/1.1 Host: x GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="00000000000000000000000000000000000000000000", uri="/a", response="e" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d051.bin0000664000175000017500000000011315232434352020214 m0GNegotibte =1 HTTP/1.1 Hos: x Cookie: a=b \e2 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d391.bin0000664000175000017500000000000115232414252021102 Rlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d495.bin0000664000175000017500000000004215232414252021114 tGET /%d HTTP/1.1 Hoslibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d372.bin0000664000175000017500000000032615232414252021113 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 523 ----abc Z+GT Content-Type: multipart/mixed; bounad 52 ----abc da HTTPlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d004.bin0000664000175000017500000000000515232414252022332 - -Bulibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d305.bin0000664000175000017500000000003015232414252021102 os#G' libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d370.bin0000664000175000017500000000004715232414252021114 0 Gt:] lQT / HTTP/0.1 HoCoklibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d061.bin0000664000175000017500000000043615232414252022345 --abc ----abc Content-D%0d}SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSdŖomixed;bboundary=y=Q@ult\"nb-abc-=Z%0dZZZZZlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d136.bin0000664000175000017500000000001215232434352021427 $b4 #%libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d432.bin0000664000175000017500000000003115232414252021101 ;ext="POST GET / : x < libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d188.bin0000664000175000017500000000003015232434352021436 "30@6Q@@Dlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d878.bin0000664000175000017500000000260715232414252021132 cl oes|GET / HTTchunketupgrade]Negotiate 297a4)?b&c9E=ET / HTTP/1.1 Host: x 2'ET / HTTP/1.1 Host: xchunked]Negotiate 296a4)upgrade]Negotiate 296a4)?b&c9E=ET / HTTP/1.1 Host: x 2'ET / HTTP/1.1 Host: xchunked2^U]Negotaate 296a4)?b&c9E=ET / HTTP/1.1 Host: x 2'ET / HTTP/1.0 Host: xupgrade]Negotiate 297a4)?b&c9E=ET / HTTP/1.1 Host: x 2'ET / HTTP/1.1 Host: xchunked]Negotiate 296a4)upgrade]Negotiate 296a4)?b&c9E=ET / HTTP/1.1 Host: x 2'ET / HTTP/1.1 Host: xc]Negotiate 592a4?b&c9E=ET / HTTP/1.1 HoPOPOST ]Nelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d158.bin0000664000175000017500000000035715232434352020236 AiGET /aaaaaaaaaaaa4a4aaaa3a HTTP/1.1 H1$ost: xn: Up-----BEGIN PKCS12ost: Cookie:''''''''''= /''GET1GET ="1 HTTP/1.1 Cookie:''''''''''GET1G-----BEGIN DH PARAMETERSET =Host: Cookie:''''''''''= 4444gz4I libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d545.bin0000664000175000017500000000004615232414252021114 &ET /CCC%2BCC HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d267.bin0000664000175000017500000000000515232414252020230  %7libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d158.bin0000664000175000017500000000001415232434352021435 'b1bEEElibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d064.bin0000664000175000017500000000002115232434352020216 !GET libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d050.bin0000664000175000017500000000001015232414252021653 Digest libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d308.bin0000664000175000017500000000003115232414252021106 . x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d107.bin0000664000175000017500000000011015232434352021424 7a59275a4aQ ETQ0G: HTTP/1.1 Host: x Cookie: c; xnpa=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d635.bin0000664000175000017500000000011315232414252021107 0GETQ /path?a=1zC HTTP/1.1 Host: x Cookie:--b-- abcdef libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d153.bin0000664000175000017500000000001315232434352021427 !@2aV:libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d327.bin0000664000175000017500000000011715232414252021111 realm="GET / HTTP/1.1 Host: x -procol Content-Length: 0 ed 0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d636.bin0000664000175000017500000000011315232414252021110 ?GET /a HTTP/1.1 Host: x Authorization: Basic dXNlc`pwYXNz libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d096.bin0000664000175000017500000000001015232414252022341 %C3%A0=libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d090.bin0000664000175000017500000000004515232414252021111 GET / HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d074.bin0000664000175000017500000000001415232434352021432 36;libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d620.bin0000664000175000017500000000011215232414252021100 @>GET / HTTP/1.1 Host: x Authorization: Basic dXNlXwYNpjc= libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d342.bin0000664000175000017500000000004415232414252021110 /0ET /a HTTP/1.1 H$olibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d180.bin0000664000175000017500000000002215232434352021427  05libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d022.bin0000664000175000017500000000000515232414252022332  -libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d023.bin0000664000175000017500000000013415232434352021427  7a59#275a4a? ?QQ#::4@&0Gt: HTTP/1.1 Hopo HosoTR.nP:@libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_str-d289.bin0000664000175000017500000000001015232414252020230 3cdcdcflibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d214.bin0000664000175000017500000000005515232434352021433 :Aa515a4a=Q %ET%8Gt: HTTP/1.1 Coe0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d264.bin0000664000175000017500000000002115232414252021103 SHA-512-256 6libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d516.bin0000664000175000017500000000004315232414252021107 tGEV /a HTTP/1.2 Ht: x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_postprocessor-d132.bin0000664000175000017500000000020415232414252022335 =a=1&b=%41&c!a=2&b=%41&clibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d089.bin0000664000175000017500000000001215232434352021436 22libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d028.bin0000664000175000017500000000014515232434352021436 :P P7 :jjjj0_libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d821.bin0000664000175000017500000000040015232414252021103 Upgrade: GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaa-----------aaaaaaaaaaaa", username*=UTF-8''au"%DEL%DELE%300username="%f9e6%f9e"%DOPTuserne62TRACEe46a=babcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_options-d149.bin0000664000175000017500000000017115232414252021116 -v?cE! ST /a=1 HTTP/1.1 Host: x Content-Length: 000000000000000000000000000018446744073709551615 a#bcdlibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d156.bin0000664000175000017500000000003715232414252021112 ڒ /1.1 HTTP/1.1 J7uRelibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d507.bin0000664000175000017500000000004315232414252021107 @/ E%%FFNFFFF HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_eventloop-d128.bin0000664000175000017500000000001215232434352021430 %G1 !libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d053.bin0000664000175000017500000000001015232414252021656 Digestblibmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d618.bin0000664000175000017500000000011115232414252021106  RET : HTTP/1.1 Hie:nce="ost:` x Cookie: a=HTT.1e: a=b 0libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_tls-d089.bin0000664000175000017500000000004715232434352020235 GET / HTTP/1.1 Hos48 x libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d248.bin0000664000175000017500000000036015232414252021113 GET /a HTTP/1.1 Host: x =GET a HTTP/1.1 Host: x Authorization: Digest useUpgrade: rname-"user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", username*=UTF-8''a%0015%2-A6, response="0123456789abcd8123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_auth_header-d089.bin0000664000175000017500000000003015232414252021671 Digest qop="s?-e\it "libmicrohttpd-1.0.10/src/fuzz/corpus/distilled/fuzz_request-d861.bin0000664000175000017500000000066515232414252021124 OPTIONS GET / HTTP/1.1 ;ext="a\"b" Cooki\"b" Cookie: a=x Content-Type: multipart/form-data; boundary="us00/a?b000 ;ext="a\";ext="a\"b"a\"b" Cookiez a= Transfer-Encoding: chunked 52 --ext="a\"CV000957770279;abcdef libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-29.bin0000664000175000017500000000004715232141452016710 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-44.bin0000664000175000017500000000005615232214516016712 <GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-10.bin0000664000175000017500000000004515232141452017455 Digest nc="ffffffffffffffffffffffff"libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-01.bin0000664000175000017500000000001515232214516017216 !1@!1libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-45.bin0000664000175000017500000000005615232214516016713 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-19.bin0000664000175000017500000000001015232414252017221 2@libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-04.bin0000664000175000017500000000001215232214516017216 23@2libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-39.bin0000664000175000017500000000016015232141452016705 dGET / HTTP/1.1 Host: x Authorization: Digest userhash=true, username="aabb", realm="TestRealm" libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-24.bin0000664000175000017500000000005615232214516016710 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-18.bin0000664000175000017500000000001315232214516017224 @2@2libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-32.bin0000664000175000017500000000004715232141452016702  GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-17.bin0000664000175000017500000000004715232141452016705 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-11.bin0000664000175000017500000000002015232214516017213 !1!1!1@libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-16.bin0000664000175000017500000000002415232141452017460 "user:TestRealm:passlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-58.bin0000664000175000017500000000005615232214516016717 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-47.bin0000664000175000017500000000005615232214516016715 `GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-60.bin0000664000175000017500000000010615232214516016704 4POST /a HTTP/1.1 Host: x Content-Length: 4 abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/README0000664000175000017500000004260215232434352014107 Seed corpus for the src/fuzz harnesses ====================================== `-NN.bin` is the built-in seed corpus of that harness, dumped to disk. Regenerate at any time with ./fuzz_ --write-corpus= or, from the build tree, make -C src/fuzz refresh-corpus Replay everything (this is what a CI regression run should do): make -C src/fuzz check-corpus # or, per harness: ./fuzz_request --corpus-dir=src/fuzz/corpus Files belonging to another harness are simply uninteresting inputs for the harness that reads them, so pointing every harness at the whole directory is fine and gives some extra cross-pollination. The set is kept minimal: every seed here adds coverage that no other seed provides. After changing a seed table, re-check that with -merge=1 from an OSS-Fuzz style build (contrib/oss-fuzz/build.sh); a seed the merge does not copy across is redundant and should be deleted from the table rather than left in the corpus. Note that fuzz_request is mildly non-deterministic -- MHD timestamps its nonces and its connection timeouts -- so a single merge decision worth ~0.1% of the regions is noise; only drop a seed that several independent merges agree on. fuzz_request seeds ------------------ 00 content-length-body body oracle, Content-Length 01 chunked-with-extensions body oracle, chunk extensions -> chunk-extension CRLF bug 02 chunked-split body oracle, chunk boundary split across two send() calls 03 small-pool-trailing-query-arg 128..512 byte connection pool, no header lines, "?novalue" -> read-buffer shift-back bug 04 small-pool-trailing-query-arg-2 same with "?a=1&b" 05 digest-unknown-algorithm algorithm=BOGUS -> MHD_DIGEST_AUTH_ALGO3_INVALID MHD_PANIC() 06 digest-overlong-response 401 challenge, then a replay on a fresh connection with the harvested nonce and a 128 hex digit response= -> stack buffer overflow 07 digest-userhash userhash=true with a 128 char username 08 basic-auth Authorization: Basic 09 multipart-post chunked multipart/form-data 10 urlencoded-post application/x-www-form-urlencoded 11 folded-header obs-fold continuation line 12 pipelined two requests in one segment Seeds 00-12 leave the API-selection block (bytes 4-9, see section 2.2.1 of ../README) zero and only drive the request parser. Seeds 13-39 each switch on one area of it; without them those entry points are reachable only by guessing six configuration bytes. 13 ext-callback-chunked MHD_SIZE_UNKNOWN content reader, response headers and a trailer 14 ext-callback-error known-length reader that fails part way through 15 ext-fd-response MHD_create_response_from_fd() 16 ext-fd-at-offset-response ..._from_fd_at_offset() 17 ext-pipe-response ..._from_pipe() 18 ext-iovec-response ..._from_iovec() 19 ext-empty-response-hdrapi ..._empty() plus get/del header and MHD_set_response_options() 20 ext-digest-check-digest3 pre-computed userdigest path 21 ext-digest-v1-wrappers MHD_digest_auth_check() 22 ext-digest-request-info MHD_digest_auth_get_request_info3() 23 ext-external-event-loop MHD_get_fdset2()/run_from_select2() plus the timeout accessors 24 ext-external-event-loop-v1 the v1 fdset/run_from_select pair 25 ext-connection-api every introspection accessor 26 ext-suspend-resume suspend, resume from the pump loop 27 ext-suspend-two-connections two connections parked at once 28 ext-upgrade 101 + MHD_upgrade_action() 29 ext-buffer-persistent buffer/MHD_RESPMEM_PERSISTENT 30 ext-buffer-free-callback ..._with_free_callback() 31 ext-from-data MHD_create_response_from_data() 32 ext-fd64-response ..._from_fd64() 33 ext-basic-auth-v1 MHD_basic_auth_get_username_password() 34 ext-basic-auth-challenge MHD_queue_basic_auth_fail_response() 35 ext-basic-auth-challenge-utf8 ..._response3() with UTF-8 charset 36 ext-digest-check-digest-v1 MHD_digest_auth_check_digest() 37 ext-digest-check-digest2 ..._digest2() (never with MHD_DIGEST_ALG_AUTO, see K8) 38 ext-digest-get-username-v1 MHD_digest_auth_get_username() 39 ext-digest-get-username3 ..._username3() fuzz_str seeds -------------- Cover MHD_hex_to_bin (including the 128 character input that digestauth.c used to allow into a 32 byte buffer), MHD_bin_to_hex[_z], the percent-decoders (strict, lenient, in place), MHD_str_unquote, MHD_str_quote, MHD_base64_to_bin_n, MHD_str[x]_to_uint64_n_ and the token helpers. fuzz_auth_header seeds ---------------------- Well-formed and broken Digest parameter lists (unknown algorithm, extended `username*` notation, unterminated quoted strings, empty parameter list, over-long values) plus Basic `token68` variants, and -- with bit 0x02 of byte 0 -- the connection-less digest helpers at several algorithms and several deliberately undersized output buffers. fuzz_postprocessor seeds ------------------------ urlencoded bodies with broken percent escapes, multipart bodies with ordinary, degenerate ("-") and quote-containing boundaries, a multipart Content-Type without a boundary, and a non-POST Content-Type. distilled/ ---------- The edge-minimal residue of the fuzzing campaigns: 2562 inputs, 240 KB, named `-dNNN.bin` and routed by that prefix exactly like the seeds above. Files are numbered in the order the cover picked them, so `-d000` is the highest-gain input of its harness. Unlike `-NN.bin` these are *not* generated from a built-in table, so `refresh-corpus` neither writes nor clobbers them; and unlike `known-findings/` they are not hand-edited and carry no individual meaning. Do not document them one by one -- the set is only ever regenerated wholesale. Provenance: an 8 hour, 12 core, 1.62 billion execution campaign (ASan+UBSan, libFuzzer, hourly restarts) starting from the seed corpus above. The campaign corpus was 18 226 inputs / 12 MB, which is too much to carry in a source tree, so it was reduced by greedy set cover over *edges* rather than by `-merge=1`, which minimises for features and keeps roughly seven times as many files: -merge=1 -merge_control_file=mcf.txt writes a `COV` line per input, and the cover is computed from those offline. Because these harnesses are mildly non-deterministic, the cover is built only from edges that two independent merges agree an input reproduces -- the same "several independent merges" rule stated at the top of this file. The `fuzz_eventloop` and `fuzz_tls` inputs come from a second, 1 hour / 4 core / 17.0 million execution campaign (same sanitizers, same engine, `--enable-https` so that `fuzz_tls` could be built at all -- note that `contrib/oss-fuzz/build.sh` configures `--disable-https`, which is why `fuzz_tls` had no distilled inputs before and started that campaign from its seed table alone). It ran after the PSK scenario and the queue-and-stop scenario were added to those two harnesses, and its starting corpus was this directory plus the first campaign's residue, so what it contributed is beyond what 8 core-hours per harness had already reached: `fuzz_tls` 6355 -> 6844 edges, `fuzz_eventloop` 7406 -> 7655. The other six harnesses were not re-run; their inputs are unchanged. A `COV` line holds only the edges its input was *first* to reach in that merge, so what a cover has to pay for depends on what it is credited with already having. Credit it with everything else that stays in the tree -- both seed sets and the distilled inputs of the harnesses not being regenerated -- because `check-corpus` replays all three directories through every harness, and an input is worth carrying only if it adds an edge none of them reach. Doing that costs nothing and is worth roughly a third of the files: the `fuzz_tls` cover needed 490 edges and 167 inputs against the whole tree, against 1580 edges and 282 inputs when credited with the seed corpus alone -- identical coverage either way, because the other harnesses' inputs were already reaching those 1090 edges. Compute every harness's cover against the same base so that no two of them depend on each other. **An engine-produced corpus is not pristine, and this directory has to be filtered before it can be committed.** `fuzz_request` inputs carry a ground-truth body declaration in their `op == 1` segment, and the body oracle is armed only for a `fuzz_pristine` input precisely because "random mutations invalidate such declarations" (`fuzz_common.h`). libFuzzer mutates that segment independently of the wire segments, so a campaign corpus is full of inputs whose declaration no longer describes their own request -- 383 of 6884 here, 5.6%. Under libFuzzer that is harmless: `-DFUZZ_NO_MAIN` compiles out every assignment to `fuzz_pristine`, so the oracle never arms and the campaign never notices. But `--corpus-dir` sets `fuzz_pristine = 1` for *every* file it reads, so replaying such an input reports a "request body desync" against a declaration that was never true -- a false positive, and one that looks exactly like a request-smuggling finding. Committing the raw cover therefore broke `make check-corpus` with 42 such reports. The fix is to sweep every candidate with `--file=` first and exclude the ones that fire *before* computing the cover, which is what produced the set in this directory; all 2562 files replay clean through all eight harnesses. Anyone replaying a downloaded ClusterFuzz corpus locally will hit the same thing, and it is not a bug in MHD. Sweep every candidate anyway, but expect this particular exclusion only for `fuzz_request`: it is the sole reader of `fuzz_pristine`, so it is the only harness that can report a desync against its own stale declaration. The second campaign's 15 554 candidates produced no rejects at all for that reason. The set reaches ~99% of the first campaign's edges, not 100%: 3763/3798 for fuzz_request, and exactly 100% for the four direct-API harnesses, which are deterministic. Two thirds of that shortfall is the exclusion above -- 64 edges were reached only by inputs with a stale declaration -- and the rest is edges no single input reproduces reliably. Forcing the latter in by adding every input that covers a rare edge was tried and moved the number by one, so that part is inherent to minimising rather than a fixable omission. Trading 1% of edges for 86% fewer files is the intended bargain. Do not chase it. The second campaign lost nothing: `fuzz_eventloop` ends at 7655 of the 7656 edges its campaign corpus reaches, and `fuzz_tls` at 6844 against that corpus' 6770 -- above it, because a `fuzz_tls` cover measured inside the tree also gets the other harnesses' inputs, which are uninteresting to it but not inert. Both harnesses are deterministic enough here that all three `-runs=0` measurements agreed to within two edges. To regenerate after a long campaign: keep the campaign corpus, sweep it for oracle-firing inputs, run two independent merges over what is left, recompute the cover against everything that stays in the tree, and replace the affected harnesses' files wholesale. Check the result the same way it was checked here -- replay both the campaign corpus and the distilled set with `-runs=0` three times each and compare the `INITED cov:` figures, because a single measurement of either is worth a few edges of noise -- and finish with `make check-corpus`. Measure *every* harness before and after, not just the ones being regenerated: dropping an input removes it from the other seven as well. Replacing the 320 first-campaign `fuzz_eventloop` inputs with 248 new ones moved the other six harnesses by at most three edges, which is noise, but that is a thing to confirm rather than assume. Note also that `make check-corpus` is a weaker gate than it looks on a tree configured without `--enable-asserts`, where `mhd_assert()` compiles away entirely; the campaign build has them, so inputs that survived the merges have already been through the stronger one. known-findings/ --------------- Reproducers for the issues that this suite found in MHD itself; see section 6 of ../README, which records the status of each. All of them are fixed on master, so all of them replay clean, and `check-corpus` replays this directory too. A file is named `K--.bin` for the harness that found it; the ones without a harness in the name predate that convention and are all fuzz_request inputs. `contrib/oss-fuzz/make_seed_corpus.sh` routes each into the seed corpus of its own harness on that basis. They are kept as a separate, explicitly named set rather than being folded into the main corpus because the files there are *generated*: a hand-written input would be clobbered or renumbered by the next `refresh-corpus`. Replay one with ./fuzz_request --file=src/fuzz/corpus/known-findings/K1-digest-empty-realm.bin K1-digest-empty-realm.bin digestauth.c is_param_equal() mhd_assert (0 != param->value.len) K2-chunkext-no-space.bin connection.c handle_recv_no_space() K3-chunkext-stop-with-error.bin connection.c transmit_error_response_len() K4a-wsp-first-header.bin connection.c get_req_header(), CLIENT_DISCIPLINE_LVL <= -1 K4b-empty-header-name.bin connection.c get_req_header(), CLIENT_DISCIPLINE_LVL <= -2 K5-bare-cr-keep.bin connection.c get_req_header(), CLIENT_DISCIPLINE_LVL == -3 K6-nonce-length-collision.bin digestauth.c check_nonce_nc() mhd_assert (0 == nn->nonce[noncelen]) K7-upgrade-after-must-close.bin connection.c build_header_response() mhd_assert (upgrade -> MUST_UPGRADE); a single request carrying both Content-Length and chunked Transfer-Encoding, then an upgrade K9-fuzz_postprocessor- postprocessor.c post_process_multipart() nested-boundary-leak.bin leaked the previous nested boundary on every extra nested multipart/mixed part K14-fuzz_eventloop- daemon.c call_handlers() asserted a force-close-not-closed.bin post-condition that MHD_connection_handle_read() does not guarantee when the read buffer is full *** still open, see ../../../patches *** Only fires on an --enable-asserts *ASan* build: the redzones change the pool arithmetic that reaches it. K15-fuzz_eventloop- daemon.c close_all_connections() stop-with-queued-connection.bin asserted that only a daemon with an internal polling thread can have connections queued by MHD_add_connection(), while the code that fills that list queues for any thread-safe daemon. An external event loop that adds a connection and stops before the next MHD_run() aborts on an --enable-asserts build. These files are *not* regenerated by `--write-corpus`; they are edited by hand. When the input format changes they have to be migrated, and the migration has to be checked -- replay each one with `--verbose` before and after and confirm the daemon, handler, body and challenge counts are unchanged. The last such change made the API-selection block unconditional, which is six zero bytes inserted at offset 4 for K1-K6. K8 has no reproducer here: its trigger is an argument the application chooses, not network input, so the harness never performs it. See section 6 of ../README for how to reach it by hand. A reproducer added while its finding is still open will make `make check-corpus` fail, which is intended -- that is what a regression test for an unfixed bug does. `contrib/oss-fuzz/make_seed_corpus.sh` skips such a file so that ClusterFuzz does not spend every run rediscovering it; the rule it uses is whether `patches/$ID.diff` exists. libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-04.bin0000664000175000017500000000005615232214516016706 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-33.bin0000664000175000017500000000004715232414252016016 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-04.bin0000664000175000017500000000004715232214516016015 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-11.bin0000664000175000017500000000006715232141452016701 +GET /a HTTP/1.1 Host: x X-Fold: a b libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-37.bin0000664000175000017500000000005615232214516016714 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-32.bin0000664000175000017500000000004715232414252016015 (GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-10.bin0000664000175000017500000000010115232214516016672 /GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-02.bin0000664000175000017500000000000715232103064020125 a=%libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-03.bin0000664000175000017500000000001015232103064020120 &&&&libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-03.bin0000664000175000017500000000001315232214516017216 #1$1@libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-03.bin0000664000175000017500000000010615232214516016010 AGET /a HTTP/1.1 Host: x GET /b HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-01.bin0000664000175000017500000000016015232141452016672 @ABCDE]POST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 2;ext=val AB 3;a="b;c" CDE 0 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-48.bin0000664000175000017500000000005615232214516016716 2GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-19.bin0000664000175000017500000000005615232214516016714 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-52.bin0000664000175000017500000000005615232214516016711 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-16.bin0000664000175000017500000000004715232141452016704  GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-05.bin0000664000175000017500000000017215232103064020133 --abc ----abc Content-Disposition: form-data; name="k"; filename="f" Content-Type: text/plain value ----abc-- libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-01.bin0000664000175000017500000000005615232214516016703 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-00.bin0000664000175000017500000000002715232214516017407   libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-33.bin0000664000175000017500000000005615232214516016710 @GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-09.bin0000664000175000017500000000001415232103064016015 %41%42%%%0libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-22.bin0000664000175000017500000000004715232141452016701 (GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-30.bin0000664000175000017500000000005715232214516016706 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-37.bin0000664000175000017500000000004715232141452016707 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-43.bin0000664000175000017500000000005615232214516016711 `GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-13.bin0000664000175000017500000000004715232214516016015 !GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-14.bin0000664000175000017500000000002615232103064016014 18446744073709551615libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-17.bin0000664000175000017500000000001215232214516017222 @2@libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-14.bin0000664000175000017500000000005615232214516016707 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-13.bin0000664000175000017500000000002415232214516017410   ` libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-28.bin0000664000175000017500000000006415232414252016021 (GET / HTTP/1.1 Host: test-mhdserver libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-02.bin0000664000175000017500000000005615232214516016704 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-04.bin0000664000175000017500000000012215232103064020125 --abc ----abc Content-Disposition: form-data; name="k" value ----abc-- libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-18.bin0000664000175000017500000000020215232103064016014 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeflibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-05.bin0000664000175000017500000000001415232214516016010 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-11.bin0000664000175000017500000000004715232214516016013 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-12.bin0000664000175000017500000000001315232214516017216 2@_@2libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-07.bin0000664000175000017500000000010115232214516016700 /GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-16.bin0000664000175000017500000000001315232214516017222 !1@2libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-08.bin0000664000175000017500000000001515232214516017225 22@p2libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-40.bin0000664000175000017500000000004715232414252016014 AGET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-17.bin0000664000175000017500000000002015232103064016011 CHUNKEDchunkedlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-03.bin0000664000175000017500000000002115232214516017404 @libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-11.bin0000664000175000017500000000010115232214516016673  /GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-08.bin0000664000175000017500000000004715232214516016021 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-00.bin0000664000175000017500000000001715232103064020124 a=1&b=%41&clibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-09.bin0000664000175000017500000000002715232214516017420 @ libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-05.bin0000664000175000017500000000000415232103064016010 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-30.bin0000664000175000017500000000004715232414252016013 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-06.bin0000664000175000017500000000010115232214516016677 /GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-10.bin0000664000175000017500000000002115232214516017402 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-31.bin0000664000175000017500000000004715232141452016701 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-18.bin0000664000175000017500000000004715232141452016706 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-26.bin0000664000175000017500000000004715232414252016020 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-02.bin0000664000175000017500000000002415232214516017406 @@ @libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-00.bin0000664000175000017500000000023515232103064017452 Digest username="user", realm="TestRealm", nonce="0123456789abcdef", uri="/a", qop=auth, nc=00000001, cnonce="x", algorithm=MD5, response="0123456789abcdef"libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-55.bin0000664000175000017500000000005615232214516016714 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-07.bin0000664000175000017500000000060215232141452016701 GET /a HTTP/1.1 Host: x XGET /a HTTP/1.1 Host: x Authorization: Digest username="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", userhash=true, realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response="0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-05.bin0000664000175000017500000000002415232103064017453 Digest username="\"libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-12.bin0000664000175000017500000000004715232214516016014 )GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-36.bin0000664000175000017500000000004715232141452016706 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-26.bin0000664000175000017500000000005615232214516016712 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-20.bin0000664000175000017500000000004715232414252016012 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-19.bin0000664000175000017500000000004715232414252016022 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-16.bin0000664000175000017500000000001015232214516017406 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-13.bin0000664000175000017500000000001415232214516017220 @@2@libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-14.bin0000664000175000017500000000004715232214516016016 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-00.bin0000664000175000017500000000020215232103064016003 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeflibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-08.bin0000664000175000017500000000002615232103064020134 no boundary at alllibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-39.bin0000664000175000017500000000011015232414252016013 A<POST /a HTTP/1.1 Host: x Content-Length: 11 hello worldlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-06.bin0000664000175000017500000000054715232141452016710 GET /a HTTP/1.1 Host: x =GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/a", qop=auth, nc=00000001, cnonce="deadbeef", algorithm=SHA-256, response="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-12.bin0000664000175000017500000000000715232141452017455 Basic libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-35.bin0000664000175000017500000000004715232141452016705 0GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-32.bin0000664000175000017500000000005615232214516016707 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-31.bin0000664000175000017500000000004715232414252016014  GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-10.bin0000664000175000017500000000003615232103064020126 a"b --a"b v --a"b-- libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-01.bin0000664000175000017500000000005115232214516016005 AGET / HTTP/1.1 Ho st: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-14.bin0000664000175000017500000000004015232214516017407 }0P } libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-14.bin0000664000175000017500000000004715232141452016702  GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-53.bin0000664000175000017500000000005615232214516016712  GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-34.bin0000664000175000017500000000011415232414252016012  @MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUxlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-18.bin0000664000175000017500000000004715232414252016021 !GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-04.bin0000664000175000017500000000002415232103064017452 Digest username*=''libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-01.bin0000664000175000017500000000002715232103064017452 Digest algorithm=BOGUSlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-17.bin0000664000175000017500000000005615232214516016712  GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-05.bin0000664000175000017500000000023215232141452016676 GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="0000", uri="/a", algorithm=BOGUS, response="00" libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-17.bin0000664000175000017500000000004715232414252016020 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-07.bin0000664000175000017500000000001615232214516017225 2`!@1p2libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-08.bin0000664000175000017500000000011315232141452016677 ?GET /a HTTP/1.1 Host: x Authorization: Basic dXNlcjpwYXNz libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-20.bin0000664000175000017500000000030715232141452016676 GET / HTTP/1.1 Host: x GET / HTTP/1.1 Host: x Authorization: Digest username="user", realm="TestRealm", nonce="%%NONCE%%", uri="/", response="00000000000000000000000000000000" libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-00.bin0000664000175000017500000000011015232141452016664 @hello5POST /a HTTP/1.1 Host: x Content-Length: 5 hellolibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-25.bin0000664000175000017500000000010615232214516016705 l4POST /a HTTP/1.1 Host: x Content-Length: 4 abcdlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-03.bin0000664000175000017500000000000415232103064016006 zzlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-08.bin0000664000175000017500000000002415232214516017414 &libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-07.bin0000664000175000017500000000001615232214516017414 & libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-49.bin0000664000175000017500000000013215232214516016712 HGET / HTTP/1.1 Host: x Connection: Upgrade Upgrade: fuzz-protocol libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-35.bin0000664000175000017500000000005615232214516016712 @GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-16.bin0000664000175000017500000000003415232103064016015 chunked, identity, chunkedlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-19.bin0000664000175000017500000000004715232141452016707 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-09.bin0000664000175000017500000000001515232141452017462 Digest ,,,,,libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-02.bin0000664000175000017500000000013115232214516016005 AGET /a HTTP/1.1 Host: x /GET /b HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-12.bin0000664000175000017500000000010115232214516016674 `0/GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-28.bin0000664000175000017500000000005615232214516016714 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-03.bin0000664000175000017500000000004615232141452016677 GET /?novalue HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-13.bin0000664000175000017500000000005615232214516016706 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-04.bin0000664000175000017500000000004415232141452016676 GET /?a=1&b HTTP/1.0 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-12.bin0000664000175000017500000000001215232103064016005 QUJDRA==libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-18.bin0000664000175000017500000000002415232141452017462 user:TestRealm:passlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-28.bin0000664000175000017500000000012615232141452016705  HGET / HTTP/1.1 Host: x Connection: Upgrade Upgrade: fuzz-protocol libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-46.bin0000664000175000017500000000005615232214516016714  GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-36.bin0000664000175000017500000000005615232214516016713 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-14.bin0000664000175000017500000000001615232214516017223 2222@libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-30.bin0000664000175000017500000000004715232141452016700 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-11.bin0000664000175000017500000000002415232214516017406 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-31.bin0000664000175000017500000000005615232214516016706 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-09.bin0000664000175000017500000000031215232141452016701 POST /a HTTP/1.1 Host: x Content-Type: multipart/form-data; boundary=--abc Transfer-Encoding: chunked 52 ----abc Content-Disposition: form-data; name="k" value ----abc-- 0 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-08.bin0000664000175000017500000000010115232214516016701 /GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-15.bin0000664000175000017500000000001315232214516017410 @libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-35.bin0000664000175000017500000000001715232414252016015 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-57.bin0000664000175000017500000000005615232214516016716 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-02.bin0000664000175000017500000000001315232214516017215 "1"@1libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-15.bin0000664000175000017500000000004715232214516016017 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-12.bin0000664000175000017500000000010615232141452016674 :GET /a HTTP/1.1 Host: x GET /b?q HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-40.bin0000664000175000017500000000007115232214516016703 'GET /%41%42?a=%43 HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-19.bin0000664000175000017500000000000315232141452017460 ::libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-34.bin0000664000175000017500000000006215232214516016706 GET /a%00b HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-51.bin0000664000175000017500000000005615232214516016710 @GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-39.bin0000664000175000017500000000005615232214516016716 @GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-07.bin0000664000175000017500000000003015232103064020126 - --- x ----- libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-15.bin0000664000175000017500000000005615232214516016710 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-21.bin0000664000175000017500000000004715232141452016700 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-10.bin0000664000175000017500000000001515232214516017216 !1!@1libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-29.bin0000664000175000017500000000005615232214516016715 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-25.bin0000664000175000017500000000007415232141452016704 0GET /path?a=1 HTTP/1.1 Host: x Cookie: a=b libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-06.bin0000664000175000017500000000002415232214516017412 0} libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-15.bin0000664000175000017500000000004715232141452016703  GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-18.bin0000664000175000017500000000010115232214516016702 /GET /a HTTP/1.1 Host: x Connection: close libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-09.bin0000664000175000017500000000004715232214516016022 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-08.bin0000664000175000017500000000000715232103064017457 Digestlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_memorypool-05.bin0000664000175000017500000000001615232214516017412  DDDlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-27.bin0000664000175000017500000000005615232214516016713 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-07.bin0000664000175000017500000000004715232214516016020 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-20.bin0000664000175000017500000000000115232141452017446 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-13.bin0000664000175000017500000000004715232141452016701 j GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-59.bin0000664000175000017500000000013015232214516016711 FPOST /a HTTP/1.1 Host: x Transfer-Encoding: chunked 3 abc 0 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-41.bin0000664000175000017500000000004715232414252016015 AGET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-00.bin0000664000175000017500000000004715232214516016011 AGET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-06.bin0000664000175000017500000000001615232103064016014 /a%41%42%zz%libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-26.bin0000664000175000017500000000005115232141452016700 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-09.bin0000664000175000017500000000002315232103064020132 text/plain bodylibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-42.bin0000664000175000017500000000005615232214516016710  GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-21.bin0000664000175000017500000000004715232414252016013 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-04.bin0000664000175000017500000000000615232103064016011 libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-06.bin0000664000175000017500000000004615232103064017460 Digest userhash=true, username="aaaa"libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-36.bin0000664000175000017500000000002515232414252016015 ?libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-14.bin0000664000175000017500000000001715232141452017460 Basic QQ==QQ==libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_request-23.bin0000664000175000017500000000004715232141452016702 GET / HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-17.bin0000664000175000017500000000002415232141452017461 Buser:TestRealm:passlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_postprocessor-06.bin0000664000175000017500000000004315232103064020131 XY --XY noheaders --XY-- libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_tls-38.bin0000664000175000017500000000016515232414252016024 AiGET /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa HTTP/1.1 Host: x X-Long: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_eventloop-15.bin0000664000175000017500000000001315232214516017221 4444@libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_str-13.bin0000664000175000017500000000001215232103064016006 QUJDR===libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-15.bin0000664000175000017500000000002415232141452017457 user:TestRealm:passlibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-05.bin0000664000175000017500000000005615232214516016707 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-00.bin0000664000175000017500000000005615232214516016702 GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_auth_header-03.bin0000664000175000017500000000003615232103064017454 Digest username*=UTF-8''a%20blibmicrohttpd-1.0.10/src/fuzz/corpus/fuzz_options-54.bin0000664000175000017500000000005615232214516016713 @GET /a HTTP/1.1 Host: x libmicrohttpd-1.0.10/src/fuzz/BUILD-INTEGRATION.md0000664000175000017500000002205015232144110014637 # Build integration for `src/fuzz/` > **Status: applied.** The three changes described below are already > present in this tree — `configure.ac` carries the `--enable-fuzzing` > option and the `ENABLE_FUZZING` conditional, `AC_CONFIG_FILES` lists > `src/fuzz/Makefile`, and `src/Makefile.am` adds `fuzz` to `SUBDIRS` > under that conditional. Only §1.3 (the optional configuration-summary > line) is *not* applied. The sections below are kept as the record of > what was changed and as the recipe for porting `src/fuzz/` to another > branch. > > For running these same harnesses on OSS-Fuzz — a different build path > that does **not** go through `src/fuzz/Makefile.am` — see > `../../contrib/oss-fuzz/` and §6 at the end of this file. `src/fuzz/Makefile.am` is complete. Three files outside `src/fuzz/` have to be touched. The snippets below are the *exact* text that was added; nothing else changes. The harnesses are guarded by a new automake conditional `ENABLE_FUZZING` (`--enable-fuzzing`, default **no**), because they are only meaningful in a build with sanitizers and assertions, and because they need a static archive of the library (they call functions that are hidden in the shared object). --- ## 1. `configure.ac` ### 1.1 The `--enable-fuzzing` option and the conditional Add this next to the other feature checks — a good spot is right after the `AM_CONDITIONAL([RUN_ZZUF_TESTS], ...)` / `AM_CONDITIONAL([FORCE_USE_ZZUF_SOCAT], ...)` pair (around line 5833 in the v1.0.7 tree): ```m4 # Fuzzing harnesses (src/fuzz) AC_MSG_CHECKING([[whether to build the fuzzing harnesses]]) AC_ARG_ENABLE([[fuzzing]], [AS_HELP_STRING([[--enable-fuzzing]], [build the in-process fuzzing harnesses in src/fuzz and run them ] [as part of "make check"; requires a static build of the library ] [and is only really useful together with --enable-asserts and ] [--enable-sanitizers=address,undefined [no]])], [], [enable_fuzzing="no"]) AS_VAR_IF([enable_fuzzing], ["yes"], [ AS_VAR_IF([enable_static], ["no"], [AC_MSG_RESULT([[no]]) AC_MSG_ERROR([[--enable-fuzzing requires --enable-static]])], [AC_MSG_RESULT([[yes]])]) ], [enable_fuzzing="no" AC_MSG_RESULT([[no]])]) AM_CONDITIONAL([ENABLE_FUZZING], [[test "x$enable_fuzzing" = "xyes"]]) ``` ### 1.2 Register the new `Makefile` In the final `AC_CONFIG_FILES([...])` list (around line 5931 of the v1.0.7 tree) add `src/fuzz/Makefile`, i.e. change ``` src/microhttpd/Makefile ... src/testzzuf/Makefile]) ``` to ``` src/microhttpd/Makefile ... src/testzzuf/Makefile src/fuzz/Makefile]) ``` ### 1.3 (optional, NOT applied) mention it in the configuration summary If you want the harness state to show up in the final summary, add a line next to the other `AC_MSG_NOTICE` entries: ```m4 AC_MSG_NOTICE([[ Fuzzing harnesses: ${enable_fuzzing}]]) ``` --- ## 2. `src/Makefile.am` Add the conditional `SUBDIRS` entry. The current file reads ```make SUBDIRS = include microhttpd . if RUN_LIBCURL_TESTS SUBDIRS += testcurl if RUN_ZZUF_TESTS SUBDIRS += testzzuf endif endif ``` Add immediately after that block: ```make if ENABLE_FUZZING SUBDIRS += fuzz endif ``` Automake derives `DIST_SUBDIRS` from all branches of `SUBDIRS` automatically, so `make dist` keeps working and ships `src/fuzz/` regardless of the conditional. --- ## 3. `Makefile.am` (top level) — nothing to do `src/fuzz/` is reached through `src/Makefile.am`; the top-level file needs no change. --- ## 4. Regenerate and build ```sh autoreconf -fi # or ./bootstrap ./configure --enable-fuzzing \ --enable-static \ --enable-asserts \ --enable-sanitizers=address,undefined \ --disable-doc --disable-examples make make -C src/fuzz check ``` A full fuzzing session: ```sh make -C src/fuzz check \ MHD_FUZZ_ITERATIONS=5000000 \ MHD_FUZZ_SEED=$RANDOM ``` Replay the checked-in corpus (what CI should do after a fix): ```sh make -C src/fuzz check-corpus ``` --- ## 5. Notes / caveats * **`--enable-static` is mandatory.** `fuzz_str` and `fuzz_auth_header` call `MHD_hex_to_bin()`, `MHD_str_quote()`, `MHD_pool_create()`, `MHD_get_rq_dauth_params_()` etc., which are built with `$(HIDDEN_VISIBILITY_CFLAGS)` and are therefore not exported from `libmicrohttpd.so`. The `-static` in the per-program `_LDFLAGS` makes libtool pick `.libs/libmicrohttpd.a`. * `fuzz_auth_header` is only built when `HAVE_ANYAUTH` is true (Basic or Digest authentication enabled). Inside the harness the individual code paths are additionally guarded by `DAUTH_SUPPORT` / `BAUTH_SUPPORT`, and `fuzz_str` guards `MHD_str_unquote()`, `MHD_str_quote()` and `MHD_base64_to_bin_n()` the same way, so a `--disable-dauth --disable-bauth` build still compiles. * `fuzz_postprocessor` needs `--enable-postprocessor` (the default); if you build with `--disable-postprocessor`, additionally guard it with the existing `HAVE_POSTPROCESSOR` conditional: ```make if HAVE_POSTPROCESSOR check_PROGRAMS += fuzz_postprocessor endif ``` (it is currently listed unconditionally, matching the default build). * The harnesses include internal headers (`internal.h`, `memorypool.h`, `gen_auth.h`, `mhd_str.h`), hence the `-I$(top_srcdir)/src/microhttpd` in `AM_CPPFLAGS`. `MHD_config.h` is found through automake's default `-I$(top_builddir)`. * `make check` in `src/fuzz` runs the full discipline / memory-limit range (`MHD_FUZZ_MIN_DISCIPLINE=-3`, `MHD_FUZZ_MIN_MEM_LIMIT=0`) with 50000 iterations per harness, roughly 3 seconds in total under ASAN+UBSAN. The findings K1-K8 of `README` section 6 are all fixed on master, so the full range is clean; their reproducers stay in `corpus/known-findings/`, and `make check-corpus` replays that directory alongside the generated corpus. Both only mean anything on a tree configured with `--enable-asserts`: most of those reproducers trip an `mhd_assert()`, which compiles away without it. --- ## 6. The OSS-Fuzz build path (does not use this Makefile.am) `contrib/oss-fuzz/` builds the *same four harness sources* for libFuzzer/AFL++/honggfuzz without going through `src/fuzz/Makefile.am` at all. It configures the library out of tree, then compiles each harness by hand with `-DFUZZ_NO_MAIN` and links it against `$LIB_FUZZING_ENGINE`: ```sh $CC $CFLAGS -DFUZZ_NO_MAIN \ -I$BUILD -I$SRCDIR -I$SRCDIR/src/include \ -I$SRCDIR/src/microhttpd -I$SRCDIR/src/fuzz \ -c $SRCDIR/src/fuzz/fuzz_request.c -o $WORK/fuzz_request.o $CXX $CXXFLAGS $WORK/fuzz_request.o -o $OUT/fuzz_request \ $LIB_FUZZING_ENGINE $BUILD/src/microhttpd/.libs/libmicrohttpd.a -lpthread ``` Two consequences for anyone editing `src/fuzz/`: * **`LLVMFuzzerTestOneInput()` must stay unconditional.** Only `main()` may be `#ifndef FUZZ_NO_MAIN`; a harness whose fuzz target is itself conditional silently produces an empty OSS-Fuzz binary. * **Anything the fuzz target needs must not live inside the `#ifndef FUZZ_NO_MAIN` block of `fuzz_common.h`.** The PRNG, the crash bookkeeping, `fuzz_report_finding()` and `fuzz_ignore_sigpipe()` are outside it; the generator loop, the mutator, the corpus walker and `main()` are inside. This is easy to get wrong and the failure is silent, so it is worth spelling out how it already bit us once. `signal (SIGPIPE, SIG_IGN)` used to sit in `fuzz_install_handlers()`, i.e. inside the block. Under the built-in driver everything looked perfect; under `-DFUZZ_NO_MAIN` the call vanished, and since `fuzz_request` writes into a socketpair whose peer MHD closes on any input that terminates the connection early, the process took a SIGPIPE and died after a few dozen executions. libFuzzer does not intercept SIGPIPE (there is no `-handle_sigpipe`; see `-help=1`), so there was no stack trace, no artifact and no crash report -- the target just stopped, which reads exactly like a clean run that found nothing. It is now `fuzz_ignore_sigpipe()`, called from both the driver and `LLVMFuzzerTestOneInput()`. The lesson generalises: a bug in this split cannot be caught by `make -C src/fuzz check`, because that path always defines `main()`. After touching `fuzz_common.h`, build the OSS-Fuzz way as well and confirm the target still runs -- `contrib/oss-fuzz/build.sh` works standalone on any machine with clang and `libclang-rt-dev`: ```sh git clone --shared . /tmp/mhd-fuzz-src # build.sh needs a tree # with no in-tree config.status WORK=/tmp/mhd-fuzz-work OUT=/tmp/mhd-fuzz-out \ MHD_SRC=/tmp/mhd-fuzz-src /tmp/mhd-fuzz-src/contrib/oss-fuzz/build.sh /tmp/mhd-fuzz-out/fuzz_request /tmp/mhd-fuzz-out/../corpus -max_total_time=60 echo "exit=$?" # anything but 0 here is a bug in the harness, # not a finding ``` `contrib/oss-fuzz/` also relies on two things this directory provides: `make -C src/fuzz refresh-corpus` (to regenerate `corpus/`) and the `corpus/known-findings/` reproducers, which it packages into `fuzz_request_seed_corpus.zip` so that they become permanent regressions. It is deliberately **not** part of `contrib/ci/jobs/`. libmicrohttpd-1.0.10/src/fuzz/fuzz_postprocessor.c0000664000175000017500000003156715232103064016064 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file fuzz/fuzz_postprocessor.c * @brief Fuzzer for MHD_post_process() * @author Christian Grothoff * * MHD_create_post_processor() only ever looks at the "Content-Type" * header of the connection it is given, so this harness fabricates the * minimal connection object instead of pushing a whole request through * a socket. That keeps the harness fast and lets the fuzzer control * three dimensions that matter for the post processor and that a real * request would not expose directly: * * - the raw Content-Type (encoding and multipart boundary), * - the post processor buffer size, * - how the POST data is split across MHD_post_process() calls. * * Input format: * byte 0 content type selector * byte 1 post processor buffer size selector * byte 2 chunking pattern selector * byte 3 length of the boundary taken from the payload * byte 4.. the POST data */ #define FUZZ_HARNESS_NAME "fuzz_postprocessor" #include "fuzz_common.h" /* internal.h pulls in MHD_config.h and in the right order; including first would redefine _MHD_EXTERN. */ #include "internal.h" static const size_t pp_buf_sizes[] = { 256, 257, 300, 512, 1024, 2048, 4096, 65536 }; static const size_t chunk_patterns[] = { 1, 2, 3, 5, 7, 13, 32, 64, 1024, 0 /* 0 == everything at once */ }; static struct MHD_Daemon *shared_daemon; /** Statistics, printed at exit with --verbose. */ static unsigned long stat_pp_created; static unsigned long stat_pp_failed; static unsigned long stat_values; static enum MHD_Result dummy_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; (void) connection; (void) url; (void) method; (void) version; (void) upload_data; (void) upload_data_size; (void) req_cls; return MHD_NO; } static void stop_shared_daemon (void) { if (NULL != shared_daemon) { MHD_stop_daemon (shared_daemon); shared_daemon = NULL; } } static void print_stats (void) { if (! fuzz_verbose) return; fprintf (stderr, "%s: post processors created=%lu rejected=%lu, " "values reported=%lu\n", FUZZ_HARNESS_NAME, stat_pp_created, stat_pp_failed, stat_values); } static struct MHD_Daemon * get_shared_daemon (void) { if (NULL == shared_daemon) { shared_daemon = MHD_start_daemon (MHD_USE_NO_LISTEN_SOCKET | (fuzz_verbose ? MHD_USE_ERROR_LOG : 0u), 0, NULL, NULL, &dummy_ahc, NULL, MHD_OPTION_END); if (NULL != shared_daemon) { (void) atexit (&stop_shared_daemon); (void) atexit (&print_stats); } } return shared_daemon; } struct pp_ctx { const char *data; size_t data_len; uint64_t max_off; }; static enum MHD_Result post_iter (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct pp_ctx *ctx = (struct pp_ctx *) cls; volatile size_t sink = 0; (void) kind; stat_values++; /* Touch every string the post processor claims to have produced; ASAN turns any dangling or out-of-bounds pointer into an error. */ if (NULL != key) sink += strlen (key); if (NULL != filename) sink += strlen (filename); if (NULL != content_type) sink += strlen (content_type); if (NULL != transfer_encoding) sink += strlen (transfer_encoding); if ( (NULL != data) && (0 != size) ) { size_t i; for (i = 0; i < size; i++) sink += (size_t) (unsigned char) data[i]; } else if (NULL == data) { if (0 != size) fuzz_report_finding ("MHD_PostDataIterator called with NULL data but " "non-zero size"); } /* A single value is delivered in order and can never be longer than the POST data that was fed in. */ if (off + size > ctx->data_len + 1) fuzz_report_finding ("MHD_PostDataIterator reported more value data " "than the POST data contained"); if (off > ctx->max_off + ctx->data_len) fuzz_report_finding ("MHD_PostDataIterator offset jumped implausibly"); ctx->max_off = off; (void) sink; return MHD_YES; } int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { struct MHD_Connection c; struct MHD_HTTP_Req_Header h; struct MHD_PostProcessor *pp; struct pp_ctx ctx; char *ctype; char *body; size_t body_len; size_t buf_size; size_t chunk; size_t off; size_t blen; unsigned int sel; if (size < 5) return 0; if (NULL == get_shared_daemon ()) return 0; sel = data[0]; buf_size = pp_buf_sizes[data[1] % (sizeof (pp_buf_sizes) / sizeof (pp_buf_sizes[0]))]; chunk = chunk_patterns[data[2] % (sizeof (chunk_patterns) / sizeof (chunk_patterns[0]))]; blen = data[3]; body_len = size - 4; if (body_len > 8192) body_len = 8192; if (blen > body_len) blen = body_len; /* Exactly sized copies so that ASAN catches reads past the end. */ body = (char *) malloc (body_len + 1); if (NULL == body) return 0; memcpy (body, data + 4, body_len); body[body_len] = '\0'; ctype = (char *) malloc (blen + 64); if (NULL == ctype) { free (body); return 0; } switch (sel % 6) { case 0: memcpy (ctype, MHD_HTTP_POST_ENCODING_FORM_URLENCODED, sizeof (MHD_HTTP_POST_ENCODING_FORM_URLENCODED)); break; case 1: case 2: { /* multipart with a boundary taken from the payload */ size_t o = 0; size_t i; memcpy (ctype, MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA, sizeof (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA) - 1); o = sizeof (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA) - 1; memcpy (ctype + o, "; boundary=", 11); o += 11; for (i = 0; i < blen; i++) { char ch = body[i]; /* A NUL would truncate the header value; map it away. */ ctype[o++] = ('\0' == ch) ? 'x' : ch; } ctype[o] = '\0'; break; } case 3: (void) snprintf (ctype, blen + 64, "multipart/form-data; boundary=\"%.*s\"", (int) ((blen > 40) ? 40 : blen), body); break; case 4: memcpy (ctype, MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA, sizeof (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA)); break; default: memcpy (ctype, "text/plain", sizeof ("text/plain")); break; } memset (&c, 0, sizeof (c)); memset (&h, 0, sizeof (h)); h.header = MHD_HTTP_HEADER_CONTENT_TYPE; h.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE); h.value = ctype; h.value_size = strlen (ctype); h.kind = MHD_HEADER_KIND; c.daemon = shared_daemon; c.rq.headers_received = &h; c.rq.headers_received_tail = &h; c.state = MHD_CONNECTION_HEADERS_PROCESSED; ctx.data = body; ctx.data_len = body_len; ctx.max_off = 0; pp = MHD_create_post_processor (&c, buf_size, &post_iter, &ctx); if (NULL == pp) { stat_pp_failed++; free (ctype); free (body); return 0; } stat_pp_created++; off = 0; while (off < body_len) { size_t n = (0 == chunk) ? (body_len - off) : chunk; if (n > body_len - off) n = body_len - off; (void) MHD_post_process (pp, body + off, n); off += n; } /* Final, zero-length call: what MHD itself does at the end of the upload. */ (void) MHD_post_process (pp, body + body_len, 0); (void) MHD_destroy_post_processor (pp); free (ctype); free (body); return 0; } /* ------------------------------------------------------------------ */ /* Generator */ /* ------------------------------------------------------------------ */ static const char *const gen_disp[] = { "Content-Disposition: form-data; name=\"a\"", "Content-Disposition: form-data; name=\"a\"; filename=\"f.txt\"", "Content-Disposition: form-data; name=a", "Content-Disposition: form-data", "Content-Disposition: attachment; name=\"a\"", "Content-Disposition: form-data; name=\"\"", "Content-Disposition: form-data; name=\"a", "Content-Type: text/plain", "Content-Transfer-Encoding: binary", "X-Other: value" }; static const char *const gen_kv[] = { "a=1", "b=%41", "c", "d=", "=e", "&", "&&", "a=%", "a=%4", "a=%zz", "verylongkeyname=verylongvaluewithlotsofcharacters", "a+b=c+d", "%41%42=%43%44" }; static size_t fuzz_generate (struct fuzz_rng *rng, uint8_t *buf, size_t cap) { size_t len = 0; int multipart; const char *boundary; unsigned int nparts; unsigned int i; static const char *const boundaries[] = { "--abc", "XY", "boundary", "-", "aa", "0123456789012345678901234567890", "a\"b" }; #define ADD(s) \ do { \ const char *s_ = (s); \ size_t l_ = strlen (s_); \ if (len + l_ >= cap) \ return len; \ memcpy (buf + len, s_, l_); \ len += l_; \ } while (0) if (cap < 64) return 0; multipart = ! fuzz_chance (rng, 3); boundary = boundaries[fuzz_below (rng, (uint32_t) (sizeof (boundaries) / sizeof (char *)))]; buf[len++] = (uint8_t) (multipart ? (1 + fuzz_below (rng, 2)) : 0); buf[len++] = fuzz_byte (rng); buf[len++] = fuzz_byte (rng); buf[len++] = (uint8_t) strlen (boundary); if (multipart) { /* The first strlen(boundary) bytes of the body double as the boundary in the Content-Type header (see the input format). */ ADD (boundary); nparts = 1 + fuzz_below (rng, 4); for (i = 0; i < nparts; i++) { unsigned int nhdr = fuzz_below (rng, 3); unsigned int k; ADD ("\r\n--"); ADD (boundary); ADD ("\r\n"); for (k = 0; k <= nhdr; k++) { ADD (gen_disp[fuzz_below (rng, (uint32_t) (sizeof (gen_disp) / sizeof (char *)))]); ADD ("\r\n"); } ADD ("\r\n"); { unsigned int n = fuzz_below (rng, 40); for (k = 0; (k < n) && (len < cap); k++) buf[len++] = (uint8_t) ('A' + fuzz_below (rng, 26)); } } ADD ("\r\n--"); ADD (boundary); ADD (fuzz_chance (rng, 4) ? "\r\n" : "--\r\n"); } else { unsigned int n = 1 + fuzz_below (rng, 10); for (i = 0; i < n; i++) { if (0 != i) ADD ("&"); ADD (gen_kv[fuzz_below (rng, (uint32_t) (sizeof (gen_kv) / sizeof (char *)))]); } } #undef ADD return len; } /* ------------------------------------------------------------------ */ /* Seed corpus */ /* ------------------------------------------------------------------ */ struct pp_seed { const char *txt; size_t len; }; #define PSEED(t) { t, sizeof (t) - 1 } static const struct pp_seed pp_seeds[] = { PSEED ("\x00\x00\x00\x00" "a=1&b=%41&c"), PSEED ("\x00\x00\x04\x00" "a=1&b=%41&c"), PSEED ("\x00\x00\x00\x00" "a=%"), PSEED ("\x00\x00\x00\x00" "&&&&"), PSEED ("\x01\x00\x00\x05" "--abc\r\n----abc\r\n" "Content-Disposition: form-data; name=\"k\"\r\n\r\nvalue\r\n" "----abc--\r\n"), PSEED ("\x01\x00\x01\x05" "--abc\r\n----abc\r\n" "Content-Disposition: form-data; name=\"k\"; filename=\"f\"\r\n" "Content-Type: text/plain\r\n\r\nvalue\r\n----abc--\r\n"), PSEED ("\x01\x07\x02\x02" "XY\r\n--XY\r\n\r\nnoheaders\r\n--XY--\r\n"), PSEED ("\x01\x00\x00\x01" "-\r\n---\r\n\r\nx\r\n-----\r\n"), PSEED ("\x04\x00\x00\x00" "no boundary at all"), PSEED ("\x05\x00\x00\x00" "text/plain body"), PSEED ("\x03\x00\x00\x03" "a\"b\r\n--a\"b\r\n\r\nv\r\n--a\"b--\r\n") }; static size_t fuzz_seed_count (void) { return sizeof (pp_seeds) / sizeof (pp_seeds[0]); } static const uint8_t * fuzz_seed_get (size_t idx, size_t *len) { *len = pp_seeds[idx].len; return (const uint8_t *) pp_seeds[idx].txt; } libmicrohttpd-1.0.10/src/fuzz/README0000664000175000017500000013717415232414252012602 GNU libmicrohttpd -- in-process fuzzing harnesses ================================================= This directory contains eight in-process fuzzing harnesses for MHD. All of them are *dual mode*: * they export the libFuzzer entry point int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size); so the very same source can be linked with clang/libFuzzer, AFL++ or OSS-Fuzz, and * they ship a **built-in standalone driver** (`fuzz_common.h`) with a deterministic, seeded generator + mutator loop, so they are useful with nothing but gcc and `-fsanitize=address,undefined`. The standalone driver is compiled unless `FUZZ_NO_MAIN` is defined. ------------------------------------------------------------------- 1. The harnesses ------------------------------------------------------------------- fuzz_request.c the flagship. Feeds arbitrary bytes into a real `struct MHD_Daemon` through a `socketpair()`, using MHD_USE_NO_LISTEN_SOCKET + MHD_add_connection() and external polling (MHD_run()). Everything runs in one thread, so the harness is deterministic and fast (~20k requests/s under ASAN+UBSAN). fuzz_str.c direct fuzzing of the string primitives in src/microhttpd/mhd_str.c. Every output buffer is malloc()ed at *exactly* the documented size so that ASAN's redzone catches a one-byte overrun. fuzz_auth_header.c direct fuzzing of the "Authorization:" header parsers, MHD_get_rq_dauth_params_() and MHD_get_rq_bauth_params_() (gen_auth.c), through a minimal fabricated `struct MHD_Connection`. ~250k execs/s. fuzz_postprocessor.c fuzzing of MHD_post_process() with random Content-Type (urlencoded / multipart with random boundaries), random post-processor buffer sizes and random chunking of the POST data. fuzz_options.c the daemon *configuration* surface. fuzz_request always starts the daemon in one shape; this one lets the input pick the MHD_FLAG bits and the MHD_OPTION array, so the flag validation in MHD_start_daemon(), parse_options_va(), the internal polling thread, the thread pool, epoll/poll/select, the listen socket, the per-IP and per-daemon connection limits and quiesce all become reachable. fuzz_eventloop.c the external event loop and the scheduling of the connection life cycle. The input is not a request but a *schedule*: a program of one-byte opcodes interpreted against a live daemon, so the application can poll at adversarial times, ignore the timeout it was given, call MHD_run_from_select() with descriptor sets that do not match what MHD asked for, and suspend/resume across those calls. Byte 3 bit 4 also lets it stop the daemon with a connection queued by MHD_add_connection() but never started, which is the only way into new_connection_close_() -- see section 5.5. fuzz_memorypool.c direct fuzzing of src/microhttpd/memorypool.c, the per-connection bump allocator. A single mis-computed offset there is a cross-request information leak that ASAN cannot see on its own, because the whole pool is one malloc()ed object; the harness therefore carries its own oracles and knows the red zone size that MHD_ASAN_POISON_ACTIVE adds between two blocks. fuzz_tls.c MHD's own TLS plumbing -- the MHD_USE_TLS option surface (HTTPS_MEM_KEY/CERT/TRUST/DHPARAMS, PRIORITIES, CRED_TYPE, KEY_PASSWORD, ALPN, SNI, GNUTLS_PSK_CRED_HANDLER) rather than GnuTLS, which has its own OSS-Fuzz project. Byte 9 bit 7 switches on the TLS-PSK scenario, the only route to psk_gnutls_adapter() -- see section 5.5. It needs a TLS backend and is therefore the one harness contrib/oss-fuzz/build.sh does not build (that build is --disable-https). Shared code lives in `fuzz_common.h` (header-only, so every harness stays a single translation unit). ------------------------------------------------------------------- 2. Design of fuzz_request ------------------------------------------------------------------- 2.1 Why a socketpair -------------------- MHD_add_connection() accepts any already-connected socket, so a `socketpair(AF_UNIX, SOCK_STREAM)` is enough: no listen socket, no port, no TCP stack, no second thread. The daemon is started with MHD_USE_NO_LISTEN_SOCKET and *without* MHD_USE_INTERNAL_POLLING_THREAD, and the harness pumps it with MHD_run() between sends. A fake 127.0.0.1 `struct sockaddr_in` is passed so that per-IP accounting and MHD_get_connection_info() see something sane. 2.2 Input format ---------------- byte 0 connection memory limit selector (index into {default,128,192,256,320,384,512,768,1024, 1400,1500,2048,4096,32768}) byte 1 handler behaviour bitmask 0x01 call MHD_digest_auth_check3() / MHD_queue_auth_required_response3() 0x02 call MHD_basic_auth_get_username_password3() 0x04 run the request body through MHD_post_process() 0x08 iterate MHD_get_connection_values() over headers, GET arguments, cookies and footers 0x10 unused (see 2.2.1) 0x20 reply with a larger, copied response body (only meaningful for response kind 0) 0x40 reply 403 instead of 200 0x80 unused byte 2 low nibble: MHD_OPTION_CLIENT_DISCIPLINE_LVL selector (index into {-3,-2,-1,0,1,2}); high nibble: reserved for MHD_OPTION_SERVER_INSANITY (MHD 1.0.7 only defines MHD_DSC_SANE, so the value is 0) byte 3 digest configuration: bits 0-1 select the algorithm of the 401 challenge {SHA-256, MD5, SHA-512-256, SHA-256}, bit 2 selects the QOP, bits 4-5 select MHD_OPTION_NONCE_NC_SIZE byte 4-9 the API-selection block, see 2.2.1 byte 10. a sequence of *send segments*. Each segment starts with a little-endian 16 bit header: (op << 14) | length length <= 0x3FFF op 0 send `length` bytes on the current connection op 1 the payload is the *expected decoded request body* (ground truth for the body oracle, see 2.4); it is not sent op 2 send, then pump the daemon for extra rounds op 3 close the current connection, open a fresh one on the same daemon, then send An explicit length encoding (rather than a magic delimiter) is used so that the fuzzer can move a split point without having to invent an escaping scheme. Splitting matters: MHD's parser is incremental and several bugs only appear for particular split points. An input shorter than ten bytes is rejected: the configuration block is mandatory, and an input that short has no segment stream either. 2.2.1 The API-selection block ----------------------------- Bytes 4-9 pick which parts of the public API the iteration touches. They are always present. Bytes 0-3 alone decide how MHD *parses* the request; these six decide which of the response constructors, which authentication entry point, which event loop, and which introspection calls run against the parsed result. The all-zero setting is the plainest one -- a static two byte buffer response, MHD_run() as the event loop, no suspend, no upgrade, no extra introspection -- so zeroing bytes 4-9 of any input reduces it to the request-parsing-only behaviour that the harness had before these bytes existed. These bytes were gated behind bit 0x10 of byte 1 while they were being brought up, so that the corpus predating them kept its byte-exact meaning. The gate is gone; bit 0x10 is left unused rather than reassigned, so that a corpus file written while it was a gate cannot silently change meaning. The reproducers in known-findings/ that predate the change (K1-K6, seven files) were migrated by inserting six zero bytes at offset 4 -- the identity transformation, since the all-zero block is the old behaviour -- and all seven still drive MHD along their recorded paths, verified by comparing the --verbose daemon, handler, body and challenge counts before and after. byte 4 response construction bits 0-3 which constructor to use: 0 buffer_static 1 buffer_copy 2 empty 3 buffer/PERSISTENT 4 buffer/MUST_FREE 5 buffer/MUST_COPY 6 buffer_with_free_callback 7 data (copy) 8 data (free) 9 callback, known length 10 callback, MHD_SIZE_UNKNOWN (chunked reply) 11 fd 12 fd_at_offset 13 fd64 14 pipe 15 iovec bits 4-5 number of response headers to add (0-3) bit 6 also add a response footer (a chunked trailer) bit 7 exercise MHD_get_response_header(), MHD_get_response_headers(), MHD_del_response_header() and MHD_set_response_options() byte 5 authentication entry point bits 0-3 0 check3 (as before) 1 check 2 check2 3 check_digest 4 check_digest2 5 check_digest3 6 get_username 7 get_username3 8 get_request_info3 9 as 0 bits 4-5 challenge variant: 0 queue_auth_required_response3, 1 queue_auth_fail_response, 2 queue_auth_fail_response2, 3 the basic-auth pair bit 6 use the v1 MHD_basic_auth_get_username_password() bit 7 also call the connection-less digest helpers byte 6 event loop and introspection bits 0-1 0 MHD_run(), 1 MHD_get_fdset()+run_from_select(), 2 and 3 the *2 variants bit 2 query all four MHD_get_timeout*() forms bit 3 MHD_lookup_connection_value(), MHD_lookup_connection_value_n(), MHD_get_connection_URI_path_n() bit 4 MHD_set_connection_value() bit 5 MHD_get_connection_info() / MHD_get_daemon_info() bit 6 MHD_set_connection_option() bit 7 MHD_quiesce_daemon() before stopping byte 7 suspend and upgrade bits 0-1 0 none, 1 suspend+resume in the handler, 2 suspend and resume from the pump loop, 3 as 1 bit 2 allow HTTP "Upgrade" (only acted on when the request really asks for one, see below) bits 3-4 which MHD_upgrade_action() to issue first byte 8 seed picking the response header names and values, and the MHD_RF_* flags for MHD_set_response_options() byte 9 seed for the content-reader callback: body length, block size, and whether it fails part way through Two constraints on the harness are worth stating, because both are application-contract requirements rather than things worth fuzzing, and violating either makes MHD abort on input that is perfectly legal: * the connection is only suspended when the handler is about to return MHD_YES. Returning MHD_NO asks MHD to terminate the connection, and terminating one that the same callback just suspended trips mhd_assert (! connection->suspended) in MHD_connection_close_(); * a 101 response is only queued for a request that is actually an upgrade request (HTTP/1.1, an "Upgrade" header, and a "Connection" header naming the upgrade token and not "close"). All three come off the wire, so the path stays attacker-driven. This is exactly the check a real application can perform, and no more. It deliberately does not try to predict whether MHD will accept the upgrade: a request that passes it used to abort MHD, which is finding K7 in section 6, and MHD_queue_response() now answers MHD_NO for that case instead. Do not tighten the condition to keep the suite green -- an application cannot do better than this, so neither should the harness. The message-framing headers (Content-Length, Transfer-Encoding) are deliberately absent from the response-header table: MHD generates them itself from the response object, so an application that also sets them by hand is lying to the library about its own body. MHD_RF_INSANITY_HEADER_CONTENT_LENGTH is the sanctioned way to explore that corner and is reachable through bit 7 of byte 4. 2.3 The %%NONCE%% placeholder ----------------------------- Interesting parts of digestauth.c are only reached *after* the client presents a nonce that MHD itself generated. A stateless fuzzer can never guess one. Therefore the harness rewrites the literal ASCII token %%NONCE%% inside a segment, at send time, into the most recent `nonce="..."` value seen in a response from the daemon. A generated (or hand-written) input can thus be: request 1: GET /a -> handler calls MHD_digest_auth_check3(), gets MHD_DAUTH_WRONG_HEADER and replies 401 + WWW-Authenticate: Digest ... nonce="X" op 3: new connection request 2: GET /a with Authorization: Digest ... nonce="%%NONCE%%" which walks all the way into the 'response' comparison. Without this the over-long `response=` stack overflow (see 5.4) is unreachable. 2.4 Oracles ----------- Memory errors are caught by ASAN/UBSAN and aborts by the signal handlers. In addition fuzz_request installs two behavioural oracles: a) MHD_set_panic_func() -- any MHD_PANIC() reached from network input is a finding (a remote abort), not a legitimate "API violation". b) A request-body oracle. Framing bugs (chunked transfer coding, Content-Length) do not corrupt memory, they corrupt *data*, which is exactly what HTTP request smuggling exploits. The input can therefore declare the expected decoded body in an `op 1` segment. Every byte that MHD hands to the application must be the next expected byte, and when MHD completes the request the delivered body must be complete. MHD is free to reject the request at any point -- only what it *does* deliver is checked. The declaration is honoured only for un-mutated inputs (the driver exposes this as `fuzz_pristine`), because a random mutation would of course invalidate the ground truth. 2.5 The generator ----------------- Purely random bytes essentially never form a valid HTTP request, so the standalone driver uses a small HTTP grammar (`fuzz_generate()`), and then optionally applies byte-level mutations on top. Shapes: 0 SHAPE_PLAIN random method/target/version + headers 1 SHAPE_NOHDR_QARG *no header lines at all* plus a trailing query argument without '=' (this is the exact shape needed for the read-buffer shift-back bug; the generator also forces a small connection memory pool for it) 2 SHAPE_CL_BODY Content-Length body + body oracle 3 SHAPE_CHUNKED chunked body with chunk extensions (";ext", ";ext=val", ";ext=\"quoted\"", ";a=1;b=2;c") + trailers + body oracle 4 SHAPE_DIGEST_SIMPLE Authorization: Digest with a randomised parameter set, including unknown `algorithm=` tokens and `response=` values of every length up to 128 hex digits 5 SHAPE_DIGEST_REPLAY the two-request nonce handshake of 2.3 6 SHAPE_BASIC Authorization: Basic with random base64 7 SHAPE_POST_FORM urlencoded / multipart POST bodies 8 SHAPE_WEIRD folded headers, bare CR, bare LF, whitespace before the colon, percent encoding, absolute-form targets, ... `MHD_FUZZ_SHAPE=` restricts the generator to a single shape, which is very handy for triage and for regression-testing a specific past bug. ------------------------------------------------------------------- 3. Running the harnesses ------------------------------------------------------------------- Build (gcc only, no clang required): SRC=/path/to/libmicrohttpd # configured build tree gcc -g -O1 -Wall -Wextra \ -fsanitize=address,undefined -fno-sanitize-recover=all \ -I$SRC -I$SRC/src/include -I$SRC/src/microhttpd -I$SRC/src/fuzz \ -o fuzz_request $SRC/src/fuzz/fuzz_request.c \ $SRC/src/microhttpd/.libs/libmicrohttpd.a -lpthread (the same command line for fuzz_str, fuzz_auth_header and fuzz_postprocessor; the static archive is required because fuzz_str and fuzz_auth_header use functions that are hidden in the shared object). Options of the built-in driver (identical for all harnesses): --iterations=N number of generate/mutate iterations [3000] --seed=N PRNG seed; (harness, seed) fully determines a run --corpus-dir=DIR replay every regular file in DIR and exit --file=PATH replay a single input and exit (crash repro) --crash-dir=DIR where reproducers are written [crashes] --timeout=SEC per-iteration watchdog, 0 disables [20] --write-corpus=DIR dump the built-in seed corpus to DIR --skip-seeds do not replay the built-in corpus first --verbose enable MHD's error log + print statistics --help Environment variables (all optional): MHD_FUZZ_ITERATIONS, MHD_FUZZ_SEED, MHD_FUZZ_TIMEOUT, MHD_FUZZ_CRASH_DIR, MHD_FUZZ_VERBOSE, MHD_FUZZ_SKIP_SEEDS MHD_FUZZ_SHAPE= (fuzz_request) restrict the generator to one grammar shape MHD_FUZZ_MIN_DISCIPLINE= (fuzz_request) lower bound for MHD_OPTION_CLIENT_DISCIPLINE_LVL, default -3 (the full range) MHD_FUZZ_MIN_MEM_LIMIT= (fuzz_request) lower bound for MHD_OPTION_CONNECTION_MEMORY_LIMIT, default 0 (the full range) MHD_FUZZ_MODEL_DIGEST_SINK=1 (fuzz_str) enable the modelled digest 'response' call site, see 5.4 Typical use: # quick smoke test (a couple of seconds) ./fuzz_request # a real session ./fuzz_request --iterations=5000000 --seed=$RANDOM # regression: replay the whole checked-in corpus ./fuzz_request --corpus-dir=corpus ./fuzz_str --corpus-dir=corpus # ignores foreign files gracefully # reproduce a crash ./fuzz_request --file=crashes/crash-fuzz_request-seed3-iter55.bin ------------------------------------------------------------------- 4. Reproducing a failure ------------------------------------------------------------------- Whenever the process dies -- ASAN error, UBSAN error, `mhd_assert()`, MHD_PANIC(), a body-oracle finding, or the watchdog -- the input of the running iteration is written to $MHD_FUZZ_CRASH_DIR/crash--seed-iter.bin and a line is printed telling you the harness, the seed and the iteration. The dump is produced from * `__sanitizer_set_death_callback()` (weakly linked; present whenever the binary is built with ASAN), and * SIGABRT/SIGSEGV/SIGBUS/SIGILL/SIGFPE/SIGALRM handlers, using only async-signal-safe calls. Replay with `--file=...`; the run is fully deterministic, so `--seed=S --iterations=N+1` reproduces the whole session as well. ------------------------------------------------------------------- 5. What these harnesses find (regression coverage) ------------------------------------------------------------------- The four vulnerabilities fixed in MHD 1.0.7+1 are all rediscovered from scratch. Each has a dedicated seed in `corpus/`, and the generator finds each of them on its own within a few thousand iterations. 5.1 digestauth.c: unknown `algorithm=` token -> MHD_PANIC() An `algorithm=` token MHD does not know parses to MHD_DIGEST_AUTH_ALGO3_INVALID, which is 0, so the allow-mask test `c_algo == (c_algo & malgo3)` passes for *any* mask; the code then calls digest_init_one_time() with an invalid algorithm and panics. Found by: SHAPE_DIGEST_SIMPLE / SHAPE_DIGEST_REPLAY, the panic hook, corpus seed `digest-unknown-algorithm`. 5.2 connection.c get_req_headers(): read-buffer shift-back underflow Needs, all at once: a small MHD_OPTION_CONNECTION_MEMORY_LIMIT (MHD_BUF_INC_SIZE (1500) > read_buffer_size), *no header lines*, and a trailing query argument without '=' (whose `value` is NULL). Found by: SHAPE_NOHDR_QARG, corpus seeds `small-pool-trailing-query-arg[-2]`. 5.3 connection.c process_request_body(): chunk-extension CRLF `chunk_size_line_len = i` instead of `i + 2` leaves the CRLF of the chunk-size line in the stream, so the following chunk data is shifted -- a body desync, i.e. a request-smuggling primitive. This corrupts no memory, so it is caught by the body oracle (2.4). Found by: SHAPE_CHUNKED, corpus seeds `chunked-with-extensions`, `chunked-split`. 5.4 digestauth.c: over-long `response=` -> stack buffer overflow `response` was accepted up to `digest_size * 4` characters (128 for SHA-256) and then decoded with MHD_hex_to_bin() into `uint8_t hash1_bin[MAX_DIGEST]` (32 bytes) -- up to 64 bytes written, 32 bytes of stack smashed. Reaching it requires a *valid* nonce, hence the %%NONCE%% mechanism of 2.3. Found by: SHAPE_DIGEST_REPLAY, corpus seed `digest-overlong-response`. fuzz_str additionally reproduces the underlying primitive: MHD_hex_to_bin() has no output-size parameter and writes len/2 bytes, so any caller with a fixed-size buffer must bound the input length itself. `MHD_FUZZ_MODEL_DIGEST_SINK=1` enables a target that replays exactly the pre-fix call site (32 byte heap buffer, input length bounded only by 4 * 32) and ASAN reports the overflow immediately. The target models a *caller*, not the library, so it is off by default. 5.5 Code that only a deliberate scenario reaches A coverage-guided engine gets to a branch by mutating towards it, so it never gets to one that needs several unrelated configuration bytes to be right at the same time: the intermediate inputs score no better than the ones around them, and the fuzzer has no gradient to follow. An 8 hour, 12 core, 1.6 billion execution campaign, on top of the whole test suite, left exactly three library functions at zero coverage for that reason. All three now have a scenario: psk_gnutls_adapter() (daemon.c) -- MHD's only piece of TLS code that takes a buffer straight from an application callback. Needs GNUTLS_CRD_PSK, a PSK-capable priority string *on both ends* ("NORMAL" has none), MHD_OPTION_GNUTLS_PSK_CRED_HANDLER, and a client offering a PSK identity. fuzz_tls byte 9 bit 7 switches all four on together; bits 3-5 then pick which arm of the adapter to exercise (missing callback, failing callback, 4 KiB key, key length taken from the identity the client sent, size above UINT_MAX, and the two sizes below the MHD_PSK_MIN_SIZE the adapter enforces -- zero and one byte short, which together with the exactly-minimum PSK_OK bracket that check from both sides). Seeds `psk-*`. new_connection_close_() (daemon.c) -- frees a connection that was accepted but never started. On a thread-safe daemon (the default, including a pure external event loop) MHD_add_connection() only queues the socket; the connection object is built by the next run. The function is reachable only if the daemon is stopped before that run happens, and every harness used to call MHD_run() once more during teardown. fuzz_eventloop byte 3 bit 4 queues one connection after the teardown and stops without running. Seeds `stop-with-queued-connection`, `stop-with-queued-after-quiesce`. It is not a race: no second thread is involved. MHD_check_response_header_token_ci() (response.c) -- this one was not a fuzzing problem. The function was added in 2017 and never called, so no input could reach it. The single place that wants it, the "Connection: upgrade" check in MHD_queue_response(), open-coded the scan against response->first_header instead; that now calls the helper, and the existing `ext-upgrade` seed and K7 cover it. ------------------------------------------------------------------- 6. Findings against MHD 1.0.7 - all fixed, kept as regressions ------------------------------------------------------------------- Running these harnesses against v1.0.7 built with `--enable-asserts` reported the following *additional* issues on top of the four vulnerabilities of section 5. All of them were `mhd_assert()`s reachable from network input, i.e. a remote abort in builds that keep assertions enabled, and all of them are fixed on master. They are documented here because the reproducers are kept as a regression corpus: a failure of one of them means the corresponding fix has been undone. Byte-exact reproducers are in `corpus/known-findings/`; replay one with ./fuzz_request --file=corpus/known-findings/K1-digest-empty-realm.bin K1 digestauth.c:2467 is_param_equal(): mhd_assert (0 != param->value.len) -> fixed in 300a2ab0 Trigger (default daemon configuration!), one request: GET /a HTTP/1.1 Host: x Authorization: Digest username="user", realm="", nonce="0000", uri="/a", response="00" digest_auth_check_all_inner() rejects a *missing* realm/username but not an *empty* one, so a zero-length parameter reaches is_param_equal(), whose documented precondition is a non-empty value. Requires only that the application calls MHD_digest_auth_check3(). Real defect (missing validation). Repro: corpus/known-findings/K1-digest-empty-realm.bin K2 connection.c:3582 handle_recv_no_space(): mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) || ! c->rq.some_payload_processed) -> fixed in 68c83f22 Trigger: small MHD_OPTION_CONNECTION_MEMORY_LIMIT (<= ~400 bytes) plus a chunked body whose *second* chunk-size line carries a chunk extension that does not fit into the remaining read buffer. The flag reflects the last application callback only and survives later reads, so the assertion is over-strong; the code below it already handles the situation. Stale assertion. Repro: corpus/known-findings/K2-chunkext-no-space.bin K3 connection.c:2881 transmit_error_response_len(): mhd_assert (! connection->stop_with_error) -> fixed in e04eb218 Trigger: small connection memory pool plus an over-long, unterminated chunk extension: POST /a HTTP/1.1 / Transfer-Encoding: chunked d;ext="qqqqqqqq... (longer than the read buffer) handle_req_chunk_size_line_no_space() is missing a `return` after it has already queued the "chunk extension too big" response. Real defect: in a release build the second call forces the connection to MHD_CONNECTION_CLOSED and the 413 response is never sent. Repro: corpus/known-findings/K3-chunkext-stop-with-error.bin K4 connection.c:6099 get_req_header(): mhd_assert ((0 == c->rq.hdrs.hdr.value_start) || (0 != c->rq.hdrs.hdr.name_len)) -> fixed in 0b750975 Trigger a) MHD_OPTION_CLIENT_DISCIPLINE_LVL <= -1, first header line starting with whitespace: GET /a HTTP/1.1\r\n Host: x\r\n\r\n Trigger b) MHD_OPTION_CLIENT_DISCIPLINE_LVL <= -2, empty header name: GET /a HTTP/1.1\r\n: value\r\nHost: x\r\n\r\n Both shapes are explicitly allowed by those discipline levels. Stale assertion. Repro: corpus/known-findings/K4a-wsp-first-header.bin, corpus/known-findings/K4b-empty-header-name.bin K5 connection.c:6394 get_req_header(): mhd_assert ('\r' != chr) -> fixed in 6fcdfd43 Trigger: MHD_OPTION_CLIENT_DISCIPLINE_LVL = -3, which sets `bare_cr_keep = true`; the branch that keeps a bare CR falls through into the "not a whitespace, not the end of the line" arm whose assertion predates that mode. GET /a HTTP/1.1\r\nHost: x\r\nX: y\r\r\n\r\n Stale assertion. Repro: corpus/known-findings/K5-bare-cr-keep.bin K6 digestauth.c:860 check_nonce_nc(): mhd_assert (0 == nn->nonce[noncelen]) The nonce-nc slot array is indexed by a hash of the nonce, but the slot content is compared assuming the *stored* nonce has the same length as the presented one. A client can therefore make MHD read the terminator of a nonce at the wrong offset by presenting a nonce whose length belongs to a different digest algorithm. Note that this one is *timing dependent*: the nonce carries a millisecond timestamp and whether it counts as stale depends on the wall clock, so the same input reproduces only in a fraction of the replays (about 1 in 30 for the corpus file below). Replay it in a loop. Trigger (MHD_OPTION_NONCE_NC_SIZE = 1 makes every nonce land in slot 0, which turns the collision into a certainty; larger arrays only need more attempts): request 1: GET /a -> 401 with a SHA-256 nonce (76 chars) stored in the slot request 2: Authorization: Digest username="user", realm="TestRealm", nonce="<44 zeros>", uri="/a", response="e" (no algorithm parameter -> MD5 -> nonce length 44, all-zero timestamp -> not stale) The generator needs ~150k iterations to hit it on its own. Repro: corpus/known-findings/K6-nonce-length-collision.bin K7 connection.c:2596 build_header_response(): mhd_assert ((NULL == r->upgrade_handler) || (MHD_CONN_MUST_UPGRADE == c->keepalive)) Fixed by commit acef58a0. Was driven entirely from the wire, with default daemon options. While parsing the request headers, connection.c sets c->keepalive = MHD_CONN_MUST_CLOSE in three places for requests whose message framing it distrusts: 4988 two "Content-Length" headers with different values (client discipline -3 only) 5012 "Transfer-Encoding" on an HTTP/1.0 request (client discipline <= 0) 5051 "Content-Length" *and* "Transfer-Encoding: chunked" in the same request -- no discipline gate at all, so this one fires with the default configuration In every case the request is then handed to the access handler as a normal request. If the handler answers 101 with a response from MHD_create_response_for_upgrade(), MHD_queue_response() accepts it: it checks MHD_ALLOW_UPGRADE, the status code, the "Connection" header and the HTTP version, but not whether the connection can still be kept open. keepalive_possible() then returns MHD_CONN_MUST_CLOSE from its very first test, which is placed *before* the upgrade branch, and the assertion above fires while the reply header is being built. The application cannot defend itself. The harness checks the request the way an application would -- HTTP/1.1, an "Upgrade" header, and a "Connection" header naming the upgrade token and not "close" -- and the reproducer satisfies all three. MHD's decision is not exposed through any public accessor. It needs --enable-asserts and an application that answers upgrade requests, so it is a robustness defect rather than a memory-safety one; but it is reachable from a single well-formed request against a default-configured server, which is a good deal worse than the "application misuse" it first looked like. The fix rejects the response in MHD_queue_response() (connection.c:8338) next to the other upgrade preconditions, so the application gets MHD_NO -- which it already has to handle -- instead of an abort. Repro: corpus/known-findings/K7-upgrade-after-must-close.bin GET / HTTP/1.1 Host: x Connection: Upgrade Upgrade: fuzz-protocol Content-Length: 0 Transfer-Encoding: chunked (then "0\r\n\r\n") K8 digestauth.c MHD_digest_auth_check_digest2(): MHD_PANIC ("Wrong 'malgo3' value, only one base hashing algorithm ... must be specified, API violation") Fixed by commit 07c051dd. An API-contract defect rather than a parsing bug: unlike K7 the offending argument came from the application, not from the network. MHD_DIGEST_ALG_AUTO is a documented member of enum MHD_DigestAuthAlgorithm, and the `algo` parameter of MHD_digest_auth_check_digest2() is documented only as "digest algorithms allowed for verification". But the function maps AUTO to MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION and forwards it to MHD_digest_auth_check_digest3(), which requires *exactly one* base hashing algorithm because the caller supplies a pre-computed digest of one specific length -- and aborts through MHD_PANIC() when more than one is named. So MHD_digest_auth_check_digest2 (..., MHD_DIGEST_ALG_AUTO) deterministically kills the process. The same is not true of MHD_digest_auth_check2(), which takes a password rather than a digest and whose AUTO handling is fine. Unlike K7 this is entirely under the application's control -- no network input is involved -- so it is a usability trap rather than a robustness bug: AUTO simply cannot be used with the pre-computed-digest entry points, and no mapping can rescue it, because the digest length does not identify the algorithm (SHA-256 and SHA-512/256 digests are both 32 bytes). The fix documents the restriction in microhttpd.h and returns MHD_NO instead of aborting. AUTO is left unusable with the pre-computed-digest entry points, deliberately: there is nothing to map it to. Repro: none committed. The argument is the application's, so the harness never passes AUTO there (see run_digest_check() in fuzz_request.c); to see it, change the MHD_DIGEST_ALG_* argument of the variant-4 call to MHD_DIGEST_ALG_AUTO and replay corpus/fuzz_request-37.bin. K9 postprocessor.c:1119 post_process_multipart(): LeakSanitizer: direct leak, strdup() from MHD_post_process() Found by fuzz_postprocessor, not fuzz_request -- the first finding that did not come from the daemon harness. Remotely triggerable, default configuration, no assertions needed. On entering PP_PerformCheckMultipart the code did pp->nested_boundary = strstr (pp->content_type, "boundary="); ... pp->nested_boundary = strdup (&pp->nested_boundary[9]); The first assignment stores an *interior pointer into pp->content_type* over whatever pp->nested_boundary held. If the post processor already owned a boundary -- which it does for every nested "multipart/mixed" part after the first, unless the state machine happened to pass through PP_PerformCleanup in between -- that allocation is lost. MHD_destroy_post_processor() frees only the last one. So a body with N nested multipart/mixed parts, each carrying its own "boundary=", leaks N-1 blocks, and the client picks how long each one is. That makes it a memory-exhaustion vector against any application that calls MHD_post_process() on multipart input, not the one byte the reproducer happens to leak (its boundary is the empty string). Fixed by copying into a local first and releasing any previously owned boundary before taking ownership of the new one; the error path no longer overwrites the old pointer either. Repro: corpus/known-findings/K9-fuzz_postprocessor-nested-boundary-leak.bin K10 memorypool.c MHD_pool_deallocate(): end block of an exactly-full pool was never returned; the front/end dispatch tested pool->pos, where the two ranges meet. Fixed. K11 memorypool.c MHD_pool_reallocate(): returned non-NULL for a wrapping @a new_size, handing the caller a block it believed was nearly SIZE_MAX bytes long. Fixed. K12 daemon.c MHD_start_daemon_va(): leaked the GnuTLS DH parameters built from MHD_OPTION_HTTPS_MEM_DHPARAMS on every startup-failure exit. The application cannot free them. Fixed. K13 daemon.c MHD_epoll() / MHD_quiesce_daemon(): both threads remove the listening socket from the epoll set, and the loser aborts on ENOENT. Open; two alternative fixes are proposed as ../../patches/K13.diff (tolerate ENOENT everywhere) and ../../patches/K13b.diff (take a lock, keep the strict check). K14 daemon.c:1358 call_handlers(): mhd_assert (! force_close || MHD_CONNECTION_CLOSED == con->state) Open, fix proposed in ../../patches/K14.diff. MHD_connection_handle_read() closes the connection when its @a socket_error argument is set -- but only once it gets far enough to try. It returns early, leaving the state untouched, when the connection is suspended, when a TLS handshake is in progress, and when the read buffer has no free space at all. The caller asserts the post-condition unconditionally. Instrumenting the assertion site with the reproducer gives state=12 (HEADERS_PROCESSED) suspended=0 rb_size=2021 rb_off=2021 evinfo=READ i.e. the read buffer is exactly full. A client that fills the connection memory pool without the application consuming the body gets there; no unusual API use is involved. Observed through MHD_run_from_select2(), i.e. from the external event loop. The reproducer does NOT fire on a plain in-tree gcc build: ASan's pool redzones change the buffer arithmetic enough to matter, so confirm it against the OSS-Fuzz build configuration. Repro: corpus/known-findings/K14-fuzz_eventloop-force-close-not-closed.bin K15 daemon.c:9201 close_all_connections(): mhd_assert (MHD_D_IS_USING_THREADS_ (daemon)) Fixed; found while giving new_connection_close_() its first coverage (section 5.5). Three places describe the same invariant and one of them disagreed. internal_add_connection() queues a connection when `external_add && MHD_D_IS_THREAD_SAFE_(daemon)`, and new_connections_list_process_() asserts MHD_D_IS_THREAD_SAFE_ -- that is, whenever the daemon was not started with MHD_USE_NO_THREAD_SAFETY, which includes every external event loop. The shutdown drain asserted the much stronger MHD_D_IS_USING_THREADS_ instead, i.e. that the daemon has an internal polling thread. So an application that drives an external event loop, calls MHD_add_connection() and then MHD_stop_daemon() before the next MHD_run() aborts on an --enable-asserts build. No threads and no race are involved, and a build with NDEBUG handles the same sequence correctly, which is why nothing had noticed: the list is exactly what holds the connection at that point and new_connection_close_() frees it properly. The assert was the outlier and now matches the other two sites. The opposite reading -- that an external event loop should not queue at all and internal_add_connection() should test MHD_D_IS_USING_THREADS_ -- would change MHD_add_connection()'s threading contract, since queueing is what makes that call safe from another thread on a daemon with no thread of its own. Repro: corpus/known-findings/K15-fuzz_eventloop-stop-with-queued-connection.bin Status ------ K1-K12 and K15 are fixed on master: K1 300a2ab0 K4a 0b750975 K7 acef58a0 K10 (memorypool) K2 68c83f22 K4b 0b750975 K8 07c051dd K11 (memorypool) K3 e04eb218 K5 6fcdfd43 K9 (postproc) K12 (daemon/TLS) K6 f438804c K15 (daemon) K13 and K14 are open, with proposed fixes in ../../patches/. Until K14 lands, `make check-corpus` fails on an `--enable-asserts` build, because its reproducer is committed and still reproduces -- which is the documented behaviour for an open finding, but worth knowing before a CI run. The reproducers in `corpus/known-findings/` otherwise all replay clean on a build configured with `--enable-asserts`, and `make check-corpus` asserts exactly that -- it replays that directory along with the generated corpus. K8 has no reproducer, because its trigger is an argument the application chooses rather than anything that comes off the wire. A reproducer belongs to the harness that found it, and says so in its name: `K--.bin`. The ones without a harness in the name predate the convention and are all fuzz_request inputs. `contrib/oss-fuzz/make_seed_corpus.sh` routes each one into the right target's seed corpus on that basis -- a fuzz_postprocessor reproducer in fuzz_request's corpus would just be an uninteresting input. When the next finding is opened, its reproducer goes into `corpus/known-findings/` and will make `make check-corpus` fail until the fix lands. That is the intended behaviour: it is the same arrangement as the `XFAIL_TESTS` entries in `src/microhttpd/Makefile.am`, except that here the expectation is not encoded, so the commit that adds a live reproducer should say so. `contrib/oss-fuzz/make_seed_corpus.sh` has to skip such a reproducer as well, or every ClusterFuzz run starts by rediscovering it; see the comment there. The `make check` defaults in Makefile.am MHD_FUZZ_ITERATIONS = 50000 MHD_FUZZ_MIN_DISCIPLINE = -3 (full range) MHD_FUZZ_MIN_MEM_LIMIT = 0 (full range) exercise the whole matrix and take about three seconds in total under ASAN+UBSAN. A real session: MHD_FUZZ_MIN_DISCIPLINE=-3 MHD_FUZZ_MIN_MEM_LIMIT=0 \ ./fuzz_request --iterations=1000000 --seed=1 ------------------------------------------------------------------- 7. Building with clang/libFuzzer or AFL++ ------------------------------------------------------------------- Both need `-DFUZZ_NO_MAIN` so that the driver's `main()` is left out. 7.1 libFuzzer ------------- # build the library itself with the same instrumentation ./configure --enable-static --disable-shared --enable-asserts \ CC=clang \ CFLAGS="-g -O1 -fsanitize=fuzzer-no-link,address,undefined \ -fno-sanitize-recover=all -fprofile-instr-generate \ -fcoverage-mapping" make -C src/microhttpd clang -g -O1 -DFUZZ_NO_MAIN \ -fsanitize=fuzzer,address,undefined -fno-sanitize-recover=all \ -I. -Isrc/include -Isrc/microhttpd -Isrc/fuzz \ -o fuzz_request src/fuzz/fuzz_request.c \ src/microhttpd/.libs/libmicrohttpd.a -lpthread mkdir -p CORPUS && ./fuzz_request --help >/dev/null 2>&1 || true ./fuzz_request CORPUS src/fuzz/corpus \ -max_len=8192 -rss_limit_mb=4096 -timeout=20 # minimise a crash found by libFuzzer ./fuzz_request -minimize_crash=1 -runs=100000 crash- 7.2 AFL++ --------- export CC=afl-clang-lto AFL_USE_ASAN=1 AFL_USE_UBSAN=1 ./configure --enable-static --disable-shared --enable-asserts make -C src/microhttpd afl-clang-lto -g -O1 -DFUZZ_NO_MAIN \ -I. -Isrc/include -Isrc/microhttpd -Isrc/fuzz \ -o fuzz_request src/fuzz/fuzz_request.c \ $(afl-config --libdir 2>/dev/null || echo /usr/local/lib/afl)/afl-compiler-rt.o \ /usr/local/lib/afl/libAFLDriver.a \ src/microhttpd/.libs/libmicrohttpd.a -lpthread afl-fuzz -i src/fuzz/corpus -o findings -- ./fuzz_request @@ (`libAFLDriver.a` provides a `main()` that reads the file named on the command line and calls LLVMFuzzerTestOneInput(); that is why `-DFUZZ_NO_MAIN` is required. With `AFL_LLVM_PERSISTENT` / `__AFL_LOOP` the same binary can be used in persistent mode.) 7.3 OSS-Fuzz ------------ Ready to go: see `../../contrib/oss-fuzz/` and its README. That directory holds the OSS-Fuzz `build.sh`, `project.yaml` and `Dockerfile`, per-harness dictionaries (`dicts/fuzz_*.dict`), per-harness `.options` files (`max_len`, `dict`) and `make_seed_corpus.sh`, which packages `corpus/` — including the `corpus/known-findings/` reproducers of the findings that are already *fixed*, so that they become permanent regressions — into the `_seed_corpus.zip` files OSS-Fuzz expects. `build.sh` configures out of tree with --enable-static --disable-shared --with-pic --enable-fuzzing --enable-asserts --disable-https --disable-curl --disable-doc --disable-examples --disable-tools --enable-build-type=neutral honouring OSS-Fuzz's `$CFLAGS` (no `--enable-sanitizers`: OSS-Fuzz supplies the instrumentation), and then compiles each harness exactly as in 7.1 but against `$LIB_FUZZING_ENGINE`. HTTPS is off on purpose — the harnesses never speak TLS, and leaving GnuTLS out is what makes the MemorySanitizer build possible. Two things to know before reading a report from there: * the request-body oracle of 2.4 is **inactive** under libFuzzer. It is gated on `fuzz_pristine`, which nothing sets when `FUZZ_NO_MAIN` is defined — correctly so, since libFuzzer's mutations invalidate the declared ground truth. Pure framing/desync defects (5.3) therefore remain the job of the built-in driver, i.e. of `make check`; * `primary_contact` in `project.yaml` is a placeholder. OSS-Fuzz needs an address the maintainer controls; it has to be filled in before the project can be submitted. The token list in `fuzz_common.h` (`fuzz_interesting_str`) is the generator's equivalent of those dictionaries; the two are intentionally similar but are not generated from each other. OSS-Fuzz is deliberately not part of `contrib/ci/jobs/`; the bounded in-tree equivalents for CI are `make -C src/fuzz check` and `make -C src/fuzz check-corpus`. ------------------------------------------------------------------- 8. Adding a harness ------------------------------------------------------------------- Create `fuzz_.c` with #define FUZZ_HARNESS_NAME "fuzz_" #include "fuzz_common.h" and implement int LLVMFuzzerTestOneInput (const uint8_t *, size_t); static size_t fuzz_generate (struct fuzz_rng *, uint8_t *, size_t); static size_t fuzz_seed_count (void); static const uint8_t *fuzz_seed_get (size_t, size_t *); then add it to `check_PROGRAMS` in Makefile.am. Report non-crashing findings with `fuzz_report_finding("...")`, which dumps the reproducer and aborts. Two rules learnt the hard way: * do not violate documented *preconditions* of the function under test (e.g. MHD_str_remove_token_caseless_() asserts that the token contains no space, tab, comma or NUL) -- otherwise the harness only finds its own bugs; * never evaluate a macro argument twice when it contains a PRNG call. libmicrohttpd-1.0.10/src/fuzz/fuzz_options.c0000664000175000017500000022557415232414252014641 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file fuzz/fuzz_options.c * @brief In-process fuzzer for MHD's daemon option handling and for the * daemon start-up / shutdown paths. * @author Christian Grothoff * * fuzz_request.c fuzzes what MHD does with the *bytes on the wire*, but * it always starts the daemon in one single shape: external polling, no * listen socket, five fixed options. Everything in daemon.c that is * reached through any other configuration -- the flag validation in * MHD_start_daemon(), parse_options_va(), the internal polling thread, * the thread pool, epoll/poll/select, the listen socket, the per-IP and * per-daemon connection limits, quiesce -- is therefore dead code as far * as the fuzzing suite is concerned. This harness closes that gap: the * input bytes pick a *combination* of MHD_FLAG bits and an MHD_OPTION * array, the daemon is started with them, one short HTTP request is * driven through it over a socketpair, and the daemon is stopped again. * * The request-driving machinery is the one from fuzz_request.c: * MHD_USE_NO_LISTEN_SOCKET plus MHD_add_connection() on an AF_UNIX * socketpair(), with a fake 127.0.0.1 peer address so that the per-IP * accounting sees something sane, and MHD_set_panic_func() installed as * a tripwire. What is new here is that the *daemon* is a variable. * * Two shapes of daemon exist, and the harness drives them differently: * * - "external polling" (no MHD_USE_INTERNAL_POLLING_THREAD and no * MHD_USE_THREAD_PER_CONNECTION). Single threaded and fully * deterministic: the segments are fed in one at a time and the * daemon is pumped with MHD_run() / MHD_get_fdset2() + select() + * MHD_run_from_select2() / MHD_run_wait() between them. This is the * majority of the iterations and the only shape in which the harness * suspends a connection. * * - "internal thread" (an internal polling thread, a thread pool, or * thread-per-connection). MHD_add_connection() is explicitly * supported in these modes -- it is how an application with its own * accept() loop hands sockets over -- but the harness must not also * poll the daemon, and it cannot know when the worker is done. So * the whole request is written at once, the write side is shut down * (which makes MHD finish the request immediately rather than * waiting for more data), and the answer is awaited with a short * bounded poll() before the daemon is stopped. MHD_USE_ITC is * forced on in this shape so that the worker picks the new * connection up at once instead of waiting for its poll timeout. * No connection is ever suspended here. * * Input format (see README section 2.2 for the fuzz_request one, which * the segment stream below is deliberately identical to): * * byte 0 daemon shape: index into mode_tbl[] (event loop and * threading; the entries are the combinations MHD documents * as valid, so that most iterations get a live daemon) * byte 1 MHD_FLAG bits, group A (see flags_from_input()) * byte 2 MHD_FLAG bits, group B; 0xC0 in the top two bits switches * on the "raw" escape, which feeds bytes 1, 2 and 15 * straight into the flags word. That is what fuzzes * MHD_start_daemon()'s own combination checks; MHD answering * NULL is a normal outcome and simply ends the iteration. * byte 3 option presence mask A (sizes and limits) * byte 4 option presence mask B (discipline, insanity, fd_setsize) * byte 5 option presence mask C (the callbacks and the pointers) * byte 6 value selector: connection memory limit / increment * byte 7 value selector: connection limit / per-IP limit * byte 8 value selector: connection timeout / pool size / stack * byte 9 value selector: nonce-nc size / digest random / bind type * byte 10 value selector: discipline / strict / insanity / bzero URI * byte 11 value selector: backlog / fd_setsize / reuse / fastopen * byte 12 driver behaviour: event loop variant, quiesce, * introspection, suspend mode, number of connections * byte 13 handler behaviour (which response, MHD_NO, per-connection * option) and the accept path: whether an accept policy * callback is installed, what it answers, and whether the * iteration additionally connect()s to the daemon's real * listening socket * byte 14 option presence mask D (the digest and TLS-adjacent * options, MHD_OPTION_LISTEN_SOCKET, and the deliberately * invalid option number) * byte 15 spare entropy; also supplies flag bits 14+ in raw mode * byte 16. a sequence of send segments, each introduced by a little * endian 16 bit header (op << 14) | length * op 0 send the payload on the current connection * op 1 send the payload, then pump extra rounds * op 2 send the payload, then pump extra rounds * op 3 close the current connection, open a fresh one on * the same daemon, then send * * The sixteen configuration bytes are mandatory; a shorter input is * rejected. An input of exactly sixteen bytes is meaningful and is not * a degenerate case: it starts and stops a daemon with one connection * and no traffic at all, which is precisely the start-up/shutdown path * this harness is about. * * Two rules the harness obeys, both of them application contract rather * than anything worth fuzzing: * * - every daemon that starts is stopped, and no connection is left * suspended when that happens, because MHD_stop_daemon() answers a * suspended connection with MHD_PANIC(). Suspended connections are * tracked in pending_resume[] and flushed during teardown, exactly * as in fuzz_request.c; * - the socket that MHD_quiesce_daemon() returns belongs to the * caller. It is closed after MHD_stop_daemon() (not before: with * internal threads a worker may still be using it), otherwise the * harness runs out of file descriptors within a few thousand * iterations. * * Environment: * * MHD_FUZZ_QUIESCE_EPOLL_RACE=1 let the harness call * MHD_quiesce_daemon() on an epoll daemon that runs its own * thread(s). Off by default because that combination reaches an * open MHD defect; see quiesce_epoll_race_allowed() below. */ #define FUZZ_HARNESS_NAME "fuzz_options" #include "fuzz_common.h" #include #include #include #include #include #include /* MHD_OPTION_STRICT_FOR_CLIENT is superseded by MHD_OPTION_CLIENT_DISCIPLINE_LVL but is still shipped API, and its mapping onto the discipline level is exactly the kind of thing this harness is for. */ #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif /** Number of mandatory configuration bytes at the start of the input. */ #define CFG_BYTES 16 #define MAX_SEGMENTS 48 #define MAX_CONNECTIONS 6 #define MAX_OPTS 40 #define RESP_DRAIN_BUF 4096 #define GEN_BUF_SIZE 4096 /** * Milliseconds the internal-thread shape waits for the daemon to answer. * The write side of the socketpair is shut down before the wait, so the * daemon never sits on an incomplete request: either it answers (the * common case, tens of microseconds) or it closes the connection, and * both wake poll() up immediately. The timeout is therefore only paid * by inputs that make MHD drop the connection without a reply. */ #define THREAD_WAIT_MS 2 /** Rounds of MHD_run() after each segment in the external shape. */ #define PUMP_ROUNDS 3 /** Rounds of MHD_run() after a segment sent with op 1 or 2. */ #define PUMP_ROUNDS_LONG 10 /* ------------------------------------------------------------------ */ /* Per-iteration configuration */ /* ------------------------------------------------------------------ */ struct fuzz_cfg { /** Daemon runs its own thread(s); the harness must not call MHD_run(). */ int uses_threads; /** A real listening socket was requested (no MHD_USE_NO_LISTEN_SOCKET). */ int listen_sock; /** MHD_USE_ERROR_LOG was requested, so an external logger is mandatory. */ int err_log; /** 0 none, 1 suspend+resume in the handler, 2 resume from the pump. */ int suspend_mode; /** 0 MHD_run(), 1 MHD_get_fdset2()+select()+MHD_run_from_select2(), 2 MHD_run_wait(0), 3 the v1 MHD_get_fdset()/MHD_run_from_select(). */ unsigned int loop_mode; /** Call MHD_quiesce_daemon() before stopping. */ int quiesce; /** Query MHD_get_daemon_info() / MHD_get_timeout*() while pumping. */ int daemon_info; /** Call MHD_set_connection_option() from the handler. */ int conn_option; /** Which response constructor the handler uses. */ unsigned int resp_kind; /** Handler answers MHD_NO instead of queueing a response. */ int handler_no; /** Upper bound on the number of connections the iteration opens. */ unsigned int nconn_max; /** Really connect() to the daemon's listening socket. */ int real_connect; /** Install an accept policy callback, and what it should answer. */ int accept_policy; int accept_policy_deny; }; static struct fuzz_cfg cfg; /** * Connections suspended by suspend mode 2, which the pump loop still has * to resume. Cleared by completed_cb() so that a connection MHD has * finished with is never resumed afterwards. A connection that is still * suspended when MHD_stop_daemon() runs makes MHD answer with * MHD_PANIC ("MHD_stop_daemon() called while we have suspended * connections"), which would look exactly like an MHD bug. */ static struct MHD_Connection *pending_resume[MAX_CONNECTIONS]; /** * Set once the iteration only wants to drain the daemon. The handler * then stops parking new connections, which is what makes the flush loop * in the teardown provably terminate. */ static int tearing_down; /** Statistics, printed at exit with --verbose. */ static unsigned long stat_daemons; static unsigned long stat_daemons_failed; static unsigned long stat_threaded; static unsigned long stat_handler_calls; static unsigned long stat_conns_added; static unsigned long stat_conns_refused; static unsigned long stat_real_conns; static int stats_registered; static void print_stats (void) { if (! fuzz_verbose) return; fprintf (stderr, "%s: daemons=%lu (failed to start=%lu, threaded=%lu) " "connections=%lu (refused=%lu, accepted from a real socket=%lu) " "handler calls=%lu\n", FUZZ_HARNESS_NAME, stat_daemons, stat_daemons_failed, stat_threaded, stat_conns_added, stat_conns_refused, stat_real_conns, stat_handler_calls); } /* ------------------------------------------------------------------ */ /* Flags */ /* ------------------------------------------------------------------ */ /** * The event-loop / threading core of the flags word. Every entry is a * combination MHD documents as valid, so that the ordinary path through * this harness gets a live daemon and actually exercises the option * handling; the deliberately invalid combinations are reached through * the raw escape of byte 2 instead. * * The distribution is on purpose: entries 0..17 are the external polling * modes, 18..23 the ones with internal threads. An iteration with * internal threads costs a thread creation, a join and a short wait for * the answer, i.e. roughly an order of magnitude more than an external * one, so they are a quarter of the iterations rather than a half. */ static const unsigned int mode_tbl[] = { 0, 0, 0, 0, 0, 0, /* external, select() */ 0, 0, 0, 0, 0, 0, MHD_USE_EPOLL, MHD_USE_EPOLL, /* external, epoll */ MHD_USE_EPOLL, MHD_USE_EPOLL, MHD_USE_AUTO, MHD_USE_AUTO, /* external, MHD picks */ MHD_USE_INTERNAL_POLLING_THREAD, MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_POLL, MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_EPOLL, MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_POLL, MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD }; #define MODE_COUNT (sizeof (mode_tbl) / sizeof (mode_tbl[0])) /** * Flag bits the raw escape is allowed to set. MHD_USE_TLS is masked * out: without a certificate the daemon merely fails to start, so it * would only waste iterations, and fuzzing GnuTLS is not what this * harness is for. Everything else, including the bits above * MHD_USE_NO_THREAD_SAFETY that no MHD_FLAG uses, is fair game. */ #define RAW_FLAG_MASK (~((unsigned int) MHD_USE_TLS)) /** * The bit that MHD_suspend_connection() actually tests. * * MHD_ALLOW_SUSPEND_RESUME is a *compound* value (8192 | MHD_USE_ITC), * so "0 != (flags & MHD_ALLOW_SUSPEND_RESUME)" is already true for a * daemon that merely asked for MHD_USE_ITC -- and suspending such a * connection is answered with * MHD_PANIC ("Cannot suspend connections without enabling * MHD_ALLOW_SUSPEND_RESUME"), which is the harness violating the API * rather than a finding. internal.h calls the single bit * MHD_TEST_ALLOW_SUSPEND_RESUME; this is the same value, expressed * without reaching into a private header. */ #define SUSPEND_BIT \ (((unsigned int) MHD_ALLOW_SUSPEND_RESUME) \ & ~((unsigned int) MHD_USE_ITC)) /** * Build the flags word from bytes 0, 1, 2 and 15 of the input. * * @param data the input * @return the flags to pass to MHD_start_daemon() */ static unsigned int flags_from_input (const uint8_t *data) { unsigned int flags; if (0xC0 == (data[2] & 0xC0)) { /* Raw escape: the flags word comes straight off the input. This is what exercises MHD_start_daemon()'s combination checks (POLL with EPOLL, EPOLL with thread-per-connection, AUTO with either, ...), every one of which answers NULL. */ flags = ((unsigned int) data[1]) | (((unsigned int) (data[2] & 0x3F)) << 8) | (((unsigned int) data[15]) << 14); flags &= RAW_FLAG_MASK; cfg.listen_sock = (0 == (flags & MHD_USE_NO_LISTEN_SOCKET)); cfg.err_log = (0 != (flags & MHD_USE_ERROR_LOG)); return flags; } flags = mode_tbl[data[0] % MODE_COUNT]; if (0 != (data[1] & 0x01)) flags |= MHD_USE_PEDANTIC_CHECKS; if (0 != (data[1] & 0x02)) flags |= MHD_USE_SUPPRESS_DATE_NO_CLOCK; if (0 != (data[1] & 0x04)) flags |= MHD_ALLOW_SUSPEND_RESUME; if ( (0 != (data[1] & 0x08)) && (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_UPGRADE)) ) flags |= MHD_ALLOW_UPGRADE; if (0 != (data[1] & 0x10)) flags |= MHD_USE_TURBO; if (0 != (data[1] & 0x20)) flags |= MHD_USE_ITC; if (0 != (data[1] & 0x40)) cfg.err_log = 1; if (0 != (data[1] & 0x80)) flags |= MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT; /* ignored without TLS */ if (0 != (data[2] & 0x01)) cfg.listen_sock = 1; if (0 != (data[2] & 0x02)) flags |= MHD_USE_IPv6; if (0 != (data[2] & 0x04)) flags |= MHD_USE_DUAL_STACK; if (0 != (data[2] & 0x08)) flags |= MHD_USE_TCP_FASTOPEN; if (0 != (data[2] & 0x10)) flags |= MHD_USE_NO_THREAD_SAFETY; if (0 != (data[2] & 0x20)) flags |= MHD_USE_INSECURE_TLS_EARLY_DATA; /* ignored without TLS */ /* MHD_USE_NO_THREAD_SAFETY together with any internal thread is documented as unsupported and answered with NULL. Drop it here rather than burning the iteration; the raw escape above still reaches that check. */ if (0 != (flags & (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION))) flags &= ~((unsigned int) MHD_USE_NO_THREAD_SAFETY); return flags; } /** * @return non-zero if @a flags make MHD use epoll * * MHD_USE_AUTO resolves to epoll for everything except * thread-per-connection, which it resolves to poll. */ static int uses_epoll (unsigned int flags) { if (0 != (flags & MHD_USE_EPOLL)) return 1; return (0 != (flags & MHD_USE_AUTO)) && (0 == (flags & MHD_USE_THREAD_PER_CONNECTION)); } /** * Is the harness allowed to call MHD_quiesce_daemon() on an epoll * daemon that runs its own thread(s)? * * It is not, by default, because that combination reaches an *open* MHD * defect and would make "make check" fail at random: * * MHD_quiesce_daemon() sets daemon->was_quiesced and then removes the * listen FD from the epoll set itself (daemon.c:6208), tolerating * ENOENT with the comment "can happen due to race with MHD_epoll()". * MHD_epoll() removes the very same FD in two places. The first * (daemon.c:5556) mirrors that and tolerates ENOENT. The second * (daemon.c:5593), the "at the connection limit, disable listen * socket" branch, also fires when daemon->was_quiesced is set -- and * it does not tolerate anything: * * if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, ls, NULL)) * MHD_PANIC (_ ("Failed to remove listen FD from epoll set.")); * * The worker can read daemon->was_quiesced as already true and * daemon->listen_socket_in_epoll as still true -- neither is atomic * and neither is under a lock -- and then lose the race for the * removal, so epoll_ctl() answers ENOENT and MHD aborts the process. * Confirmed with errno == ENOENT, was_quiesced == 1, connections == 0. * The same unguarded MHD_PANIC() sits in the worker-pool loop of * MHD_quiesce_daemon() itself (daemon.c:6189). * * Set MHD_FUZZ_QUIESCE_EPOLL_RACE=1 to reach it. Quiescing is left * enabled everywhere else, so the poll()/select() side of * MHD_quiesce_daemon(), including its worker-pool loop, keeps being * exercised. */ static int quiesce_epoll_race_allowed (void) { static int val = -1; if (0 > val) { const char *e = getenv ("MHD_FUZZ_QUIESCE_EPOLL_RACE"); val = ((NULL != e) && (0 != atoi (e))) ? 1 : 0; } return val; } /* ------------------------------------------------------------------ */ /* Option values */ /* ------------------------------------------------------------------ */ static const size_t mem_limit_tbl[] = { 0 /* MHD default */, 128, 192, 256, 384, 512, 1024, 1400, 1500, 2048, 4096, 8192, 32768, 64, 0, 0 }; static const size_t mem_increment_tbl[] = { 0 /* MHD default */, 1, 16, 64, 128, 256, 1024, 4096, 1500, 32768, 0, 0, 0, 0, 0, 0 }; static const unsigned int conn_limit_tbl[] = { 0, 1, 2, 3, 8, 64, 1024, 100000 }; static const unsigned int per_ip_limit_tbl[] = { 0, 1, 2, 3, 4, 8, 64, 1000 }; static const unsigned int timeout_tbl[] = { 0, 1, 2, 5, 60, 3600, 86400, UINT_MAX }; static const unsigned int pool_size_tbl[] = { 2, 3, 4, 2 }; /* Small stacks make pthread_create() fail outright under ASAN, which only produces a NULL daemon; keep the values plausible. */ static const size_t stack_size_tbl[] = { 0, 1024u * 1024u, 2048u * 1024u, 8192u * 1024u }; /* Bounded on purpose: the nonce-nc array is nonce_nc_size * sizeof(struct MHD_NonceNc) (about 130 bytes per slot) and is allocated and freed once per iteration. */ static const unsigned int nonce_nc_tbl[] = { 0, 1, 4, 32 }; static const int discipline_tbl[] = { -3, -2, -1, 0, 1, 2, 3, -4 }; static const int strict_tbl[] = { -1, 0, 1, 2 }; static const unsigned int backlog_tbl[] = { 0, 1, 5, 511 }; static const unsigned int fastopen_tbl[] = { 0, 1, 5, 10 }; /* Anything but the platform's own FD_SETSIZE is rejected unless MHD was built with HAS_FD_SETSIZE_OVERRIDABLE, so the odd values are a small minority: they cost a whole iteration each. */ static const int fd_setsize_tbl[] = { (int) FD_SETSIZE, (int) FD_SETSIZE, (int) FD_SETSIZE, (int) FD_SETSIZE, (int) FD_SETSIZE, (int) FD_SETSIZE, 64, 0 }; /** Fixed entropy, so that a digest nonce is reproducible across runs. */ static const char digest_rnd[32] = "\x01\x23\x45\x67\x89\xab\xcd\xef\x01\x23\x45\x67\x89\xab\xcd\xef" "\xfe\xdc\xba\x98\x76\x54\x32\x10\xfe\xdc\xba\x98\x76\x54\x32\x10"; /* Bind addresses for MHD_OPTION_SOCK_ADDR / MHD_OPTION_SOCK_ADDR_LEN. Filled in by prepare_sock_addrs() because htons()/htonl() are not constant expressions. */ static struct sockaddr_in bind4; #ifdef AF_INET6 static struct sockaddr_in6 bind6; #endif static int bind_addrs_ready; static void prepare_sock_addrs (void) { if (bind_addrs_ready) return; bind_addrs_ready = 1; memset (&bind4, 0, sizeof (bind4)); bind4.sin_family = AF_INET; bind4.sin_port = htons (0); /* ephemeral */ bind4.sin_addr.s_addr = htonl (INADDR_LOOPBACK); #ifdef AF_INET6 memset (&bind6, 0, sizeof (bind6)); bind6.sin6_family = AF_INET6; bind6.sin6_port = htons (0); bind6.sin6_addr = in6addr_loopback; #endif } /* ------------------------------------------------------------------ */ /* The daemon callbacks */ /* ------------------------------------------------------------------ */ /** * MHD_OPTION_EXTERNAL_LOGGER. Swallows the message unless --verbose is * in effect. This is what makes MHD_USE_ERROR_LOG affordable: with the * flag set, MHD executes several hundred MHD_DLOG() call sites in * daemon.c that are otherwise dead, and without a logger of our own all * of that would land on stderr. */ static void logger_cb (void *cls, const char *fmt, va_list ap) { (void) cls; if (! fuzz_verbose) return; (void) vfprintf (stderr, fmt, ap); } /** * MHD_OPTION_URI_LOG_CALLBACK. The return value becomes the initial * `*req_cls` of the request, so it has to stay NULL: the access handler * uses "req_cls is still NULL" to recognise its first invocation, and a * non-NULL value here would also have to be freed somewhere, which is * not possible when MHD_OPTION_NOTIFY_COMPLETED is not set. */ static void * uri_log_cb (void *cls, const char *uri, struct MHD_Connection *con) { volatile size_t sink; (void) cls; (void) con; sink = (NULL != uri) ? strlen (uri) : 0; (void) sink; return NULL; } /** * MHD_OPTION_UNESCAPE_CALLBACK. Replaces MHD's own unescaping, so it * must honour the contract: unescape @a s in place and return the new * length. Leaving the string alone is a legal implementation and keeps * the harness out of the business of re-testing mhd_str.c, which * fuzz_str does. */ static size_t unescape_cb (void *cls, struct MHD_Connection *conn, char *s) { (void) cls; (void) conn; return strlen (s); } static void completed_cb (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { (void) cls; (void) toe; /* MHD is done with this connection, so the deferred resume of suspend mode 2 must not fire for it any more. */ if (! cfg.uses_threads) { unsigned int i; for (i = 0; i < MAX_CONNECTIONS; i++) if (pending_resume[i] == connection) pending_resume[i] = NULL; } *req_cls = NULL; } static void notify_connection_cb (void *cls, struct MHD_Connection *connection, void **socket_context, enum MHD_ConnectionNotificationCode toe) { (void) cls; (void) connection; if (MHD_CONNECTION_NOTIFY_STARTED == toe) *socket_context = NULL; } static void panic_cb (void *cls, const char *file, unsigned int line, const char *reason) { char msg[512]; (void) cls; (void) snprintf (msg, sizeof (msg), "MHD_PANIC() reached at %s:%u: %s", (NULL != file) ? file : "?", line, (NULL != reason) ? reason : "?"); fuzz_report_finding (msg); } /* ------------------------------------------------------------------ */ /* Suspend bookkeeping */ /* ------------------------------------------------------------------ */ static void pending_resume_add (struct MHD_Connection *c) { unsigned int i; for (i = 0; i < MAX_CONNECTIONS; i++) { if (NULL == pending_resume[i]) { pending_resume[i] = c; return; } } } /** * Resume everything still parked. * * @return non-zero if at least one connection was resumed, so that the * caller knows the daemon needs another round to act on it */ static int pending_resume_flush (void) { unsigned int i; int any = 0; for (i = 0; i < MAX_CONNECTIONS; i++) { struct MHD_Connection *c = pending_resume[i]; if (NULL == c) continue; /* Clear first: MHD_resume_connection() can make MHD run the handler, which may suspend the very same connection again. */ pending_resume[i] = NULL; MHD_resume_connection (c); any = 1; } return any; } /** * Suspend the connection if the input asks for it. Only ever called in * the external-polling shape: resuming from the harness thread while an * internal worker owns the connection is legal but untimed, and this * harness has no way to tell whether the resume happened before or after * the worker looked at the connection. */ static void suspend_maybe (struct MHD_Connection *connection) { if ( (0 == cfg.suspend_mode) || cfg.uses_threads || tearing_down) return; MHD_suspend_connection (connection); if (1 == cfg.suspend_mode) { MHD_resume_connection (connection); return; } pending_resume_add (connection); } /* ------------------------------------------------------------------ */ /* The access handler */ /* ------------------------------------------------------------------ */ static const char resp_body[] = "hello"; static enum MHD_Result ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { /* The address of this object is the "request already started" marker. Nothing is allocated per request on purpose: this harness runs millions of iterations in one process and the daemon shapes with internal threads cannot guarantee that MHD_OPTION_NOTIFY_COMPLETED is even set, so anything malloc()ed here could leak. */ static int req_marker; struct MHD_Response *resp; enum MHD_Result ret; unsigned int code; volatile size_t sink = 0; (void) cls; (void) upload_data; if (&req_marker != *req_cls) { *req_cls = &req_marker; return MHD_YES; } stat_handler_calls++; /* Touch the parsed request line the way a real application would. */ if (NULL != url) sink += strlen (url); if (NULL != method) sink += strlen (method); if (NULL != version) sink += strlen (version); (void) sink; if (0 != *upload_data_size) { *upload_data_size = 0; return MHD_YES; } if (cfg.conn_option) (void) MHD_set_connection_option (connection, MHD_CONNECTION_OPTION_TIMEOUT, (unsigned int) 30); if (cfg.handler_no) return MHD_NO; /* never suspend on this path: MHD_NO terminates the connection and terminating a suspended one trips mhd_assert (! connection->suspended) */ code = MHD_HTTP_OK; switch (cfg.resp_kind) { case 1: resp = MHD_create_response_empty (MHD_RF_NONE); code = MHD_HTTP_NO_CONTENT; break; case 2: resp = MHD_create_response_from_buffer (sizeof (resp_body) - 1, (void *) (intptr_t) resp_body, MHD_RESPMEM_MUST_COPY); code = MHD_HTTP_FORBIDDEN; break; case 3: resp = MHD_create_response_from_buffer_static (0, ""); code = MHD_HTTP_INTERNAL_SERVER_ERROR; break; default: resp = MHD_create_response_from_buffer_static (sizeof (resp_body) - 1, resp_body); break; } if (NULL == resp) return MHD_NO; ret = MHD_queue_response (connection, code, resp); MHD_destroy_response (resp); if (MHD_YES == ret) suspend_maybe (connection); return ret; } /* ------------------------------------------------------------------ */ /* Driving the daemon */ /* ------------------------------------------------------------------ */ /** * Read and discard whatever the daemon has produced so far. The harness * has no response oracle -- fuzz_request owns that job -- but the data * has to be taken off the socket so that MHD's writes keep succeeding. */ static void drain (int sock) { char tmp[RESP_DRAIN_BUF]; if (0 > sock) return; while (0 < recv (sock, tmp, sizeof (tmp), MSG_DONTWAIT)) /* nothing */; } /** * Advance an externally polled daemon by one cycle, through whichever of * the four event-loop entry points byte 12 selected. * * The select() timeout is always zero: the harness is single threaded * and everything the daemon could be waiting for has already been * written into the socketpair, so blocking would only burn wall clock. */ static void run_once (struct MHD_Daemon *d) { fd_set rs; fd_set ws; fd_set es; MHD_socket max_fd = MHD_INVALID_SOCKET; struct timeval tv; if (cfg.daemon_info) { MHD_UNSIGNED_LONG_LONG tl = 0; volatile int64_t sink; (void) MHD_get_timeout (d, &tl); sink = MHD_get_timeout64s (d); sink += (int64_t) MHD_get_timeout_i (d); (void) sink; } switch (cfg.loop_mode) { case 1: case 3: FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); /* MHD_get_fdset and MHD_run_from_select are also macros forwarding to the *2 variants, so the names have to be parenthesised for the v1 entry points to be reached at all. */ if (1 == cfg.loop_mode) { if (MHD_YES != MHD_get_fdset2 (d, &rs, &ws, &es, &max_fd, (unsigned int) FD_SETSIZE)) { (void) MHD_run (d); return; } } else { if (MHD_YES != (MHD_get_fdset) (d, &rs, &ws, &es, &max_fd)) { (void) MHD_run (d); return; } } tv.tv_sec = 0; tv.tv_usec = 0; if (MHD_INVALID_SOCKET != max_fd) (void) select ((int) max_fd + 1, &rs, &ws, &es, &tv); if (1 == cfg.loop_mode) (void) MHD_run_from_select2 (d, &rs, &ws, &es, (unsigned int) FD_SETSIZE); else (void) (MHD_run_from_select) (d, &rs, &ws, &es); break; case 2: (void) MHD_run_wait (d, 0); break; default: (void) MHD_run (d); break; } } static void pump (struct MHD_Daemon *d, int sock, unsigned int rounds) { unsigned int i; if (cfg.uses_threads) return; for (i = 0; i < rounds; i++) { /* Deferred resume of suspend mode 2. Each slot is cleared before its connection is resumed, which stays correct even when the resume makes MHD complete (and forget) the connection. */ (void) pending_resume_flush (); run_once (d); drain (sock); } } /** * Wait, briefly and with a hard bound, for a daemon with internal * threads to answer. The caller has already shut the write side down, * so MHD sees end-of-stream and either answers or closes; both wake * poll() immediately. An input that makes MHD do neither pays the full * timeout, which is why it is only a couple of milliseconds. */ static void wait_threaded (int sock) { unsigned int round; if (0 > sock) return; for (round = 0; round < 4; round++) { struct pollfd p; char tmp[RESP_DRAIN_BUF]; ssize_t n; p.fd = sock; p.events = POLLIN; p.revents = 0; if (0 >= poll (&p, 1, THREAD_WAIT_MS)) return; if (0 == (p.revents & POLLIN)) return; /* POLLHUP/POLLERR only: peer is gone */ n = recv (sock, tmp, sizeof (tmp), MSG_DONTWAIT); if (0 >= n) return; } } static void send_all (struct MHD_Daemon *d, int sock, const uint8_t *data, size_t len) { size_t off = 0; unsigned int stall = 0; if (0 > sock) return; while ( (off < len) && (stall < 64) ) { ssize_t s = send (sock, data + off, len - off, MSG_DONTWAIT); if (0 < s) { off += (size_t) s; stall = 0; continue; } stall++; if (cfg.uses_threads) { struct pollfd p; p.fd = sock; p.events = POLLOUT; p.revents = 0; if (0 >= poll (&p, 1, THREAD_WAIT_MS)) break; } else { pump (d, sock, 2); } if ( (0 > s) && (EAGAIN != errno) && (EWOULDBLOCK != errno) && (EINTR != errno) ) break; } } /** * Hand a fresh socketpair to the daemon. * * @param d the daemon * @param[out] sock set to the harness side of the pair * @return 0 on success, -1 if MHD refused the connection (which is a * perfectly ordinary outcome: MHD_OPTION_CONNECTION_LIMIT and * MHD_OPTION_PER_IP_CONNECTION_LIMIT are part of what is fuzzed) */ static int new_connection (struct MHD_Daemon *d, int *sock) { int sv[2]; struct sockaddr_in sa; *sock = -1; if (0 != socketpair (AF_UNIX, SOCK_STREAM, 0, sv)) return -1; memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (44444); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (MHD_YES != MHD_add_connection (d, (MHD_socket) sv[1], (const struct sockaddr *) &sa, (socklen_t) sizeof (sa))) { /* MHD has already closed sv[1] in that case */ (void) close (sv[0]); stat_conns_refused++; return -1; } stat_conns_added++; *sock = sv[0]; return 0; } static void close_connection (struct MHD_Daemon *d, int *sock) { if (0 > *sock) return; (void) shutdown (*sock, SHUT_WR); if (cfg.uses_threads) wait_threaded (*sock); else pump (d, *sock, 4); (void) close (*sock); *sock = -1; } /* ------------------------------------------------------------------ */ /* Building the option array */ /* ------------------------------------------------------------------ */ #define PICK(tbl, idx) ((tbl)[(idx) % (sizeof (tbl) / sizeof ((tbl)[0]))]) static void add_opt (struct MHD_OptionItem *opts, unsigned int *nopt, enum MHD_OPTION option, intptr_t value, void *ptr_value) { if (*nopt + 1 >= MAX_OPTS) return; opts[*nopt].option = option; opts[*nopt].value = value; opts[*nopt].ptr_value = ptr_value; (*nopt)++; } /** * Translate the presence masks (bytes 3, 4, 14) and the value selectors * (bytes 6..11, 15) into an MHD_OptionItem array. * * Only the options that can be expressed through MHD_OPTION_ARRAY are * built here. The five callback options take two pointers, and putting * a function pointer into the array's `intptr_t value` member is not * strictly conforming C, so those go through the varargs of * MHD_start_daemon() instead (see start_daemon_variant()). */ static unsigned int build_options (const uint8_t *data, struct MHD_OptionItem *opts, unsigned int flags) { unsigned int nopt = 0; const uint8_t mask_a = data[3]; const uint8_t mask_b = data[4]; const uint8_t mask_d = data[14]; /* A thread pool needs an internal polling thread and is incompatible with thread-per-connection. */ const int pool_ok = (0 != (flags & MHD_USE_INTERNAL_POLLING_THREAD)) && (0 == (flags & MHD_USE_THREAD_PER_CONNECTION)); /* Offer options in configurations where MHD rejects them. One input in eight: the rejection branches are worth reaching, but each one costs the whole rest of the iteration, because the daemon does not start at all. */ const int misfit = (0xE0 == (data[15] & 0xE0)); if (0 != (mask_a & 0x01)) add_opt (opts, &nopt, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (intptr_t) PICK (mem_limit_tbl, data[6] & 0x0F), NULL); if (0 != (mask_a & 0x02)) add_opt (opts, &nopt, MHD_OPTION_CONNECTION_MEMORY_INCREMENT, (intptr_t) PICK (mem_increment_tbl, (data[6] >> 4) & 0x0F), NULL); if (0 != (mask_a & 0x04)) add_opt (opts, &nopt, MHD_OPTION_CONNECTION_LIMIT, (intptr_t) PICK (conn_limit_tbl, data[7] & 0x07), NULL); if (0 != (mask_a & 0x08)) add_opt (opts, &nopt, MHD_OPTION_PER_IP_CONNECTION_LIMIT, (intptr_t) PICK (per_ip_limit_tbl, (data[7] >> 4) & 0x07), NULL); if (0 != (mask_a & 0x10)) add_opt (opts, &nopt, MHD_OPTION_CONNECTION_TIMEOUT, (intptr_t) PICK (timeout_tbl, data[8] & 0x07), NULL); /* MHD_OPTION_THREAD_POOL_SIZE is rejected outright without an internal polling thread, and again when combined with MHD_USE_THREAD_PER_CONNECTION. Both branches are worth reaching, but a daemon that fails to start exercises nothing else, so the mismatched combinations are gated behind an extra bit instead of being half of all the inputs that name the option. */ if ( (0 != (mask_a & 0x20)) && (pool_ok || misfit) ) add_opt (opts, &nopt, MHD_OPTION_THREAD_POOL_SIZE, (intptr_t) PICK (pool_size_tbl, (data[8] >> 3) & 0x03), NULL); if (0 != (mask_a & 0x40)) add_opt (opts, &nopt, MHD_OPTION_THREAD_STACK_SIZE, (intptr_t) PICK (stack_size_tbl, (data[8] >> 5) & 0x03), NULL); if (0 != (mask_a & 0x80)) add_opt (opts, &nopt, MHD_OPTION_LISTENING_ADDRESS_REUSE, (intptr_t) (unsigned int) (data[11] & 0x01), NULL); if (0 != (mask_b & 0x01)) add_opt (opts, &nopt, MHD_OPTION_LISTEN_BACKLOG_SIZE, (intptr_t) PICK (backlog_tbl, (data[11] >> 1) & 0x03), NULL); if (0 != (mask_b & 0x02)) add_opt (opts, &nopt, MHD_OPTION_NONCE_NC_SIZE, (intptr_t) PICK (nonce_nc_tbl, data[9] & 0x03), NULL); if (0 != (mask_b & 0x04)) add_opt (opts, &nopt, MHD_OPTION_SERVER_INSANITY, (intptr_t) (unsigned int) ((data[10] >> 6) & 0x03), NULL); if (0 != (mask_b & 0x08)) add_opt (opts, &nopt, MHD_OPTION_STRICT_FOR_CLIENT, (intptr_t) PICK (strict_tbl, (data[10] >> 4) & 0x03), NULL); if (0 != (mask_b & 0x10)) add_opt (opts, &nopt, MHD_OPTION_CLIENT_DISCIPLINE_LVL, (intptr_t) PICK (discipline_tbl, data[10] & 0x07), NULL); if (0 != (mask_b & 0x20)) add_opt (opts, &nopt, MHD_OPTION_SIGPIPE_HANDLED_BY_APP, /* Truthful: LLVMFuzzerTestOneInput() ignores SIGPIPE process-wide before anything else happens. */ (intptr_t) 1, NULL); if (0 != (mask_b & 0x40)) add_opt (opts, &nopt, MHD_OPTION_APP_FD_SETSIZE, (intptr_t) PICK (fd_setsize_tbl, (data[11] >> 3) & 0x07), NULL); if (0 != (mask_b & 0x80)) add_opt (opts, &nopt, MHD_OPTION_ALLOW_BIN_ZERO_IN_URI_PATH, (intptr_t) (int) ((data[11] >> 5) & 0x03), NULL); if (0 != (mask_d & 0x01)) add_opt (opts, &nopt, MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE, (intptr_t) (unsigned int) ((data[9] >> 2) & 0x0F), NULL); if (0 != (mask_d & 0x02)) add_opt (opts, &nopt, MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT, (intptr_t) (unsigned int) (data[15] & 0x7F), NULL); if (0 != (mask_d & 0x04)) add_opt (opts, &nopt, MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC, (intptr_t) (uint32_t) data[15], NULL); if (0 != (mask_d & 0x08)) add_opt (opts, &nopt, MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE, (intptr_t) PICK (fastopen_tbl, (data[11] >> 6) & 0x03), NULL); if (0 != (mask_d & 0x10)) add_opt (opts, &nopt, MHD_OPTION_TLS_NO_ALPN, (intptr_t) (int) (data[15] & 0x01), NULL); if (0 != (mask_d & 0x20)) /* MHD_INVALID_SOCKET means "use the socket MHD creates itself"; a real descriptor is deliberately not offered, because MHD takes ownership of it and the harness would have to track that. */ add_opt (opts, &nopt, MHD_OPTION_LISTEN_SOCKET, (intptr_t) MHD_INVALID_SOCKET, NULL); /* MHD_OPTION_DIGEST_AUTH_RANDOM keeps the caller's buffer, the _COPY variant makes MHD malloc() a copy that MHD_stop_daemon() has to free again -- a leak this harness would notice immediately. */ if (0 != (data[5] & 0x20)) add_opt (opts, &nopt, (0 != (data[5] & 0x40)) ? MHD_OPTION_DIGEST_AUTH_RANDOM_COPY : MHD_OPTION_DIGEST_AUTH_RANDOM, (intptr_t) sizeof (digest_rnd), (void *) (intptr_t) digest_rnd); /* A bind address is rejected together with MHD_USE_NO_LISTEN_SOCKET; same reasoning as for the thread pool above. */ if ( (0 != (data[5] & 0x80)) && (cfg.listen_sock || misfit) ) { prepare_sock_addrs (); /* The address family has to match MHD_USE_IPv6, otherwise MHD rejects the daemon; that check is reached through the raw flag escape rather than by feeding a mismatched address on purpose. */ #ifdef AF_INET6 if (0 != (flags & MHD_USE_IPv6)) { if (0 != (data[15] & 0x02)) add_opt (opts, &nopt, MHD_OPTION_SOCK_ADDR_LEN, (intptr_t) (socklen_t) sizeof (bind6), &bind6); else add_opt (opts, &nopt, MHD_OPTION_SOCK_ADDR, 0, &bind6); } else #endif if (0 != (data[15] & 0x02)) add_opt (opts, &nopt, MHD_OPTION_SOCK_ADDR_LEN, (intptr_t) (socklen_t) sizeof (bind4), &bind4); else add_opt (opts, &nopt, MHD_OPTION_SOCK_ADDR, 0, &bind4); } /* An option number MHD does not know at all. parse_options_va() answers MHD_NO for it and MHD_start_daemon() returns NULL, which is the branch this reaches; keep it last so that everything above has already been parsed. */ if (0 != (mask_d & 0x40)) add_opt (opts, &nopt, (enum MHD_OPTION) (200 + (data[15] & 0x0F)), 0, NULL); opts[nopt].option = MHD_OPTION_END; opts[nopt].value = 0; opts[nopt].ptr_value = NULL; return nopt; } /* The three callback options whose "not set" state is representable as a NULL function pointer; MHD checks all three for NULL before calling them, so passing NULL is exactly equivalent to omitting the option. */ typedef void *(*fuzz_uri_log_cb)(void *, const char *, struct MHD_Connection *); #define VARARG_CALLBACKS \ MHD_OPTION_NOTIFY_COMPLETED, cb_completed, NULL, \ MHD_OPTION_NOTIFY_CONNECTION, cb_notify, NULL, \ MHD_OPTION_URI_LOG_CALLBACK, cb_uri_log, NULL /* The accept policy callback, defined with the accept path further down. */ static enum MHD_Result apc_cb (void *cls, const struct sockaddr *addr, socklen_t addrlen); /** * Start the daemon. * * MHD_OPTION_EXTERNAL_LOGGER and MHD_OPTION_UNESCAPE_CALLBACK cannot be * "passed as NULL": MHD calls both unconditionally, so their absence has * to be expressed by leaving the option out of the varargs, which is why * there are four spellings of the same call. The logger comes first on * purpose -- MHD_OPTION_EXTERNAL_LOGGER only catches the messages * emitted after it has been parsed, and parsing the option array emits * several. */ static struct MHD_Daemon * start_daemon_variant (unsigned int flags, struct MHD_OptionItem *opts, unsigned int cbsel) { MHD_AcceptPolicyCallback apc = cfg.accept_policy ? &apc_cb : NULL; MHD_RequestCompletedCallback cb_completed = (0 != (cbsel & 0x01)) ? &completed_cb : NULL; MHD_NotifyConnectionCallback cb_notify = (0 != (cbsel & 0x02)) ? ¬ify_connection_cb : NULL; fuzz_uri_log_cb cb_uri_log = (0 != (cbsel & 0x04)) ? &uri_log_cb : NULL; switch ((cbsel >> 3) & 0x03) { case 1: return MHD_start_daemon (flags, 0, apc, NULL, &ahc, NULL, MHD_OPTION_ARRAY, opts, VARARG_CALLBACKS, MHD_OPTION_UNESCAPE_CALLBACK, &unescape_cb, NULL, MHD_OPTION_END); case 2: return MHD_start_daemon (flags, 0, apc, NULL, &ahc, NULL, MHD_OPTION_EXTERNAL_LOGGER, &logger_cb, NULL, MHD_OPTION_ARRAY, opts, VARARG_CALLBACKS, MHD_OPTION_END); case 3: return MHD_start_daemon (flags, 0, apc, NULL, &ahc, NULL, MHD_OPTION_EXTERNAL_LOGGER, &logger_cb, NULL, MHD_OPTION_ARRAY, opts, VARARG_CALLBACKS, MHD_OPTION_UNESCAPE_CALLBACK, &unescape_cb, NULL, MHD_OPTION_END); default: return MHD_start_daemon (flags, 0, apc, NULL, &ahc, NULL, MHD_OPTION_ARRAY, opts, VARARG_CALLBACKS, MHD_OPTION_END); } } /** * The accept policy callback. MHD_accept_connection() calls it with the * peer address of every socket it accepts, and answering MHD_NO makes * new_connection_prepare_() close the socket and drop the IP-limit entry * before any connection object exists -- a path nothing else here * reaches. (It does *not* reach new_connection_close_(): that one is * only called from close_all_connections(), for connections queued by * MHD_add_connection() and never started. See the byte 3 bit 4 * scenario in fuzz_eventloop.c.) */ static enum MHD_Result apc_cb (void *cls, const struct sockaddr *addr, socklen_t addrlen) { volatile size_t sink; (void) cls; sink = (size_t) addrlen + ((NULL != addr) ? (size_t) addr->sa_family : 0u); (void) sink; return cfg.accept_policy_deny ? MHD_NO : MHD_YES; } /** * Really connect to the daemon's listening socket. * * MHD_add_connection() bypasses accept(), so without this the whole * accept path -- MHD_accept_connection(), the accept policy callback, * the listen-socket branches of the three event loops -- is unreachable. * The client end is given SO_LINGER {1, 0} so that close() sends a RST * and neither side ends up in TIME_WAIT: at fuzzing rates the ephemeral * port range would otherwise be exhausted within a couple of minutes. * * @param d the daemon, which must have a listening socket * @param flags the flags it was started with, to pick the address family * @return the connected socket, or -1 */ static int connect_real (struct MHD_Daemon *d, unsigned int flags) { const union MHD_DaemonInfo *di; struct linger lg; int s; uint16_t port; di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == di) || (0 == di->port) ) return -1; port = (uint16_t) di->port; prepare_sock_addrs (); #ifdef AF_INET6 if (0 != (flags & MHD_USE_IPv6)) { struct sockaddr_in6 to = bind6; to.sin6_port = htons (port); s = socket (AF_INET6, SOCK_STREAM, 0); if (0 > s) return -1; if (0 != connect (s, (const struct sockaddr *) &to, sizeof (to))) { (void) close (s); return -1; } } else #endif { struct sockaddr_in to = bind4; to.sin_port = htons (port); s = socket (AF_INET, SOCK_STREAM, 0); if (0 > s) return -1; if (0 != connect (s, (const struct sockaddr *) &to, sizeof (to))) { (void) close (s); return -1; } } lg.l_onoff = 1; lg.l_linger = 0; (void) setsockopt (s, SOL_SOCKET, SO_LINGER, &lg, sizeof (lg)); stat_real_conns++; return s; } /** * Ask MHD_is_feature_supported() about one feature. The function is a * large switch in daemon.c that no other harness touches; the index * comes off the input so that invalid values reach its default branch * as well. */ static void query_feature (uint8_t sel) { volatile int sink; sink = (int) MHD_is_feature_supported ((enum MHD_FEATURE) (sel % 40u)); (void) sink; } /** * Read everything MHD_get_daemon_info() offers. All of it lives in * daemon.c and none of it is reachable from the other harnesses. */ static void query_daemon_info (struct MHD_Daemon *d) { volatile unsigned int sink = 0; const union MHD_DaemonInfo *di; sink += (unsigned int) (NULL != MHD_get_version ()); sink += MHD_get_version_bin (); di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_CURRENT_CONNECTIONS); if (NULL != di) sink += di->num_connections; di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL != di) sink += (unsigned int) di->flags; di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL != di) sink += di->port; di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (NULL != di) sink += (unsigned int) (di->listen_fd + 1); di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_EPOLL_FD); if (NULL != di) sink += (unsigned int) (di->listen_fd + 1); (void) sink; } /* ------------------------------------------------------------------ */ /* The fuzz target */ /* ------------------------------------------------------------------ */ int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { struct MHD_Daemon *d; struct MHD_OptionItem opts[MAX_OPTS]; unsigned int flags; int sock = -1; int rsock = -1; size_t pos; unsigned int nseg = 0; unsigned int nconn = 1; unsigned int cbsel; MHD_socket quiesced = MHD_INVALID_SOCKET; /* Must happen before the first write() into the socketpair, and must not be left to the built-in driver: fuzz_install_handlers() is compiled out under -DFUZZ_NO_MAIN, which is exactly the build every external fuzzing engine uses. The call is idempotent. See fuzz_ignore_sigpipe() in fuzz_common.h for what happens without it. */ fuzz_ignore_sigpipe (); /* The sixteen configuration bytes are mandatory. An input of exactly that length is fine and starts a daemon with no traffic. */ if (size < CFG_BYTES) return 0; memset (&cfg, 0, sizeof (cfg)); memset (pending_resume, 0, sizeof (pending_resume)); tearing_down = 0; flags = flags_from_input (data); if (cfg.listen_sock) flags &= ~((unsigned int) MHD_USE_NO_LISTEN_SOCKET); else flags |= MHD_USE_NO_LISTEN_SOCKET; if (cfg.err_log) flags |= MHD_USE_ERROR_LOG; else flags &= ~((unsigned int) MHD_USE_ERROR_LOG); cfg.uses_threads = (0 != (flags & (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION))); if (cfg.uses_threads && (0 == (flags & MHD_USE_NO_THREAD_SAFETY))) { /* Without the inter-thread communication channel a worker only notices a connection handed to it by MHD_add_connection() when its own poll times out, so every threaded iteration would pay the full wait. MHD forces ITC on anyway whenever there is no listen socket; this extends that to the daemons that have one. */ flags |= MHD_USE_ITC; } cfg.loop_mode = (unsigned int) (data[12] & 0x03); cfg.quiesce = (0 != (data[12] & 0x04)); if (cfg.quiesce && cfg.uses_threads && uses_epoll (flags) && (! quiesce_epoll_race_allowed ())) cfg.quiesce = 0; cfg.daemon_info = (0 != (data[12] & 0x08)); cfg.suspend_mode = (0 != (flags & SUSPEND_BIT)) ? (int) ((data[12] >> 4) & 0x03) : 0; if (3 == cfg.suspend_mode) cfg.suspend_mode = 1; cfg.nconn_max = 1u + (unsigned int) ((data[12] >> 6) & 0x03); if (cfg.nconn_max > MAX_CONNECTIONS) cfg.nconn_max = MAX_CONNECTIONS; cfg.resp_kind = (unsigned int) (data[13] & 0x03); cfg.handler_no = (0 != (data[13] & 0x04)); cfg.conn_option = (0 != (data[13] & 0x08)); cfg.accept_policy = (0 != (data[13] & 0x10)); cfg.accept_policy_deny = (0 != (data[13] & 0x20)); /* One iteration in four of those that have a listening socket at all; a real connect()/accept() pair is much more expensive than MHD_add_connection() on a socketpair. */ cfg.real_connect = cfg.listen_sock && (0xC0 == (data[13] & 0xC0)); (void) build_options (data, opts, flags); cbsel = (unsigned int) data[5]; /* MHD_USE_ERROR_LOG without MHD_OPTION_EXTERNAL_LOGGER sends every message MHD produces to stderr through MHD_default_logger_, which at fuzzing rates is tens of megabytes of noise. The flag is far too valuable to drop -- with it set, several hundred MHD_DLOG() call sites in daemon.c become live -- so the logger is forced on instead (bit 4 of the callback selector). */ if (cfg.err_log) cbsel |= 0x10u; MHD_set_panic_func (&panic_cb, NULL); d = start_daemon_variant (flags, opts, cbsel); if (NULL == d) { /* Entirely normal: an unsupported flag combination, an option MHD rejects, a bind() failure, ... */ stat_daemons_failed++; return 0; } stat_daemons++; if (cfg.uses_threads) stat_threaded++; if (! stats_registered) { stats_registered = 1; (void) atexit (&print_stats); } if (cfg.daemon_info) query_daemon_info (d); query_feature (data[15]); if (cfg.real_connect) { rsock = connect_real (d, flags); if (0 <= rsock) { static const char req[] = "GET / HTTP/1.1\r\nHost: x\r\n\r\n"; (void) send (rsock, req, sizeof (req) - 1, MSG_DONTWAIT); if (cfg.uses_threads) wait_threaded (rsock); else pump (d, rsock, PUMP_ROUNDS_LONG); } } (void) new_connection (d, &sock); pos = CFG_BYTES; while ( (pos + 2 <= size) && (nseg < MAX_SEGMENTS) ) { unsigned int hdr = (unsigned int) data[pos] | ((unsigned int) data[pos + 1] << 8); unsigned int op = hdr >> 14; size_t slen = (size_t) (hdr & 0x3FFF); pos += 2; nseg++; if (slen > size - pos) slen = size - pos; if ( (3 == op) && (nconn < cfg.nconn_max) ) { close_connection (d, &sock); (void) new_connection (d, &sock); nconn++; } if (0 != slen) send_all (d, sock, data + pos, slen); pos += slen; if (cfg.uses_threads) continue; /* the threaded shape drains at close */ pump (d, sock, (0 == op) ? PUMP_ROUNDS : PUMP_ROUNDS_LONG); } close_connection (d, &sock); pump (d, sock, 4); if (0 <= rsock) { (void) shutdown (rsock, SHUT_WR); if (cfg.uses_threads) wait_threaded (rsock); else pump (d, rsock, 4); (void) close (rsock); rsock = -1; } /* A connection left suspended makes MHD_stop_daemon() MHD_PANIC(), and MHD_resume_connection() alone is not enough: it only raises a flag, and the connection is taken off the daemon's suspended list by MHD_run(). So flush and run until nothing is parked any more. tearing_down keeps the handler from parking anything new, which is what bounds this loop; the cap is only a backstop. */ tearing_down = 1; if (! cfg.uses_threads) { unsigned int i; for (i = 0; i < MAX_CONNECTIONS + 2u; i++) { if (! pending_resume_flush ()) break; (void) MHD_run (d); } } if (cfg.quiesce) { /* The returned socket belongs to the caller from here on, and with internal threads it must not be closed before MHD_stop_daemon() has joined them. */ quiesced = MHD_quiesce_daemon (d); } MHD_stop_daemon (d); if (MHD_INVALID_SOCKET != quiesced) (void) close ((int) quiesced); return 0; } /* ------------------------------------------------------------------ */ /* Structure-aware generator */ /* ------------------------------------------------------------------ */ /* Defined unconditionally, exactly like the rest of the harness API: only main() may live behind #ifndef FUZZ_NO_MAIN, and fuzz_common.h already declares these three with FUZZ_UNUSED so that the libFuzzer and AFL++ builds, which never call them, compile without a warning. */ struct sbuf { uint8_t *p; size_t len; size_t cap; }; static void sb_raw (struct sbuf *b, const void *s, size_t n) { if (b->len + n > b->cap) n = b->cap - b->len; memcpy (b->p + b->len, s, n); b->len += n; } static void sb_str (struct sbuf *b, const char *s) { sb_raw (b, s, strlen (s)); } static void sb_u64 (struct sbuf *b, uint64_t v, int hex) { char tmp[32]; (void) snprintf (tmp, sizeof (tmp), hex ? "%llx" : "%llu", (unsigned long long) v); sb_str (b, tmp); } static const char *const gen_methods[] = { "GET", "POST", "HEAD", "PUT", "OPTIONS", "DELETE", "TRACE", "CONNECT", "PATCH", "get", "BREW", "" }; static const char *const gen_targets[] = { "/", "/a", "/a/b/c", "*", "http://x/a", "/%41%42", "/a?b=c&d", "/very/long/path/that/does/not/fit/into/a/small/connection/memory/pool", "/a?novalue", "//", "/.%2e/", "/\x01" }; static const char *const gen_versions[] = { "HTTP/1.1", "HTTP/1.0", "HTTP/1.2", "HTTP/0.9", "HTTP/1", "" }; static const char *const gen_hdr_names[] = { "Host", "Connection", "Accept", "User-Agent", "Cookie", "Expect", "Content-Type", "X-Fuzz", "Upgrade", "Accept-Encoding", "Range", "If-Modified-Since" }; static const char *const gen_hdr_values[] = { "x", "keep-alive", "close", "*/*", "a=b; c=d", "100-continue", "text/plain", "1", "fuzz-protocol", "gzip", "bytes=0-1", "chunked" }; /** * Emit one HTTP request into @a b. * * The shapes are deliberately unambitious -- the request parser is * fuzz_request's subject, not this harness's. What matters here is that * the bytes form something MHD will actually take through its state * machine under whatever daemon configuration the configuration bytes * describe, so that the option handling is exercised against a live * connection rather than against a connection MHD drops on the first * byte. */ static void gen_request (struct fuzz_rng *rng, struct sbuf *b, unsigned int shape) { unsigned int nhdr; unsigned int i; switch (shape % 10) { case 9: /* Not HTTP at all: MHD has to reject it, which is its own path. */ for (i = 0; i < 24; i++) { uint8_t c = fuzz_byte (rng); sb_raw (b, &c, 1); } return; case 6: /* Two pipelined requests on one connection. */ sb_str (b, "GET /a HTTP/1.1\r\nHost: x\r\n\r\n"); sb_str (b, "GET /b HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n"); return; default: break; } sb_str (b, gen_methods[fuzz_below (rng, (uint32_t) (sizeof (gen_methods) / sizeof (gen_methods[0] )))]); sb_str (b, " "); sb_str (b, gen_targets[fuzz_below (rng, (uint32_t) (sizeof (gen_targets) / sizeof (gen_targets[0] )))]); sb_str (b, " "); sb_str (b, gen_versions[fuzz_below (rng, (uint32_t) (sizeof (gen_versions) / sizeof (gen_versions[0]))) ]); sb_str (b, "\r\n"); nhdr = (5 == (shape % 10)) ? (8 + fuzz_below (rng, 24)) : fuzz_below (rng, 5); for (i = 0; i < nhdr; i++) { sb_str (b, gen_hdr_names[fuzz_below (rng, (uint32_t) (sizeof (gen_hdr_names) / sizeof (gen_hdr_names[0] )))]); sb_str (b, ": "); sb_str (b, gen_hdr_values[fuzz_below (rng, (uint32_t) (sizeof (gen_hdr_values) / sizeof (gen_hdr_values[ 0])))]); sb_str (b, "\r\n"); } switch (shape % 10) { case 2: /* Content-Length body */ { uint32_t n = fuzz_below (rng, 64); sb_str (b, "Content-Length: "); sb_u64 (b, n, 0); sb_str (b, "\r\n\r\n"); for (i = 0; i < n; i++) sb_str (b, "A"); break; } case 3: /* chunked body */ { unsigned int nch = 1 + fuzz_below (rng, 3); sb_str (b, "Transfer-Encoding: chunked\r\n\r\n"); for (i = 0; i < nch; i++) { uint32_t n = 1 + fuzz_below (rng, 16); uint32_t k; sb_u64 (b, n, 1); sb_str (b, "\r\n"); for (k = 0; k < n; k++) sb_str (b, "B"); sb_str (b, "\r\n"); } sb_str (b, "0\r\n\r\n"); break; } case 4: /* expect 100-continue */ sb_str (b, "Expect: 100-continue\r\nContent-Length: 4\r\n\r\nabcd"); break; case 7: /* upgrade request */ sb_str (b, "Connection: Upgrade\r\nUpgrade: fuzz-protocol\r\n\r\n"); break; case 8: /* truncated: MHD keeps waiting for more */ sb_str (b, "X-Trunc: "); break; default: sb_str (b, "\r\n"); break; } } /** * Serialise @a body into the segment stream understood by * LLVMFuzzerTestOneInput(). */ static void emit_segments (struct fuzz_rng *rng, struct sbuf *out, const uint8_t *body, size_t body_len, int new_conn_first) { size_t off = 0; int first = 1; while (off < body_len) { size_t chunk; unsigned int op; uint8_t hdr[2]; unsigned int hv; switch (fuzz_below (rng, 5)) { case 0: chunk = 1; break; case 1: chunk = 2 + fuzz_below (rng, 8); break; default: chunk = body_len - off; break; } if (chunk > body_len - off) chunk = body_len - off; if (chunk > 0x3FFF) chunk = 0x3FFF; op = (first && new_conn_first) ? 3u : (fuzz_chance (rng, 5) ? 2u : 0u); hv = (op << 14) | (unsigned int) chunk; hdr[0] = (uint8_t) (hv & 0xFF); hdr[1] = (uint8_t) (hv >> 8); if (out->len + 2 + chunk > out->cap) return; sb_raw (out, hdr, 2); sb_raw (out, body + off, chunk); off += chunk; first = 0; } } /** * The generator. * * Purely random configuration bytes are already useful for this harness * -- unlike an HTTP request, an option array has no grammar to get wrong * -- but two things still need help. Byte 0 is biased into the range of * mode_tbl[] so that most iterations get a daemon that actually starts, * and the tail of the input has to look like HTTP, or MHD closes every * connection before any of the configured behaviour has a chance to * matter. */ static size_t fuzz_generate (struct fuzz_rng *rng, uint8_t *buf, size_t cap) { struct sbuf out; uint8_t cfg_bytes[CFG_BYTES]; uint8_t req[GEN_BUF_SIZE]; struct sbuf rb; unsigned int nreq; unsigned int i; out.p = buf; out.len = 0; out.cap = cap; for (i = 0; i < CFG_BYTES; i++) cfg_bytes[i] = fuzz_byte (rng); /* Byte 0 selects the daemon shape; keep it inside the table so that the value is not folded by the modulo in an uneven way. */ cfg_bytes[0] = (uint8_t) fuzz_below (rng, (uint32_t) MODE_COUNT); /* The raw flag escape is 1 in 4 of the byte-2 values, which is far too often: those daemons mostly fail to start and never reach the option handling. Clear the escape unless it is explicitly rolled. */ if (! fuzz_chance (rng, 10)) cfg_bytes[2] &= (uint8_t) ~0xC0u; else cfg_bytes[2] |= (uint8_t) 0xC0u; /* Likewise the deliberately invalid option number: useful, but every input carrying it ends in MHD_start_daemon() == NULL. */ if (! fuzz_chance (rng, 20)) cfg_bytes[14] &= (uint8_t) ~0x40u; sb_raw (&out, cfg_bytes, CFG_BYTES); nreq = 1u + (fuzz_chance (rng, 4) ? 1u : 0u); for (i = 0; i < nreq; i++) { rb.p = req; rb.len = 0; rb.cap = sizeof (req); gen_request (rng, &rb, fuzz_below (rng, 10)); emit_segments (rng, &out, req, rb.len, (0 != i) || fuzz_chance (rng, 6)); } return out.len; } /* ------------------------------------------------------------------ */ /* Built-in seed corpus */ /* ------------------------------------------------------------------ */ /** * A seed is sixteen configuration bytes plus one request, rendered into * the wire format at run time so that segment lengths never have to be * spelled out by hand. * * Every seed turns on exactly one area, so that a corpus minimiser keeps * them distinguishable, and the configuration bytes of a seed that does * not care about an area are zero -- which is the plainest setting: * external polling with select(), no listen socket, no options at all, * one connection, MHD_run() as the event loop. */ struct seed_def { const char *name; unsigned char cfg[CFG_BYTES]; const char *req; }; /* Byte positions inside seed_def::cfg, for readability. */ #define C_MODE 0 #define C_FLAGA 1 #define C_FLAGB 2 #define C_OPTA 3 #define C_OPTB 4 #define C_OPTC 5 #define C_VAL_MEM 6 #define C_VAL_CONN 7 #define C_VAL_THR 8 #define C_VAL_DAUTH 9 #define C_VAL_DISC 10 #define C_VAL_SOCK 11 #define C_DRIVE 12 #define C_HANDLER 13 #define C_OPTD 14 #define C_SPARE 15 #define REQ_PLAIN "GET /a HTTP/1.1\r\nHost: x\r\n\r\n" #define REQ_CLOSE "GET /a HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n" #define REQ_POST \ "POST /a HTTP/1.1\r\nHost: x\r\nContent-Length: 4\r\n\r\nabcd" #define REQ_CHUNKED \ "POST /a HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n" \ "\r\n3\r\nabc\r\n0\r\n\r\n" static const struct seed_def seeds[] = { /* ---- the event loops, all external ---- */ { "plain-external-run", { 0 }, REQ_PLAIN }, { "external-fdset2", { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01 | 0x08, 0, 0, 0 }, REQ_PLAIN }, { "external-run-wait", { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02, 0, 0, 0 }, REQ_PLAIN }, { "external-fdset-v1", { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x03, 0, 0, 0 }, REQ_PLAIN }, { "external-epoll", { 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "external-auto", { 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, /* ---- the daemon shapes that run their own threads ---- */ { "internal-thread-select", { 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_CLOSE }, { "internal-thread-poll", { 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_CLOSE }, { "internal-thread-epoll", { 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_CLOSE }, { "thread-per-connection", { 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_CLOSE }, { "thread-per-connection-poll", { 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_CLOSE }, /* A thread pool needs MHD_OPTION_THREAD_POOL_SIZE (option mask A bit 5) on top of an internal polling thread, and is rejected outright with thread-per-connection. */ { "thread-pool", { 18, 0, 0, 0x20, 0, 0, 0, 0, 0x00, 0, 0, 0, 0, 0, 0, 0 }, REQ_CLOSE }, { "thread-pool-epoll-stack", { 20, 0, 0, 0x20 | 0x40, 0, 0, 0, 0, 0x10 | 0x20, 0, 0, 0, 0, 0, 0, 0 }, REQ_CLOSE }, /* ---- a real listening socket ---- */ { "listen-socket", { 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "listen-socket-reuse-backlog", { 0, 0, 0x01, 0x80, 0x01, 0, 0, 0, 0, 0, 0, 0x01 | 0x06, 0, 0, 0, 0 }, REQ_PLAIN }, { "listen-socket-sockaddr", { 0, 0, 0x01, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "listen-socket-ipv6-dual", { 0, 0, 0x01 | 0x02 | 0x04, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "listen-socket-quiesce", { 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04 | 0x08, 0, 0, 0 }, REQ_PLAIN }, { "listen-socket-internal-thread", { 18, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, 0, 0, 0 }, REQ_CLOSE }, /* ---- the accept() path: a real client on the listening socket ---- Byte 13 bit 0x40|0x80 asks for the connect(), bit 0x10 installs the accept policy callback and bit 0x20 makes it say no. Without these MHD_accept_connection() and the listen-socket branches of the three event loops are never entered at all: MHD_add_connection() bypasses accept() completely. */ { "real-connect", { 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xC0, 0, 0 }, REQ_PLAIN }, { "real-connect-accept-policy", { 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xC0 | 0x10, 0, 0 }, REQ_PLAIN }, { "real-connect-accept-denied", { 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xC0 | 0x10 | 0x20, 0, 0 }, REQ_PLAIN }, { "real-connect-internal-thread", { 18, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xC0, 0, 0 }, REQ_CLOSE }, { "real-connect-external-epoll", { 12, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xC0, 0, 0 }, REQ_PLAIN }, /* ---- the memory options ---- */ { "tiny-pool", { 0, 0, 0, 0x01 | 0x02, 0, 0, 0x01 | 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "big-pool-big-increment", { 0, 0, 0, 0x01 | 0x02, 0, 0, 0x0C | 0x60, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_POST }, /* ---- the connection limits ---- */ { "connection-limit-one", { 0, 0, 0, 0x04, 0, 0, 0, 0x01, 0, 0, 0, 0, 0xC0, 0, 0, 0 }, REQ_PLAIN }, { "per-ip-limit-one", { 0, 0, 0, 0x08, 0, 0, 0, 0x10, 0, 0, 0, 0, 0xC0, 0, 0, 0 }, REQ_PLAIN }, { "connection-limit-zero", { 0, 0, 0, 0x04, 0, 0, 0, 0x00, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "connection-timeout", { 0, 0, 0, 0x10, 0, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, /* ---- parsing discipline and insanity ---- */ { "discipline-lowest", { 0, 0, 0, 0, 0x10, 0, 0, 0, 0, 0, 0x00, 0, 0, 0, 0, 0 }, "GET /a HTTP/1.1\r\n Host: x\r\n\r\n" }, { "discipline-highest-pedantic", { 0, 0x01, 0, 0, 0x10, 0, 0, 0, 0, 0, 0x05, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "strict-for-client", { 0, 0, 0, 0, 0x08, 0, 0, 0, 0, 0, 0x00, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "server-insanity", { 0, 0, 0, 0, 0x04, 0, 0, 0, 0, 0, 0x40, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "bin-zero-in-uri-path", { 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0x20, 0, 0, 0, 0 }, "GET /a%00b HTTP/1.1\r\nHost: x\r\n\r\n" }, { "app-fd-setsize", { 0, 0, 0, 0, 0x40, 0, 0, 0, 0, 0, 0, 0x00, 0x01, 0, 0, 0 }, REQ_PLAIN }, /* ---- the callbacks ---- */ { "notify-completed", { 0, 0, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "notify-connection", { 0, 0, 0, 0, 0, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "uri-log-callback", { 0, 0, 0, 0, 0, 0x04, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, "GET /a?q=%41 HTTP/1.1\r\nHost: x\r\n\r\n" }, { "external-logger", { 0, 0x40, 0, 0, 0, 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "unescape-callback", { 0, 0, 0, 0, 0, 0x08, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, "GET /%41%42?a=%43 HTTP/1.1\r\nHost: x\r\n\r\n" }, { "all-callbacks-error-log", { 0, 0x40, 0, 0, 0, 0x01 | 0x02 | 0x04 | 0x08 | 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, /* ---- digest-auth related options ---- */ { "digest-random", { 0, 0, 0, 0, 0x02, 0x20, 0, 0, 0, 0x02, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "digest-random-copy", { 0, 0, 0, 0, 0x02, 0x20 | 0x40, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "digest-nonce-bind-and-defaults", { 0, 0, 0, 0, 0, 0x20, 0, 0, 0, 0x3C, 0, 0, 0, 0, 0x01 | 0x02 | 0x04, 0x11 }, REQ_PLAIN }, /* ---- suspend / resume ---- */ { "suspend-immediate", { 0, 0x04, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0x10, 0, 0, 0 }, REQ_PLAIN }, { "suspend-deferred", { 0, 0x04, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0x20, 0, 0, 0 }, REQ_PLAIN }, { "suspend-deferred-two-connections", { 0, 0x04, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0x20 | 0x40, 0, 0, 0 }, REQ_PLAIN }, /* ---- the remaining flag bits ---- */ { "turbo-itc-suppress-date", { 0, 0x02 | 0x10 | 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "allow-upgrade", { 0, 0x08, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, "GET / HTTP/1.1\r\nHost: x\r\nConnection: Upgrade\r\n" "Upgrade: fuzz-protocol\r\n\r\n" }, { "no-thread-safety", { 0, 0, 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "tcp-fastopen-listen", { 0, 0, 0x01 | 0x08, 0, 0, 0, 0, 0, 0, 0, 0, 0x40, 0, 0, 0x08, 0 }, REQ_PLAIN }, { "sigpipe-handled-by-app", { 0, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, { "listen-socket-option-invalid-fd", { 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x20, 0 }, REQ_PLAIN }, /* ---- inputs whose daemon must not start ---- */ /* Raw flag escape: MHD_USE_POLL together with MHD_USE_EPOLL. */ { "raw-flags-poll-and-epoll", { 0, 0x40, 0xC0 | 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, /* Raw flag escape: MHD_USE_EPOLL with MHD_USE_THREAD_PER_CONNECTION. */ { "raw-flags-epoll-thread-per-conn", { 0, 0x04 | 0x08, 0xC0 | 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, /* An option number MHD does not know. */ { "invalid-option-number", { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x40, 0 }, REQ_PLAIN }, /* MHD_OPTION_THREAD_POOL_SIZE without an internal polling thread. */ { "thread-pool-without-threads", { 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, REQ_PLAIN }, /* ---- the handler behaviours ---- */ { "handler-returns-no", { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, 0, 0 }, REQ_PLAIN }, { "empty-and-copied-responses", { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01 | 0x08, 0, 0 }, REQ_CHUNKED }, { "error-response", { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x03, 0, 0 }, REQ_POST }, /* ---- everything at once ---- */ { "kitchen-sink-external", { 0, 0x02 | 0x04 | 0x10 | 0x20 | 0x40, 0x01, 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x80, 0x02 | 0x10 | 0x20 | 0x40 | 0x80, 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20, 0x63, 0x45, 0x21, 0x13, 0x02, 0x0A, 0x01 | 0x04 | 0x08 | 0x20, 0x08, 0x01 | 0x02 | 0x04 | 0x10, 0x33 }, REQ_POST }, { "kitchen-sink-thread-pool", { 18, 0x02 | 0x10 | 0x20 | 0x40, 0x01, 0x01 | 0x04 | 0x08 | 0x10 | 0x20 | 0x40 | 0x80, 0x01 | 0x02 | 0x80, 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20, 0x03, 0x46, 0x39, 0x02, 0x00, 0x0A, 0x04 | 0x08, 0x00, 0x01 | 0x08, 0x22 }, REQ_CLOSE } }; static uint8_t seed_render_buf[1024]; static size_t fuzz_seed_count (void) { return sizeof (seeds) / sizeof (seeds[0]); } static const uint8_t * fuzz_seed_get (size_t idx, size_t *len) { const struct seed_def *sd = &seeds[idx]; struct sbuf b; b.p = seed_render_buf; b.len = 0; b.cap = sizeof (seed_render_buf); sb_raw (&b, sd->cfg, CFG_BYTES); if (NULL != sd->req) { size_t n = strlen (sd->req); unsigned int hv; uint8_t hdr[2]; if (n > 0x3FFF) n = 0x3FFF; hv = (0u << 14) | (unsigned int) n; hdr[0] = (uint8_t) (hv & 0xFF); hdr[1] = (uint8_t) (hv >> 8); sb_raw (&b, hdr, 2); sb_raw (&b, sd->req, n); } *len = b.len; return seed_render_buf; } libmicrohttpd-1.0.10/src/fuzz/fuzz_tls.c0000664000175000017500000027615715232414252013753 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file fuzz/fuzz_tls.c * @brief In-process fuzzer for MHD's HTTPS/TLS integration layer. * @author Christian Grothoff * * The target is **MHD's own TLS plumbing**, not GnuTLS. GnuTLS has its * own OSS-Fuzz project and its record parser is not our bug surface, so * only a small part of the input budget is spent throwing raw bytes at a * TLS socket. What this harness really exercises is * * - the @c MHD_USE_TLS daemon option surface: #MHD_OPTION_HTTPS_MEM_KEY, * #MHD_OPTION_HTTPS_MEM_CERT, #MHD_OPTION_HTTPS_MEM_TRUST, * #MHD_OPTION_HTTPS_MEM_DHPARAMS, #MHD_OPTION_HTTPS_PRIORITIES, * #MHD_OPTION_HTTPS_PRIORITIES_APPEND, #MHD_OPTION_HTTPS_CRED_TYPE, * #MHD_OPTION_HTTPS_KEY_PASSWORD, #MHD_OPTION_TLS_NO_ALPN and the SNI * callback #MHD_OPTION_HTTPS_CERT_CALLBACK -- with malformed PEM * blobs, mismatched key/certificate pairs, bogus priority strings, * credential types MHD does not support, and an SNI callback that * fails or answers with garbage; * - the pre-shared key path: #MHD_OPTION_GNUTLS_PSK_CRED_HANDLER and * @c psk_gnutls_adapter(), which is the one place where MHD takes a * buffer straight from an application callback and hands it to * GnuTLS. See the "TLS-PSK" note below for why one input bit turns * the whole scenario on rather than four independent ones; * - the handshake state machine of connection_https.c * (#MHD_TLS_CONN_INIT -> HANDSHAKING -> CONNECTED / TLS_FAILED) and * what MHD does when the handshake fails, is abandoned half way, or * the peer disappears while MHD is still in it; * - the transition from the handshake to the ordinary HTTP parser, and * the TLS receive/send adapters and @c gnutls_bye() shutdown path that * the connection uses afterwards. * * To reach that last group the harness contains a real, in-process GnuTLS * *client*. Both ends of an @c AF_UNIX @c socketpair() are non-blocking * and everything runs in one thread: the client's @c gnutls_handshake() * is called until it answers @c GNUTLS_E_AGAIN, then the daemon is pumped * with MHD_run(), and so on. No threads, no ports, no TCP stack, and -- * because the client's handshake timeout is set to * @c GNUTLS_INDEFINITE_TIMEOUT -- no wall clock either. * * Input format (see README): * * byte 0 certificate/key pair selector (valid, mismatched, truncated, * garbage, absent, or built from the fuzzer's own bytes) * byte 1 which TLS daemon options to pass at all (bitmask) * 0x01 MHD_OPTION_HTTPS_MEM_TRUST * 0x02 MHD_OPTION_HTTPS_MEM_DHPARAMS * 0x04 MHD_OPTION_HTTPS_CERT_CALLBACK (the SNI callback) * 0x08 MHD_OPTION_HTTPS_PRIORITIES[_APPEND] * 0x10 MHD_OPTION_HTTPS_CRED_TYPE * 0x20 MHD_OPTION_TLS_NO_ALPN * 0x40 MHD_OPTION_HTTPS_KEY_PASSWORD * 0x80 use _PRIORITIES_APPEND instead of _PRIORITIES * byte 2 priority string selector * byte 3 bits 0-2 credential type (certificate, PSK, anon, SRP, IA, * and two values GnuTLS does not define) * bits 3-5 SNI callback behaviour * bit 6 trust blob: CA certificate or garbage * bit 7 DH parameters: valid or garbage * byte 4 bits 0-1 client mode * 0 raw bytes, 1 real TLS client, * 2 real client, handshake abandoned half way, * 3 raw bytes shaped like TLS records * bit 2 client sends a server name (SNI) * bit 3 client presents a client certificate * bits 4-5 client priority string selector * bit 6 gnutls_bye() before closing * bit 7 shutdown(SHUT_WR) before closing * byte 5 bits 0-3 MHD_OPTION_CONNECTION_MEMORY_LIMIT selector * bits 4-5 event loop: MHD_run() vs MHD_get_fdset*() + * MHD_run_from_select*() * bit 6 hand the daemon one more connection at the very * end and stop it without running the loop again, * so that a TLS session is torn down for a * connection MHD never started * bit 7 unused * byte 6 handler behaviour and introspection * bits 0-1 response constructor * bit 2 MHD_get_connection_info() for the TLS members * bit 3 MHD_get_daemon_info() * bit 4 MHD_set_connection_option() * bit 5 answer 403 instead of 200 * bit 6 add a response header * bit 7 MHD_quiesce_daemon() before stopping * byte 7 bits 0-2 handshake round budget (client mode 2) * bit 3 pass the HTTPS options to a daemon started *without* * MHD_USE_TLS * bit 4 MHD_ALLOW_UPGRADE * bits 5-7 extra pump rounds * byte 8 how many bytes of the segment stream are spliced into the * fuzzer-built PEM blobs (see cred_tbl entries 12 and 13) * byte 9 bits 0-2 the server name the client presents, as an index * into a small built-in table; an op 1 segment overrides it. * In the TLS-PSK scenario that same string is also the PSK * identity the client sends, so an op 1 segment gives byte * level control over the @a username that reaches * psk_gnutls_adapter() * bits 3-5 behaviour of the PSK credentials callback * bit 6 the client offers PSK credentials * bit 7 run the TLS-PSK scenario (see below) * byte 10. a sequence of segments, each introduced by a little-endian * 16 bit header (op << 14) | length * op 0 send the payload * op 1 the payload is the server name the *next* client * connection presents; nothing is sent * op 2 send the payload and pump the daemon extra rounds * op 3 close the connection, open a fresh one (which means * a fresh handshake), then send * * All ten configuration bytes are mandatory; a shorter input is * rejected. * * The segment encoding is byte-for-byte the one fuzz_request uses, and * `corpus/` is shared by every harness in this directory (see README * section 3), so the seeds below deliberately contain **no op 1 * segment**: fuzz_request reads op 1 as the declared decoded request * body of its own body oracle, and would report a spurious finding when * it replays a fuzz_tls seed. That is what byte 9 is for. Inputs the * generator or a mutator produces may use op 1 freely -- they never end * up in `corpus/`. * * TLS-PSK. Reaching psk_gnutls_adapter() needs four unrelated things to * be true at the same time: the daemon's credential type has to be * #GNUTLS_CRD_PSK, both ends need a priority string that actually has a * PSK key exchange in it ("NORMAL" does not), the daemon needs * #MHD_OPTION_GNUTLS_PSK_CRED_HANDLER, and the client has to offer a PSK * identity. Spread over four independent input bits that combination * comes up once in a few hundred thousand inputs, and an 8 hour campaign * duly left the function at zero coverage. Bit 7 of byte 9 therefore * switches the whole scenario on at once and the remaining PSK bits only * choose between its variants. * * The variants are the branches of psk_gnutls_adapter() itself: the * callback is missing, fails, or answers 0 with a key of a workable * size, of 4 KiB, of zero size, of one byte less than the * @c MHD_PSK_MIN_SIZE the adapter enforces, and of a size that exceeds * @c UINT_MAX. The two undersized ones and #PSK_OK bracket that * minimum from both sides -- #PSK_OK is exactly @c MHD_PSK_MIN_SIZE * bytes -- which is what makes an off-by-one in the check visible. * * One behaviour is deliberately *not* offered: answering 0 without * writing the two output parameters. MHD would then read uninitialised * memory, but the application has broken the documented contract, so a * report from that would be a harness bug rather than an MHD bug. * * The certificates and keys are the ones from * `src/testcurl/https/tls_test_keys.h` (the CA certificate, the * CA-signed server certificate with its key, and the self-signed server * certificate with its key), reproduced verbatim so that this harness * stays a single translation unit. The DH parameters are RFC 3526 * group 14, as emitted by `certtool --get-dh-params --sec-param medium`. * * The whole harness is guarded by #HTTPS_SUPPORT: `contrib/oss-fuzz/ * build.sh` configures `--disable-https` (that is what makes the * MemorySanitizer build possible), and in such a build this file must * still compile to a valid, trivially passing fuzz target. */ #define FUZZ_HARNESS_NAME "fuzz_tls" #include "fuzz_common.h" /* Pulls in MHD_config.h, which is where HTTPS_SUPPORT is defined. It must come before : it also settles FD_SETSIZE. */ #include "mhd_options.h" #ifdef HTTPS_SUPPORT #include #include #include #include #include #include #include /** * LeakSanitizer suppressions, compiled into the harness so that they * cannot be forgotten on the command line. * * There is exactly one entry and it is *not* about MHD. GnuTLS 3.8.9 * leaks the partially parsed certificate when a PEM certificate blob * ends before its "-----END CERTIFICATE-----" line: * * gnutls_certificate_allocate_credentials (&cred); * gnutls_certificate_set_x509_key_mem (cred, &truncated_cert, * &good_key, * GNUTLS_X509_FMT_PEM); * -> GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR (-207) * gnutls_certificate_free_credentials (cred); * * leaks 9672 bytes in 57 allocations with no libmicrohttpd in the * picture at all (reproduced with a 40 line program). MHD passes the * blob straight through and frees the credentials on every path, so * there is nothing for MHD to fix and nothing for this harness to find; * GnuTLS is fuzzed separately by its own OSS-Fuzz project. * * The suppression matches only allocations made *inside* GnuTLS's * certificate parser. A credential object leaked by MHD itself is a * direct leak from gnutls_certificate_allocate_credentials() and is * still reported, as is every other MHD allocation. */ const char * __lsan_default_suppressions (void); const char * __lsan_default_suppressions (void) { return "leak:gnutls_x509_crt_init\n"; } #define MAX_SEGMENTS 48 #define MAX_CONNECTIONS 3 #define RESP_BUF_SIZE 16384 #define GEN_BUF_SIZE 4096 #define MAX_SNI_LEN 255 #define FUZZ_PEM_BODY_MAX 1024 /** Number of client priority strings offered to the input. */ #define CLIENT_PRIO_COUNT 4 /** * Upper bound on the number of client/server round trips spent on one * handshake. A TLS 1.3 handshake over a socketpair needs a handful; the * cap only has to guarantee termination. */ #define HANDSHAKE_ROUNDS 64 /* ------------------------------------------------------------------ */ /* Test credentials */ /* ------------------------------------------------------------------ */ /* * Taken verbatim from src/testcurl/https/tls_test_keys.h (the CA * certificate, the CA-signed server certificate and its key, and the * self-signed server certificate and its key), so that this harness * stays a single translation unit. dh_params_pem is RFC 3526 group 14, * as emitted by "certtool --get-dh-params --sec-param medium". */ static const char ca_cert_pem[] = "-----BEGIN CERTIFICATE-----\n" "MIIGITCCBAmgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n" "DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n" "LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n" "ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMTA0MDcxNzM2MThaGA8yMTIxMDMxNDE3\n" "MzYxOFowgYExCzAJBgNVBAYTAlJVMQ8wDQYDVQQIDAZNb3Njb3cxDzANBgNVBAcM\n" "Bk1vc2NvdzEbMBkGA1UECgwSdGVzdC1saWJtaWNyb2h0dHBkMSEwHwYJKoZIhvcN\n" "AQkBFhJub2JvZHlAZXhhbXBsZS5vcmcxEDAOBgNVBAMMB3Rlc3QtQ0EwggIiMA0G\n" "CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDdaWupA4qZjCBNkJoJOm5xnCaizl36\n" "ZLUwp4xBL/YfXPWE3LkmAREiVI/YnAb8l6G7CJnz8dTsOJWkNXG6T1KVP5/2RvBI\n" "IaaaufRIAl7hEnj1j9E2hQlV2fxF2ZNhz+nqi0LqKV4LJSpclkXADf2FA9HsVRP/\n" "B7zYh+DP0fSU8V6bsu8XCeRGshroAPrc8rH8lFEEXpNLNIqQr8yKx6SmdB6hfja6\n" "6SQ0++qBhl0aJtn4LHWZohgjBmkIaGFPYIJLgxQ/xyp2Grz2q7lGKJ+zBkBF8iOP\n" "t3x+F1hSCBnr/DGYWmjEm5tYm+7pyuriPddXdCc8+qa2LxMZo3EXxLo5YISpPCyw\n" "Z7V3YAOZTr3m1C24LiYvPehCq1CTIkhhmqtlVJXU7ISD48cx9y+5Pi34wtbTI/gN\n" "x4voyTLAfyavKMmIpxxIRsWldiF2n06HdvCRVdihDQUad10ygTmWf1J/s2ZETAtH\n" "QaSd7MD389t6nQFtTIXigsNKnnDPlrtxt7rOLvLQeR0K04Gzrf/scheOanRAfOXH\n" "KNBFU7YkDFG8rqizlC65rx9qeXFYXQcHZTuqxK7tgZnSgJat3E70VbTSCsEEG7eR\n" "bNX/fChUKAIIpWaiW6HDlKLl6m2y+BzM91umBsKOqTvntMVFBSF9pVYlXK854aIR\n" "q8A2Xujd012seQIDAQABo4GfMIGcMAsGA1UdDwQEAwICpDASBgNVHRMBAf8ECDAG\n" "AQH/AgEBMB0GA1UdDgQWBBRYdUPApWoxw4U13Rqsjf9AHdbpLDATBgNVHSUEDDAK\n" "BggrBgEFBQcDATAkBglghkgBhvhCAQ0EFxYVVGVzdCBsaWJtaWNyb2h0dHBkIENB\n" "MB8GA1UdIwQYMBaAFFh1Q8ClajHDhTXdGqyN/0Ad1uksMA0GCSqGSIb3DQEBCwUA\n" "A4ICAQBvrrcTKVeI1EYnXo4BQD4oCvf9z1fYQmL21EbHwgjg1nmaPkvStgWAc5p1\n" "kKwySrpEMKXfu68X76RccXZyWWIamEjz2OCWYZgjX6d6FpjhLphL8WxXDy5C9eay\n" "ixN7+URz2XQoi22wqR+tCPDhrIzcMPyMkx/6gRgcYeDnaFrkdSeSsKsID4plfcIj\n" "ISWJDvv+IAgrtsG1NVHnGwpAv0od3A8/4/fR6PPyewaU3aydvjZ7Au8O9DGDjlU9\n" "9HdlOkkY6GVJ1pfGZib7cV7lhy0D2kj1g9xZh97YjpoUfppPl9r+6A8gDm0hXlAD\n" "TlzNYlwTb681ZEoSd9PiLEY8HETssHlays2dYXdcNwAEp69iIHz8q1Q98Be9LScl\n" "WEzgaOT9U7lpIw/MWbELoMsC+Ecs1cVWBIuiIq8aSG2kRr1x3S8yVXbAohAXif2s\n" "E6puieM/VJ25iaNhkbLmDkk58QVVmn9NZNv6ETxuSQMp9e0EwbVlj68vzClQ91Y/\n" "nmAiGcLFUEwB9G0szv9+vR+oDW4IkvdFZSUbcICd2cnynnwAD395onqS4hEZO1xM\n" "Gy5ZldbTMTjgn7fChNopz15ChPBnwFIjhm+S0CyiLRQAowfknRVq2IBkj7/5kOWg\n" "4mcxcq76HoQWK/8X/8RFL1eFVAvY7TNHYJ0RS51DMuwCNQictA==\n" "-----END CERTIFICATE-----\n"; static const char srv_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n" "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n" "rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n" "UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n" "+sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n" "HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n" "CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n" "dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n" "+SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n" "XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n" "znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n" "pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n" "D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n" "Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n" "pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n" "zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n" "pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n" "KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n" "W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n" "OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n" "XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n" "wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n" "ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n" "0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n" "ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n" "QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n" "qdJNJ1DkyUc9dN2cliX4R+rG\n" "-----END PRIVATE KEY-----\n"; static const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n" "MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n" "DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n" "LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n" "ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n" "NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n" "TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n" "c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n" "psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n" "atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n" "7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n" "n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n" "qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n" "kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n" "AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n" "c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n" "8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n" "IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n" "Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n" "X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n" "aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n" "HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n" "hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n" "18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n" "UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n" "B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n" "SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n" "WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n" "OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n" "/w0gW9EVWzFhsFeGEssi\n" "-----END CERTIFICATE-----\n"; static const char srv_self_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n" "MIIDJzCCAg+gAwIBAgIUOKf6e6Heee2XA+yF5St3t+fVM40wDQYJKoZIhvcNAQEF\n" "BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTIyMTAxMDA4MzQ0N1oYDzIxMjIw\n" "OTE2MDgzNDQ3WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB\n" "AQUAA4IBDwAwggEKAoIBAQClivgF8Xq0ekQli++0l7Q5JFwJCuLf04Cb1UKIS80U\n" "CfphFd1ILJepNw4bWR3OV1sRI1vFiw6LnCz53vOwVNyiZ+sMGi4bDX4AV9Xd+F83\n" "xhG8AjOmKTayW0TxSIvt47Qd5S/4fgraxMtvqrRRBen30iKOwX7uNF/4dYb9vdin\n" "OldV/e8uzbqSurMGkNDznOeSaNBmdO/7x0VMFZM2hwmHyiiw75/j4BhUlLCcMEvK\n" "oN+YHNCNcTt3Qm1vVuiGXmh9QreOV09Gc1SzAltxF2gmI0jzw8r/duz18QXMNsMw\n" "El/Ah4+02gR70L7qlgttN1NPU3RJpK/L34J7yg649wHTAgMBAAGjbzBtMB0GA1Ud\n" "DgQWBBROVferD+YYcV1YEnFgC0jYm5X9BjAfBgNVHSMEGDAWgBROVferD+YYcV1Y\n" "EnFgC0jYm5X9BjAPBgNVHRMBAf8EBTADAQH/MBoGA1UdEQQTMBGCCWxvY2FsaG9z\n" "dIcEfwAAATANBgkqhkiG9w0BAQUFAAOCAQEAoRbozsm5xXdNX3VO++s2LMzw5KM9\n" "RpIInHNkMJbnyLJFKJ8DF7nTxSGCA38YMkX3tphPNKZXbg+V64Dqr/XpzOVyiinU\n" "7hIwyUdSSKKyErZxIWR97lY6Q3SOyPAg8ZElbtvSsSzmd772VE23VTXGDi7AW0PQ\n" "hag9N2EEnHURMvID15O+UXyFpDdyUyQIbx3HuswsGDH9xBTm4irLyrZwO0KwKg5a\n" "JBeUiPs0SYRRfn9/MoE6VwAnmOCg3LLR6ZPU3hQtTPLHj2Op1g5fey3X3X6lC+JC\n" "K6dNZc1zBFPz8KANGUsFYbmoP2bvAAA+6KwCnZZEflUgE7/HFEmQhVOezw==\n" "-----END CERTIFICATE-----\n"; static const char srv_self_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n" "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQClivgF8Xq0ekQl\n" "i++0l7Q5JFwJCuLf04Cb1UKIS80UCfphFd1ILJepNw4bWR3OV1sRI1vFiw6LnCz5\n" "3vOwVNyiZ+sMGi4bDX4AV9Xd+F83xhG8AjOmKTayW0TxSIvt47Qd5S/4fgraxMtv\n" "qrRRBen30iKOwX7uNF/4dYb9vdinOldV/e8uzbqSurMGkNDznOeSaNBmdO/7x0VM\n" "FZM2hwmHyiiw75/j4BhUlLCcMEvKoN+YHNCNcTt3Qm1vVuiGXmh9QreOV09Gc1Sz\n" "AltxF2gmI0jzw8r/duz18QXMNsMwEl/Ah4+02gR70L7qlgttN1NPU3RJpK/L34J7\n" "yg649wHTAgMBAAECggEAERbbCtYGakoy7cNX8Ac3Kiz4OVC/4gZWAQBPeX2FwrtS\n" "9yHIMbK0x1mxIZ6eBpabBpZlW2vDCSOKuxLKiloAWt2qdJnhR5apesSWhe8leT7/\n" "xq5dgZpAlMH6SIRKObknd2yY+qicW0A0licDrVeUcypkueL8xP9wJtiPInOuQXkI\n" "QROhB13eStRuRKYwOn5gtwAHJ+J1DFKKiqpBOkrSYf4625StGegJO9+bjK0ei+0W\n" "tp6unpiwA/lXTgz6Xim1Z3fzWs4XjFgVKzK5s/6yBJjr8spHX6lv7QsahP4w6HZ/\n" "VcRxP6cJNd/otiTEtJXpbxiiyccwXm/AOcOn22P1cQKBgQDAnY/0G/ap/G98pneE\n" "suzNXhWOQ8JoL8d66Io8vwTvfiJggfgUcwblI7pPCrSlaZMR7/q6JImE53lZtPk8\n" "eI3c9lN0ocr8E7+huDpYdk7cMYj9SuxySsXoMLiMqzHFi+NcIhKMF56kk6a5CFCt\n" "yP1Ofy76LVweGE3XvTwpwE7wUQKBgQDcBLyH1cC71s0I0Gz28AyELV9hPhasjAKO\n" "12CVbeBVTPd+28uk/3o80wSrTksc6H5ehAA2aTvrb4OhwssWNL+D0fS8YK2cJ3V0\n" "FJxGAM266+vC4d/8jRTHJnc+6PP3ix5t6vAt+K2Y0fePtefLqf4ebgXx/ODAj3J2\n" "aZKBldjK4wKBgGIRFpTLk/eR/dUyEBHw4x3gdAsdtqJDCUYrlQ4+ly20Q55tLbiD\n" "pBQP77CEm9rH+MgeLcKODbIsBB3HRUojet7wTydHpMhY6a1V1ebqPVZgpgWIGwBJ\n" "z59bBusf0lRo15Y2Bslq0SurvSvh7um8NjO8D1fytj7gUumvgC0lq0sxAoGBAI1+\n" "kkx9IBTtIDER8XGhkTsT/uoHxwcyh5abVmbjIclZ1TUFX2L+Vft17ePJVy8BKfvY\n" "wlY7uShBMBNAteDTDXNV/CGFv0DUc4myk4nFjIkwng9XufeuN3WX/Eo+AF/rXSdt\n" "VwcJjYLhTWdjoe1tppqlQTeN3HCaEA+s92ZVGvXnAoGAMCXGS6WZl1e5wsHRq0Yy\n" "8Ef2Wrk620bBjKHolkTfvgfhlvxeZM1sv1ioZGsOeQ0z7O7wdJhvL0M/WAG+3yQj\n" "HSXp81T1vOICPwNYZf8xcvbLKmvj7rHFt6ZAZF2o4EK8ReZTRyA3DUpBCDY+s3FN\n" "GmBv0D7N3QP0CT3SzfQrPkc=\n" "-----END PRIVATE KEY-----\n"; static const char dh_params_pem[] = "-----BEGIN DH PARAMETERS-----\n" "MIIBDAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz\n" "+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a\n" "87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7\n" "YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi\n" "7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD\n" "ssbzSibBsu/6iGtCOGEoXJf//////////wIBAgICAQA=\n" "-----END DH PARAMETERS-----\n"; /** A PEM blob whose armour is fine but whose payload is not base64. */ static const char garbage_cert_pem[] = "-----BEGIN CERTIFICATE-----\n" "this is not base64 at all, not even close !!!! ????\n" "-----END CERTIFICATE-----\n"; static const char garbage_key_pem[] = "-----BEGIN PRIVATE KEY-----\n" "@@@@ neither is this @@@@\n" "-----END PRIVATE KEY-----\n"; /** Correct base64, but the armour never ends. */ static const char truncated_cert_pem[] = "-----BEGIN CERTIFICATE-----\n" "MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n" "DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n"; static const char truncated_key_pem[] = "-----BEGIN PRIVATE KEY-----\n" "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n"; /** Base64 of a certificate, but with no PEM armour at all. */ static const char no_armour_pem[] = "MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n" "DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n"; static const char garbage_dh_pem[] = "-----BEGIN DH PARAMETERS-----\n" "not-dh-parameters\n" "-----END DH PARAMETERS-----\n"; /** * PEM blobs assembled from the fuzzer's own bytes, see cred_tbl entries * 12 and 13. Static so that the pointer handed to MHD stays valid for * the whole lifetime of the daemon. */ static char fuzz_cert_pem[FUZZ_PEM_BODY_MAX + 128]; static char fuzz_key_pem[FUZZ_PEM_BODY_MAX + 128]; /** * A certificate/key pair for #MHD_OPTION_HTTPS_MEM_CERT and * #MHD_OPTION_HTTPS_MEM_KEY. A NULL member means "do not pass the * option at all", which is a configuration MHD has to reject cleanly. */ struct cred_pair { const char *cert; const char *key; }; static const struct cred_pair cred_tbl[] = { { srv_signed_cert_pem, srv_signed_key_pem }, /* 0 valid, CA signed */ { srv_self_signed_cert_pem, srv_self_signed_key_pem }, /* 1 valid, self signed */ { srv_signed_cert_pem, srv_self_signed_key_pem }, /* 2 key does not match */ { srv_self_signed_cert_pem, srv_signed_key_pem }, /* 3 key does not match */ { srv_signed_cert_pem, NULL }, /* 4 certificate only */ { NULL, srv_signed_key_pem }, /* 5 key only */ { NULL, NULL }, /* 6 neither */ { "", "" }, /* 7 empty strings */ { truncated_cert_pem, srv_signed_key_pem }, /* 8 truncated armour */ { srv_signed_cert_pem, truncated_key_pem }, /* 9 truncated armour */ { garbage_cert_pem, garbage_key_pem }, /* 10 armour, no base64 */ { no_armour_pem, srv_signed_key_pem }, /* 11 base64, no armour */ { fuzz_cert_pem, srv_signed_key_pem }, /* 12 PEM from the input */ { srv_signed_cert_pem, fuzz_key_pem }, /* 13 PEM from the input */ { fuzz_cert_pem, fuzz_key_pem }, /* 14 PEM from the input */ { srv_signed_cert_pem, srv_signed_key_pem } /* 15 valid (bias) */ }; #define CRED_COUNT (sizeof (cred_tbl) / sizeof (cred_tbl[0])) /** * Priority strings. The first entries are the ones a real server would * use, the rest are what MHD has to reject without falling over. MHD * hands these to gnutls_priority_init() (or appends them to its own * base string) and fails daemon startup if GnuTLS does not like them. */ static const char *const prio_tbl[] = { "NORMAL", "NORMAL:-VERS-ALL:+VERS-TLS1.3", "NORMAL:-VERS-ALL:+VERS-TLS1.2", "SECURE128", "PERFORMANCE", "@LIBMICROHTTPD", "@SYSTEM", "NONE", "", "BOGUS-PRIORITY-STRING", "NORMAL:!!!", "NORMAL:-VERS-ALL", "NORMAL:+ANON-ECDH", "NORMAL:%SERVER_PRECEDENCE", "SECURE256:-CIPHER-ALL", ":::::" }; #define PRIO_COUNT (sizeof (prio_tbl) / sizeof (prio_tbl[0])) /** Priority strings offered to the *client* side. */ static const char *const client_prio_tbl[CLIENT_PRIO_COUNT] = { "NORMAL", "NORMAL:-VERS-ALL:+VERS-TLS1.3", "NORMAL:-VERS-ALL:+VERS-TLS1.2", "PERFORMANCE" }; /** * Priority strings for the TLS-PSK scenario, used on both ends. * "NORMAL" carries no PSK key exchange, so without one of these the * ciphersuite is never negotiated, GnuTLS never asks the server for a * key, and psk_gnutls_adapter() is never called. Index is the client * priority selector (byte 4, bits 4-5), which the ordinary tables no * longer use once the scenario is on. * * The TLS 1.2 entry has to remove the other key exchanges explicitly. * A daemon with #GNUTLS_CRD_PSK has no certificate credentials, so with * the certificate key exchanges still in the list the TLS 1.2 handshake * dies with "received handshake message out of context" before GnuTLS * ever asks for a key. Under TLS 1.3 the same list is fine, which is * what entries 0 and 2 cover. */ static const char *const psk_prio_tbl[CLIENT_PRIO_COUNT] = { "NORMAL:+ECDHE-PSK:+DHE-PSK:+PSK", "NORMAL:-VERS-ALL:+VERS-TLS1.2:-KX-ALL:+ECDHE-PSK:+DHE-PSK:+PSK", "NORMAL:-VERS-ALL:+VERS-TLS1.3:+ECDHE-PSK:+DHE-PSK:+PSK", "NORMAL:-KX-ALL:+ECDHE-PSK:+DHE-PSK:+PSK" }; /** * Credential types. Only GNUTLS_CRD_CERTIFICATE and GNUTLS_CRD_PSK are * accepted by MHD_TLS_init(); everything else must make daemon startup * fail rather than reach the MHD_PANIC() in new_connection_prepare_(). */ static const int cred_type_tbl[] = { (int) GNUTLS_CRD_CERTIFICATE, (int) GNUTLS_CRD_PSK, (int) GNUTLS_CRD_ANON, (int) GNUTLS_CRD_SRP, (int) GNUTLS_CRD_IA, (int) GNUTLS_CRD_CERTIFICATE, 99, -1 }; #define CRED_TYPE_COUNT (sizeof (cred_type_tbl) / sizeof (cred_type_tbl[0])) /** Index of #GNUTLS_CRD_PSK in #cred_type_tbl. */ #define PSK_CRED_TYPE_IDX 1u /** * The pre-shared key the client uses, and the one #PSK_OK hands back. * They match, so that variant completes the handshake and MHD goes on to * serve ordinary HTTP over a session with no certificate at all -- which * is a different shape again for the connection introspection calls. * * Its length is exactly the @c MHD_PSK_MIN_SIZE that psk_gnutls_adapter() * enforces (16, RFC 4279 section 7.1). That is not a coincidence and * the two have to be kept in step: #PSK_OK and #PSK_ONE_SHORT bracket * the check from both sides, and #PSK_ONE_SHORT derives its length from * this array. The minimum is private to daemon.c, so this is a mirror * rather than a shared constant; if daemon.c changes, so must this. */ static const unsigned char psk_key_bytes[16] = { 0x9e, 0x1d, 0x4c, 0x7b, 0x30, 0xa5, 0xf2, 0x68, 0x11, 0xc3, 0x54, 0xd9, 0x87, 0x2a, 0x6f, 0xb0 }; static const size_t mem_limit_tbl[] = { 0 /* MHD default */, 256, 512, 1024, 1400, 1500, 2048, 4096, 8192, 32768, 0, 1024, 2048, 4096, 16384, 0 }; #define MEM_LIMIT_COUNT (sizeof (mem_limit_tbl) / sizeof (mem_limit_tbl[0])) static const char https_key_password[] = "not-the-password"; /* ------------------------------------------------------------------ */ /* Per-iteration configuration */ /* ------------------------------------------------------------------ */ /** Behaviour of the SNI callback, selected by bits 3-5 of byte 3. */ enum sni_behaviour { SNI_ALWAYS_OK = 0, /**< always answer with the signed pair */ SNI_FAIL, /**< always answer -1 */ SNI_EMPTY, /**< answer 0 with an empty certificate list */ SNI_BY_NAME, /**< look the server name up, -1 if unknown */ SNI_MISMATCH, /**< answer with a key that is not the cert's */ SNI_NO_KEY, /**< answer 0, certificate but no key */ SNI_SELF_SIGNED, /**< always answer with the self-signed pair */ SNI_BEHAVIOUR_COUNT }; /** * Behaviour of the PSK credentials callback, selected by bits 3-5 of * byte 9. Each entry corresponds to one branch of psk_gnutls_adapter(). */ enum psk_behaviour { PSK_OK = 0, /**< the key the client expects; handshake works */ PSK_FAIL, /**< the callback answers -1 */ PSK_EMPTY, /**< a zero length key: rejected as too short */ PSK_LONG, /**< a 4 KiB key */ PSK_FROM_ID, /**< key built from the identity the client sent, so its length is attacker-chosen and lands on either side of MHD_PSK_MIN_SIZE */ PSK_HUGE, /**< a size above UINT_MAX */ PSK_NO_HANDLER, /**< the option is not passed at all */ /* Appended rather than grouped with PSK_EMPTY on purpose: the seeds below encode the behaviour as a literal index, so inserting in the middle would silently re-point every one of them. */ PSK_ONE_SHORT, /**< MHD_PSK_MIN_SIZE - 1 bytes: the boundary */ PSK_BEHAVIOUR_COUNT }; /** Client behaviour, selected by bits 0-1 of byte 4. */ enum client_mode { CLIENT_RAW = 0, /**< raw bytes straight at the TLS socket */ CLIENT_TLS, /**< a real GnuTLS client */ CLIENT_TLS_ABANDON, /**< a real client that stops mid-handshake */ CLIENT_RECORDS /**< raw bytes shaped like TLS records */ }; struct fuzz_cfg { /* ---- daemon ---- */ const char *cert; const char *key; int use_tls; /**< set MHD_USE_TLS at all */ int use_trust; int trust_garbage; int use_dhparams; int dh_garbage; int use_sni; int use_prio; int prio_append; unsigned int prio_idx; const char *prio_str; /**< what use_prio actually passes */ int use_cred_type; unsigned int cred_type_idx; int no_alpn; int key_password; int allow_upgrade; size_t mem_limit; unsigned int loop_mode; /* ---- SNI callback ---- */ enum sni_behaviour sni_mode; /* ---- TLS-PSK ---- */ int psk_scenario; /**< the whole PSK bundle is on */ enum psk_behaviour psk_mode; /* ---- client ---- */ enum client_mode mode; int client_sni; int client_cert; int client_psk; /**< offer PSK credentials */ unsigned int client_prio_idx; int client_bye; int client_shut_wr; unsigned int hs_budget; /**< handshake rounds in CLIENT_TLS_ABANDON */ unsigned int extra_pump; /* ---- handler ---- */ unsigned int resp_kind; int conn_info; int daemon_info; int conn_option; int error_reply; int resp_header; int quiesce; int stop_with_queued; /**< stop with a connection still queued */ }; static struct fuzz_cfg cfg; /** * Server names the client can present. Which one is used comes from * byte 9 of the input; an op 1 segment overrides it. MHD itself never * looks at the name -- GnuTLS parses the extension and the application * callback reads it back -- so a fixed table costs no MHD coverage. */ static const char *const sni_name_tbl[] = { "test-mhdserver", "localhost", "mhdhost1", "nobody.example.org", "", "example.org", "TEST-MHDSERVER", "a.very.long.name.that.nobody.has.a.certificate.for.example.org" }; #define SNI_NAME_COUNT (sizeof (sni_name_tbl) / sizeof (sni_name_tbl[0])) /** Server name the next client connection presents. */ static char sni_name[MAX_SNI_LEN + 1]; static size_t sni_name_len; /** Bytes received from the daemon during the current iteration. */ static char resp_buf[RESP_BUF_SIZE]; static size_t resp_len; /** Statistics, printed at exit with --verbose. */ static unsigned long stat_daemons; static unsigned long stat_daemons_failed; static unsigned long stat_connections; static unsigned long stat_handshakes_ok; static unsigned long stat_handshakes_failed; static unsigned long stat_handler_calls; static unsigned long stat_sni_calls; static unsigned long stat_psk_calls; static int stats_registered; static void print_stats (void) { if (! fuzz_verbose) return; fprintf (stderr, "%s: daemons=%lu (start failed=%lu) connections=%lu " "handshakes ok=%lu failed=%lu handler calls=%lu SNI calls=%lu " "PSK calls=%lu\n", FUZZ_HARNESS_NAME, stat_daemons, stat_daemons_failed, stat_connections, stat_handshakes_ok, stat_handshakes_failed, stat_handler_calls, stat_sni_calls, stat_psk_calls); } /* ------------------------------------------------------------------ */ /* The SNI (certificate retrieve) callback */ /* ------------------------------------------------------------------ */ /** * Certificates for the SNI callback, parsed once and then kept in these * statics for the whole life of the process: they are configuration, not * per-iteration state, and re-parsing them on every execution would cost * more than everything else the harness does. They are reachable from * globals, so LeakSanitizer does not count them. */ struct sni_host { const char *name; const char *cert_pem; const char *key_pem; gnutls_pcert_st pcrt; gnutls_privkey_t key; int loaded; }; static struct sni_host sni_hosts[2] = { { "test-mhdserver", NULL, NULL, { 0, { NULL, 0 }, 0 }, NULL, 0 }, { "localhost", NULL, NULL, { 0, { NULL, 0 }, 0 }, NULL, 0 } }; static int sni_hosts_ready; /** * @return 0 if the certificates are usable */ static int sni_hosts_init (void) { unsigned int i; if (0 != sni_hosts_ready) return (1 == sni_hosts_ready) ? 0 : -1; sni_hosts[0].cert_pem = srv_signed_cert_pem; sni_hosts[0].key_pem = srv_signed_key_pem; sni_hosts[1].cert_pem = srv_self_signed_cert_pem; sni_hosts[1].key_pem = srv_self_signed_key_pem; sni_hosts_ready = 1; for (i = 0; i < sizeof (sni_hosts) / sizeof (sni_hosts[0]); i++) { struct sni_host *h = &sni_hosts[i]; gnutls_datum_t d; d.data = (unsigned char *) (intptr_t) h->cert_pem; d.size = (unsigned int) strlen (h->cert_pem); if (GNUTLS_E_SUCCESS != gnutls_pcert_import_x509_raw (&h->pcrt, &d, GNUTLS_X509_FMT_PEM, 0)) { sni_hosts_ready = -1; continue; } if (GNUTLS_E_SUCCESS != gnutls_privkey_init (&h->key)) { gnutls_pcert_deinit (&h->pcrt); sni_hosts_ready = -1; continue; } d.data = (unsigned char *) (intptr_t) h->key_pem; d.size = (unsigned int) strlen (h->key_pem); if (GNUTLS_E_SUCCESS != gnutls_privkey_import_x509_raw (h->key, &d, GNUTLS_X509_FMT_PEM, NULL, 0)) { gnutls_privkey_deinit (h->key); h->key = NULL; gnutls_pcert_deinit (&h->pcrt); sni_hosts_ready = -1; continue; } h->loaded = 1; } return (1 == sni_hosts_ready) ? 0 : -1; } /** * #MHD_OPTION_HTTPS_CERT_CALLBACK. Deliberately badly behaved for most * of the settings of @e cfg.sni_mode: an application callback that fails * or answers with nothing is exactly the case MHD has to survive. */ static int sni_callback (gnutls_session_t session, const gnutls_datum_t *req_ca_dn, int nreqs, const gnutls_pk_algorithm_t *pk_algos, int pk_algos_length, gnutls_pcert_st **pcert, unsigned int *pcert_length, gnutls_privkey_t *pkey) { char name[MAX_SNI_LEN + 1]; size_t name_len = sizeof (name); unsigned int type; unsigned int i; (void) req_ca_dn; (void) nreqs; (void) pk_algos; (void) pk_algos_length; stat_sni_calls++; if (! sni_hosts[0].loaded) return -1; switch (cfg.sni_mode) { case SNI_FAIL: return -1; case SNI_EMPTY: *pcert = NULL; *pcert_length = 0; *pkey = NULL; return 0; case SNI_NO_KEY: *pcert = &sni_hosts[0].pcrt; *pcert_length = 1; *pkey = NULL; return 0; case SNI_MISMATCH: if (! sni_hosts[1].loaded) return -1; *pcert = &sni_hosts[0].pcrt; *pcert_length = 1; *pkey = sni_hosts[1].key; return 0; case SNI_SELF_SIGNED: if (! sni_hosts[1].loaded) return -1; *pcert = &sni_hosts[1].pcrt; *pcert_length = 1; *pkey = sni_hosts[1].key; return 0; case SNI_BY_NAME: if (GNUTLS_E_SUCCESS != gnutls_server_name_get (session, name, &name_len, &type, 0)) return -1; for (i = 0; i < sizeof (sni_hosts) / sizeof (sni_hosts[0]); i++) if ( (sni_hosts[i].loaded) && (0 == strncmp (name, sni_hosts[i].name, name_len)) ) { *pcert = &sni_hosts[i].pcrt; *pcert_length = 1; *pkey = sni_hosts[i].key; return 0; } return -1; case SNI_ALWAYS_OK: case SNI_BEHAVIOUR_COUNT: default: break; } *pcert = &sni_hosts[0].pcrt; *pcert_length = 1; *pkey = sni_hosts[0].key; return 0; } /* ------------------------------------------------------------------ */ /* The application */ /* ------------------------------------------------------------------ */ static const char resp_body[] = "hello world over TLS"; static enum MHD_Result ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *r; enum MHD_Result ret; (void) cls; (void) url; (void) method; (void) version; (void) upload_data; stat_handler_calls++; if (NULL == *req_cls) { /* first call: MHD only wants to know that we are interested */ *req_cls = ▮ return MHD_YES; } if (0 != *upload_data_size) { /* discard the request body */ *upload_data_size = 0; return MHD_YES; } if (cfg.conn_info) { /* The TLS-specific members of MHD_ConnectionInfo; all three answer NULL on a connection without a session, which is a state this harness can produce. */ (void) MHD_get_connection_info (connection, MHD_CONNECTION_INFO_CIPHER_ALGO); (void) MHD_get_connection_info (connection, MHD_CONNECTION_INFO_PROTOCOL); (void) MHD_get_connection_info (connection, MHD_CONNECTION_INFO_GNUTLS_SESSION); (void) MHD_get_connection_info (connection, MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT); (void) MHD_get_connection_info (connection, MHD_CONNECTION_INFO_CLIENT_ADDRESS); (void) MHD_get_connection_info (connection, MHD_CONNECTION_INFO_CONNECTION_FD); } if (cfg.conn_option) (void) MHD_set_connection_option (connection, MHD_CONNECTION_OPTION_TIMEOUT, (unsigned int) 0); switch (cfg.resp_kind) { case 1: r = MHD_create_response_from_buffer_copy (sizeof (resp_body) - 1, resp_body); break; case 2: r = MHD_create_response_empty (MHD_RF_NONE); break; case 3: r = MHD_create_response_from_buffer_static (0, ""); break; case 0: default: r = MHD_create_response_from_buffer_static (sizeof (resp_body) - 1, resp_body); break; } if (NULL == r) return MHD_NO; if (cfg.resp_header) (void) MHD_add_response_header (r, "X-Fuzz", "tls"); ret = MHD_queue_response (connection, cfg.error_reply ? MHD_HTTP_FORBIDDEN : MHD_HTTP_OK, r); MHD_destroy_response (r); return ret; } static void panic_cb (void *cls, const char *file, unsigned int line, const char *reason) { char msg[512]; (void) cls; (void) snprintf (msg, sizeof (msg), "MHD_PANIC() reached at %s:%u: %s", (NULL != file) ? file : "?", line, (NULL != reason) ? reason : "?"); fuzz_report_finding (msg); } /* ------------------------------------------------------------------ */ /* Driving the daemon */ /* ------------------------------------------------------------------ */ /** * Advance the daemon by one cycle, through the event-loop API selected * by byte 5 of the input. The select() timeout is always zero: the * harness is single threaded, whatever the daemon is waiting for has * already been written into the socketpair, and blocking would only burn * wall clock. */ static void run_once (struct MHD_Daemon *d) { fd_set rs; fd_set ws; fd_set es; MHD_socket max_fd = MHD_INVALID_SOCKET; struct timeval tv; if (0 == cfg.loop_mode) { (void) MHD_run (d); return; } FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (1 == cfg.loop_mode) { /* Parenthesised so that the real v1 function is called: microhttpd.h also defines MHD_get_fdset as a macro forwarding to MHD_get_fdset2. Same trick for MHD_run_from_select below. */ if (MHD_YES != (MHD_get_fdset) (d, &rs, &ws, &es, &max_fd)) { (void) MHD_run (d); return; } } else { if (MHD_YES != MHD_get_fdset2 (d, &rs, &ws, &es, &max_fd, (unsigned int) FD_SETSIZE)) { (void) MHD_run (d); return; } } tv.tv_sec = 0; tv.tv_usec = 0; if (MHD_INVALID_SOCKET != max_fd) (void) select ((int) max_fd + 1, &rs, &ws, &es, &tv); if (1 == cfg.loop_mode) (void) (MHD_run_from_select) (d, &rs, &ws, &es); else (void) MHD_run_from_select2 (d, &rs, &ws, &es, (unsigned int) FD_SETSIZE); } /* ------------------------------------------------------------------ */ /* The PSK credentials callback */ /* ------------------------------------------------------------------ */ #if GNUTLS_VERSION_MAJOR >= 3 /** * #MHD_OPTION_GNUTLS_PSK_CRED_HANDLER. GnuTLS calls * psk_gnutls_adapter() with the identity the client sent, and that * function calls this; whatever comes back is copied into a * gnutls_malloc()ed buffer and handed to GnuTLS, with @a psk freed by * MHD on every path. The buffer therefore has to come from plain * malloc() -- see the doxygen on #MHD_PskServerCredentialsCallback. * * @param cls unused * @param connection the connection GnuTLS is handshaking * @param username the identity claimed by the client * @param[out] psk the key * @param[out] psk_size its length * @return 0 on success, -1 on error */ static int psk_cred_cb (void *cls, const struct MHD_Connection *connection, const char *username, void **psk, size_t *psk_size) { unsigned char *buf; size_t len; (void) cls; (void) connection; stat_psk_calls++; switch (cfg.psk_mode) { case PSK_FAIL: return -1; case PSK_EMPTY: len = 0; break; case PSK_ONE_SHORT: /* One byte below the minimum the adapter enforces. Deliberately written in terms of sizeof (psk_key_bytes), which is exactly that minimum, so this stays on the boundary if the minimum changes. */ len = sizeof (psk_key_bytes) - 1; break; case PSK_LONG: len = 4096; break; case PSK_FROM_ID: len = (NULL != username) ? strlen (username) : 0; if (len > 1024) len = 1024; break; case PSK_HUGE: #if SIZE_MAX > UINT_MAX /* The size MHD is told about, not the size allocated: the point is the "PSK too long" branch, which rejects before reading @a psk. MHD still free()s the pointer, so it has to be a real one. */ buf = (unsigned char *) malloc (1); if (NULL == buf) return -1; buf[0] = 0; *psk = buf; *psk_size = (size_t) UINT_MAX + 1u; return 0; #else len = sizeof (psk_key_bytes); break; #endif case PSK_OK: case PSK_NO_HANDLER: /* not reached: the option is not passed at all */ case PSK_BEHAVIOUR_COUNT: default: len = sizeof (psk_key_bytes); break; } /* malloc(0) may answer NULL, which would be indistinguishable from failure here; always ask for at least one byte and report the length separately. */ buf = (unsigned char *) malloc (0 != len ? len : 1); if (NULL == buf) return -1; if (0 != len) { size_t i; for (i = 0; i < len; i++) buf[i] = psk_key_bytes[i % sizeof (psk_key_bytes)]; } else buf[0] = 0; *psk = buf; *psk_size = len; return 0; } #endif /* GNUTLS_VERSION_MAJOR >= 3 */ /* ------------------------------------------------------------------ */ /* The in-process TLS client */ /* ------------------------------------------------------------------ */ struct tls_client { gnutls_session_t sess; /**< NULL in the raw modes */ gnutls_certificate_credentials_t cred; gnutls_psk_client_credentials_t psk; /**< only in the PSK scenario */ int fd; /**< our end of the socketpair */ int hs_done; int dead; }; static void pump (struct MHD_Daemon *d, unsigned int rounds) { unsigned int i; for (i = 0; i < rounds; i++) run_once (d); } /** * Read whatever the daemon has produced so far. In the raw modes this * is a plain recv(); with a real client it goes through GnuTLS, which is * what actually drives MHD's send path and its TLS shutdown handling. */ static void tc_drain (struct tls_client *tc) { unsigned int i; char tmp[4096]; if (0 > tc->fd) return; if (NULL == tc->sess) { for (;;) { ssize_t n = recv (tc->fd, tmp, sizeof (tmp), MSG_DONTWAIT); if (0 >= n) break; if (resp_len + (size_t) n < RESP_BUF_SIZE) { memcpy (resp_buf + resp_len, tmp, (size_t) n); resp_len += (size_t) n; } } return; } if (tc->dead || (! tc->hs_done)) return; for (i = 0; i < 8; i++) { ssize_t n = gnutls_record_recv (tc->sess, tmp, sizeof (tmp)); if (0 < n) { if (resp_len + (size_t) n < RESP_BUF_SIZE) { memcpy (resp_buf + resp_len, tmp, (size_t) n); resp_len += (size_t) n; } continue; } if (0 == n) break; /* peer closed the TLS connection */ if ( (GNUTLS_E_AGAIN == n) || (GNUTLS_E_INTERRUPTED == n) ) break; if (0 != gnutls_error_is_fatal ((int) n)) tc->dead = 1; break; } } static void pump_and_drain (struct MHD_Daemon *d, struct tls_client *tc, unsigned int rounds) { unsigned int i; for (i = 0; i < rounds; i++) { run_once (d); tc_drain (tc); } } /** * Let the client and the daemon take turns at the handshake until it * completes, fails, or @a rounds is exhausted. Exhausting @a rounds on * purpose (client mode 2) is what leaves MHD's connection parked in * #MHD_TLS_CONN_HANDSHAKING. */ static void tc_handshake (struct MHD_Daemon *d, struct tls_client *tc, unsigned int rounds) { unsigned int i; if ( (NULL == tc->sess) || (0 != tc->dead) || (0 != tc->hs_done) ) return; for (i = 0; i < rounds; i++) { int ret = gnutls_handshake (tc->sess); if (GNUTLS_E_SUCCESS == ret) { tc->hs_done = 1; stat_handshakes_ok++; return; } if (0 != gnutls_error_is_fatal (ret)) { tc->dead = 1; stat_handshakes_failed++; return; } /* GNUTLS_E_AGAIN / GNUTLS_E_INTERRUPTED / a warning alert: give the daemon a chance to answer. */ run_once (d); } } /** * Open a fresh connection: a socketpair, one end handed to MHD with * MHD_add_connection(), the other end ours. With a real client the * GnuTLS session is set up here too, but the handshake itself is driven * by tc_handshake(). * * @return 0 on success */ static int tc_open (struct MHD_Daemon *d, struct tls_client *tc) { int sv[2]; struct sockaddr_in sa; int fl; #if GNUTLS_VERSION_NUMBER >= 0x030500 gnutls_init_flags_t flags; #else unsigned int flags; #endif memset (tc, 0, sizeof (*tc)); tc->fd = -1; if (0 != socketpair (AF_UNIX, SOCK_STREAM, 0, sv)) return -1; memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (44444); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (MHD_YES != MHD_add_connection (d, (MHD_socket) sv[1], (const struct sockaddr *) &sa, (socklen_t) sizeof (sa))) { /* MHD has already closed sv[1] in that case */ (void) close (sv[0]); return -1; } tc->fd = sv[0]; stat_connections++; /* Our end must never block: the daemon is pumped from this very thread, so a blocking write would deadlock the process. */ fl = fcntl (tc->fd, F_GETFL, 0); if (0 <= fl) (void) fcntl (tc->fd, F_SETFL, fl | O_NONBLOCK); if ( (CLIENT_TLS != cfg.mode) && (CLIENT_TLS_ABANDON != cfg.mode) ) return 0; if (GNUTLS_E_SUCCESS != gnutls_certificate_allocate_credentials (&tc->cred)) { tc->cred = NULL; tc->dead = 1; return 0; } if (cfg.client_cert) { gnutls_datum_t c; gnutls_datum_t k; c.data = (unsigned char *) (intptr_t) srv_self_signed_cert_pem; c.size = (unsigned int) strlen (srv_self_signed_cert_pem); k.data = (unsigned char *) (intptr_t) srv_self_signed_key_pem; k.size = (unsigned int) strlen (srv_self_signed_key_pem); (void) gnutls_certificate_set_x509_key_mem (tc->cred, &c, &k, GNUTLS_X509_FMT_PEM); } flags = GNUTLS_CLIENT; #if GNUTLS_VERSION_MAJOR >= 3 flags |= GNUTLS_NONBLOCK; #endif #if GNUTLS_VERSION_NUMBER >= 0x030402 flags |= GNUTLS_NO_SIGNAL; #endif if (GNUTLS_E_SUCCESS != gnutls_init (&tc->sess, flags)) { tc->sess = NULL; tc->dead = 1; return 0; } if (GNUTLS_E_SUCCESS != gnutls_priority_set_direct (tc->sess, cfg.psk_scenario ? psk_prio_tbl[cfg.client_prio_idx] : client_prio_tbl[cfg.client_prio_idx], NULL)) (void) gnutls_priority_set_direct (tc->sess, "NORMAL", NULL); if (GNUTLS_E_SUCCESS != gnutls_credentials_set (tc->sess, GNUTLS_CRD_CERTIFICATE, tc->cred)) tc->dead = 1; if (cfg.client_psk) { /* The identity is the same string byte 9 (or an op 1 segment) picked for SNI; it is what arrives as @a username in psk_gnutls_adapter(). A client that offers no PSK credentials at all against a PSK-only server is the other half of this: the handshake then fails without the adapter ever being asked. */ gnutls_datum_t k; k.data = (unsigned char *) (intptr_t) psk_key_bytes; k.size = (unsigned int) sizeof (psk_key_bytes); if (GNUTLS_E_SUCCESS != gnutls_psk_allocate_client_credentials (&tc->psk)) tc->psk = NULL; else { if (GNUTLS_E_SUCCESS != gnutls_psk_set_client_credentials (tc->psk, sni_name, &k, GNUTLS_PSK_KEY_RAW)) tc->dead = 1; else if (GNUTLS_E_SUCCESS != gnutls_credentials_set (tc->sess, GNUTLS_CRD_PSK, tc->psk)) tc->dead = 1; } } if ( (cfg.client_sni) && (0 != sni_name_len) ) (void) gnutls_server_name_set (tc->sess, GNUTLS_NAME_DNS, sni_name, sni_name_len); gnutls_transport_set_int (tc->sess, tc->fd); /* GNUTLS_INDEFINITE_TIMEOUT: the default handshake timeout is a wall clock deadline, and this harness must not depend on the clock. */ gnutls_handshake_set_timeout (tc->sess, 0); return 0; } static void tc_send (struct MHD_Daemon *d, struct tls_client *tc, const uint8_t *buf, size_t len) { size_t off = 0; unsigned int stall = 0; if ( (0 > tc->fd) || (0 == len) ) return; if (NULL == tc->sess) { while ( (off < len) && (stall < 64) ) { ssize_t s = send (tc->fd, buf + off, len - off, MSG_DONTWAIT); if (0 < s) { off += (size_t) s; stall = 0; continue; } stall++; pump_and_drain (d, tc, 2); if ( (0 > s) && (EAGAIN != errno) && (EWOULDBLOCK != errno) && (EINTR != errno) ) break; } return; } if ( (0 != tc->dead) || (0 == tc->hs_done) ) return; while ( (off < len) && (stall < 64) ) { /* On GNUTLS_E_AGAIN the call has to be repeated with exactly the same arguments, which is why @a off is only advanced on success. */ ssize_t s = gnutls_record_send (tc->sess, buf + off, len - off); if (0 < s) { off += (size_t) s; stall = 0; continue; } if ( (GNUTLS_E_AGAIN == s) || (GNUTLS_E_INTERRUPTED == s) ) { stall++; pump_and_drain (d, tc, 2); continue; } if (0 != gnutls_error_is_fatal ((int) s)) tc->dead = 1; break; } } /** * Tear the client end down. Every GnuTLS object is released on every * path, including the ones where the session never got off the ground. */ static void tc_close (struct MHD_Daemon *d, struct tls_client *tc) { if (NULL != tc->sess) { if ( (cfg.client_bye) && (0 == tc->dead) && (0 != tc->hs_done) ) { unsigned int i; for (i = 0; i < 8; i++) { int ret = gnutls_bye (tc->sess, GNUTLS_SHUT_WR); if ( (GNUTLS_E_AGAIN != ret) && (GNUTLS_E_INTERRUPTED != ret) ) break; run_once (d); } } gnutls_deinit (tc->sess); tc->sess = NULL; } if (NULL != tc->cred) { gnutls_certificate_free_credentials (tc->cred); tc->cred = NULL; } if (NULL != tc->psk) { gnutls_psk_free_client_credentials (tc->psk); tc->psk = NULL; } if (0 <= tc->fd) { if (cfg.client_shut_wr) (void) shutdown (tc->fd, SHUT_WR); pump (d, 2); (void) close (tc->fd); tc->fd = -1; } tc->hs_done = 0; tc->dead = 1; pump (d, 4); } /** * Hand the daemon one more connection and do not run the loop again. * * See the comment at the call site: this is what leaves a fully prepared * connection -- GnuTLS session and all -- on the daemon's * new_connections list when MHD_stop_daemon() runs. * * @param d the daemon, about to be stopped * @return our end of the socket pair, or -1 if nothing was queued */ static int queue_unprocessed_conn (struct MHD_Daemon *d) { int sv[2]; struct sockaddr_in sa; if (0 != socketpair (AF_UNIX, SOCK_STREAM, 0, sv)) return -1; memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (44444); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (MHD_YES != MHD_add_connection (d, (MHD_socket) sv[1], (const struct sockaddr *) &sa, (socklen_t) sizeof (sa))) { /* MHD has closed sv[1] already. */ (void) close (sv[0]); return -1; } return sv[0]; } /** * Bring a fresh connection up to the point where payload can be sent. */ static void tc_start (struct MHD_Daemon *d, struct tls_client *tc) { if (0 != tc_open (d, tc)) { tc->fd = -1; return; } if (CLIENT_TLS == cfg.mode) tc_handshake (d, tc, HANDSHAKE_ROUNDS); else if (CLIENT_TLS_ABANDON == cfg.mode) tc_handshake (d, tc, cfg.hs_budget); else pump (d, 1); } /* ------------------------------------------------------------------ */ /* PEM blobs assembled from the input */ /* ------------------------------------------------------------------ */ /** * Build @a out as "-----BEGIN @a label-----\n\n-----END @a * label-----\n", with @a body_len bytes of @a body as the payload. The * result is always NUL terminated, because MHD calls strlen() on it. */ static void build_fuzz_pem (char *out, size_t out_size, const char *label, const uint8_t *body, size_t body_len) { size_t o = 0; size_t i; int n; n = snprintf (out, out_size, "-----BEGIN %s-----\n", label); if ( (0 > n) || ((size_t) n >= out_size) ) { out[0] = '\0'; return; } o = (size_t) n; if (body_len > FUZZ_PEM_BODY_MAX) body_len = FUZZ_PEM_BODY_MAX; for (i = 0; (i < body_len) && (o + 32 < out_size); i++) { /* Keep the blob a C string; a NUL inside would simply truncate it for MHD's strlen(), which is a less interesting shape. */ out[o++] = (char) ((0 == body[i]) ? 'A' : body[i]); } n = snprintf (out + o, out_size - o, "\n-----END %s-----\n", label); if (0 > n) out[o] = '\0'; } /* ------------------------------------------------------------------ */ /* The fuzz target */ /* ------------------------------------------------------------------ */ int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { struct MHD_Daemon *d; struct MHD_OptionItem opts[12]; unsigned int nopt = 0; unsigned int flags; struct tls_client tc; size_t pos; unsigned int nseg = 0; unsigned int nconn = 1; int queued_fd = -1; /**< see queue_unprocessed_conn() */ /* Must happen before the first write() into the socketpair; see fuzz_ignore_sigpipe() in fuzz_common.h for why the process dies without it. Idempotent. */ fuzz_ignore_sigpipe (); /* The ten configuration bytes are mandatory. */ if (size < 10) return 0; resp_len = 0; memset (&cfg, 0, sizeof (cfg)); { const char *nm = sni_name_tbl[(data[9] & 0x07) % SNI_NAME_COUNT]; sni_name_len = strlen (nm); memcpy (sni_name, nm, sni_name_len + 1); } cfg.cert = cred_tbl[data[0] % CRED_COUNT].cert; cfg.key = cred_tbl[data[0] % CRED_COUNT].key; cfg.use_trust = (0 != (data[1] & 0x01)); cfg.use_dhparams = (0 != (data[1] & 0x02)); cfg.use_sni = (0 != (data[1] & 0x04)); cfg.use_prio = (0 != (data[1] & 0x08)); cfg.use_cred_type = (0 != (data[1] & 0x10)); cfg.no_alpn = (0 != (data[1] & 0x20)); cfg.key_password = (0 != (data[1] & 0x40)); cfg.prio_append = (0 != (data[1] & 0x80)); cfg.prio_idx = (unsigned int) (data[2] % PRIO_COUNT); cfg.cred_type_idx = (unsigned int) (data[3] & 0x07) % CRED_TYPE_COUNT; cfg.sni_mode = (enum sni_behaviour) (((unsigned int) (data[3] >> 3) & 0x07) % (unsigned int) SNI_BEHAVIOUR_COUNT); cfg.trust_garbage = (0 != (data[3] & 0x40)); cfg.dh_garbage = (0 != (data[3] & 0x80)); cfg.prio_str = prio_tbl[cfg.prio_idx]; cfg.mode = (enum client_mode) (data[4] & 0x03); cfg.client_sni = (0 != (data[4] & 0x04)); cfg.client_cert = (0 != (data[4] & 0x08)); cfg.client_prio_idx = (unsigned int) ((data[4] >> 4) & 0x03); cfg.client_bye = (0 != (data[4] & 0x40)); cfg.client_shut_wr = (0 != (data[4] & 0x80)); cfg.mem_limit = mem_limit_tbl[(data[5] & 0x0F) % MEM_LIMIT_COUNT]; cfg.loop_mode = (unsigned int) ((data[5] >> 4) & 0x03); cfg.stop_with_queued = (0 != (data[5] & 0x40)); cfg.resp_kind = (unsigned int) (data[6] & 0x03); cfg.conn_info = (0 != (data[6] & 0x04)); cfg.daemon_info = (0 != (data[6] & 0x08)); cfg.conn_option = (0 != (data[6] & 0x10)); cfg.error_reply = (0 != (data[6] & 0x20)); cfg.resp_header = (0 != (data[6] & 0x40)); cfg.quiesce = (0 != (data[6] & 0x80)); cfg.hs_budget = 1u + (unsigned int) (data[7] & 0x07); cfg.use_tls = (0 == (data[7] & 0x08)); cfg.allow_upgrade = (0 != (data[7] & 0x10)) && (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_UPGRADE)); cfg.extra_pump = (unsigned int) ((data[7] >> 5) & 0x07); cfg.psk_mode = (enum psk_behaviour) (((unsigned int) (data[9] >> 3) & 0x07) % (unsigned int) PSK_BEHAVIOUR_COUNT); cfg.client_psk = (0 != (data[9] & 0x40)); #if GNUTLS_VERSION_MAJOR >= 3 cfg.psk_scenario = (0 != (data[9] & 0x80)); #else /* MHD refuses MHD_OPTION_GNUTLS_PSK_CRED_HANDLER outright when it was built against GnuTLS 2, so there is nothing to reach there. */ cfg.psk_scenario = 0; #endif /* The PSK bundle. Four things have to line up before GnuTLS asks the server for a key at all; see the TLS-PSK note at the top of this file for why they are not four independent input bits. */ if (cfg.psk_scenario) { cfg.use_tls = 1; cfg.use_cred_type = 1; cfg.cred_type_idx = PSK_CRED_TYPE_IDX; cfg.use_prio = 1; cfg.prio_append = 0; cfg.prio_str = psk_prio_tbl[cfg.client_prio_idx]; /* Raw bytes never negotiate anything; the abandoning client is kept because stopping half way through a PSK handshake is its own shape. */ if ( (CLIENT_TLS != cfg.mode) && (CLIENT_TLS_ABANDON != cfg.mode) ) cfg.mode = CLIENT_TLS; } else cfg.client_psk = 0; /* A real handshake is pointless without a working credential setup on our own side; fall back to the raw modes if the SNI certificates could not be parsed. */ if ( (cfg.use_sni) && (0 != sni_hosts_init ()) ) cfg.use_sni = 0; /* The PEM blobs built from the input. They are only referenced by cred_tbl entries 12-14, but filling them unconditionally keeps this out of the option assembly below. */ { size_t body = (size_t) data[8] * 4u; if (body > size - 10) body = size - 10; build_fuzz_pem (fuzz_cert_pem, sizeof (fuzz_cert_pem), "CERTIFICATE", data + 10, body); build_fuzz_pem (fuzz_key_pem, sizeof (fuzz_key_pem), "PRIVATE KEY", data + 10, body); } if (0 != cfg.mem_limit) { opts[nopt].option = MHD_OPTION_CONNECTION_MEMORY_LIMIT; opts[nopt].value = (intptr_t) cfg.mem_limit; opts[nopt].ptr_value = NULL; nopt++; } if (NULL != cfg.key) { opts[nopt].option = MHD_OPTION_HTTPS_MEM_KEY; opts[nopt].value = 0; opts[nopt].ptr_value = (void *) (intptr_t) cfg.key; nopt++; } if (NULL != cfg.cert) { opts[nopt].option = MHD_OPTION_HTTPS_MEM_CERT; opts[nopt].value = 0; opts[nopt].ptr_value = (void *) (intptr_t) cfg.cert; nopt++; } if (cfg.key_password) { opts[nopt].option = MHD_OPTION_HTTPS_KEY_PASSWORD; opts[nopt].value = 0; opts[nopt].ptr_value = (void *) (intptr_t) https_key_password; nopt++; } if (cfg.use_trust) { opts[nopt].option = MHD_OPTION_HTTPS_MEM_TRUST; opts[nopt].value = 0; opts[nopt].ptr_value = (void *) (intptr_t) (cfg.trust_garbage ? garbage_cert_pem : ca_cert_pem); nopt++; } if (cfg.use_dhparams) { opts[nopt].option = MHD_OPTION_HTTPS_MEM_DHPARAMS; opts[nopt].value = 0; opts[nopt].ptr_value = (void *) (intptr_t) (cfg.dh_garbage ? garbage_dh_pem : dh_params_pem); nopt++; } if (cfg.use_prio) { opts[nopt].option = cfg.prio_append ? MHD_OPTION_HTTPS_PRIORITIES_APPEND : MHD_OPTION_HTTPS_PRIORITIES; opts[nopt].value = 0; opts[nopt].ptr_value = (void *) (intptr_t) cfg.prio_str; nopt++; } if (cfg.use_cred_type) { opts[nopt].option = MHD_OPTION_HTTPS_CRED_TYPE; opts[nopt].value = (intptr_t) cred_type_tbl[cfg.cred_type_idx]; opts[nopt].ptr_value = NULL; nopt++; } if (cfg.no_alpn) { opts[nopt].option = MHD_OPTION_TLS_NO_ALPN; opts[nopt].value = 1; opts[nopt].ptr_value = NULL; nopt++; } opts[nopt].option = MHD_OPTION_END; opts[nopt].value = 0; opts[nopt].ptr_value = NULL; flags = MHD_USE_NO_LISTEN_SOCKET; if (cfg.use_tls) flags |= MHD_USE_TLS; if (fuzz_verbose) flags |= MHD_USE_ERROR_LOG; if (cfg.allow_upgrade) flags |= MHD_ALLOW_UPGRADE; MHD_set_panic_func (&panic_cb, NULL); /* The callback options go through the varargs rather than through the option array: the array's ptr_value is a void *, and a function pointer does not portably fit in one. A NULL callback is exactly equivalent to not passing the option -- which is what makes PSK_NO_HANDLER (the "PSK not supported by this server" arm of psk_gnutls_adapter()) reachable without a second call site. MHD_OPTION_GNUTLS_PSK_CRED_HANDLER is the exception: an MHD built against GnuTLS 2 rejects it whatever the callback is, and rejecting an option fails the whole MHD_start_daemon(), so on such a build the option must not be passed at all. */ #if GNUTLS_VERSION_MAJOR >= 3 d = MHD_start_daemon (flags, 0, NULL, NULL, &ahc, NULL, MHD_OPTION_ARRAY, opts, MHD_OPTION_HTTPS_CERT_CALLBACK, cfg.use_sni ? &sni_callback : NULL, MHD_OPTION_GNUTLS_PSK_CRED_HANDLER, (cfg.psk_scenario && (PSK_NO_HANDLER != cfg.psk_mode)) ? &psk_cred_cb : NULL, NULL, MHD_OPTION_END); #else d = MHD_start_daemon (flags, 0, NULL, NULL, &ahc, NULL, MHD_OPTION_ARRAY, opts, MHD_OPTION_HTTPS_CERT_CALLBACK, cfg.use_sni ? &sni_callback : NULL, MHD_OPTION_END); #endif if (NULL == d) { stat_daemons_failed++; return 0; } stat_daemons++; if (! stats_registered) { stats_registered = 1; (void) atexit (&print_stats); } if (cfg.daemon_info) { (void) MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); (void) MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); (void) MHD_get_daemon_info (d, MHD_DAEMON_INFO_CURRENT_CONNECTIONS); (void) MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); } /* The connection is opened lazily, when the first segment that carries wire data is reached, so that a leading op 1 segment can still override the server name byte 9 selected. */ tc.sess = NULL; tc.cred = NULL; tc.psk = NULL; tc.fd = -1; tc.hs_done = 0; tc.dead = 1; pos = 10u; while ( (pos + 2 <= size) && (nseg < MAX_SEGMENTS) ) { unsigned int hdr = (unsigned int) data[pos] | ((unsigned int) data[pos + 1] << 8); unsigned int op = hdr >> 14; size_t slen = (size_t) (hdr & 0x3FFF); pos += 2; nseg++; if (slen > size - pos) slen = size - pos; if (1 == op) { /* Server name declaration for the next connection, not wire data. */ size_t n = slen; if (n > MAX_SNI_LEN) n = MAX_SNI_LEN; memcpy (sni_name, data + pos, n); /* GnuTLS wants a plain host name, and an embedded NUL would only shorten it behind our back. */ while ( (0 != n) && ('\0' == sni_name[n - 1]) ) n--; sni_name[n] = '\0'; sni_name_len = n; pos += slen; continue; } if (0 > tc.fd) { tc_start (d, &tc); if (0 > tc.fd) break; } else if ( (3 == op) && (nconn < MAX_CONNECTIONS) ) { tc_close (d, &tc); tc_start (d, &tc); nconn++; if (0 > tc.fd) break; } if (0 != slen) tc_send (d, &tc, data + pos, slen); pos += slen; pump_and_drain (d, &tc, (2 == op) ? (6u + cfg.extra_pump) : 3u); } if (0 > tc.fd) tc_start (d, &tc); pump_and_drain (d, &tc, 2u + cfg.extra_pump); tc_close (d, &tc); if (cfg.quiesce) (void) MHD_quiesce_daemon (d); /* Last, so that no run can drain the list again. MHD_add_connection() on a thread-safe daemon (the default) only queues the socket, but new_connection_prepare_() has already built the GnuTLS session for it; stopping before the next run is what makes MHD free that session from new_connection_close_() rather than from the ordinary connection teardown. fuzz_eventloop covers the same shape without TLS -- see its byte 3 bit 4. */ if (cfg.stop_with_queued) queued_fd = queue_unprocessed_conn (d); MHD_stop_daemon (d); if (0 <= queued_fd) (void) close (queued_fd); return 0; } /* ------------------------------------------------------------------ */ /* Structure-aware generator */ /* ------------------------------------------------------------------ */ struct sbuf { uint8_t *p; size_t len; size_t cap; }; static void sb_raw (struct sbuf *b, const void *v, size_t n) { if (b->len + n > b->cap) n = b->cap - b->len; memcpy (b->p + b->len, v, n); b->len += n; } static void sb_str (struct sbuf *b, const char *s) { sb_raw (b, s, strlen (s)); } static void sb_u32 (struct sbuf *b, uint32_t v) { char tmp[16]; unsigned int n = 0; do { tmp[n++] = (char) ('0' + (v % 10u)); v /= 10u; } while ( (0 != v) && (n < sizeof (tmp)) ); while (0 != n) { char c = tmp[--n]; sb_raw (b, &c, 1); } } enum gen_shape { SHAPE_TLS_HTTP = 0, /**< good credentials, real handshake, HTTP over TLS */ SHAPE_RAW_BYTES, /**< good credentials, junk at the TLS socket */ SHAPE_ABANDON, /**< a real client that walks away mid-handshake */ SHAPE_BAD_CREDS, /**< mismatched/garbage/absent key or certificate */ SHAPE_BAD_OPTIONS, /**< bogus priorities, credential types, no MHD_USE_TLS */ SHAPE_SNI, /**< the certificate callback, all behaviours */ SHAPE_PEM_FUZZ, /**< PEM blobs built from the generator's own bytes */ SHAPE_RECORDS, /**< hand-built TLS records */ SHAPE_PSK, /**< the pre-shared key credentials path */ SHAPE_COUNT }; static int forced_shape = -1; static int forced_shape_read; static const char *const gen_methods[] = { "GET", "POST", "HEAD", "PUT", "OPTIONS", "BREW" }; static const char *const gen_targets[] = { "/", "/a", "/index.html", "/a?b=c", "/%41%42", "*", "//" }; static const char *const gen_versions[] = { "HTTP/1.1", "HTTP/1.0", "HTTP/1.2", "HTTP/9.9" }; static const char *const gen_hdr_names[] = { "Host", "User-Agent", "Accept", "Connection", "X-Fuzz", "Cookie", "Content-Type", "Expect" }; static const char *const gen_hdr_values[] = { "x", "localhost", "*/*", "keep-alive", "close", "100-continue", "text/plain", "a=b" }; /** * A plain HTTP request; over TLS this is what makes MHD leave the * handshake state machine and enter the ordinary parser. */ static void gen_http_request (struct fuzz_rng *rng, struct sbuf *b) { unsigned int nh; unsigned int i; int with_body; sb_str (b, gen_methods[fuzz_below (rng, (uint32_t) (sizeof (gen_methods) / sizeof (gen_methods[0])))]); sb_str (b, " "); sb_str (b, gen_targets[fuzz_below (rng, (uint32_t) (sizeof (gen_targets) / sizeof (gen_targets[0])))]); sb_str (b, " "); sb_str (b, gen_versions[fuzz_below (rng, (uint32_t) (sizeof (gen_versions) / sizeof (gen_versions[0])))]); sb_str (b, "\r\n"); with_body = fuzz_chance (rng, 3); nh = fuzz_below (rng, 4); for (i = 0; i < nh; i++) { sb_str (b, gen_hdr_names[fuzz_below (rng, (uint32_t) (sizeof (gen_hdr_names) / sizeof (gen_hdr_names[0])))]); sb_str (b, ": "); sb_str (b, gen_hdr_values[fuzz_below (rng, (uint32_t) (sizeof (gen_hdr_values) / sizeof (gen_hdr_values[0])))]); sb_str (b, "\r\n"); } if (with_body) { unsigned int blen = fuzz_below (rng, 64); sb_str (b, "Content-Length: "); sb_u32 (b, blen); sb_str (b, "\r\n\r\n"); for (i = 0; i < blen; i++) { char c = (char) ('a' + (int) fuzz_below (rng, 26)); sb_raw (b, &c, 1); } return; } sb_str (b, "\r\n"); } /** * Something that looks like a TLS record: a content type, a version, a * length and a payload. Most of this lands in GnuTLS's record parser * rather than in MHD, which is why the generator spends only one shape * on it. */ static void gen_tls_records (struct fuzz_rng *rng, struct sbuf *b) { unsigned int n = 1 + fuzz_below (rng, 4); unsigned int i; unsigned int j; for (i = 0; i < n; i++) { uint8_t hdr[5]; unsigned int plen = fuzz_below (rng, 96); unsigned int declared = fuzz_chance (rng, 3) ? fuzz_below (rng, 0x4000) : plen; hdr[0] = fuzz_chance (rng, 4) ? fuzz_byte (rng) : (uint8_t) (20 + fuzz_below (rng, 4)); hdr[1] = 0x03; hdr[2] = (uint8_t) fuzz_below (rng, 5); hdr[3] = (uint8_t) ((declared >> 8) & 0xFF); hdr[4] = (uint8_t) (declared & 0xFF); sb_raw (b, hdr, sizeof (hdr)); for (j = 0; j < plen; j++) { uint8_t v = fuzz_byte (rng); sb_raw (b, &v, 1); } } } /** * Number of leading entries of #prio_tbl that GnuTLS accepts. Beyond * that the daemon refuses to start, which is a fine thing to fuzz but a * poor way to reach the handshake. */ #define PRIO_VALID_COUNT 7 /** * Constrain the configuration bytes so that MHD_start_daemon() actually * succeeds. Used by the shapes whose point is what happens *after* the * daemon is up; the option surface itself is fuzzed by the shapes that * do not call this. */ static void make_daemon_startable (struct fuzz_rng *rng, uint8_t *cfg_bytes) { cfg_bytes[1] &= (uint8_t) ~0x10u; /* no credential type override */ cfg_bytes[3] &= (uint8_t) ~0xC0u; /* valid trust store, valid DH */ if (0 != (cfg_bytes[1] & 0x08u)) cfg_bytes[2] = (uint8_t) fuzz_below (rng, PRIO_VALID_COUNT); cfg_bytes[7] &= (uint8_t) ~0x08u; /* keep MHD_USE_TLS */ } /** * Emit one segment with the given op code. */ static void emit_segment (struct sbuf *out, unsigned int op, const uint8_t *payload, size_t len) { unsigned int hv; uint8_t hdr[2]; if (len > 0x3FFF) len = 0x3FFF; hv = (op << 14) | (unsigned int) len; hdr[0] = (uint8_t) (hv & 0xFF); hdr[1] = (uint8_t) (hv >> 8); sb_raw (out, hdr, 2); sb_raw (out, payload, len); } static size_t fuzz_generate (struct fuzz_rng *rng, uint8_t *buf, size_t cap) { struct sbuf out; struct sbuf rb; uint8_t req[GEN_BUF_SIZE]; uint8_t cfg_bytes[10]; enum gen_shape shape; unsigned int nreq; unsigned int i; out.p = buf; out.len = 0; out.cap = cap; if (! forced_shape_read) { const char *e = getenv ("MHD_FUZZ_SHAPE"); forced_shape_read = 1; if (NULL != e) forced_shape = atoi (e); } if (0 <= forced_shape) shape = (enum gen_shape) (forced_shape % (int) SHAPE_COUNT); else shape = (enum gen_shape) fuzz_below (rng, (uint32_t) SHAPE_COUNT); for (i = 0; i < sizeof (cfg_bytes); i++) cfg_bytes[i] = fuzz_byte (rng); /* Byte 0 picks the credentials, byte 4 (bits 0-1) the client, and byte 1 which options are passed at all; every shape below narrows exactly those and leaves the rest of the configuration space random. */ cfg_bytes[7] &= (uint8_t) ~0x08u; /* keep MHD_USE_TLS by default */ switch (shape) { case SHAPE_TLS_HTTP: cfg_bytes[0] = (uint8_t) (fuzz_chance (rng, 2) ? 0 : 1); cfg_bytes[4] = (uint8_t) ((cfg_bytes[4] & ~0x03u) | CLIENT_TLS); cfg_bytes[1] &= (uint8_t) ~0x04u; /* no SNI callback */ make_daemon_startable (rng, cfg_bytes); break; case SHAPE_RAW_BYTES: cfg_bytes[0] = 0; cfg_bytes[4] = (uint8_t) ((cfg_bytes[4] & ~0x03u) | CLIENT_RAW); make_daemon_startable (rng, cfg_bytes); break; case SHAPE_ABANDON: cfg_bytes[0] = (uint8_t) (fuzz_chance (rng, 2) ? 0 : 1); cfg_bytes[4] = (uint8_t) ((cfg_bytes[4] & ~0x03u) | CLIENT_TLS_ABANDON); cfg_bytes[7] = (uint8_t) ((cfg_bytes[7] & ~0x07u) + fuzz_below (rng, 6)); make_daemon_startable (rng, cfg_bytes); break; case SHAPE_BAD_CREDS: /* entries 2-11 of cred_tbl are the broken ones */ cfg_bytes[0] = (uint8_t) (2 + fuzz_below (rng, 10)); cfg_bytes[4] = (uint8_t) ((cfg_bytes[4] & ~0x03u) | (fuzz_chance (rng, 2) ? CLIENT_TLS : CLIENT_RAW)); break; case SHAPE_BAD_OPTIONS: cfg_bytes[1] |= 0x18u; /* priorities + credential type */ cfg_bytes[2] = (uint8_t) fuzz_below (rng, (uint32_t) PRIO_COUNT); cfg_bytes[3] = fuzz_byte (rng); if (fuzz_chance (rng, 4)) cfg_bytes[7] |= 0x08u; /* HTTPS options, but no MHD_USE_TLS */ cfg_bytes[4] = (uint8_t) ((cfg_bytes[4] & ~0x03u) | (fuzz_chance (rng, 2) ? CLIENT_TLS : CLIENT_RAW)); break; case SHAPE_SNI: cfg_bytes[0] = (uint8_t) (fuzz_chance (rng, 3) ? 6 : 0); cfg_bytes[3] = (uint8_t) ((cfg_bytes[3] & ~0x38u) | (fuzz_below (rng, (uint32_t) SNI_BEHAVIOUR_COUNT) << 3)); cfg_bytes[4] = (uint8_t) ((cfg_bytes[4] & ~0x03u) | CLIENT_TLS | 0x04u); cfg_bytes[9] = (uint8_t) fuzz_below (rng, (uint32_t) SNI_NAME_COUNT); make_daemon_startable (rng, cfg_bytes); cfg_bytes[1] |= 0x04u; /* the certificate callback */ break; case SHAPE_PEM_FUZZ: cfg_bytes[0] = (uint8_t) (12 + fuzz_below (rng, 3)); cfg_bytes[8] = (uint8_t) (1 + fuzz_below (rng, 64)); cfg_bytes[4] = (uint8_t) ((cfg_bytes[4] & ~0x03u) | (fuzz_chance (rng, 2) ? CLIENT_TLS : CLIENT_RAW)); break; case SHAPE_RECORDS: cfg_bytes[0] = 0; cfg_bytes[4] = (uint8_t) ((cfg_bytes[4] & ~0x03u) | CLIENT_RECORDS); make_daemon_startable (rng, cfg_bytes); break; case SHAPE_PSK: /* The certificate is irrelevant to a PSK handshake but still has to let the daemon start, so keep the valid pair. */ cfg_bytes[0] = 0; cfg_bytes[4] = (uint8_t) ((cfg_bytes[4] & ~0x03u) | (fuzz_chance (rng, 5) ? CLIENT_TLS_ABANDON : CLIENT_TLS)); cfg_bytes[1] &= (uint8_t) ~0x04u; /* no SNI callback */ make_daemon_startable (rng, cfg_bytes); cfg_bytes[9] = (uint8_t) (0x80u /* the scenario itself */ | (fuzz_chance (rng, 6) ? 0u : 0x40u) /* client PSK */ | (uint8_t) (fuzz_below (rng, (uint32_t) PSK_BEHAVIOUR_COUNT) << 3) | (uint8_t) fuzz_below (rng, (uint32_t) SNI_NAME_COUNT)); break; case SHAPE_COUNT: default: break; } /* Byte 9 already carries a server name; now and then hand the same one over as an op 1 segment instead, so that the segment form is exercised too. Generated inputs are never written to corpus/, so unlike the seeds they may use op 1 (see the note at the top). */ sb_raw (&out, cfg_bytes, sizeof (cfg_bytes)); if (fuzz_chance (rng, 4)) { const char *nm = sni_name_tbl[cfg_bytes[9] & 0x07]; emit_segment (&out, 1u, (const uint8_t *) nm, strlen (nm)); } nreq = 1u + (fuzz_chance (rng, 4) ? 1u : 0u); for (i = 0; i < nreq; i++) { unsigned int op; rb.p = req; rb.len = 0; rb.cap = sizeof (req); switch (shape) { case SHAPE_RECORDS: gen_tls_records (rng, &rb); break; case SHAPE_RAW_BYTES: { unsigned int n = 1 + fuzz_below (rng, 256); unsigned int j; for (j = 0; j < n; j++) { uint8_t v = fuzz_byte (rng); sb_raw (&rb, &v, 1); } break; } default: gen_http_request (rng, &rb); break; } if (0 != i) op = 3u; /* a fresh connection */ else op = fuzz_chance (rng, 3) ? 2u : 0u; /* Split the payload now and then: MHD's parser is incremental and the TLS record boundaries move with the split. */ if ( (rb.len > 8) && fuzz_chance (rng, 3) ) { size_t cut = 1 + fuzz_below (rng, (uint32_t) (rb.len - 1)); emit_segment (&out, op, req, cut); emit_segment (&out, 2u, req + cut, rb.len - cut); } else { emit_segment (&out, op, req, rb.len); } } return out.len; } /* ------------------------------------------------------------------ */ /* Built-in seed corpus */ /* ------------------------------------------------------------------ */ struct seed_part { unsigned int op; /**< 0 send, 1 server name, 2 send+pump, 3 new */ const char *txt; /**< NUL terminated payload */ }; struct seed_def { const char *name; unsigned char cfg[10]; struct seed_part parts[4]; }; #define P_END { 0, NULL } /* The configuration bytes are written out in full so that a seed can be read without decoding: see the input format at the top of this file. */ static const struct seed_def seeds[] = { /* A complete TLS 1.3 handshake followed by an ordinary request: the only shape that reaches the handshake -> HTTP parser transition. */ { "tls-handshake-get", { 0, 0x00, 0, 0, 0x41, 0x00, 0x04, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* The same, but the request arrives in two TLS records. */ { "tls-handshake-split", { 0, 0x00, 0, 0, 0x41, 0x00, 0x04, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHo" }, { 2, "st: x\r\n\r\n" }, P_END, P_END } }, /* Keep-alive over TLS: two requests on one session, then gnutls_bye(). */ { "tls-keepalive", { 0, 0x00, 0, 0, 0x41, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET /a HTTP/1.1\r\nHost: x\r\n\r\n" }, { 2, "GET /b HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n" }, P_END, P_END } }, /* A second connection, i.e. a second handshake on the same daemon. */ { "tls-second-connection", { 0, 0x00, 0, 0, 0x41, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET /a HTTP/1.1\r\nHost: x\r\n\r\n" }, { 3, "GET /b HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END } }, /* Plain HTTP at a TLS port: the record layer sees "GET ..." and the handshake fails, which is MHD_run_tls_handshake_()'s error arm. */ { "plain-http-at-tls-port", { 0, 0x00, 0, 0, 0x00, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* Nothing at all, then EOF: the connection dies in MHD_TLS_CONN_INIT. */ { "eof-in-init", { 0, 0x00, 0, 0, 0x80, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "" }, P_END, P_END, P_END } }, /* A real client that walks away after a single handshake round: MHD is left in MHD_TLS_CONN_HANDSHAKING when the socket closes. */ { "abandon-handshake", { 0, 0x00, 0, 0, 0x02, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "" }, P_END, P_END, P_END } }, /* Certificate and key do not belong together. */ { "mismatched-key", { 2, 0x00, 0, 0, 0x01, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* No certificate at all: MHD_start_daemon() has to fail cleanly. */ { "no-certificate", { 6, 0x00, 0, 0, 0x01, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* PEM armour with a payload that is not base64. */ { "garbage-pem", { 10, 0x00, 0, 0, 0x01, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* A priority string GnuTLS rejects (index 9 of prio_tbl). */ { "bogus-priorities", { 0, 0x08, 9, 0, 0x01, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* The same string through MHD_OPTION_HTTPS_PRIORITIES_APPEND. */ { "bogus-priorities-append", { 0, 0x88, 10, 0, 0x01, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* TLS 1.2 only on both ends, with the trust store and a client certificate request. */ { "tls12-with-trust", { 0, 0x01, 2, 0, 0x29, 0x00, 0x04, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* Valid Diffie-Hellman parameters (RFC 3526 group 14). */ { "valid-dhparams", { 0, 0x02, 0, 0, 0x21, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* Malformed Diffie-Hellman parameters: MHD_start_daemon() must fail. */ { "garbage-dhparams", { 0, 0x02, 0, 0x80, 0x01, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* A credential type MHD does not support (GNUTLS_CRD_ANON). */ { "cred-type-anon", { 0, 0x10, 0, 0x02, 0x01, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* GNUTLS_CRD_PSK without a PSK callback: the daemon starts, the handshake cannot. */ { "cred-type-psk", { 0, 0x10, 0, 0x01, 0x01, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* The TLS-PSK scenario (byte 9 bit 7), one seed per branch of psk_gnutls_adapter(). Byte 9 is 0x80 scenario | 0x40 client offers PSK | behaviour << 3 | identity. Byte 4 bits 4-5 pick the PSK priority string, which is what decides the protocol version the PSK key exchange runs under. */ /* The whole path end to end: identity accepted, key matches, handshake completes, and MHD then serves plain HTTP over a session that has no certificate at all (byte 6 bit 2 reads the TLS members back). */ { "psk-handshake", { 0, 0x00, 0, 0, 0x11, 0x00, 0x04, 0x00, 0, 0xC0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* The same over TLS 1.3, where GnuTLS treats the key as an external PSK and the exchange has a different shape. */ { "psk-handshake-tls13", { 0, 0x00, 0, 0, 0x21, 0x00, 0x00, 0x00, 0, 0xC0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* The application refuses the identity: the adapter's -1 arm. */ { "psk-callback-fails", { 0, 0x00, 0, 0, 0x11, 0x00, 0x00, 0x00, 0, 0xC8 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* Zero length key: the "PSK too short" arm, and the reason MHD never reaches gnutls_malloc(0). */ { "psk-empty-key", { 0, 0x00, 0, 0, 0x11, 0x00, 0x00, 0x00, 0, 0xD0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* One byte below the minimum -- the other side of the boundary that psk-handshake (exactly the minimum) sits on. */ { "psk-one-byte-short", { 0, 0x00, 0, 0, 0x11, 0x00, 0x00, 0x00, 0, 0xF8 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* 4 KiB key: the copy into the gnutls_malloc()ed buffer, at a size no ciphersuite expects. */ { "psk-long-key", { 0, 0x00, 0, 0, 0x11, 0x00, 0x00, 0x00, 0, 0xD8 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* Key length taken from the identity, with the longest identity in the table (sni_name_tbl entry 7, 62 characters): the callback then hands back a 62 byte key, which no PSK ciphersuite expects. */ { "psk-key-from-identity", { 0, 0x00, 0, 0, 0x11, 0x00, 0x00, 0x00, 0, 0xE7 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* A key size above UINT_MAX: the "PSK too long" arm, which has to free the application's buffer and fail. */ { "psk-oversized-key", { 0, 0x00, 0, 0, 0x11, 0x00, 0x00, 0x00, 0, 0xE8 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* PSK credential type, PSK ciphersuite, but no credentials callback: the "PSK not supported by this server" arm. */ { "psk-no-handler", { 0, 0x00, 0, 0, 0x11, 0x00, 0x00, 0x00, 0, 0xF0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* A PSK-only server against a client that offers no PSK identity: the handshake fails before the adapter is ever asked. */ { "psk-client-no-creds", { 0, 0x00, 0, 0, 0x11, 0x00, 0x00, 0x00, 0, 0x80 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* Byte 5 bit 6: stop the daemon with a connection queued but never started, so that its GnuTLS session is freed by new_connection_close_() instead of by the ordinary teardown. */ { "stop-with-queued-connection", { 0, 0x00, 0, 0, 0x01, 0x40, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* The SNI callback, answering for the presented name (byte 9 = 0, "test-mhdserver"). No op 1 segment here or below: see the note on the shared corpus at the top of this file. */ { "sni-by-name", { 6, 0x04, 0, 0x18, 0x05, 0x00, 0x04, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: test-mhdserver\r\n\r\n" }, P_END, P_END, P_END } }, /* The SNI callback failing outright. */ { "sni-callback-fails", { 6, 0x04, 0, 0x08, 0x05, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* The SNI callback answering with an empty certificate list. */ { "sni-callback-empty", { 6, 0x04, 0, 0x10, 0x05, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* The SNI callback answering with a key that is not the certificate's (byte 9 = 1, "localhost"). */ { "sni-callback-mismatch", { 6, 0x04, 0, 0x20, 0x05, 0x00, 0x00, 0x00, 0, 1 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* The SNI callback answering with a certificate but no key. */ { "sni-callback-no-key", { 6, 0x04, 0, 0x28, 0x05, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* An unknown server name with the by-name callback (byte 9 = 3, "nobody.example.org"): no certificate. */ { "sni-unknown-name", { 6, 0x04, 0, 0x18, 0x05, 0x00, 0x00, 0x00, 0, 3 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* A PEM blob assembled from the payload below (cred_tbl entry 14). */ { "fuzzed-pem", { 14, 0x00, 0, 0, 0x01, 0x00, 0x00, 0x00, 32, 0 }, { { 0, "MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx" }, P_END, P_END, P_END } }, /* A truncated TLS record header, then EOF. */ { "short-record", { 0, 0x00, 0, 0, 0x00, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "\x16\x03\x01" }, P_END, P_END, P_END } }, /* A record that promises far more data than it delivers. */ { "record-length-lie", { 0, 0x00, 0, 0, 0x00, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "\x16\x03\x01\x3f\xff\x01\x02\x03\x04" }, P_END, P_END, P_END } }, /* The HTTPS options on a daemon started without MHD_USE_TLS. */ { "no-use-tls-flag", { 0, 0x0F, 0, 0, 0x00, 0x00, 0x00, 0x08, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* A tiny connection memory pool with a real TLS session. */ { "small-pool-tls", { 0, 0x00, 0, 0, 0x41, 0x01, 0x00, 0x00, 0, 0 }, { { 0, "GET /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa HTTP/1.1\r\n" "Host: x\r\nX-Long: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n\r\n" }, P_END, P_END, P_END } }, /* A request body over TLS, so that the receive adapter is used for more than the request line. */ { "tls-request-body", { 0, 0x00, 0, 0, 0x41, 0x00, 0x00, 0x00, 0, 0 }, { { 0, "POST /a HTTP/1.1\r\nHost: x\r\nContent-Length: 11\r\n\r\n" "hello world" }, P_END, P_END, P_END } }, /* The external event loop (MHD_get_fdset() + MHD_run_from_select()). */ { "tls-external-loop", { 0, 0x00, 0, 0, 0x41, 0x10, 0x04, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* MHD_quiesce_daemon() with a live TLS connection. */ { "tls-quiesce", { 0, 0x00, 0, 0, 0x41, 0x00, 0x80, 0x00, 0, 0 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } } }; static uint8_t seed_render_buf[2048]; static size_t fuzz_seed_count (void) { return sizeof (seeds) / sizeof (seeds[0]); } static const uint8_t * fuzz_seed_get (size_t idx, size_t *len) { const struct seed_def *sd = &seeds[idx]; struct sbuf b; unsigned int i; b.p = seed_render_buf; b.len = 0; b.cap = sizeof (seed_render_buf); sb_raw (&b, sd->cfg, sizeof (sd->cfg)); for (i = 0; i < sizeof (sd->parts) / sizeof (sd->parts[0]); i++) { if (NULL == sd->parts[i].txt) break; emit_segment (&b, sd->parts[i].op, (const uint8_t *) sd->parts[i].txt, strlen (sd->parts[i].txt)); } *len = b.len; return seed_render_buf; } #else /* ! HTTPS_SUPPORT */ /* * MHD was configured without HTTPS (which is what * contrib/oss-fuzz/build.sh does for the MemorySanitizer build), so * there is no TLS layer to fuzz. The file still has to produce a valid * fuzz target: LLVMFuzzerTestOneInput() must exist unconditionally, or * an OSS-Fuzz build of this harness would silently be an empty binary. */ int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { fuzz_ignore_sigpipe (); (void) data; (void) size; return 0; } static size_t fuzz_generate (struct fuzz_rng *rng, uint8_t *buf, size_t cap) { (void) rng; if (0 == cap) return 0; buf[0] = 0; return 1; } static const uint8_t no_https_seed[] = { 0 }; static size_t fuzz_seed_count (void) { return 1; } static const uint8_t * fuzz_seed_get (size_t idx, size_t *len) { (void) idx; *len = sizeof (no_https_seed); return no_https_seed; } #endif /* ! HTTPS_SUPPORT */ /* end of fuzz_tls.c */ libmicrohttpd-1.0.10/src/fuzz/fuzz_request.c0000664000175000017500000030321515232144110014614 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file fuzz/fuzz_request.c * @brief End-to-end in-process fuzzer for the MHD request parser. * @author Christian Grothoff * * A real `struct MHD_Daemon` is created with #MHD_USE_NO_LISTEN_SOCKET * and driven through a `socketpair()` that is handed to MHD with * #MHD_add_connection(). The daemon runs in external-polling mode, so * everything happens in the fuzzer's thread: fully deterministic, no * TCP stack, no ports, no races. * * Input format (see README): * * byte 0 configuration: connection memory limit * byte 1 configuration: handler behaviour bitmask * byte 2 configuration: client discipline / insanity level * byte 3 configuration: digest-auth parameters * byte 4 response construction: which MHD_create_response_*() * to use, how many response headers to add, footers, * header-manipulation API * byte 5 which authentication entry point to call: the v1/v2 * compatibility wrappers, the username/request-info * queries, or the differing fail-response variants * byte 6 event-loop mode (MHD_run() vs MHD_get_fdset*() + * MHD_run_from_select*()) and the connection-introspection * calls * byte 7 suspend/resume and HTTP "Upgrade" * byte 8 seed for the generated response header names/values * byte 9 seed for the content-reader callback behaviour * byte 10. a sequence of send-segments, each introduced by a * little-endian 16 bit header (op << 14) | length * op 0 send the payload * op 1 the payload is the *expected* decoded request body * (ground truth for the body oracle); nothing is sent * op 2 send the payload and pump the daemon extra rounds * op 3 close the connection, open a fresh one, send * * All ten configuration bytes are always present; an input shorter * than that is rejected outright. The all-zero configuration is the * plainest one -- a static two byte buffer response, MHD_run() as the * event loop, no suspend, no upgrade, no extra introspection -- so * zeroing bytes 4-9 of any input reduces it to what the harness did * before those bytes existed. * * Splitting the byte stream into explicit segments matters: MHD's * parser is incremental and several past bugs only showed up for * particular split points. * * The literal ASCII token "%%NONCE%%" inside a segment is replaced, * at send time, by the most recent `nonce="..."` value seen in a * response from the daemon. This is what allows the fuzzer to walk * through the Digest-Auth challenge/response handshake and reach the * code that is only executed for a *valid* nonce. */ /* Must precede every #include: memfd_create() and MFD_CLOEXEC are only declared by under _GNU_SOURCE, and the OSS-Fuzz build compiles this file with nothing but -DFUZZ_NO_MAIN (the library gets _GNU_SOURCE from configure, the hand-compiled harnesses do not). Without this the fd-backed response kinds silently fall back to a buffer response and MHD_create_response_from_fd*() is never reached -- a failure mode with no error message at all. */ #ifndef _GNU_SOURCE #define _GNU_SOURCE 1 #endif #define FUZZ_HARNESS_NAME "fuzz_request" #include "fuzz_common.h" #include #include #include #include /* MHD_create_response_from_data() and MHD_create_response_from_buffer() with an explicit MHD_ResponseMemoryMode are deprecated but are still shipped API and are therefore still worth fuzzing; the deprecation warning would otherwise drown the build output. */ #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif /* memfd_create() gives a file descriptor backed by anonymous memory, which is what makes the MHD_create_response_from_fd*() variants affordable at fuzzing rates: no filesystem is touched. Where it is unavailable the fd-backed response kinds fall back to a buffer response (see make_response()). */ #if defined(__linux__) #include #if defined(MFD_CLOEXEC) #define FUZZ_HAVE_MEMFD 1 #endif #endif #define MAX_SEGMENTS 96 #define MAX_CONNECTIONS 8 #define RESP_BUF_SIZE 16384 #define GEN_BUF_SIZE 8192 #define MAX_EXPECT_BODY 4096 /** Number of entries in the response-construction table. */ #define RESP_KIND_COUNT 16 /** Number of authentication entry points selectable by byte 5. */ #define DAUTH_VARIANT_COUNT 10 /** Largest digest MHD_digest_auth_calc_userdigest() can produce. */ #define MAX_DIGEST_BIN 64 #define DIGEST_REALM "TestRealm" #define DIGEST_USER "user" #define DIGEST_PASS "pass" /* ------------------------------------------------------------------ */ /* Per-iteration state */ /* ------------------------------------------------------------------ */ struct fuzz_cfg { size_t mem_limit; int discipline; unsigned int insanity; unsigned int nonce_nc_size; enum MHD_DigestAuthMultiAlgo3 algo; enum MHD_DigestAuthMultiQOP qop; int do_digest; int do_basic; int do_postproc; int do_iterate; int chunked_reply; int error_reply; /* ---- configuration bytes 4-9; all zero is the plainest setting ---- */ unsigned int resp_kind; /**< index into the response constructors */ unsigned int resp_nhdr; /**< how many response headers to add */ int resp_footer; /**< also add a response footer/trailer */ int resp_hdr_api; /**< exercise get/del/set_response_options */ unsigned int dauth_variant; /**< which digest entry point to call */ unsigned int fail_variant; /**< which *_fail_response to queue */ int basic_v1; /**< use the v1 basic-auth getter */ int calc_helpers; /**< call the userdigest/userhash helpers */ unsigned int loop_mode; /**< 0 MHD_run, 1..3 external event loop */ int use_timeouts; /**< query MHD_get_timeout*() while pumping */ int conn_lookup; /**< MHD_lookup_connection_value*() */ int conn_setvalue; /**< MHD_set_connection_value() */ int conn_info; /**< MHD_get_connection_info/daemon_info */ int conn_option; /**< MHD_set_connection_option() */ int quiesce; /**< MHD_quiesce_daemon() before stopping */ unsigned int suspend_mode; /**< 0 none, 1 immediate, 2 deferred */ int allow_upgrade; /**< MHD_ALLOW_UPGRADE + upgrade response */ unsigned int upgrade_action; /**< which MHD_upgrade_action() to issue */ uint8_t hdr_seed; /**< picks response header name/value */ uint8_t crc_seed; /**< content-reader callback behaviour */ }; static struct fuzz_cfg cfg; /** Most recent nonce harvested from a 401 response. */ static char nonce_val[192]; static size_t nonce_len; /** Ground-truth body of a generated (pristine) request, see README. */ static uint8_t expect_body[MAX_EXPECT_BODY]; static size_t expect_body_len; static int oracle_on; /** Statistics, printed at exit with --verbose. */ static unsigned long stat_daemons; static unsigned long stat_handler_calls; static unsigned long stat_final_calls; static unsigned long stat_body_bytes; static unsigned long stat_challenges; static unsigned long stat_auth_ok; static int stats_registered; static void print_stats (void) { if (! fuzz_verbose) return; fprintf (stderr, "%s: daemons=%lu handler calls=%lu (final=%lu) body bytes=%lu " "401 challenges=%lu authenticated=%lu\n", FUZZ_HARNESS_NAME, stat_daemons, stat_handler_calls, stat_final_calls, stat_body_bytes, stat_challenges, stat_auth_ok); } /** Bytes received from the daemon during the current iteration. */ static char resp_buf[RESP_BUF_SIZE]; static size_t resp_len; static const size_t mem_limit_tbl[] = { 0 /* MHD default */, 128, 192, 256, 320, 384, 512, 768, 1024, 1400, 1500, 2048, 4096, 32768 }; static const int discipline_tbl[] = { -3, -2, -1, 0, 1, 2 }; /** * Lower bound for MHD_OPTION_CLIENT_DISCIPLINE_LVL, -3 is the full * range. On a tree without the patches listed in README section 6, * levels below 0 reach two stale mhd_assert()s in get_req_header(); * set MHD_FUZZ_MIN_DISCIPLINE=0 there so that the rest of the state * space keeps being explored. */ static int min_discipline = -3; static int min_discipline_read; /** * Restrict the generator to a single grammar shape (see enum gen_shape). * -1 (the default) means "pick a random shape every time". Set with * MHD_FUZZ_SHAPE=; handy for triage and for regression testing a * specific past bug. */ static int forced_shape = -1; static int forced_shape_read; /** * Lower bound for MHD_OPTION_CONNECTION_MEMORY_LIMIT. 0 (the default) * fuzzes the full range, including the 128 byte pools that are needed * to reach the read-buffer "shift back" code. On a tree without the * patches listed in README section 6, pools below ~500 bytes combined * with a chunked request body reach two mhd_assert()s in connection.c; * set MHD_FUZZ_MIN_MEM_LIMIT=512 there. */ static size_t min_mem_limit; static int min_mem_limit_read; static const enum MHD_DigestAuthMultiAlgo3 algo_tbl[] = { MHD_DIGEST_AUTH_MULT_ALGO3_SHA256, MHD_DIGEST_AUTH_MULT_ALGO3_MD5, MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256, MHD_DIGEST_AUTH_MULT_ALGO3_SHA256 }; static const unsigned int nnc_tbl[] = { 4, 1, 8, 64 }; /** Fixed entropy so that nonces are reproducible across runs. */ static const char digest_rnd[32] = "\x01\x23\x45\x67\x89\xab\xcd\xef\x01\x23\x45\x67\x89\xab\xcd\xef" "\xfe\xdc\xba\x98\x76\x54\x32\x10\xfe\xdc\xba\x98\x76\x54\x32\x10"; /* ------------------------------------------------------------------ */ /* Configuration byte 4: response construction */ /* ------------------------------------------------------------------ */ /* Defined with the access handler further down; decorate_response() hands it to MHD_get_response_headers(). */ static enum MHD_Result kv_iter (void *cls, enum MHD_ValueKind kind, const char *key, const char *value); /** Daemon of the current iteration; needed by MHD_get_daemon_info(). */ static struct MHD_Daemon *cur_daemon; /** * Connections suspended by suspend mode 2, which the pump loop still has * to resume. An entry is cleared by completed_cb() so that a connection * MHD has finished with is never resumed afterwards. * * This has to be a set, not a single slot: op 3 opens a fresh connection * without waiting for the previous one to finish, so several connections * can be parked at the same time. A single slot silently loses all but * the last, and the forgotten one is still suspended when the iteration * calls MHD_stop_daemon(), which answers with * MHD_PANIC ("MHD_stop_daemon() called while we have suspended * connections") -- a harness bug that looks exactly like an MHD bug. */ static struct MHD_Connection *pending_resume[MAX_CONNECTIONS]; /** * Set once the iteration has stopped feeding the daemon and only wants * to drain it. suspend_maybe() then does nothing, which is what makes * the flush loop in the teardown provably terminate: without it, * resuming a connection lets the handler run and park it again, for as * many rounds as there are pipelined requests still buffered. */ static int tearing_down; /** * Record @a c as suspended. Silently ignores the overflow case: the * array has one slot per connection the harness can open, so it cannot * overflow, and a dropped entry would only cost the resume below. */ static void pending_resume_add (struct MHD_Connection *c) { unsigned int i; for (i = 0; i < MAX_CONNECTIONS; i++) { if (NULL == pending_resume[i]) { pending_resume[i] = c; return; } } } /** Forget @a c without resuming it (it is gone). */ static void pending_resume_drop (const struct MHD_Connection *c) { unsigned int i; for (i = 0; i < MAX_CONNECTIONS; i++) if (pending_resume[i] == c) pending_resume[i] = NULL; } /** * Resume everything still parked. * * @return non-zero if at least one connection was resumed, so that the * caller knows the daemon needs another round to act on it */ static int pending_resume_flush (void) { unsigned int i; int any = 0; for (i = 0; i < MAX_CONNECTIONS; i++) { struct MHD_Connection *c = pending_resume[i]; if (NULL == c) continue; /* Clear first: MHD_resume_connection() can run the handler, which may suspend the very same connection again. */ pending_resume[i] = NULL; MHD_resume_connection (c); any = 1; } return any; } /** Body used by the buffer / fd / pipe / iovec response kinds. */ static const char resp_body[] = "hello world, this is the response body"; #define RESP_BODY_LEN (sizeof (resp_body) - 1) /** * Response header names and values, indexed by cfg.hdr_seed. The list * mixes ordinary headers with ones MHD has to reject or handle * specially: an empty name, a name carrying a control character, and a * value containing CRLF -- the classic response-splitting vector, which * MHD_add_response_header() is supposed to refuse. Exercising that * validator is the point of this table. * * The message-framing headers are deliberately NOT here. MHD generates * Content-Length and Transfer-Encoding itself from the response object, * so an application that also sets them by hand is lying to the library * about its own body: a manual "Transfer-Encoding: chunked" on, say, an * iovec response sends MHD down the chunked path for a response that * has neither a content reader nor a flat buffer, and it aborts in * try_ready_chunked_body(). That is the harness misusing the API * rather than a defect worth reporting, and leaving it in would bury * every real finding under the same false report. MHD_RF_INSANITY_- * HEADER_CONTENT_LENGTH, set through MHD_set_response_options() in * decorate_response(), is the sanctioned way to explore that corner. */ static const char *const hdr_names[] = { "X-Fuzz", "Content-Type", "Cache-Control", "Accept-Ranges", /* "\x01" is split from the rest so that the hex escape stops after one digit instead of swallowing the following "Bad". */ "Connection", "Set-Cookie", "X-\x01" "Bad", "", "Trailer", "Date", "X-Fuzz", "Server", "Location", "ETag", "Vary", "Age" }; static const char *const hdr_values[] = { "1", "text/plain", "no-cache", "bytes", "keep-alive", "a=b", "x\r\nInjected: yes", "", "X-Fuzz", "Thu, 01 Jan 1970 00:00:00 GMT", "\x7f", "mhd", "/", "\"tag\"", "*", "0" }; #define HDR_COUNT (sizeof (hdr_names) / sizeof (hdr_names[0])) /** * State of one MHD_create_response_from_callback() response. Allocated * per response and released through the free callback that MHD invokes * from MHD_destroy_response(). */ struct crc_state { uint64_t total; /**< bytes to produce before end-of-stream */ int calls; /**< how often the reader has been called */ int err_at; /**< fail after this many calls, -1 to never fail */ unsigned int pattern; }; static ssize_t crc_cb (void *cls, uint64_t pos, char *buf, size_t max) { struct crc_state *st = (struct crc_state *) cls; size_t n; size_t i; st->calls++; /* Deliberately reachable: an application content reader is allowed to fail half way through a response body, and how MHD terminates the connection in that case (especially a chunked one that can no longer be framed correctly) is worth exercising. */ if ( (0 <= st->err_at) && (st->calls > st->err_at) ) return MHD_CONTENT_READER_END_WITH_ERROR; if (pos >= st->total) return MHD_CONTENT_READER_END_OF_STREAM; n = (size_t) (st->total - pos); if (n > max) n = max; if (0 == n) return MHD_CONTENT_READER_END_OF_STREAM; for (i = 0; i < n; i++) buf[i] = (char) ('a' + (int) ((pos + i + st->pattern) % 26)); return (ssize_t) n; } static void crc_free (void *cls) { free (cls); } /** * Handler for an upgraded ("101 Switching Protocols") connection. * * @a extra_in holds whatever the client had already pipelined behind * the request, which is attacker-controlled and therefore read here. * * The connection MUST be closed through MHD_upgrade_action(): the * socket belongs to the application from this point on and * MHD_stop_daemon() cannot complete while an upgraded connection is * still outstanding. */ static void upgrade_cb (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) { volatile size_t sink = 0; (void) cls; (void) connection; (void) req_cls; (void) sock; if ( (NULL != extra_in) && (0 != extra_in_size) ) sink += (size_t) (unsigned char) extra_in[extra_in_size - 1]; (void) sink; if (0 != (cfg.upgrade_action & 0x01u)) (void) MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CORK_ON); if (0 != (cfg.upgrade_action & 0x02u)) (void) MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CORK_OFF); (void) MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } /** * A file descriptor holding RESP_BODY_LEN bytes, backed by anonymous * memory so that no filesystem is involved. * * @return -1 if unavailable, in which case the caller falls back to a * buffer response */ static int make_memfd (void) { #ifdef FUZZ_HAVE_MEMFD int fd; fd = memfd_create ("mhd-fuzz", MFD_CLOEXEC); if (0 > fd) return -1; if (RESP_BODY_LEN != (size_t) write (fd, resp_body, RESP_BODY_LEN)) { (void) close (fd); return -1; } return fd; #else return -1; #endif } /** * The read end of a pipe holding RESP_BODY_LEN bytes. The body is far * below the pipe capacity, so the write cannot block. */ static int make_pipe_fd (void) { int pf[2]; if (0 != pipe (pf)) return -1; if (RESP_BODY_LEN != (size_t) write (pf[1], resp_body, RESP_BODY_LEN)) { (void) close (pf[0]); (void) close (pf[1]); return -1; } (void) close (pf[1]); return pf[0]; } /** * Add response headers, footers and option flags as selected by byte 4 * and the header seed in byte 8. * * Footers are only meaningful for a chunked response -- MHD emits them * as trailers after the last chunk -- which is why they are worth * fuzzing together with the callback-based response kinds. */ static void decorate_response (struct MHD_Response *r) { unsigned int i; for (i = 0; i < cfg.resp_nhdr; i++) { unsigned int k = (cfg.hdr_seed + i) % HDR_COUNT; (void) MHD_add_response_header (r, hdr_names[k], hdr_values[k]); } if (cfg.resp_footer) { unsigned int k = (unsigned int) (cfg.hdr_seed + 1u) % HDR_COUNT; (void) MHD_add_response_footer (r, hdr_names[k], hdr_values[k]); } if (cfg.resp_hdr_api) { unsigned int k = cfg.hdr_seed % HDR_COUNT; volatile size_t sink = 0; const char *v; v = MHD_get_response_header (r, hdr_names[k]); if (NULL != v) sink += strlen (v); (void) sink; (void) MHD_get_response_headers (r, &kv_iter, NULL); (void) MHD_del_response_header (r, hdr_names[k], hdr_values[k]); (void) MHD_set_response_options (r, (enum MHD_ResponseFlags) (((cfg.hdr_seed & 0x01) ? MHD_RF_HTTP_VERSION_1_0_RESPONSE : 0) | ((cfg.hdr_seed & 0x02) ? MHD_RF_SEND_KEEP_ALIVE_HEADER : 0) | ((cfg.hdr_seed & 0x04) ? MHD_RF_INSANITY_HEADER_CONTENT_LENGTH : 0) | ((cfg.hdr_seed & 0x08) ? MHD_RF_HEAD_ONLY_RESPONSE : 0)), MHD_RO_END); } } /** * Build the response body for this iteration. * * Every constructor that fails is responsible for nothing: MHD releases * neither the buffer nor the file descriptor when it returns NULL (see * MHD_create_response_from_buffer_with_free_callback_cls() and * MHD_create_response_from_pipe() in response.c), so ownership stays * here and the resource has to be released explicitly. Getting this * backwards would produce double frees that look exactly like MHD bugs. */ static struct MHD_Response * make_response (void) { struct MHD_Response *r = NULL; struct crc_state *st; void *heap; int fd; switch (cfg.resp_kind) { case 0: /* The two responses the harness used before byte 4 existed. Bit 0x20 of byte 1 (cfg.chunked_reply) selects between them and has no other effect, so keeping the pair here is what keeps that bit meaningful. */ if (cfg.chunked_reply) r = MHD_create_response_from_buffer_copy (11, "hello world"); else r = MHD_create_response_from_buffer_static (2, "ok"); break; case 1: r = MHD_create_response_from_buffer_copy (RESP_BODY_LEN, resp_body); break; case 2: r = MHD_create_response_empty (MHD_RF_NONE); break; case 3: r = MHD_create_response_from_buffer (RESP_BODY_LEN, (void *) (intptr_t) resp_body, MHD_RESPMEM_PERSISTENT); break; case 4: heap = malloc (RESP_BODY_LEN); if (NULL == heap) return NULL; memcpy (heap, resp_body, RESP_BODY_LEN); r = MHD_create_response_from_buffer (RESP_BODY_LEN, heap, MHD_RESPMEM_MUST_FREE); if (NULL == r) free (heap); break; case 5: r = MHD_create_response_from_buffer (RESP_BODY_LEN, (void *) (intptr_t) resp_body, MHD_RESPMEM_MUST_COPY); break; case 6: heap = malloc (RESP_BODY_LEN); if (NULL == heap) return NULL; memcpy (heap, resp_body, RESP_BODY_LEN); r = MHD_create_response_from_buffer_with_free_callback (RESP_BODY_LEN, heap, &free); if (NULL == r) free (heap); break; case 7: r = MHD_create_response_from_data (RESP_BODY_LEN, (void *) (intptr_t) resp_body, 0 /* must_free */, 1 /* must_copy */); break; case 8: heap = malloc (RESP_BODY_LEN); if (NULL == heap) return NULL; memcpy (heap, resp_body, RESP_BODY_LEN); r = MHD_create_response_from_data (RESP_BODY_LEN, heap, 1 /* must_free */, 0 /* must_copy */); if (NULL == r) free (heap); break; case 9: case 10: st = (struct crc_state *) calloc (1, sizeof (struct crc_state)); if (NULL == st) return NULL; st->total = (uint64_t) (1u + (cfg.crc_seed & 0x7Fu)); st->pattern = cfg.crc_seed; /* Injecting a reader error is only interesting some of the time; otherwise the body would rarely complete. */ st->err_at = (0 != (cfg.crc_seed & 0x80u)) ? (int) (1u + (cfg.crc_seed & 0x03u)) : -1; r = MHD_create_response_from_callback ( (9 == cfg.resp_kind) ? st->total : MHD_SIZE_UNKNOWN, (size_t) (16u + (cfg.crc_seed & 0x3Fu)), &crc_cb, st, &crc_free); if (NULL == r) free (st); break; case 11: case 12: case 13: fd = make_memfd (); if (0 > fd) { r = MHD_create_response_from_buffer_static (2, "ok"); break; } if (11 == cfg.resp_kind) r = MHD_create_response_from_fd (RESP_BODY_LEN, fd); else if (12 == cfg.resp_kind) /* Parenthesised so that the deprecated *function* is called and not the same-named macro that redirects to the 64 bit variant; reaching the v1 entry point is the whole point here. */ r = (MHD_create_response_from_fd_at_offset) ( RESP_BODY_LEN / 2, fd, (off_t) (RESP_BODY_LEN / 4)); else r = MHD_create_response_from_fd64 ((uint64_t) RESP_BODY_LEN, fd); if (NULL == r) (void) close (fd); break; case 14: fd = make_pipe_fd (); if (0 > fd) { r = MHD_create_response_from_buffer_static (2, "ok"); break; } r = MHD_create_response_from_pipe (fd); if (NULL == r) (void) close (fd); break; case 15: default: { static struct MHD_IoVec iov[3]; /* Static data, so no free callback is needed; MHD copies the array itself (see the documentation of the @a iov parameter). */ iov[0].iov_base = resp_body; iov[0].iov_len = RESP_BODY_LEN / 2; iov[1].iov_base = resp_body + (RESP_BODY_LEN / 2); iov[1].iov_len = RESP_BODY_LEN - (RESP_BODY_LEN / 2); iov[2].iov_base = resp_body; iov[2].iov_len = (size_t) (cfg.crc_seed % (RESP_BODY_LEN + 1)); r = MHD_create_response_from_iovec (iov, (0 != iov[2].iov_len) ? 3u : 2u, NULL, NULL); } break; } if (NULL != r) decorate_response (r); return r; } /* ------------------------------------------------------------------ */ /* Access handler */ /* ------------------------------------------------------------------ */ struct hstate { size_t body_off; struct MHD_PostProcessor *pp; int pp_tried; }; static enum MHD_Result kv_iter (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { volatile size_t sink = 0; (void) cls; (void) kind; if (NULL != key) sink += strlen (key); if (NULL != value) sink += strlen (value); (void) sink; return MHD_YES; } /** * Length-aware counterpart of kv_iter(), for * MHD_get_connection_values_n(). Unlike the NUL-terminated iterator it * is handed explicit sizes, so it reads exactly what MHD says is there * rather than trusting a terminator. */ static enum MHD_Result kv_iter_n (void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { volatile size_t sink = 0; (void) cls; (void) kind; if ( (NULL != key) && (0 != key_size) ) sink += (size_t) (unsigned char) key[key_size - 1]; if ( (NULL != value) && (0 != value_size) ) sink += (size_t) (unsigned char) value[value_size - 1]; (void) sink; return MHD_YES; } static enum MHD_Result post_iter (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { volatile size_t sink = 0; (void) cls; (void) kind; (void) off; if (NULL != key) sink += strlen (key); if (NULL != filename) sink += strlen (filename); if (NULL != content_type) sink += strlen (content_type); if (NULL != transfer_encoding) sink += strlen (transfer_encoding); if ( (NULL != data) && (0 != size) ) sink += (size_t) (unsigned char) data[size - 1]; (void) sink; return MHD_YES; } /** * Check the body MHD hands to the application against the body that * the generator encoded into the request. MHD is allowed to reject * the request at any point, but every byte that it *does* deliver must * be the next expected byte. A mismatch means the framing layer * (Content-Length or chunked transfer coding) got out of sync, which * is exactly the class of bug that enables request smuggling. */ static void oracle_check_body (struct hstate *hs, const char *data, size_t size) { if ( (! oracle_on) || (0 == size) ) return; if ( (hs->body_off + size > expect_body_len) || (0 != memcmp (expect_body + hs->body_off, data, size)) ) fuzz_report_finding ( "request body desync: the bytes MHD delivered to the application " "differ from the body encoded in the generated request " "(chunked/Content-Length framing bug, cf. HTTP request smuggling)"); hs->body_off += size; } /* ------------------------------------------------------------------ */ /* Configuration byte 5: authentication entry points */ /* ------------------------------------------------------------------ */ static const enum MHD_DigestAuthAlgorithm algo1_tbl[] = { MHD_DIGEST_ALG_AUTO, MHD_DIGEST_ALG_MD5, MHD_DIGEST_ALG_SHA256, MHD_DIGEST_ALG_AUTO }; static const enum MHD_DigestAuthAlgo3 algo3_tbl[] = { MHD_DIGEST_AUTH_ALGO3_MD5, MHD_DIGEST_AUTH_ALGO3_SHA256, MHD_DIGEST_AUTH_ALGO3_SHA512_256, MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION, MHD_DIGEST_AUTH_ALGO3_MD5, MHD_DIGEST_AUTH_ALGO3_SHA256 }; /** Outcome of run_digest_check(). */ #define DAUTH_CHALLENGE 0 #define DAUTH_PASSED 1 #define DAUTH_STALE 2 /** * Exercise the digest helpers that take no connection: * MHD_digest_get_hash_size(), MHD_digest_auth_calc_userdigest(), * MHD_digest_auth_calc_userhash() and * MHD_digest_auth_calc_userhash_hex(). * * The output buffers are heap allocations of *exactly* the size that is * passed to MHD, and that size is deliberately varied down to zero. A * correct implementation must reject every buffer that is too small; if * it instead writes the full digest, ASAN's redzone catches it * immediately. This is the shape of the bug fixed in commit 5a73c1ae, * where an over-long userhash overflowed a fixed-size decode buffer. */ static void call_calc_helpers (void) { enum MHD_DigestAuthAlgo3 a = algo3_tbl[cfg.hdr_seed % (sizeof (algo3_tbl) / sizeof (algo3_tbl[0]))]; size_t hs; size_t claim; void *bin; char *hex; hs = MHD_digest_get_hash_size (a); if ( (0 == hs) || (hs > MAX_DIGEST_BIN) ) return; claim = hs - (size_t) (cfg.crc_seed % (unsigned int) (hs + 1u)); bin = malloc (claim); if (NULL != bin) { (void) MHD_digest_auth_calc_userdigest (a, DIGEST_USER, DIGEST_REALM, DIGEST_PASS, bin, claim); (void) MHD_digest_auth_calc_userhash (a, DIGEST_USER, DIGEST_REALM, bin, claim); free (bin); } /* The hex form needs 2*hs+1 bytes; ask for less about half the time. */ claim = (2u * hs + 1u) - (size_t) (cfg.hdr_seed % (unsigned int) (2u * hs + 2u)); hex = (char *) malloc (claim); if (NULL != hex) { (void) MHD_digest_auth_calc_userhash_hex (a, DIGEST_USER, DIGEST_REALM, hex, claim); free (hex); } } /** * Run the digest-authentication entry point selected by byte 5. * * Variant 0 is MHD_digest_auth_check3(), which is the plainest one and * what the all-zero configuration selects. Variants 1-5 are the v1/v2 compatibility * wrappers and the pre-computed-digest forms, which do their own buffer * sizing and are therefore worth driving directly. Variants 6-8 are * the query functions, which parse the client's Authorization header * but return no verdict, so they run *in addition* to check3(). * * @return one of DAUTH_CHALLENGE, DAUTH_PASSED, DAUTH_STALE */ static int run_digest_check (struct MHD_Connection *connection) { unsigned int variant = cfg.dauth_variant; enum MHD_DigestAuthResult dres; uint8_t ud[MAX_DIGEST_BIN]; size_t hs; int r1; volatile size_t sink = 0; switch (variant) { case 1: r1 = MHD_digest_auth_check (connection, DIGEST_REALM, DIGEST_USER, DIGEST_PASS, 0); if (MHD_YES == r1) return DAUTH_PASSED; return (MHD_INVALID_NONCE == r1) ? DAUTH_STALE : DAUTH_CHALLENGE; case 2: r1 = MHD_digest_auth_check2 (connection, DIGEST_REALM, DIGEST_USER, DIGEST_PASS, 0, algo1_tbl[cfg.hdr_seed & 0x03]); if (MHD_YES == r1) return DAUTH_PASSED; return (MHD_INVALID_NONCE == r1) ? DAUTH_STALE : DAUTH_CHALLENGE; case 3: /* MHD_digest_auth_check_digest() is MD5-only by definition. */ if (MHD_YES != MHD_digest_auth_calc_userdigest ( MHD_DIGEST_AUTH_ALGO3_MD5, DIGEST_USER, DIGEST_REALM, DIGEST_PASS, ud, MHD_MD5_DIGEST_SIZE)) break; r1 = MHD_digest_auth_check_digest (connection, DIGEST_REALM, DIGEST_USER, ud, 0); if (MHD_YES == r1) return DAUTH_PASSED; return (MHD_INVALID_NONCE == r1) ? DAUTH_STALE : DAUTH_CHALLENGE; case 4: case 5: { /* The pre-computed-digest entry points are stricter than the password-based ones: the digest and the algorithm have to agree, and naming more than one base hashing algorithm is an MHD_PANIC("API violation") rather than an error return. So the algorithm is chosen first here and the digest, its length and the algorithm argument are all derived from that one choice. MHD_DIGEST_ALG_AUTO is deliberately not used for variant 4: MHD_digest_auth_check_digest2() maps it to MULT_ALGO3_ANY_NON_SESSION, which names three base algorithms and therefore trips that very panic. See README section 6. */ static const enum MHD_DigestAuthAlgo3 digest_algos[] = { MHD_DIGEST_AUTH_ALGO3_MD5, MHD_DIGEST_AUTH_ALGO3_SHA256, MHD_DIGEST_AUTH_ALGO3_SHA512_256, MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION }; enum MHD_DigestAuthAlgo3 a3; if (4 == variant) /* check_digest2() only knows MD5 and SHA-256. */ a3 = (0 != (cfg.hdr_seed & 0x01)) ? MHD_DIGEST_AUTH_ALGO3_SHA256 : MHD_DIGEST_AUTH_ALGO3_MD5; else a3 = digest_algos[cfg.hdr_seed % (sizeof (digest_algos) / sizeof (digest_algos[0]))]; hs = MHD_digest_get_hash_size (a3); if ( (0 == hs) || (hs > sizeof (ud)) || (MHD_YES != MHD_digest_auth_calc_userdigest (a3, DIGEST_USER, DIGEST_REALM, DIGEST_PASS, ud, hs)) ) break; if (4 == variant) { r1 = MHD_digest_auth_check_digest2 (connection, DIGEST_REALM, DIGEST_USER, ud, hs, 0, (MHD_DIGEST_AUTH_ALGO3_SHA256 == a3) ? MHD_DIGEST_ALG_SHA256 : MHD_DIGEST_ALG_MD5); if (MHD_YES == r1) return DAUTH_PASSED; return (MHD_INVALID_NONCE == r1) ? DAUTH_STALE : DAUTH_CHALLENGE; } dres = MHD_digest_auth_check_digest3 (connection, DIGEST_REALM, DIGEST_USER, ud, hs, 0, 0, cfg.qop, /* Exactly one base algorithm. The MULT_ALGO3_* constants are numerically identical to their ALGO3_* counterparts. */ (enum MHD_DigestAuthMultiAlgo3) a3); if (MHD_DAUTH_OK == dres) return DAUTH_PASSED; return (MHD_DAUTH_NONCE_STALE == dres) ? DAUTH_STALE : DAUTH_CHALLENGE; } case 6: { char *u = MHD_digest_auth_get_username (connection); if (NULL != u) { sink += strlen (u); MHD_free (u); } } break; case 7: { struct MHD_DigestAuthUsernameInfo *ui; ui = MHD_digest_auth_get_username3 (connection); if (NULL != ui) { if (NULL != ui->username) sink += ui->username_len; if (NULL != ui->userhash_hex) sink += ui->userhash_hex_len; MHD_free (ui); } } break; case 8: { struct MHD_DigestAuthInfo *ai; ai = MHD_digest_auth_get_request_info3 (connection); if (NULL != ai) { if (NULL != ai->username) sink += ai->username_len; if (NULL != ai->realm) sink += ai->realm_len; if (NULL != ai->opaque) sink += ai->opaque_len; if (NULL != ai->userhash_hex) sink += ai->userhash_hex_len; sink += ai->cnonce_len; sink += (size_t) ai->nc; MHD_free (ai); } } break; default: break; } (void) sink; /* Variant 0, the query variants and every early break end up here. */ dres = MHD_digest_auth_check3 (connection, DIGEST_REALM, DIGEST_USER, DIGEST_PASS, 0 /* daemon default nonce timeout */, 0 /* daemon default max_nc */, cfg.qop, MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION); if (MHD_DAUTH_OK == dres) return DAUTH_PASSED; return (MHD_DAUTH_NONCE_STALE == dres) ? DAUTH_STALE : DAUTH_CHALLENGE; } /** * Send the "authentication required" reply through the variant of the * API selected by byte 5. The v1/v2 forms take a plain response and an * algorithm rather than the qop/algo pair of the v3 form. */ static enum MHD_Result queue_auth_challenge (struct MHD_Connection *connection, int stale) { struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (0, ""); if (NULL == resp) return MHD_NO; switch (cfg.fail_variant) { case 1: ret = MHD_queue_auth_fail_response (connection, DIGEST_REALM, "0123456789abcdef", resp, stale ? MHD_YES : MHD_NO); break; case 2: ret = MHD_queue_auth_fail_response2 (connection, DIGEST_REALM, "0123456789abcdef", resp, stale ? MHD_YES : MHD_NO, algo1_tbl[cfg.hdr_seed & 0x03]); break; case 3: if (0 != (cfg.hdr_seed & 0x01)) ret = MHD_queue_basic_auth_required_response3 (connection, DIGEST_REALM, (0 != (cfg.hdr_seed & 0x02)) ? MHD_YES : MHD_NO, resp); else ret = MHD_queue_basic_auth_fail_response (connection, DIGEST_REALM, resp); break; case 0: default: ret = MHD_queue_auth_required_response3 (connection, DIGEST_REALM, "0123456789abcdef" /* opaque */, "/", resp, stale ? MHD_YES : MHD_NO, cfg.qop, cfg.algo, MHD_YES /* userhash */, MHD_NO); break; } MHD_destroy_response (resp); return ret; } /* ------------------------------------------------------------------ */ /* Configuration byte 6: connection introspection */ /* ------------------------------------------------------------------ */ /** * Call the read-only connection accessors on attacker-supplied header * data. MHD_lookup_connection_value*() run the case-insensitive header * matcher over whatever the client sent, which is exactly the sort of * input the fuzzer is good at producing. */ static void exercise_connection_api (struct MHD_Connection *connection) { volatile size_t sink = 0; if (cfg.conn_lookup) { static const char *const keys[] = { "Host", "Content-Length", "Transfer-Encoding", "Authorization", "Cookie", "", "X-Fuzz", "connection" }; const char *k = keys[cfg.hdr_seed % (sizeof (keys) / sizeof (keys[0]))]; const char *v; const char *vp = NULL; size_t vlen = 0; const char *uri = NULL; size_t ulen = 0; v = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, k); if (NULL != v) sink += strlen (v); if (MHD_YES == MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, k, strlen (k), &vp, &vlen)) sink += vlen; if (MHD_YES == MHD_get_connection_URI_path_n (connection, &uri, &ulen)) sink += ulen; } if (cfg.conn_setvalue) (void) MHD_set_connection_value (connection, MHD_HEADER_KIND, "X-Fuzz-Added", "1"); if (cfg.conn_info) { static const enum MHD_ConnectionInfoType cinfo[] = { MHD_CONNECTION_INFO_CLIENT_ADDRESS, MHD_CONNECTION_INFO_DAEMON, MHD_CONNECTION_INFO_CONNECTION_FD, MHD_CONNECTION_INFO_SOCKET_CONTEXT, MHD_CONNECTION_INFO_CONNECTION_SUSPENDED, MHD_CONNECTION_INFO_CONNECTION_TIMEOUT, MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE, MHD_CONNECTION_INFO_HTTP_STATUS }; static const enum MHD_DaemonInfoType dinfo[] = { MHD_DAEMON_INFO_CURRENT_CONNECTIONS, MHD_DAEMON_INFO_FLAGS, MHD_DAEMON_INFO_LISTEN_FD, MHD_DAEMON_INFO_BIND_PORT }; unsigned int i; for (i = 0; i < sizeof (cinfo) / sizeof (cinfo[0]); i++) if (NULL != MHD_get_connection_info (connection, cinfo[i])) sink++; for (i = 0; i < sizeof (dinfo) / sizeof (dinfo[0]); i++) if ( (NULL != cur_daemon) && (NULL != MHD_get_daemon_info (cur_daemon, dinfo[i])) ) sink++; } if (cfg.conn_option) (void) MHD_set_connection_option (connection, MHD_CONNECTION_OPTION_TIMEOUT, (unsigned int) (cfg.crc_seed & 0x0F)); if (cfg.conn_info) { /* Constant-output accessors. They cannot fail on attacker input, but they are cheap and leaving them uncovered makes the coverage report harder to read. MHD_fini() is deliberately NOT called anywhere: it tears down process-global library state, so a single call would break every later iteration in the same process. */ const char *v = MHD_get_version (); if (NULL != v) sink += strlen (v); sink += (size_t) MHD_get_version_bin (); } (void) sink; } /** * Suspend the connection if byte 7 asks for it. * * Mode 1 suspends and resumes straight away, which exercises both state * transitions without leaving the connection parked. Mode 2 leaves it * suspended and records it in @e pending_resume so that the pump loop * resumes it on its next round; completed_cb() drops the record, so a * connection MHD has finished with is never resumed after the fact, and * the iteration flushes the whole set before stopping the daemon. A * connection left suspended makes MHD_stop_daemon() MHD_PANIC(). */ static void suspend_maybe (struct MHD_Connection *connection) { if ( (0 == cfg.suspend_mode) || tearing_down) return; MHD_suspend_connection (connection); if (1 == cfg.suspend_mode) { MHD_resume_connection (connection); return; } pending_resume_add (connection); } static enum MHD_Result ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct hstate *hs = (struct hstate *) *req_cls; struct MHD_Response *resp; enum MHD_Result ret; volatile size_t sink = 0; const char *conn_hdr = NULL; char conn_lc[128]; conn_lc[0] = '\0'; (void) cls; if (NULL == hs) { hs = (struct hstate *) calloc (1, sizeof (struct hstate)); if (NULL == hs) return MHD_NO; *req_cls = hs; return MHD_YES; } stat_handler_calls++; /* Touch the parsed request line the way a real application would. */ if (NULL != url) sink += strlen (url); if (NULL != method) sink += strlen (method); if (NULL != version) sink += strlen (version); (void) sink; if (0 != *upload_data_size) { stat_body_bytes += (unsigned long) *upload_data_size; oracle_check_body (hs, upload_data, *upload_data_size); if (cfg.do_postproc) { if ( (NULL == hs->pp) && (! hs->pp_tried) ) { hs->pp_tried = 1; hs->pp = MHD_create_post_processor (connection, 1024, &post_iter, NULL); } if (NULL != hs->pp) (void) MHD_post_process (hs->pp, upload_data, *upload_data_size); } *upload_data_size = 0; return MHD_YES; } stat_final_calls++; if (cfg.do_iterate) { const enum MHD_ValueKind kinds = MHD_HEADER_KIND | MHD_GET_ARGUMENT_KIND | MHD_COOKIE_KIND | MHD_FOOTER_KIND; /* Alternate between the NUL-terminated iterator and the length-aware one, which are separate code paths in MHD. */ if (0 != (cfg.hdr_seed & 0x10)) (void) MHD_get_connection_values_n (connection, kinds, &kv_iter_n, NULL); else (void) MHD_get_connection_values (connection, kinds, &kv_iter, NULL); } if (oracle_on && (hs->body_off != expect_body_len) ) fuzz_report_finding ( "request body truncated: MHD completed the request but delivered " "fewer body bytes than the generated request contained"); exercise_connection_api (connection); /* Lower-cased copy of the request's "Connection" header, used by the upgrade check further down. MHD's own token matcher is internal, so a plain case-folded substring test is used here; it only has to be good enough to keep the harness from queueing an upgrade response on a connection that cannot be upgraded. */ if (cfg.allow_upgrade) { conn_hdr = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION); if (NULL != conn_hdr) { size_t i; for (i = 0; (i + 1 < sizeof (conn_lc)) && ('\0' != conn_hdr[i]); i++) conn_lc[i] = (char) (( ('A' <= conn_hdr[i]) && ('Z' >= conn_hdr[i])) ? (conn_hdr[i] - 'A' + 'a') : conn_hdr[i]); conn_lc[i] = '\0'; } } if (cfg.do_basic) { if (cfg.basic_v1) { /* The v1 getter returns two separate malloc()ed strings and is the one that historically had to be freed by hand. */ char *pass = NULL; char *user; user = MHD_basic_auth_get_username_password (connection, &pass); if (NULL != user) sink += strlen (user); if (NULL != pass) sink += strlen (pass); if (NULL != user) MHD_free (user); if (NULL != pass) MHD_free (pass); } else { struct MHD_BasicAuthInfo *bai; bai = MHD_basic_auth_get_username_password3 (connection); if (NULL != bai) { if (NULL != bai->username) sink += bai->username_len; if (NULL != bai->password) sink += bai->password_len; MHD_free (bai); } } } if (cfg.calc_helpers) call_calc_helpers (); if (cfg.do_digest) { int dres = run_digest_check (connection); if (DAUTH_PASSED == dres) stat_auth_ok++; else { stat_challenges++; return queue_auth_challenge (connection, DAUTH_STALE == dres); } } /* Only answer 101 for a request that really is an upgrade request: HTTP/1.1, an "Upgrade" header, and a "Connection" header naming the upgrade token (RFC 9110 section 7.8). This is the check a real application performs, and all three inputs come off the wire, so the path stays fully attacker-driven. It is deliberately NOT enough to predict whether MHD will accept the upgrade, and it is not meant to be: MHD may have decided during header parsing that the connection must close, and does not expose that decision. That used to trip mhd_assert (NULL == r->upgrade_handler || MHD_CONN_MUST_UPGRADE == c->keepalive) in build_header_response() -- finding K7, see README section 6, reproducer corpus/known-findings/K7-upgrade-after-must-close.bin -- and MHD_queue_response() now returns MHD_NO for it instead, which the code below already handles. Do not "fix" this by tightening the condition here: the check above is what an application can actually do, and the harness has to behave like one. */ if (cfg.allow_upgrade && (NULL != version) && (0 == strcmp (version, MHD_HTTP_VERSION_1_1)) && (NULL != MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE)) && (NULL != conn_hdr) && (NULL != strstr (conn_lc, "upgrade")) && (NULL == strstr (conn_lc, "close"))) { resp = MHD_create_response_for_upgrade (&upgrade_cb, NULL); if (NULL != resp) { /* Mandatory: MHD_create_response_for_upgrade() documents that the upgrade headers are the application's job, and MHD_response_execute_upgrade_() asserts that "Upgrade" is present before it hands the socket over. Omitting it is an application-contract violation, not something worth fuzzing. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_UPGRADE, "fuzz-protocol"); decorate_response (resp); ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, resp); MHD_destroy_response (resp); return ret; } } resp = make_response (); if (NULL == resp) return MHD_NO; ret = MHD_queue_response (connection, cfg.error_reply ? MHD_HTTP_FORBIDDEN : MHD_HTTP_OK, resp); MHD_destroy_response (resp); /* Only after a response was actually accepted. Returning MHD_NO tells MHD to terminate the connection, and terminating a connection that this callback has just suspended trips mhd_assert (! connection->suspended) in MHD_connection_close_(). That is the harness contradicting itself, not an MHD defect: the two requests are mutually exclusive by construction. (MHD_NO is reachable here for real -- MHD_queue_response() rejects, for instance, a response carrying MHD_RF_HEAD_ONLY_RESPONSE on a GET, which decorate_response() can set.) */ if (MHD_YES == ret) suspend_maybe (connection); return ret; } static void completed_cb (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct hstate *hs = (struct hstate *) *req_cls; (void) cls; (void) toe; /* MHD is done with this connection, so the deferred resume of suspend mode 2 must not fire for it any more. */ pending_resume_drop (connection); if (NULL == hs) return; if (NULL != hs->pp) (void) MHD_destroy_post_processor (hs->pp); free (hs); *req_cls = NULL; } static void panic_cb (void *cls, const char *file, unsigned int line, const char *reason) { char msg[512]; (void) cls; (void) snprintf (msg, sizeof (msg), "MHD_PANIC() reached from network input at %s:%u: %s", (NULL != file) ? file : "?", line, (NULL != reason) ? reason : "?"); fuzz_report_finding (msg); } /* ------------------------------------------------------------------ */ /* Driving the daemon */ /* ------------------------------------------------------------------ */ /** * Read whatever the daemon has produced so far and look for a fresh * Digest-Auth nonce in it. */ static void drain_and_harvest (int sock) { for (;;) { ssize_t n; char tmp[4096]; n = recv (sock, tmp, sizeof (tmp), MSG_DONTWAIT); if (0 >= n) break; if (resp_len + (size_t) n < RESP_BUF_SIZE) { memcpy (resp_buf + resp_len, tmp, (size_t) n); resp_len += (size_t) n; resp_buf[resp_len] = '\0'; } } if (0 != resp_len) { const char *p = resp_buf; while (NULL != (p = strstr (p, "nonce=\""))) { const char *s = p + 7; const char *e = strchr (s, '"'); p = s; if (NULL == e) break; if ((size_t) (e - s) < sizeof (nonce_val)) { memcpy (nonce_val, s, (size_t) (e - s)); nonce_len = (size_t) (e - s); nonce_val[nonce_len] = '\0'; } } } } /** * Advance the daemon by one cycle, through the event-loop API selected * by byte 6 of the input. * * Mode 0 is MHD_run(), which is what the harness used before the * extension and which does the descriptor bookkeeping internally. * Modes 1-3 drive the daemon the way an application with its own event * loop does: MHD_get_fdset*() to collect the descriptors, select(), then * MHD_run_from_select*(). That is the most common production * integration and none of it was reachable before. * * The select() timeout is always zero. The harness is single threaded * and whatever the daemon is waiting for has already been written into * the socketpair, so blocking would only burn wall clock; select() is * called purely to populate the ready sets. */ static void run_once (struct MHD_Daemon *d) { fd_set rs; fd_set ws; fd_set es; MHD_socket max_fd = MHD_INVALID_SOCKET; struct timeval tv; if (0 == cfg.loop_mode) { (void) MHD_run (d); return; } FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (1 == cfg.loop_mode) { /* Parenthesised so that the real v1 function is called: microhttpd.h also defines MHD_get_fdset as a macro that forwards to MHD_get_fdset2 with FD_SETSIZE, so the unparenthesised name would never reach the v1 entry point at all. Same trick for MHD_run_from_select below. */ if (MHD_YES != (MHD_get_fdset) (d, &rs, &ws, &es, &max_fd)) { (void) MHD_run (d); return; } } else { if (MHD_YES != MHD_get_fdset2 (d, &rs, &ws, &es, &max_fd, (unsigned int) FD_SETSIZE)) { (void) MHD_run (d); return; } } if (cfg.use_timeouts) { MHD_UNSIGNED_LONG_LONG tl = 0; uint64_t t64 = 0; volatile int64_t sink; (void) MHD_get_timeout (d, &tl); (void) MHD_get_timeout64 (d, &t64); sink = MHD_get_timeout64s (d); sink += (int64_t) MHD_get_timeout_i (d); (void) sink; } tv.tv_sec = 0; tv.tv_usec = 0; if (MHD_INVALID_SOCKET != max_fd) (void) select ((int) max_fd + 1, &rs, &ws, &es, &tv); if (1 == cfg.loop_mode) (void) (MHD_run_from_select) (d, &rs, &ws, &es); else (void) MHD_run_from_select2 (d, &rs, &ws, &es, (unsigned int) FD_SETSIZE); } static void pump (struct MHD_Daemon *d, int sock, unsigned int rounds) { unsigned int i; for (i = 0; i < rounds; i++) { /* Deferred resume of suspend mode 2. Each slot is cleared before its connection is resumed, which keeps this correct even if the resume makes MHD complete (and forget) the connection, or run the handler again so that it suspends the same one anew. */ (void) pending_resume_flush (); run_once (d); drain_and_harvest (sock); } } /** * Copy @a in to @a out, expanding every occurrence of the ASCII token * "%%NONCE%%" to the harvested nonce. * * @return number of bytes written to @a out */ static size_t expand_nonce (const uint8_t *in, size_t in_len, uint8_t *out, size_t out_cap) { static const char tok[] = "%%NONCE%%"; const size_t tok_len = sizeof (tok) - 1; size_t i = 0; size_t o = 0; while (i < in_len) { if ( (i + tok_len <= in_len) && (0 == memcmp (in + i, tok, tok_len)) ) { if (o + nonce_len > out_cap) break; memcpy (out + o, nonce_val, nonce_len); o += nonce_len; i += tok_len; continue; } if (o >= out_cap) break; out[o++] = in[i++]; } return o; } static void send_all (struct MHD_Daemon *d, int sock, const uint8_t *data, size_t len) { size_t off = 0; unsigned int stall = 0; while ( (off < len) && (stall < 64) ) { ssize_t s = send (sock, data + off, len - off, MSG_DONTWAIT); if (0 < s) { off += (size_t) s; stall = 0; continue; } stall++; pump (d, sock, 2); if ( (0 > s) && (EAGAIN != errno) && (EWOULDBLOCK != errno) && (EINTR != errno) ) break; } } static int new_connection (struct MHD_Daemon *d, int *sock) { int sv[2]; struct sockaddr_in sa; if (0 != socketpair (AF_UNIX, SOCK_STREAM, 0, sv)) return -1; memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (44444); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (MHD_YES != MHD_add_connection (d, (MHD_socket) sv[1], (const struct sockaddr *) &sa, (socklen_t) sizeof (sa))) { /* MHD has already closed sv[1] in that case */ (void) close (sv[0]); return -1; } *sock = sv[0]; return 0; } static void close_connection (struct MHD_Daemon *d, int *sock) { if (0 > *sock) return; (void) shutdown (*sock, SHUT_WR); pump (d, *sock, 4); (void) close (*sock); *sock = -1; } /* ------------------------------------------------------------------ */ /* The fuzz target */ /* ------------------------------------------------------------------ */ int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { struct MHD_Daemon *d; struct MHD_OptionItem opts[8]; unsigned int nopt = 0; unsigned int flags; int sock = -1; size_t pos; unsigned int nseg = 0; unsigned int nconn = 1; static uint8_t xbuf[FUZZ_MAX_INPUT + 4096]; /* Must happen before the first write() into the socketpair. The built-in driver also does this from fuzz_install_handlers(), but that is compiled out under -DFUZZ_NO_MAIN, which is exactly the build every external fuzzing engine uses; the call is idempotent, so doing it from both places is harmless. See fuzz_ignore_sigpipe() in fuzz_common.h for why the process dies without it. */ fuzz_ignore_sigpipe (); /* The ten configuration bytes are mandatory. Anything shorter has no segment stream either, so there is nothing to fuzz. */ if (size < 10) return 0; nonce_len = 0; nonce_val[0] = '\0'; resp_len = 0; resp_buf[0] = '\0'; memset (&cfg, 0, sizeof (cfg)); cfg.mem_limit = mem_limit_tbl[data[0] % (sizeof (mem_limit_tbl) / sizeof (mem_limit_tbl[0]))]; cfg.do_digest = (0 != (data[1] & 0x01)); cfg.do_basic = (0 != (data[1] & 0x02)); cfg.do_postproc = (0 != (data[1] & 0x04)); cfg.do_iterate = (0 != (data[1] & 0x08)); /* Bits 0x10 and 0x80 of byte 1 are unused. 0x10 used to gate the configuration bytes 4-9 back when they were optional; it is left free rather than reassigned so that the meaning of the corpus files written while it was a gate does not silently change. */ cfg.chunked_reply = (0 != (data[1] & 0x20)); cfg.error_reply = (0 != (data[1] & 0x40)); if (! min_mem_limit_read) { const char *e = getenv ("MHD_FUZZ_MIN_MEM_LIMIT"); min_mem_limit_read = 1; if (NULL != e) min_mem_limit = (size_t) strtoul (e, NULL, 10); } if ( (0 != cfg.mem_limit) && (cfg.mem_limit < min_mem_limit) ) cfg.mem_limit = min_mem_limit; if (! min_discipline_read) { const char *e = getenv ("MHD_FUZZ_MIN_DISCIPLINE"); min_discipline_read = 1; if (NULL != e) min_discipline = atoi (e); } cfg.discipline = discipline_tbl[(data[2] & 0x0F) % (sizeof (discipline_tbl) / sizeof (discipline_tbl[0]))]; if (cfg.discipline < min_discipline) cfg.discipline = min_discipline; cfg.insanity = (unsigned int) MHD_DSC_SANE; cfg.algo = algo_tbl[data[3] & 0x03]; cfg.qop = (0 != (data[3] & 0x04)) ? MHD_DIGEST_AUTH_MULT_QOP_AUTH : MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT; cfg.nonce_nc_size = nnc_tbl[(data[3] >> 4) & 0x03]; cfg.resp_kind = (unsigned int) (data[4] & 0x0F); cfg.resp_nhdr = (unsigned int) ((data[4] >> 4) & 0x03); cfg.resp_footer = (0 != (data[4] & 0x40)); cfg.resp_hdr_api = (0 != (data[4] & 0x80)); cfg.dauth_variant = (unsigned int) (data[5] & 0x0F) % DAUTH_VARIANT_COUNT; cfg.fail_variant = (unsigned int) ((data[5] >> 4) & 0x03); cfg.basic_v1 = (0 != (data[5] & 0x40)); cfg.calc_helpers = (0 != (data[5] & 0x80)); cfg.loop_mode = (unsigned int) (data[6] & 0x03); cfg.use_timeouts = (0 != (data[6] & 0x04)); cfg.conn_lookup = (0 != (data[6] & 0x08)); cfg.conn_setvalue = (0 != (data[6] & 0x10)); cfg.conn_info = (0 != (data[6] & 0x20)); cfg.conn_option = (0 != (data[6] & 0x40)); cfg.quiesce = (0 != (data[6] & 0x80)); /* Only modes 0-2 exist; 3 folds onto the immediate-resume mode rather than being a fourth, unimplemented behaviour. */ cfg.suspend_mode = (unsigned int) (data[7] & 0x03); if (3 == cfg.suspend_mode) cfg.suspend_mode = 1; cfg.allow_upgrade = (0 != (data[7] & 0x04)) && (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_UPGRADE)); cfg.upgrade_action = (unsigned int) ((data[7] >> 3) & 0x03); cfg.hdr_seed = data[8]; cfg.crc_seed = data[9]; oracle_on = 0; expect_body_len = 0; /* Must never carry over: the connections these pointed at belonged to the previous iteration's daemon and are long gone. */ memset (pending_resume, 0, sizeof (pending_resume)); tearing_down = 0; if (0 != cfg.mem_limit) { opts[nopt].option = MHD_OPTION_CONNECTION_MEMORY_LIMIT; opts[nopt].value = (intptr_t) cfg.mem_limit; opts[nopt].ptr_value = NULL; nopt++; } opts[nopt].option = MHD_OPTION_CLIENT_DISCIPLINE_LVL; opts[nopt].value = (intptr_t) cfg.discipline; opts[nopt].ptr_value = NULL; nopt++; opts[nopt].option = MHD_OPTION_SERVER_INSANITY; opts[nopt].value = (intptr_t) cfg.insanity; opts[nopt].ptr_value = NULL; nopt++; opts[nopt].option = MHD_OPTION_NONCE_NC_SIZE; opts[nopt].value = (intptr_t) cfg.nonce_nc_size; opts[nopt].ptr_value = NULL; nopt++; opts[nopt].option = MHD_OPTION_DIGEST_AUTH_RANDOM; opts[nopt].value = (intptr_t) sizeof (digest_rnd); opts[nopt].ptr_value = (void *) (intptr_t) digest_rnd; nopt++; opts[nopt].option = MHD_OPTION_END; opts[nopt].value = 0; opts[nopt].ptr_value = NULL; flags = MHD_USE_NO_LISTEN_SOCKET; if (fuzz_verbose) flags |= MHD_USE_ERROR_LOG; if (0 != cfg.suspend_mode) flags |= MHD_ALLOW_SUSPEND_RESUME; if (cfg.allow_upgrade) flags |= MHD_ALLOW_UPGRADE; MHD_set_panic_func (&panic_cb, NULL); d = MHD_start_daemon (flags, 0, NULL, NULL, &ahc, NULL, MHD_OPTION_ARRAY, opts, /* passed through the varargs rather than through the option array: storing a function pointer in the array's intptr_t member is not strictly conforming C */ MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (NULL == d) return 0; cur_daemon = d; stat_daemons++; if (! stats_registered) { stats_registered = 1; (void) atexit (&print_stats); } if (0 != new_connection (d, &sock)) { MHD_stop_daemon (d); cur_daemon = NULL; return 0; } pos = 10u; while ( (pos + 2 <= size) && (nseg < MAX_SEGMENTS) ) { unsigned int hdr = (unsigned int) data[pos] | ((unsigned int) data[pos + 1] << 8); unsigned int op = hdr >> 14; size_t slen = (size_t) (hdr & 0x3FFF); size_t elen; pos += 2; nseg++; if (slen > size - pos) slen = size - pos; if (1 == op) { /* Ground-truth declaration, not wire data. */ if (fuzz_pristine && (slen <= MAX_EXPECT_BODY)) { memcpy (expect_body, data + pos, slen); expect_body_len = slen; oracle_on = 1; } pos += slen; continue; } if ( (3 == op) && (nconn < MAX_CONNECTIONS) ) { close_connection (d, &sock); if (0 != new_connection (d, &sock)) break; nconn++; } elen = expand_nonce (data + pos, slen, xbuf, sizeof (xbuf)); pos += slen; if (0 != elen) send_all (d, sock, xbuf, elen); pump (d, sock, (2 == op) ? 12u : 3u); if (0 == slen) pump (d, sock, 4); } close_connection (d, &sock); pump (d, sock, 4); /* A connection left suspended makes MHD_stop_daemon() MHD_PANIC() ("called while we have suspended connections"), and MHD_resume_connection() alone is not enough: it only raises a flag, and the connection is taken off the daemon's suspended list by MHD_run(). So flush and run until nothing is parked any more. tearing_down stops the handler from parking anything new, which is what bounds this loop; the cap is only a backstop. */ tearing_down = 1; { unsigned int i; for (i = 0; i < MAX_CONNECTIONS + 2u; i++) { if (! pending_resume_flush ()) break; (void) MHD_run (d); } } if (cfg.quiesce) (void) MHD_quiesce_daemon (d); MHD_stop_daemon (d); cur_daemon = NULL; return 0; } /* ------------------------------------------------------------------ */ /* Structure-aware HTTP request generator */ /* ------------------------------------------------------------------ */ struct sbuf { uint8_t *p; size_t len; size_t cap; }; static void sb_raw (struct sbuf *b, const void *v, size_t n) { if (b->len + n > b->cap) n = b->cap - b->len; memcpy (b->p + b->len, v, n); b->len += n; } static void sb_str (struct sbuf *b, const char *s) { sb_raw (b, s, strlen (s)); } static void sb_u64 (struct sbuf *b, uint64_t v, int hex, unsigned int min_digits) { char tmp[32]; unsigned int n = 0; do { unsigned int dig = (unsigned int) (v % (hex ? 16u : 10u)); tmp[n++] = (char) ((dig < 10) ? ('0' + dig) : ('a' + dig - 10)); v /= (hex ? 16u : 10u); } while ( (0 != v) && (n < sizeof (tmp)) ); while ( (n < min_digits) && (n < sizeof (tmp)) ) tmp[n++] = '0'; while (0 != n) { char c = tmp[--n]; sb_raw (b, &c, 1); } } static const char *const gen_methods[] = { "GET", "POST", "PUT", "HEAD", "DELETE", "OPTIONS", "TRACE", "PATCH", "CONNECT", "BREW", "get", "M-SEARCH", "\tGET", "GET " }; static const char *const gen_versions[] = { "HTTP/1.1", "HTTP/1.0", "HTTP/1.1", "HTTP/1.1", "HTTP/0.9", "HTTP/1.2", "HTTP/2.0", "http/1.1", "HTTP/1.", "HTTP/11" }; static const char *const gen_targets[] = { "/", "/a", "/a/b/c", "/a?x=1", "/a?x=1&y=2", "/?novalue", "/?a=1&b", "/?a&b&c", "/%41%42", "/a%00b", "/%zz", "/a?%41=%42", "*", "http://example.org/a", "/a?x=1&novalue", "/..%2f..%2fetc", "/a?=", "/a?&", "/very/long/path/that/keeps/going/and/going/and/going" }; static const char *const gen_hdr_names[] = { "Host", "Accept", "User-Agent", "Connection", "Cookie", "Content-Type", "Expect", "TE", "Trailer", "X-Custom", "Referer", "Accept-Encoding", "content-length", "transfer-encoding", "X-A-Very-Long-Header-Name-Indeed" }; static const char *const gen_hdr_values[] = { "example.org", "*/*", "fuzz/1.0", "keep-alive", "close", "a=1; b=2; c", "100-continue", "trailers", "X-Trail", "value", "", " ", "\ttabbed", "a, b, c", "chunked", "identity, chunked" }; /** Deliberately includes tokens MHD does not know: bug #1 lives here. */ static const char *const gen_algos[] = { "MD5", "SHA-256", "SHA-512-256", "MD5-sess", "SHA-256-sess", "SHA-512-256-sess", "sha-256", "SHA256", "BOGUS", "", "\"SHA-256\"", "MD5 ", "SHA-1", "xyzzy", "SHA-512", "\"BOGUS\"", "0" }; static const char *const gen_ctypes[] = { "application/x-www-form-urlencoded", "multipart/form-data; boundary=--abc", "multipart/form-data; boundary=\"XY\"", "multipart/form-data", "text/plain" }; /** * Append a random query string, optionally ending in an argument * without '=' (which is the shape needed for the read-buffer shift-back * bug). */ static void gen_query (struct fuzz_rng *rng, struct sbuf *b, int force_trailing_novalue) { unsigned int n = fuzz_below (rng, 4); unsigned int i; if ( (0 == n) && (! force_trailing_novalue) ) return; sb_str (b, "?"); for (i = 0; i < n; i++) { if (0 != i) sb_str (b, "&"); sb_str (b, "k"); sb_u64 (b, i, 0, 1); if (! fuzz_chance (rng, 3)) { sb_str (b, "="); sb_str (b, fuzz_chance (rng, 4) ? "%41%42" : "v"); } } if (force_trailing_novalue) { if (0 != n) sb_str (b, "&"); sb_str (b, "novalue"); } } static void gen_headers (struct fuzz_rng *rng, struct sbuf *b, unsigned int n) { unsigned int i; for (i = 0; i < n; i++) { sb_str (b, gen_hdr_names[fuzz_below (rng, (uint32_t) (sizeof (gen_hdr_names) / sizeof (char *)))]); sb_str (b, fuzz_chance (rng, 8) ? " :" : ":"); if (! fuzz_chance (rng, 6)) sb_str (b, " "); sb_str (b, gen_hdr_values[fuzz_below (rng, (uint32_t) (sizeof (gen_hdr_values) / sizeof (char *)))]); if (fuzz_chance (rng, 12)) sb_str (b, "\r\n\tfolded-continuation"); if (fuzz_chance (rng, 20)) sb_str (b, "\n"); /* bare LF */ else if (fuzz_chance (rng, 25)) sb_str (b, "\r"); /* bare CR */ else sb_str (b, "\r\n"); } } /** * Emit a chunked body. When @a oracle is non-zero the body is * strictly RFC 9112 conformant and the decoded payload is recorded in * #expect_body, so that the harness can verify what MHD hands to the * application. Chunk extensions are emitted frequently on purpose. */ static void gen_chunked_body (struct fuzz_rng *rng, struct sbuf *b, int oracle) { unsigned int nchunks = 1 + fuzz_below (rng, 4); unsigned int i; if (oracle) expect_body_len = 0; for (i = 0; i < nchunks; i++) { unsigned int clen = 1 + fuzz_below (rng, 24); unsigned int j; sb_u64 (b, clen, 1, fuzz_chance (rng, 4) ? 4 : 1); /* chunk extension -- the parsing of the terminating CRLF of this very line was broken (bug #3) */ if (! fuzz_chance (rng, 2)) { switch (fuzz_below (rng, 5)) { case 0: sb_str (b, ";ext"); break; case 1: sb_str (b, ";ext=val"); break; case 2: sb_str (b, ";ext=\"quoted value\""); break; case 3: sb_str (b, ";a=1;b=2;c"); break; default: sb_str (b, ";x=\"a;b\""); break; } } sb_str (b, "\r\n"); for (j = 0; j < clen; j++) { char c = (char) ('A' + ((i * 7 + j) % 26)); sb_raw (b, &c, 1); if (oracle && (expect_body_len < MAX_EXPECT_BODY)) expect_body[expect_body_len++] = (uint8_t) c; } sb_str (b, "\r\n"); } sb_str (b, "0"); if (fuzz_chance (rng, 4)) sb_str (b, ";final=\"x\""); sb_str (b, "\r\n"); if (fuzz_chance (rng, 3)) sb_str (b, "X-Trailer: value\r\n"); sb_str (b, "\r\n"); } static void gen_digest_header (struct fuzz_rng *rng, struct sbuf *b, const char *uri, int use_nonce_token, int overlong_response, int prefer_valid) { unsigned int nresp; unsigned int i; sb_str (b, "Authorization: Digest "); sb_str (b, "username=\""); if (fuzz_chance (rng, prefer_valid ? 20 : 6)) { /* userhash notation: a long hex string is accepted here too */ unsigned int n = 2 * (16 + fuzz_below (rng, 48)); for (i = 0; i < n; i++) sb_str (b, "a"); } else sb_str (b, DIGEST_USER); sb_str (b, "\", "); if (fuzz_chance (rng, prefer_valid ? 25 : 8)) sb_str (b, "userhash=true, "); sb_str (b, "realm=\""); sb_str (b, fuzz_chance (rng, prefer_valid ? 25 : 8) ? "OtherRealm" : DIGEST_REALM); sb_str (b, "\", nonce=\""); if (use_nonce_token) sb_str (b, "%%NONCE%%"); else { unsigned int n = 8 + fuzz_below (rng, 80); for (i = 0; i < n; i++) sb_str (b, "0"); } sb_str (b, "\", uri=\""); sb_str (b, uri); sb_str (b, "\", qop="); sb_str (b, fuzz_chance (rng, prefer_valid ? 25 : 8) ? "auth-int" : "auth"); sb_str (b, ", nc="); sb_u64 (b, 1 + fuzz_below (rng, 3), 1, 8); sb_str (b, ", cnonce=\"deadbeef\", algorithm="); if (prefer_valid && (! fuzz_chance (rng, 5))) sb_str (b, "SHA-256"); /* must match the algorithm of the challenge */ else sb_str (b, gen_algos[fuzz_below (rng, (uint32_t) (sizeof (gen_algos) / sizeof (char *)))]); sb_str (b, ", opaque=\"0123456789abcdef\", response=\""); if (overlong_response) nresp = 66 + 2 * fuzz_below (rng, 32); /* 66 .. 128 hex digits */ else nresp = 2 * (1 + fuzz_below (rng, 66)); for (i = 0; i < nresp; i++) { char c = "0123456789abcdef"[fuzz_below (rng, 16)]; sb_raw (b, &c, 1); } sb_str (b, "\"\r\n"); } enum gen_shape { SHAPE_PLAIN = 0, SHAPE_NOHDR_QARG, SHAPE_CL_BODY, SHAPE_CHUNKED, SHAPE_DIGEST_SIMPLE, SHAPE_DIGEST_REPLAY, SHAPE_BASIC, SHAPE_POST_FORM, SHAPE_WEIRD, SHAPE_COUNT }; /** * Build one HTTP request into @a b. * * @return non-zero if the request is exactly reproducible, i.e. the * #expect_body oracle may be used */ static int gen_one_request (struct fuzz_rng *rng, struct sbuf *b, enum gen_shape shape, int second_of_pair) { switch (shape) { case SHAPE_NOHDR_QARG: /* No header lines at all + a trailing query argument without '='; combined with a small connection memory pool this is the shape that reaches the read-buffer "shift back" computation. */ sb_str (b, "GET /"); gen_query (rng, b, 1); sb_str (b, " "); sb_str (b, fuzz_chance (rng, 2) ? "HTTP/1.0" : "HTTP/1.1"); sb_str (b, "\r\n\r\n"); return 0; case SHAPE_CL_BODY: { unsigned int blen = fuzz_below (rng, 64); unsigned int i; sb_str (b, "POST /a HTTP/1.1\r\nHost: x\r\nContent-Length: "); sb_u64 (b, blen, 0, 1); sb_str (b, "\r\n\r\n"); expect_body_len = 0; for (i = 0; i < blen; i++) { char c = (char) ('a' + (i % 26)); sb_raw (b, &c, 1); if (expect_body_len < MAX_EXPECT_BODY) expect_body[expect_body_len++] = (uint8_t) c; } return 1; } case SHAPE_CHUNKED: sb_str (b, "POST /a HTTP/1.1\r\nHost: x\r\n" "Transfer-Encoding: chunked\r\n\r\n"); gen_chunked_body (rng, b, 1); return 1; case SHAPE_DIGEST_SIMPLE: sb_str (b, "GET /a HTTP/1.1\r\nHost: x\r\n"); gen_digest_header (rng, b, "/a", 0, fuzz_chance (rng, 2), 0); sb_str (b, "\r\n"); return 0; case SHAPE_DIGEST_REPLAY: if (! second_of_pair) sb_str (b, "GET /a HTTP/1.1\r\nHost: x\r\n\r\n"); else { sb_str (b, "GET /a HTTP/1.1\r\nHost: x\r\n"); gen_digest_header (rng, b, "/a", 1, 1, 1); sb_str (b, "\r\n"); } return 0; case SHAPE_BASIC: sb_str (b, "GET /a HTTP/1.1\r\nHost: x\r\nAuthorization: Basic "); { unsigned int n = fuzz_below (rng, 40); unsigned int i; for (i = 0; i < n; i++) { char c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" [fuzz_below (rng, 65)]; sb_raw (b, &c, 1); } } sb_str (b, "\r\n\r\n"); return 0; case SHAPE_POST_FORM: { const char *ct = gen_ctypes[fuzz_below (rng, (uint32_t) (sizeof (gen_ctypes) / sizeof (char *)))]; sb_str (b, "POST /a HTTP/1.1\r\nHost: x\r\nContent-Type: "); sb_str (b, ct); sb_str (b, "\r\nTransfer-Encoding: chunked\r\n\r\n"); gen_chunked_body (rng, b, 0); return 0; } case SHAPE_WEIRD: sb_str (b, gen_methods[fuzz_below (rng, (uint32_t) (sizeof (gen_methods) / sizeof (char *)))]); sb_str (b, " "); sb_str (b, gen_targets[fuzz_below (rng, (uint32_t) (sizeof (gen_targets) / sizeof (char *)))]); sb_str (b, " "); sb_str (b, gen_versions[fuzz_below (rng, (uint32_t) (sizeof (gen_versions) / sizeof (char *)))]); sb_str (b, fuzz_chance (rng, 8) ? "\n" : "\r\n"); gen_headers (rng, b, fuzz_below (rng, 6)); sb_str (b, "\r\n"); return 0; case SHAPE_PLAIN: case SHAPE_COUNT: default: sb_str (b, gen_methods[fuzz_below (rng, 3)]); sb_str (b, " /"); gen_query (rng, b, fuzz_chance (rng, 3)); sb_str (b, " HTTP/1.1\r\n"); gen_headers (rng, b, fuzz_below (rng, 4)); sb_str (b, "\r\n"); return 0; } } /** * Serialise @a body into the segment format understood by * LLVMFuzzerTestOneInput(), starting at @a out[*out_len]. */ static void emit_segments (struct fuzz_rng *rng, struct sbuf *out, const uint8_t *body, size_t body_len, int new_conn_first) { size_t off = 0; int first = 1; while (off < body_len) { size_t chunk; unsigned int op; uint8_t hdr[2]; unsigned int hv; switch (fuzz_below (rng, 6)) { case 0: chunk = 1; break; case 1: chunk = 2 + fuzz_below (rng, 6); break; case 2: chunk = 8 + fuzz_below (rng, 40); break; default: chunk = body_len - off; break; } if (chunk > body_len - off) chunk = body_len - off; if (chunk > 0x3FFF) chunk = 0x3FFF; op = (first && new_conn_first) ? 3u : (fuzz_chance (rng, 4) ? 2u : 0u); hv = (op << 14) | (unsigned int) chunk; hdr[0] = (uint8_t) (hv & 0xFF); hdr[1] = (uint8_t) (hv >> 8); if (out->len + 2 + chunk > out->cap) return; sb_raw (out, hdr, 2); sb_raw (out, body + off, chunk); off += chunk; first = 0; } } static size_t fuzz_generate (struct fuzz_rng *rng, uint8_t *buf, size_t cap) { struct sbuf out; uint8_t req[GEN_BUF_SIZE]; struct sbuf rb; enum gen_shape shape; uint8_t cfg_bytes[4]; int oracle; unsigned int nreq; unsigned int i; expect_body_len = 0; out.p = buf; out.len = 0; out.cap = cap; if (! forced_shape_read) { const char *e = getenv ("MHD_FUZZ_SHAPE"); forced_shape_read = 1; if (NULL != e) forced_shape = atoi (e); } if (0 <= forced_shape) shape = (enum gen_shape) (forced_shape % (int) SHAPE_COUNT); else shape = (enum gen_shape) fuzz_below (rng, (uint32_t) SHAPE_COUNT); /* --- configuration bytes --- */ cfg_bytes[0] = fuzz_byte (rng); cfg_bytes[1] = fuzz_byte (rng); cfg_bytes[2] = fuzz_byte (rng); cfg_bytes[3] = fuzz_byte (rng); switch (shape) { case SHAPE_NOHDR_QARG: /* small connection memory pool: indices 1..9 of mem_limit_tbl */ cfg_bytes[0] = (uint8_t) (1 + fuzz_below (rng, 9)); break; case SHAPE_DIGEST_SIMPLE: case SHAPE_DIGEST_REPLAY: cfg_bytes[0] = (uint8_t) (fuzz_chance (rng, 2) ? 0 : 12); cfg_bytes[1] = (uint8_t) ((cfg_bytes[1] | 0x01u) & ~0x04u); /* SHA-256 challenge: 32 byte digest -> 128 hex chars pass the 'response' length check while hash1_bin[] is only 32 bytes */ cfg_bytes[3] = (uint8_t) ((cfg_bytes[3] & 0xF0u) | 0x00u); break; case SHAPE_POST_FORM: cfg_bytes[1] |= 0x04u; break; case SHAPE_CHUNKED: case SHAPE_CL_BODY: cfg_bytes[1] &= (uint8_t) ~0x04u; /* keep the body oracle clean */ break; default: break; } cfg_bytes[1] |= 0x08u; /* always iterate the values */ sb_raw (&out, cfg_bytes, 4); nreq = (SHAPE_DIGEST_REPLAY == shape) ? 2u : (1u + (fuzz_chance (rng, 6) ? 1u : 0u)); oracle = 0; for (i = 0; i < nreq; i++) { rb.p = req; rb.len = 0; rb.cap = sizeof (req); oracle = gen_one_request (rng, &rb, shape, (int) i); if (oracle && (1 == nreq) && (expect_body_len <= MAX_EXPECT_BODY)) { /* Declare the ground truth for the body oracle (op 1). */ unsigned int hv = (1u << 14) | (unsigned int) expect_body_len; uint8_t hdr[2]; hdr[0] = (uint8_t) (hv & 0xFF); hdr[1] = (uint8_t) (hv >> 8); sb_raw (&out, hdr, 2); sb_raw (&out, expect_body, expect_body_len); } emit_segments (rng, &out, req, rb.len, (0 != i) || fuzz_chance (rng, 8)); } (void) oracle; return out.len; } /* ------------------------------------------------------------------ */ /* Built-in seed corpus */ /* ------------------------------------------------------------------ */ /** * The built-in seed corpus is described symbolically and rendered into * the wire format at run time, so that segment lengths never have to be * spelled out by hand. */ struct seed_part { unsigned int op; /**< 0 send, 1 expected body, 3 new conn */ const char *txt; /**< NUL terminated payload */ }; struct seed_def { const char *name; unsigned char cfg[4]; struct seed_part parts[4]; /* Configuration bytes 4-9. Declared after @e parts so that a seed which only cares about the wire data can leave the member out of its brace initialiser and get the all-zero (plainest) setting. */ unsigned char ext[6]; }; #define P_END { 0, NULL } static const struct seed_def seeds[] = { /* There is deliberately no bare "GET / HTTP/1.1" seed: every seed below opens with a request at least as simple, so a plain one adds no coverage of its own (libFuzzer -merge=1 drops it). */ { "content-length-body", { 0x00, 0x08, 0x03, 0x00 }, { { 1, "hello" }, { 0, "POST /a HTTP/1.1\r\nHost: x\r\nContent-Length: 5\r\n\r\nhello" }, P_END, P_END } }, /* chunk extensions: the terminating CRLF of the chunk-size line used to be left in the stream (bug #3, commit c13f4c64) */ { "chunked-with-extensions", { 0x00, 0x08, 0x03, 0x00 }, { { 1, "ABCDE" }, { 0, "POST /a HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n" "\r\n2;ext=val\r\nAB\r\n3;a=\"b;c\"\r\nCDE\r\n0\r\n\r\n" }, P_END, P_END } }, { "chunked-split", { 0x00, 0x08, 0x03, 0x00 }, { { 1, "ABCDEF" }, { 0, "POST /a HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n" "\r\n3\r\nABC\r\n3;x=\"y\"" }, { 2, "\r\nDEF\r\n0\r\n\r\n" }, P_END } }, /* small connection memory pool + trailing query argument without '=' and no header lines at all (bug #2, commit 29eaa56b) */ { "small-pool-trailing-query-arg", { 0x06, 0x08, 0x03, 0x00 }, { { 0, "GET /?novalue HTTP/1.0\r\n\r\n" }, P_END, P_END, P_END } }, { "small-pool-trailing-query-arg-2", { 0x03, 0x08, 0x03, 0x00 }, { { 0, "GET /?a=1&b HTTP/1.0\r\n\r\n" }, P_END, P_END, P_END } }, /* unrecognised 'algorithm' token -> MHD_DIGEST_AUTH_ALGO3_INVALID (bug #1, commit bd49ce93) */ { "digest-unknown-algorithm", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET /a HTTP/1.1\r\nHost: x\r\nAuthorization: Digest " "username=\"user\", realm=\"TestRealm\", nonce=\"0000\", " "uri=\"/a\", algorithm=BOGUS, response=\"00\"\r\n\r\n" }, P_END, P_END, P_END } }, /* full digest handshake: harvest the nonce from the 401 and replay it with a 128 hex digit 'response' value (bug #4, commit 5a73c1ae) */ { "digest-overlong-response", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET /a HTTP/1.1\r\nHost: x\r\n\r\n" }, { 3, "GET /a HTTP/1.1\r\nHost: x\r\nAuthorization: Digest " "username=\"user\", realm=\"TestRealm\", nonce=\"%%NONCE%%\", " "uri=\"/a\", qop=auth, nc=00000001, cnonce=\"deadbeef\", " "algorithm=SHA-256, response=\"" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "\"\r\n\r\n" }, P_END, P_END } }, { "digest-userhash", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET /a HTTP/1.1\r\nHost: x\r\n\r\n" }, { 3, "GET /a HTTP/1.1\r\nHost: x\r\nAuthorization: Digest " "username=\"" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "\", userhash=true, realm=\"TestRealm\", nonce=\"%%NONCE%%\", " "uri=\"/a\", qop=auth, nc=00000001, cnonce=\"deadbeef\", " "algorithm=SHA-256, response=\"0123456789abcdef\"\r\n\r\n" }, P_END, P_END } }, { "basic-auth", { 0x00, 0x0a, 0x03, 0x00 }, { { 0, "GET /a HTTP/1.1\r\nHost: x\r\n" "Authorization: Basic dXNlcjpwYXNz\r\n\r\n" }, P_END, P_END, P_END } }, { "multipart-post", { 0x00, 0x0c, 0x03, 0x00 }, { { 0, "POST /a HTTP/1.1\r\nHost: x\r\n" "Content-Type: multipart/form-data; boundary=--abc\r\n" "Transfer-Encoding: chunked\r\n\r\n" "52\r\n----abc\r\nContent-Disposition: form-data; name=\"k\"\r\n\r\n" "value\r\n----abc--\r\n\r\n0\r\n\r\n" }, P_END, P_END, P_END } }, { "urlencoded-post", { 0x00, 0x0c, 0x03, 0x00 }, { { 1, "a=1&b=%41&c" }, { 0, "POST /a HTTP/1.1\r\nHost: x\r\n" "Content-Type: application/x-www-form-urlencoded\r\n" "Content-Length: 11\r\n\r\na=1&b=%41&c" }, P_END, P_END } }, { "folded-header", { 0x00, 0x08, 0x00, 0x00 }, { { 0, "GET /a HTTP/1.1\r\nHost: x\r\nX-Fold: a\r\n\tb\r\n\r\n" }, P_END, P_END, P_END } }, { "pipelined", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET /a HTTP/1.1\r\nHost: x\r\n\r\n" "GET /b?q HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END } }, /* ------------- seeds driving configuration bytes 4-9 ------------- The seeds above leave those bytes zero and only exercise the parser. Without at least one seed per area below, the rest of the API stays practically unreachable: libFuzzer would have to guess six configuration bytes before anything new runs. Each seed turns on exactly one area so that a minimiser keeps them distinguishable. ext[] is { response, auth, event-loop/introspection, suspend and upgrade, header seed, content-reader seed }. */ /* Chunked reply produced by a content-reader callback, with response headers and a trailer -- the reply-side counterpart of the chunk parsing that commit c13f4c64 fixed on the request side. */ { "ext-callback-chunked", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x0A | 0x20 | 0x40, 0x00, 0x00, 0x00, 0x01, 0x20 } }, /* Known-length callback body, with a reader error injected part way through (crc_seed bit 0x80). */ { "ext-callback-error", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x09, 0x00, 0x00, 0x00, 0x02, 0x82 } }, { "ext-fd-response", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x0B, 0x00, 0x00, 0x00, 0x00, 0x10 } }, { "ext-fd-at-offset-response", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x0C, 0x00, 0x00, 0x00, 0x00, 0x10 } }, { "ext-pipe-response", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x0E, 0x00, 0x00, 0x00, 0x00, 0x10 } }, { "ext-iovec-response", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x0F, 0x00, 0x00, 0x00, 0x00, 0x07 } }, /* Empty response plus the header manipulation API (get/del/options). */ { "ext-empty-response-hdrapi", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x02 | 0x30 | 0x40 | 0x80, 0x00, 0x00, 0x00, 0x05, 0x00 } }, /* Digest through the pre-computed-userdigest entry point. */ { "ext-digest-check-digest3", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, { 0, "GET / HTTP/1.1\r\nHost: x\r\nAuthorization: Digest " "username=\"user\", realm=\"TestRealm\", nonce=\"%%NONCE%%\", " "uri=\"/\", response=\"00000000000000000000000000000000\"\r\n\r\n" }, P_END, P_END }, { 0x00, 0x05 | 0x80, 0x00, 0x00, 0x01, 0x00 } }, /* The v1 wrappers and the request-info query. */ { "ext-digest-v1-wrappers", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x00, 0x01 | 0x10, 0x00, 0x00, 0x00, 0x00 } }, { "ext-digest-request-info", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x00, 0x08 | 0x20, 0x00, 0x00, 0x03, 0x00 } }, /* Application-driven event loop: MHD_get_fdset2() + select() + MHD_run_from_select2(), with the timeout accessors. */ { "ext-external-event-loop", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x01, 0x00, 0x02 | 0x04, 0x00, 0x00, 0x00 } }, /* The v1 fdset/run_from_select pair. */ { "ext-external-event-loop-v1", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x01, 0x00, 0x01 | 0x04, 0x00, 0x00, 0x00 } }, /* Every connection-introspection accessor at once. */ { "ext-connection-api", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET /path?a=1 HTTP/1.1\r\nHost: x\r\nCookie: a=b\r\n\r\n" }, P_END, P_END, P_END }, { 0x01, 0x00, 0x08 | 0x10 | 0x20 | 0x40 | 0x80, 0x00, 0x10, 0x00 } }, /* Suspend the connection and resume it from the pump loop. */ { "ext-suspend-resume", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, { 2, "" }, P_END, P_END }, { 0x01, 0x00, 0x00, 0x02, 0x00, 0x00 } }, /* Two connections parked at the same time (op 3 opens the second without waiting for the first). The bookkeeping behind suspend mode 2 has to be a set for this: while it was a single slot the first connection was forgotten and stayed suspended, and MHD_stop_daemon() answered with MHD_PANIC ("called while we have suspended connections"). */ { "ext-suspend-two-connections", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET /a HTTP/1.1\r\nHost: x\r\n\r\n" }, { 3, "GET /b HTTP/1.1\r\nHost: x\r\n\r\n" }, { 2, "" }, P_END }, { 0x01, 0x00, 0x00, 0x02, 0x00, 0x00 } }, /* HTTP "Upgrade": the client asks for it and the handler answers 101 with an upgrade response, after which the socket is handed over. */ { "ext-upgrade", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\nConnection: Upgrade\r\n" "Upgrade: fuzz-protocol\r\n\r\n" }, { 2, "" }, P_END, P_END }, { 0x01, 0x00, 0x00, 0x04 | 0x08, 0x00, 0x00 } }, /* The remaining response constructors. One seed each, because the constructor is picked by the low nibble of ext[0] and a seed that does not name it leaves that entry point unreachable until the fuzzer happens to mutate the nibble. */ { "ext-buffer-persistent", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 } }, { "ext-buffer-free-callback", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x06, 0x00, 0x00, 0x00, 0x00, 0x00 } }, { "ext-from-data", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x07, 0x00, 0x00, 0x00, 0x00, 0x00 } }, { "ext-fd64-response", { 0x00, 0x08, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00 } }, /* The v1 basic-auth getter, which returns two separate malloc()ed strings rather than one struct. */ { "ext-basic-auth-v1", { 0x00, 0x0a, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n" "Authorization: Basic dXNlcjpwYXNz\r\n\r\n" }, P_END, P_END, P_END }, { 0x01, 0x40, 0x00, 0x00, 0x00, 0x00 } }, /* Answer the challenge with the basic-auth responses instead of the digest ones (fail_variant 3). */ { "ext-basic-auth-challenge", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x01, 0x30, 0x00, 0x00, 0x00, 0x00 } }, { "ext-basic-auth-challenge-utf8", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x01, 0x30, 0x00, 0x00, 0x03, 0x00 } }, /* The MD5-only and algorithm-parametrised pre-computed digest wrappers. */ { "ext-digest-check-digest-v1", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x01, 0x03, 0x00, 0x00, 0x00, 0x00 } }, { "ext-digest-check-digest2", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n\r\n" }, P_END, P_END, P_END }, { 0x01, 0x04, 0x00, 0x00, 0x01, 0x00 } }, /* The username queries. */ { "ext-digest-get-username-v1", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n" "Authorization: Digest username=\"user\", realm=\"TestRealm\"\r\n\r\n" } , P_END, P_END, P_END }, { 0x01, 0x06, 0x00, 0x00, 0x00, 0x00 } }, { "ext-digest-get-username3", { 0x00, 0x09, 0x03, 0x00 }, { { 0, "GET / HTTP/1.1\r\nHost: x\r\n" "Authorization: Digest userhash=true, username=\"aabb\", " "realm=\"TestRealm\"\r\n\r\n" }, P_END, P_END, P_END }, { 0x01, 0x07, 0x00, 0x00, 0x00, 0x00 } } }; static uint8_t seed_render_buf[4096]; static size_t fuzz_seed_count (void) { return sizeof (seeds) / sizeof (seeds[0]); } static const uint8_t * fuzz_seed_get (size_t idx, size_t *len) { const struct seed_def *sd = &seeds[idx]; struct sbuf b; unsigned int i; b.p = seed_render_buf; b.len = 0; b.cap = sizeof (seed_render_buf); sb_raw (&b, sd->cfg, 4); sb_raw (&b, sd->ext, sizeof (sd->ext)); for (i = 0; i < sizeof (sd->parts) / sizeof (sd->parts[0]); i++) { size_t n; unsigned int hv; uint8_t hdr[2]; if (NULL == sd->parts[i].txt) break; n = strlen (sd->parts[i].txt); if (n > 0x3FFF) n = 0x3FFF; hv = (sd->parts[i].op << 14) | (unsigned int) n; hdr[0] = (uint8_t) (hv & 0xFF); hdr[1] = (uint8_t) (hv >> 8); sb_raw (&b, hdr, 2); sb_raw (&b, sd->parts[i].txt, n); } *len = b.len; return seed_render_buf; } libmicrohttpd-1.0.10/src/fuzz/fuzz_str.c0000664000175000017500000003704015232103064013737 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file fuzz/fuzz_str.c * @brief Direct in-process fuzzer for the string primitives of mhd_str.c * @author Christian Grothoff * * Every destination buffer is obtained with malloc() at *exactly* the * size that the documented contract of the function under test * requires -- never a generous stack array. Under AddressSanitizer the * redzone immediately after the allocation turns any one-byte * over-write into a hard error, which is precisely the property a * fixed-size stack buffer would not give us. * * In addition to the contract-exact calls, several functions are also * called with a deliberately *too small* output buffer: functions that * take a buffer size argument must detect this and must not write past * the end. * * Input format: * byte 0 target selector * byte 1 auxiliary parameter (buffer size shrink, split point, ...) * byte 2.. payload */ #define FUZZ_HARNESS_NAME "fuzz_str" #include "fuzz_common.h" #include "mhd_options.h" #include "mhd_str.h" /** * Largest digest MHD supports; this is the size of the on-stack buffers * that digestauth.c passes to MHD_hex_to_bin(). */ #define MODEL_MAX_DIGEST 32 /** * Model the (pre-2026) digestauth.c call site that fed a client * controlled, up to 4 * digest_size characters long 'response' value * into MHD_hex_to_bin() together with a digest_size byte buffer. * * MHD_hex_to_bin() has no output size parameter: it writes len/2 bytes, * so a caller with a fixed size buffer *must* bound the input length. * This target replays that call site with an exactly sized heap buffer * so that ASAN reports the overflow. It is OFF by default (it models a * caller, not the library) -- enable it with MHD_FUZZ_MODEL_DIGEST_SINK=1 * to reproduce the primitive behind the digest 'response' overflow. */ static int model_digest_sink; static int model_digest_sink_read; enum str_target { TGT_HEX_TO_BIN = 0, TGT_BIN_TO_HEX, TGT_BIN_TO_HEX_Z, TGT_PCT_STRICT, TGT_PCT_LENIENT, TGT_PCT_IN_PLACE_STRICT, TGT_PCT_IN_PLACE_LENIENT, TGT_UNQUOTE, TGT_QUOTE, TGT_BASE64, TGT_TO_UINT64, TGT_TOKENS, TGT_EQUAL_CASELESS, TGT_DIGEST_HEX_SINK, TGT_COUNT }; /** * Allocate exactly @a n bytes. Zero-sized allocations are turned into * a one byte allocation so that the returned pointer stays valid, but * the harness never tells the library about that extra byte. */ static void * xalloc (size_t n) { void *p = malloc ((0 == n) ? 1 : n); if (NULL == p) abort (); return p; } static char * dup_z (const uint8_t *d, size_t n) { char *p = (char *) xalloc (n + 1); memcpy (p, d, n); p[n] = '\0'; return p; } int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { enum str_target tgt; const uint8_t *p; size_t n; unsigned int aux; if (size < 3) return 0; tgt = (enum str_target) (data[0] % (unsigned int) TGT_COUNT); aux = data[1]; p = data + 2; n = size - 2; /* Keep the inputs small: these are unit-level primitives and short inputs explore the interesting corner cases far more efficiently. */ if (n > 512) n = 512; switch (tgt) { case TGT_HEX_TO_BIN: { /* Contract: the output buffer must be len/2 bytes long, or len/2 + 1 if len is odd. */ size_t need = (n / 2) + (n % 2); uint8_t *out = (uint8_t *) xalloc (need); size_t r = MHD_hex_to_bin ((const char *) p, n, out); if (r > need) fuzz_report_finding ("MHD_hex_to_bin() reported more bytes written " "than its documented output size"); free (out); break; } case TGT_BIN_TO_HEX: { char *out = (char *) xalloc (2 * n); size_t r = MHD_bin_to_hex (p, n, out); if (r != 2 * n) fuzz_report_finding ("MHD_bin_to_hex() did not write 2 * size chars"); free (out); break; } case TGT_BIN_TO_HEX_Z: { char *out = (char *) xalloc (2 * n + 1); size_t r = MHD_bin_to_hex_z (p, n, out); if (r != 2 * n) fuzz_report_finding ("MHD_bin_to_hex_z() did not write 2 * size chars"); if ('\0' != out[r]) fuzz_report_finding ("MHD_bin_to_hex_z() result is not " "zero-terminated"); free (out); break; } case TGT_PCT_STRICT: { /* First with the exact maximum size, then with a buffer that is deliberately too small. */ char *out = (char *) xalloc (n); size_t r = MHD_str_pct_decode_strict_n_ ((const char *) p, n, out, n); size_t small; if (r > n) fuzz_report_finding ("MHD_str_pct_decode_strict_n_() overran the " "documented output size"); free (out); small = (0 == n) ? 0 : (n * (aux % 100u)) / 100u; out = (char *) xalloc (small); (void) MHD_str_pct_decode_strict_n_ ((const char *) p, n, out, small); free (out); break; } case TGT_PCT_LENIENT: { char *out = (char *) xalloc (n); bool broken = false; size_t r = MHD_str_pct_decode_lenient_n_ ((const char *) p, n, out, n, &broken); size_t small; if (r > n) fuzz_report_finding ("MHD_str_pct_decode_lenient_n_() overran the " "documented output size"); free (out); small = (0 == n) ? 0 : (n * (aux % 100u)) / 100u; out = (char *) xalloc (small); (void) MHD_str_pct_decode_lenient_n_ ((const char *) p, n, out, small, NULL); free (out); break; } case TGT_PCT_IN_PLACE_STRICT: { char *s = dup_z (p, n); size_t r = MHD_str_pct_decode_in_place_strict_ (s); if (r > n) fuzz_report_finding ("MHD_str_pct_decode_in_place_strict_() grew " "the string"); free (s); break; } case TGT_PCT_IN_PLACE_LENIENT: { char *s = dup_z (p, n); bool broken = false; size_t r = MHD_str_pct_decode_in_place_lenient_ (s, &broken); if (r > n) fuzz_report_finding ("MHD_str_pct_decode_in_place_lenient_() grew " "the string"); free (s); break; } #ifdef DAUTH_SUPPORT case TGT_UNQUOTE: { /* Unquoting never grows the string. */ char *out = (char *) xalloc (n); size_t r = MHD_str_unquote ((const char *) p, n, out); if (r > n) fuzz_report_finding ("MHD_str_unquote() wrote more characters than " "the quoted input had"); free (out); break; } #else /* ! DAUTH_SUPPORT */ case TGT_UNQUOTE: break; #endif /* ! DAUTH_SUPPORT */ #if defined(DAUTH_SUPPORT) || defined(BAUTH_SUPPORT) case TGT_QUOTE: { /* Quoting can at most double the size. */ char *out = (char *) xalloc (2 * n); size_t r = MHD_str_quote ((const char *) p, n, out, 2 * n); size_t small; if (r > 2 * n) fuzz_report_finding ("MHD_str_quote() wrote more than 2 * len chars"); free (out); small = (0 == n) ? 0 : (n * (aux % 200u)) / 100u; out = (char *) xalloc (small); (void) MHD_str_quote ((const char *) p, n, out, small); free (out); break; } #else /* ! (DAUTH_SUPPORT || BAUTH_SUPPORT) */ case TGT_QUOTE: break; #endif /* ! (DAUTH_SUPPORT || BAUTH_SUPPORT) */ #ifdef BAUTH_SUPPORT case TGT_BASE64: { size_t need = MHD_base64_max_dec_size_ (n); uint8_t *out = (uint8_t *) xalloc (need); size_t r = MHD_base64_to_bin_n ((const char *) p, n, out, need); size_t small; if (r > need) fuzz_report_finding ("MHD_base64_to_bin_n() exceeded " "MHD_base64_max_dec_size_()"); free (out); small = (0 == need) ? 0 : (need * (aux % 100u)) / 100u; out = (uint8_t *) xalloc (small); (void) MHD_base64_to_bin_n ((const char *) p, n, out, small); free (out); break; } #else /* ! BAUTH_SUPPORT */ case TGT_BASE64: break; #endif /* ! BAUTH_SUPPORT */ case TGT_TO_UINT64: { char *s = dup_z (p, n); uint64_t v1 = 0; uint64_t v2 = 0; size_t r1 = MHD_str_to_uint64_n_ (s, n, &v1); size_t r2 = MHD_strx_to_uint64_n_ (s, n, &v2); if (r1 > n) fuzz_report_finding ("MHD_str_to_uint64_n_() consumed more than " "maxlen characters"); if (r2 > n) fuzz_report_finding ("MHD_strx_to_uint64_n_() consumed more than " "maxlen characters"); free (s); break; } case TGT_TOKENS: { /* The "token" arguments have documented preconditions (no NUL, space, tab or comma); a fuzzer that violates them would only find its own mistakes, so sanitise them here. */ char *s = dup_z (p, n); size_t split = (0 == n) ? 0 : (aux % n); char *tok = dup_z (p + split, n - split); size_t tlen; ssize_t bs; char *out; size_t k; for (k = 0; k < n - split; k++) { if ( ('\0' == tok[k]) || (' ' == tok[k]) || ('\t' == tok[k]) || (',' == tok[k]) ) tok[k] = 'x'; } tlen = strlen (tok); if (0 == tlen) { free (tok); tok = dup_z ((const uint8_t *) "chunked", 7); tlen = 7; } (void) MHD_str_has_token_caseless_ (s, tok, tlen); /* Documented worst case growth of the output is 50%. */ bs = (ssize_t) (n + n / 2 + 1); out = (char *) xalloc ((size_t) bs); (void) MHD_str_remove_token_caseless_ (s, n, tok, tlen, out, &bs); if (bs > (ssize_t) (n + n / 2 + 1)) fuzz_report_finding ("MHD_str_remove_token_caseless_() reported a " "result larger than the documented 50% growth"); if (0 <= bs) { /* The output of the previous call is normalised, which is the documented precondition of the in-place variant. */ char *norm = dup_z ((const uint8_t *) out, (size_t) bs); size_t nlen = (size_t) bs; (void) MHD_str_remove_tokens_caseless_ (norm, &nlen, tok, tlen); if (nlen > (size_t) bs) fuzz_report_finding ("MHD_str_remove_tokens_caseless_() grew the " "string"); free (norm); } free (out); free (tok); free (s); break; } case TGT_EQUAL_CASELESS: { size_t split = (0 == n) ? 0 : (aux % n); char *a = dup_z (p, split); char *b = dup_z (p + split, n - split); (void) MHD_str_equal_caseless_bin_n_ (a, b, (split < n - split) ? split : (n - split)); (void) MHD_str_equal_caseless_n_ (a, b, n); free (a); free (b); break; } case TGT_DIGEST_HEX_SINK: { /* See the comment on model_digest_sink above. */ size_t len = n; uint8_t *out; if (! model_digest_sink_read) { const char *e = getenv ("MHD_FUZZ_MODEL_DIGEST_SINK"); model_digest_sink_read = 1; if (NULL != e) model_digest_sink = (0 != atoi (e)); } if (! model_digest_sink) break; /* digestauth.c only checked 'len <= 4 * digest_size' before the fix; replay exactly that bound. */ if (len > 4 * MODEL_MAX_DIGEST) len = 4 * MODEL_MAX_DIGEST; out = (uint8_t *) xalloc (MODEL_MAX_DIGEST); (void) MHD_hex_to_bin ((const char *) p, len, out); free (out); break; } case TGT_COUNT: default: break; } return 0; } /* ------------------------------------------------------------------ */ /* Generator */ /* ------------------------------------------------------------------ */ static const char *const gen_str_atoms[] = { "%41", "%", "%%", "%zz", "%0", "%00", "%ff", "\\", "\\\"", "\"", "0123456789abcdef", "0123456789ABCDEF", "ffffffffffffffffffffffff", "gg", "0x", "18446744073709551615", "99999999999999999999", "a, b, c", "chunked", "identity", " , ", ",,", "token", "QUJD", "QQ==", "Q===", "====", "AAAA", "AA=A", "\x00\x01\x7f\x80\xff", " ", "\t", "\r\n" }; static size_t fuzz_generate (struct fuzz_rng *rng, uint8_t *buf, size_t cap) { size_t len = 0; unsigned int natoms; unsigned int i; if (cap < 8) return 0; buf[len++] = (uint8_t) fuzz_below (rng, (uint32_t) TGT_COUNT); buf[len++] = fuzz_byte (rng); natoms = 1 + fuzz_below (rng, 12); for (i = 0; i < natoms; i++) { if (fuzz_chance (rng, 3)) { /* a run of hex digits of a length that is interesting for the digest code paths (32, 64, 128 characters) */ unsigned int k; unsigned int run = 1 + fuzz_below (rng, 140); for (k = 0; (k < run) && (len < cap); k++) buf[len++] = (uint8_t) "0123456789abcdef"[fuzz_below (rng, 16)]; } else if (fuzz_chance (rng, 8)) { if (len < cap) buf[len++] = fuzz_byte (rng); } else { const char *a = gen_str_atoms[fuzz_below (rng, (uint32_t) (sizeof (gen_str_atoms) / sizeof (char *)))]; size_t al = strlen (a); if (len + al > cap) break; memcpy (buf + len, a, al); len += al; } } return len; } /* ------------------------------------------------------------------ */ /* Seed corpus */ /* ------------------------------------------------------------------ */ struct str_seed { const char *txt; size_t len; }; #define SSEED(t) { t, sizeof (t) - 1 } static const struct str_seed str_seeds[] = { /* hex -> bin, 128 characters: the length digestauth.c used to allow into a 32 byte buffer */ SSEED ("\x00\x00" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"), SSEED ("\x00\x00" "0123456789abcdef0123456789abcdef"), SSEED ("\x00\x00" "abc"), SSEED ("\x00\x00" "zz"), SSEED ("\x01\x00" "\x01\x02\x03\x04"), SSEED ("\x02\x00" "\xff\xfe"), SSEED ("\x03\x00" "/a%41%42%zz%"), SSEED ("\x04\x40" "/a%41%42%zz%"), SSEED ("\x05\x00" "%41%42%%%0"), SSEED ("\x06\x00" "%41%42%%%0"), SSEED ("\x07\x00" "a\\\"b\\\\c"), SSEED ("\x08\x00" "a\"b\\c"), SSEED ("\x09\x00" "QUJDRA=="), SSEED ("\x09\x00" "QUJDR==="), SSEED ("\x0a\x00" "18446744073709551615"), SSEED ("\x0a\x00" "ffffffffffffffff"), SSEED ("\x0b\x03" "chunked, identity, chunked"), SSEED ("\x0c\x04" "CHUNKEDchunked"), SSEED ("\x0d\x00" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") }; static size_t fuzz_seed_count (void) { return sizeof (str_seeds) / sizeof (str_seeds[0]); } static const uint8_t * fuzz_seed_get (size_t idx, size_t *len) { *len = str_seeds[idx].len; return (const uint8_t *) str_seeds[idx].txt; } libmicrohttpd-1.0.10/src/fuzz/Makefile.in0000664000175000017500000015756215235436270014001 # Makefile.in generated by automake 1.17 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2024 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # This Makefile.am is in the public domain # In-process fuzzing harnesses. See README in this directory. # # The harnesses are built only with --enable-fuzzing (see # BUILD-INTEGRATION.md). They are ordinary check_PROGRAMS with a # built-in deterministic driver, so they need neither clang nor # libFuzzer nor AFL++; with those available the very same sources can be # compiled into libFuzzer/AFL++ targets (again, see the README). VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) am__rm_f = rm -f $(am__rm_f_notfound) am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = -fprofile-arcs -ftest-coverage check_PROGRAMS = fuzz_request$(EXEEXT) fuzz_options$(EXEEXT) \ fuzz_eventloop$(EXEEXT) fuzz_str$(EXEEXT) \ fuzz_memorypool$(EXEEXT) fuzz_postprocessor$(EXEEXT) \ $(am__EXEEXT_1) $(am__EXEEXT_2) @HAVE_ANYAUTH_TRUE@am__append_2 = \ @HAVE_ANYAUTH_TRUE@ fuzz_auth_header # fuzz_tls needs a TLS backend, and it links GnuTLS directly of its own # accord: it drives a real client through the handshake rather than # feeding bytes at MHD, which is what makes MHD's own TLS plumbing -- # rather than GnuTLS's record parser -- the thing under test. @ENABLE_HTTPS_TRUE@am__append_3 = \ @ENABLE_HTTPS_TRUE@ fuzz_tls subdir = src/fuzz ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @HAVE_ANYAUTH_TRUE@am__EXEEXT_1 = fuzz_auth_header$(EXEEXT) @ENABLE_HTTPS_TRUE@am__EXEEXT_2 = fuzz_tls$(EXEEXT) am_fuzz_auth_header_OBJECTS = fuzz_auth_header.$(OBJEXT) fuzz_auth_header_OBJECTS = $(am_fuzz_auth_header_OBJECTS) fuzz_auth_header_LDADD = $(LDADD) fuzz_auth_header_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = fuzz_auth_header_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(fuzz_auth_header_LDFLAGS) $(LDFLAGS) \ -o $@ am_fuzz_eventloop_OBJECTS = fuzz_eventloop.$(OBJEXT) fuzz_eventloop_OBJECTS = $(am_fuzz_eventloop_OBJECTS) fuzz_eventloop_LDADD = $(LDADD) fuzz_eventloop_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fuzz_eventloop_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(fuzz_eventloop_LDFLAGS) $(LDFLAGS) -o \ $@ am_fuzz_memorypool_OBJECTS = fuzz_memorypool.$(OBJEXT) fuzz_memorypool_OBJECTS = $(am_fuzz_memorypool_OBJECTS) fuzz_memorypool_LDADD = $(LDADD) fuzz_memorypool_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fuzz_memorypool_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(fuzz_memorypool_LDFLAGS) $(LDFLAGS) \ -o $@ am_fuzz_options_OBJECTS = fuzz_options.$(OBJEXT) fuzz_options_OBJECTS = $(am_fuzz_options_OBJECTS) fuzz_options_LDADD = $(LDADD) fuzz_options_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fuzz_options_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(fuzz_options_LDFLAGS) $(LDFLAGS) -o $@ am_fuzz_postprocessor_OBJECTS = fuzz_postprocessor.$(OBJEXT) fuzz_postprocessor_OBJECTS = $(am_fuzz_postprocessor_OBJECTS) fuzz_postprocessor_LDADD = $(LDADD) fuzz_postprocessor_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fuzz_postprocessor_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(AM_CFLAGS) $(CFLAGS) $(fuzz_postprocessor_LDFLAGS) \ $(LDFLAGS) -o $@ am_fuzz_request_OBJECTS = fuzz_request.$(OBJEXT) fuzz_request_OBJECTS = $(am_fuzz_request_OBJECTS) fuzz_request_LDADD = $(LDADD) fuzz_request_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fuzz_request_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(fuzz_request_LDFLAGS) $(LDFLAGS) -o $@ am_fuzz_str_OBJECTS = fuzz_str.$(OBJEXT) fuzz_str_OBJECTS = $(am_fuzz_str_OBJECTS) fuzz_str_LDADD = $(LDADD) fuzz_str_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fuzz_str_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(fuzz_str_LDFLAGS) $(LDFLAGS) -o $@ am_fuzz_tls_OBJECTS = fuzz_tls-fuzz_tls.$(OBJEXT) fuzz_tls_OBJECTS = $(am_fuzz_tls_OBJECTS) am__DEPENDENCIES_1 = fuzz_tls_DEPENDENCIES = $(LDADD) $(am__DEPENDENCIES_1) fuzz_tls_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(fuzz_tls_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/fuzz_auth_header.Po \ ./$(DEPDIR)/fuzz_eventloop.Po ./$(DEPDIR)/fuzz_memorypool.Po \ ./$(DEPDIR)/fuzz_options.Po ./$(DEPDIR)/fuzz_postprocessor.Po \ ./$(DEPDIR)/fuzz_request.Po ./$(DEPDIR)/fuzz_str.Po \ ./$(DEPDIR)/fuzz_tls-fuzz_tls.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(fuzz_auth_header_SOURCES) $(fuzz_eventloop_SOURCES) \ $(fuzz_memorypool_SOURCES) $(fuzz_options_SOURCES) \ $(fuzz_postprocessor_SOURCES) $(fuzz_request_SOURCES) \ $(fuzz_str_SOURCES) $(fuzz_tls_SOURCES) DIST_SOURCES = $(fuzz_auth_header_SOURCES) $(fuzz_eventloop_SOURCES) \ $(fuzz_memorypool_SOURCES) $(fuzz_options_SOURCES) \ $(fuzz_postprocessor_SOURCES) $(fuzz_request_SOURCES) \ $(fuzz_str_SOURCES) $(fuzz_tls_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ check recheck distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ $$am__collect_skipped_logs \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(IGNORE_SKIPPED_LOGS)'; then \ am__collect_skipped_logs='--collect-skipped-logs no'; \ else \ am__collect_skipped_logs=''; \ fi; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver README DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ am__xargs_n = @am__xargs_n@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUBDIRS = . # Number of generate/mutate iterations per harness during "make check". # Raise for a real fuzzing session, e.g. # make MHD_FUZZ_ITERATIONS=1000000 MHD_FUZZ_SEED=42 check # The whole suite takes about three seconds under ASAN+UBSAN at this value. MHD_FUZZ_ITERATIONS = 50000 # PRNG seed; every run is exactly reproducible from (harness, seed). MHD_FUZZ_SEED = 1 # Lower bound for MHD_OPTION_CLIENT_DISCIPLINE_LVL in fuzz_request. # -3 is the full range: it includes the deliberately non-conformant # parsing modes, which is where the most interesting inputs live. MHD_FUZZ_MIN_DISCIPLINE = -3 # Lower bound for MHD_OPTION_CONNECTION_MEMORY_LIMIT in fuzz_request. # 0 is the full range, including the tiny pools needed to reach the # read-buffer "shift back" code path. MHD_FUZZ_MIN_MEM_LIMIT = 0 # Where reproducers for failing inputs are written. MHD_FUZZ_CRASH_DIR = crashes AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ $(CPPFLAGS_ac) AM_CFLAGS = $(CFLAGS_ac) $(am__append_1) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) \ MHD_FUZZ_ITERATIONS="$(MHD_FUZZ_ITERATIONS)" ; \ export MHD_FUZZ_ITERATIONS ; \ MHD_FUZZ_SEED="$(MHD_FUZZ_SEED)" ; export MHD_FUZZ_SEED ; \ MHD_FUZZ_MIN_DISCIPLINE="$(MHD_FUZZ_MIN_DISCIPLINE)" ; \ export MHD_FUZZ_MIN_DISCIPLINE ; \ MHD_FUZZ_MIN_MEM_LIMIT="$(MHD_FUZZ_MIN_MEM_LIMIT)" ; \ export MHD_FUZZ_MIN_MEM_LIMIT ; \ MHD_FUZZ_CRASH_DIR="$(MHD_FUZZ_CRASH_DIR)" ; \ export MHD_FUZZ_CRASH_DIR ; # fuzz_str and fuzz_auth_header call functions that are internal to the # library (mhd_str.c, gen_auth.c, memorypool.c) and therefore hidden in # the shared object; link them against the static archive. This # requires a build with --enable-static (the default). LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la TESTS = $(check_PROGRAMS) fuzz_request_SOURCES = \ fuzz_request.c fuzz_common.h fuzz_request_LDFLAGS = $(AM_LDFLAGS) -static fuzz_options_SOURCES = \ fuzz_options.c fuzz_common.h fuzz_options_LDFLAGS = $(AM_LDFLAGS) -static fuzz_eventloop_SOURCES = \ fuzz_eventloop.c fuzz_common.h fuzz_eventloop_LDFLAGS = $(AM_LDFLAGS) -static fuzz_tls_SOURCES = \ fuzz_tls.c fuzz_common.h fuzz_tls_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) fuzz_tls_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) -static fuzz_tls_LDADD = $(LDADD) $(MHD_TLS_LIBDEPS) fuzz_str_SOURCES = \ fuzz_str.c fuzz_common.h fuzz_str_LDFLAGS = $(AM_LDFLAGS) -static fuzz_auth_header_SOURCES = \ fuzz_auth_header.c fuzz_common.h fuzz_auth_header_LDFLAGS = $(AM_LDFLAGS) -static fuzz_memorypool_SOURCES = \ fuzz_memorypool.c fuzz_common.h fuzz_memorypool_LDFLAGS = $(AM_LDFLAGS) -static fuzz_postprocessor_SOURCES = \ fuzz_postprocessor.c fuzz_common.h fuzz_postprocessor_LDFLAGS = $(AM_LDFLAGS) -static # The whole corpus directory is distributed as-is. EXTRA_DIST = \ README \ BUILD-INTEGRATION.md \ corpus CLEANFILES = \ $(MHD_FUZZ_CRASH_DIR)/*.bin # Replay the whole on-disk corpus through every harness; this is what a # CI regression run should do after a crash has been fixed. # # corpus/known-findings/ and corpus/distilled/ are listed separately # because --corpus-dir does not recurse. # # known-findings/ holds the reproducers of the findings in README # section 6; all of them are fixed, so anything failing there is a # regression. The one intended exception is a reproducer committed while # its finding is still open: that fails here until the fix lands, which # is what a regression test for an unfixed bug is supposed to do. # # distilled/ is the edge-minimal residue of a fuzzing campaign; see # corpus/README. It is the slowest part of check-corpus by file count # and the most valuable part by coverage. # # Note that these only bite on a tree configured with --enable-asserts; # without it mhd_assert() compiles away and most of these reproducers # pass whether MHD is fixed or not. CORPUS_DIRS = \ $(srcdir)/corpus \ $(srcdir)/corpus/known-findings \ $(srcdir)/corpus/distilled all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/fuzz/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/fuzz/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: $(am__rm_f) $(check_PROGRAMS) test -z "$(EXEEXT)" || $(am__rm_f) $(check_PROGRAMS:$(EXEEXT)=) fuzz_auth_header$(EXEEXT): $(fuzz_auth_header_OBJECTS) $(fuzz_auth_header_DEPENDENCIES) $(EXTRA_fuzz_auth_header_DEPENDENCIES) @rm -f fuzz_auth_header$(EXEEXT) $(AM_V_CCLD)$(fuzz_auth_header_LINK) $(fuzz_auth_header_OBJECTS) $(fuzz_auth_header_LDADD) $(LIBS) fuzz_eventloop$(EXEEXT): $(fuzz_eventloop_OBJECTS) $(fuzz_eventloop_DEPENDENCIES) $(EXTRA_fuzz_eventloop_DEPENDENCIES) @rm -f fuzz_eventloop$(EXEEXT) $(AM_V_CCLD)$(fuzz_eventloop_LINK) $(fuzz_eventloop_OBJECTS) $(fuzz_eventloop_LDADD) $(LIBS) fuzz_memorypool$(EXEEXT): $(fuzz_memorypool_OBJECTS) $(fuzz_memorypool_DEPENDENCIES) $(EXTRA_fuzz_memorypool_DEPENDENCIES) @rm -f fuzz_memorypool$(EXEEXT) $(AM_V_CCLD)$(fuzz_memorypool_LINK) $(fuzz_memorypool_OBJECTS) $(fuzz_memorypool_LDADD) $(LIBS) fuzz_options$(EXEEXT): $(fuzz_options_OBJECTS) $(fuzz_options_DEPENDENCIES) $(EXTRA_fuzz_options_DEPENDENCIES) @rm -f fuzz_options$(EXEEXT) $(AM_V_CCLD)$(fuzz_options_LINK) $(fuzz_options_OBJECTS) $(fuzz_options_LDADD) $(LIBS) fuzz_postprocessor$(EXEEXT): $(fuzz_postprocessor_OBJECTS) $(fuzz_postprocessor_DEPENDENCIES) $(EXTRA_fuzz_postprocessor_DEPENDENCIES) @rm -f fuzz_postprocessor$(EXEEXT) $(AM_V_CCLD)$(fuzz_postprocessor_LINK) $(fuzz_postprocessor_OBJECTS) $(fuzz_postprocessor_LDADD) $(LIBS) fuzz_request$(EXEEXT): $(fuzz_request_OBJECTS) $(fuzz_request_DEPENDENCIES) $(EXTRA_fuzz_request_DEPENDENCIES) @rm -f fuzz_request$(EXEEXT) $(AM_V_CCLD)$(fuzz_request_LINK) $(fuzz_request_OBJECTS) $(fuzz_request_LDADD) $(LIBS) fuzz_str$(EXEEXT): $(fuzz_str_OBJECTS) $(fuzz_str_DEPENDENCIES) $(EXTRA_fuzz_str_DEPENDENCIES) @rm -f fuzz_str$(EXEEXT) $(AM_V_CCLD)$(fuzz_str_LINK) $(fuzz_str_OBJECTS) $(fuzz_str_LDADD) $(LIBS) fuzz_tls$(EXEEXT): $(fuzz_tls_OBJECTS) $(fuzz_tls_DEPENDENCIES) $(EXTRA_fuzz_tls_DEPENDENCIES) @rm -f fuzz_tls$(EXEEXT) $(AM_V_CCLD)$(fuzz_tls_LINK) $(fuzz_tls_OBJECTS) $(fuzz_tls_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fuzz_auth_header.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fuzz_eventloop.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fuzz_memorypool.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fuzz_options.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fuzz_postprocessor.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fuzz_request.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fuzz_str.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fuzz_tls-fuzz_tls.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @: >>$@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< fuzz_tls-fuzz_tls.o: fuzz_tls.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(fuzz_tls_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT fuzz_tls-fuzz_tls.o -MD -MP -MF $(DEPDIR)/fuzz_tls-fuzz_tls.Tpo -c -o fuzz_tls-fuzz_tls.o `test -f 'fuzz_tls.c' || echo '$(srcdir)/'`fuzz_tls.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/fuzz_tls-fuzz_tls.Tpo $(DEPDIR)/fuzz_tls-fuzz_tls.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='fuzz_tls.c' object='fuzz_tls-fuzz_tls.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(fuzz_tls_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o fuzz_tls-fuzz_tls.o `test -f 'fuzz_tls.c' || echo '$(srcdir)/'`fuzz_tls.c fuzz_tls-fuzz_tls.obj: fuzz_tls.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(fuzz_tls_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT fuzz_tls-fuzz_tls.obj -MD -MP -MF $(DEPDIR)/fuzz_tls-fuzz_tls.Tpo -c -o fuzz_tls-fuzz_tls.obj `if test -f 'fuzz_tls.c'; then $(CYGPATH_W) 'fuzz_tls.c'; else $(CYGPATH_W) '$(srcdir)/fuzz_tls.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/fuzz_tls-fuzz_tls.Tpo $(DEPDIR)/fuzz_tls-fuzz_tls.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='fuzz_tls.c' object='fuzz_tls-fuzz_tls.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(fuzz_tls_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o fuzz_tls-fuzz_tls.obj `if test -f 'fuzz_tls.c'; then $(CYGPATH_W) 'fuzz_tls.c'; else $(CYGPATH_W) '$(srcdir)/fuzz_tls.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ output_system_information () \ { \ echo; \ { uname -a | $(AWK) '{ \ printf "System information (uname -a):"; \ for (i = 1; i < NF; ++i) \ { \ if (i != 2) \ printf " %s", $$i; \ } \ printf "\n"; \ }'; } 2>&1; \ if test -r /etc/os-release; then \ echo "Distribution information (/etc/os-release):"; \ sed 8q /etc/os-release; \ elif test -r /etc/issue; then \ echo "Distribution information (/etc/issue):"; \ cat /etc/issue; \ fi; \ }; \ please_report () \ { \ echo "Some test(s) failed. Please report this to $(PACKAGE_BUGREPORT),"; \ echo "together with the test-suite.log file (gzipped) and your system"; \ echo "information. Thanks."; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ output_system_information; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG) for debugging.$${std}";\ if test -n "$(PACKAGE_BUGREPORT)"; then \ please_report | sed -e "s/^/$${col}/" -e s/'$$'/"$${std}"/; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) @$(am__rm_f) $(RECHECK_LOGS) @$(am__rm_f) $(RECHECK_LOGS:.log=.trs) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? fuzz_request.log: fuzz_request$(EXEEXT) @p='fuzz_request$(EXEEXT)'; \ b='fuzz_request'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) fuzz_options.log: fuzz_options$(EXEEXT) @p='fuzz_options$(EXEEXT)'; \ b='fuzz_options'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) fuzz_eventloop.log: fuzz_eventloop$(EXEEXT) @p='fuzz_eventloop$(EXEEXT)'; \ b='fuzz_eventloop'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) fuzz_str.log: fuzz_str$(EXEEXT) @p='fuzz_str$(EXEEXT)'; \ b='fuzz_str'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) fuzz_memorypool.log: fuzz_memorypool$(EXEEXT) @p='fuzz_memorypool$(EXEEXT)'; \ b='fuzz_memorypool'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) fuzz_postprocessor.log: fuzz_postprocessor$(EXEEXT) @p='fuzz_postprocessor$(EXEEXT)'; \ b='fuzz_postprocessor'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) fuzz_auth_header.log: fuzz_auth_header$(EXEEXT) @p='fuzz_auth_header$(EXEEXT)'; \ b='fuzz_auth_header'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) fuzz_tls.log: fuzz_tls$(EXEEXT) @p='fuzz_tls$(EXEEXT)'; \ b='fuzz_tls'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -$(am__rm_f) $(TEST_LOGS) -$(am__rm_f) $(TEST_LOGS:.log=.trs) -$(am__rm_f) $(TEST_SUITE_LOG) clean-generic: -$(am__rm_f) $(CLEANFILES) distclean-generic: -$(am__rm_f) $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/fuzz_auth_header.Po -rm -f ./$(DEPDIR)/fuzz_eventloop.Po -rm -f ./$(DEPDIR)/fuzz_memorypool.Po -rm -f ./$(DEPDIR)/fuzz_options.Po -rm -f ./$(DEPDIR)/fuzz_postprocessor.Po -rm -f ./$(DEPDIR)/fuzz_request.Po -rm -f ./$(DEPDIR)/fuzz_str.Po -rm -f ./$(DEPDIR)/fuzz_tls-fuzz_tls.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/fuzz_auth_header.Po -rm -f ./$(DEPDIR)/fuzz_eventloop.Po -rm -f ./$(DEPDIR)/fuzz_memorypool.Po -rm -f ./$(DEPDIR)/fuzz_options.Po -rm -f ./$(DEPDIR)/fuzz_postprocessor.Po -rm -f ./$(DEPDIR)/fuzz_request.Po -rm -f ./$(DEPDIR)/fuzz_str.Po -rm -f ./$(DEPDIR)/fuzz_tls-fuzz_tls.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) check-am install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am .PRECIOUS: Makefile $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la .NOTPARALLEL: # Regenerate the on-disk seed corpus from the built-in one. .PHONY: refresh-corpus refresh-corpus: $(check_PROGRAMS) for p in $(check_PROGRAMS) ; do \ ./$$p --write-corpus=$(srcdir)/corpus || exit 1 ; \ done .PHONY: check-corpus check-corpus: $(check_PROGRAMS) for p in $(check_PROGRAMS) ; do \ for d in $(CORPUS_DIRS) ; do \ MHD_FUZZ_MIN_DISCIPLINE="$(MHD_FUZZ_MIN_DISCIPLINE)" \ MHD_FUZZ_MIN_MEM_LIMIT="$(MHD_FUZZ_MIN_MEM_LIMIT)" \ ./$$p --corpus-dir=$$d || exit 1 ; \ done ; \ done # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: # Tell GNU make to disable its built-in pattern rules. %:: %,v %:: RCS/%,v %:: RCS/% %:: s.% %:: SCCS/s.% libmicrohttpd-1.0.10/src/fuzz/fuzz_common.h0000664000175000017500000006131215232113571014427 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file fuzz/fuzz_common.h * @brief Shared, header-only fuzzing driver for the MHD in-process fuzzers. * @author Christian Grothoff * * Every harness in this directory is a single translation unit that * includes this header. The header provides: * - a deterministic, seeded PRNG (splitmix64 / xoshiro256**), * - a generic byte-level mutator, * - crash bookkeeping (the input of the currently running iteration is * dumped to the crash directory whenever the process dies), * - a standalone @c main() driver (generator + mutator loop, corpus * replay, single-file replay) so that the harnesses are usable with * a plain gcc + ASAN/UBSAN build, i.e. without clang/libFuzzer. * * The harness itself must provide: * - @c LLVMFuzzerTestOneInput() (the actual fuzz target), * - @c fuzz_generate() (a structure-aware input generator), * - @c fuzz_seed_count() / @c fuzz_seed_get() (a built-in seed corpus). * * Define @c FUZZ_NO_MAIN when linking against libFuzzer or AFL++'s * driver, which supply their own @c main(). */ #ifndef MHD_FUZZ_COMMON_H #define MHD_FUZZ_COMMON_H 1 #include #include #include #include #include #include #include #include #include #include #include #include #ifndef FUZZ_HARNESS_NAME #define FUZZ_HARNESS_NAME "fuzz" #endif /** * Not every harness uses every helper; silence -Wunused-function. */ #define FUZZ_UNUSED __attribute__ ((unused)) /** * Hard upper bound on the size of a single fuzz input. */ #ifndef FUZZ_MAX_INPUT #define FUZZ_MAX_INPUT 32768 #endif /** * Default number of iterations of the built-in driver. Kept small so * that "make check" stays in the "couple of seconds" range; raise with * --iterations=N or the MHD_FUZZ_ITERATIONS environment variable. */ #ifndef FUZZ_DEFAULT_ITERATIONS #define FUZZ_DEFAULT_ITERATIONS 3000 #endif /** * Default per-iteration watchdog, in seconds. */ #ifndef FUZZ_DEFAULT_TIMEOUT #define FUZZ_DEFAULT_TIMEOUT 20 #endif /* ------------------------------------------------------------------ */ /* Interface to be implemented by each harness */ /* ------------------------------------------------------------------ */ /** * The fuzz target. Signature is the libFuzzer one on purpose, so that * the very same harness can be linked with libFuzzer or AFL++ later. */ int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size); struct fuzz_rng; /** * Structure-aware generator used by the built-in standalone driver. * Must write at most @a cap bytes to @a buf and return the number of * bytes written. Purely random bytes almost never form a valid HTTP * request, so this is what actually makes the gcc-only driver useful. */ FUZZ_UNUSED static size_t fuzz_generate (struct fuzz_rng *rng, uint8_t *buf, size_t cap); /** * @return number of entries in the built-in seed corpus */ FUZZ_UNUSED static size_t fuzz_seed_count (void); /** * @param idx index of the seed to retrieve * @param[out] len set to the length of the seed * @return pointer to the seed bytes */ FUZZ_UNUSED static const uint8_t * fuzz_seed_get (size_t idx, size_t *len); /* ------------------------------------------------------------------ */ /* Deterministic PRNG */ /* ------------------------------------------------------------------ */ struct fuzz_rng { uint64_t s[4]; }; FUZZ_UNUSED static uint64_t fuzz_splitmix64 (uint64_t *x) { uint64_t z; *x += UINT64_C (0x9E3779B97F4A7C15); z = *x; z = (z ^ (z >> 30)) * UINT64_C (0xBF58476D1CE4E5B9); z = (z ^ (z >> 27)) * UINT64_C (0x94D049BB133111EB); return z ^ (z >> 31); } FUZZ_UNUSED static void fuzz_rng_seed (struct fuzz_rng *r, uint64_t seed) { uint64_t x = seed; unsigned int i; for (i = 0; i < 4; i++) r->s[i] = fuzz_splitmix64 (&x); } FUZZ_UNUSED static uint64_t fuzz_rot64 (uint64_t x, unsigned int k) { return (x << k) | (x >> (64 - k)); } /** * xoshiro256** -- small, fast, deterministic and identical on every * platform, which is what we need for reproducible fuzzing runs. */ FUZZ_UNUSED static uint64_t fuzz_next (struct fuzz_rng *r) { const uint64_t res = fuzz_rot64 (r->s[1] * 5, 7) * 9; const uint64_t t = r->s[1] << 17; r->s[2] ^= r->s[0]; r->s[3] ^= r->s[1]; r->s[1] ^= r->s[2]; r->s[0] ^= r->s[3]; r->s[2] ^= t; r->s[3] = fuzz_rot64 (r->s[3], 45); return res; } /** * @return uniformly distributed value in [0, n), 0 if @a n is 0 */ FUZZ_UNUSED static uint32_t fuzz_below (struct fuzz_rng *r, uint32_t n) { if (0 == n) return 0; return (uint32_t) (fuzz_next (r) % n); } FUZZ_UNUSED static uint8_t fuzz_byte (struct fuzz_rng *r) { return (uint8_t) (fuzz_next (r) & 0xFF); } /** * @return true with a probability of 1/@a n */ FUZZ_UNUSED static int fuzz_chance (struct fuzz_rng *r, uint32_t n) { return 0 == fuzz_below (r, n); } /* ------------------------------------------------------------------ */ /* Global driver state */ /* ------------------------------------------------------------------ */ /** * Non-zero if the input of the current iteration comes from a trusted * source (the built-in generator, the built-in seed corpus, --file or * --corpus-dir) and has NOT been mutated afterwards. Harnesses use * this to enable "ground truth" oracles, e.g. the expected decoded * request body that a generated chunked request declares. Random * mutations invalidate such declarations, hence the flag. */ FUZZ_UNUSED static int fuzz_pristine; /** * Non-zero to let the harness enable MHD's own error log. */ FUZZ_UNUSED static int fuzz_verbose; /** * Non-zero to skip the replay of the built-in seed corpus at the start * of a run (useful when a seed is known to trigger an already-reported * finding and one wants to look for others). */ FUZZ_UNUSED static int fuzz_skip_seeds; /* Only read by the built-in driver; under -DFUZZ_NO_MAIN (the libFuzzer and AFL++ builds, see contrib/oss-fuzz/build.sh) they are written but never read, which is not a defect. */ FUZZ_UNUSED static uint64_t fuzz_cur_seed; FUZZ_UNUSED static uint64_t fuzz_cur_iter; static const uint8_t *fuzz_cur_input; static size_t fuzz_cur_input_len; static const char *fuzz_crash_dir = "crashes"; /* Pre-rendered, so that the death/signal handlers stay async-signal-safe (no snprintf, no malloc). */ static char fuzz_crash_path[512]; static char fuzz_crash_msg[512]; static volatile sig_atomic_t fuzz_dumped; FUZZ_UNUSED static void fuzz_write_all (int fd, const void *buf, size_t len) { const char *p = (const char *) buf; while (0 != len) { ssize_t w = write (fd, p, len); if (0 >= w) break; p += w; len -= (size_t) w; } } FUZZ_UNUSED static void fuzz_msg (const char *s) { fuzz_write_all (STDERR_FILENO, s, strlen (s)); } /** * Dump the input of the currently running iteration so that the * failure can be replayed with --file=... Async-signal-safe. */ FUZZ_UNUSED static void fuzz_dump_current (void) { int fd; if (fuzz_dumped) return; fuzz_dumped = 1; if ( (NULL == fuzz_cur_input) || ('\0' == fuzz_crash_path[0]) ) return; (void) mkdir (fuzz_crash_dir, 0755); fd = open (fuzz_crash_path, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (0 > fd) { fuzz_msg ("\n*** FUZZ: failed to write crash file ***\n"); return; } fuzz_write_all (fd, fuzz_cur_input, fuzz_cur_input_len); (void) close (fd); fuzz_msg ("\n*** FUZZ: reproducer written to "); fuzz_msg (fuzz_crash_path); fuzz_msg (" ***\n*** FUZZ: "); fuzz_msg (fuzz_crash_msg); fuzz_msg (" ***\n"); } FUZZ_UNUSED static void fuzz_death_callback (void) { fuzz_dump_current (); } FUZZ_UNUSED static void fuzz_sig_handler (int sig) { fuzz_dump_current (); if (SIGALRM == sig) { fuzz_msg ("*** FUZZ: HANG detected (watchdog fired) ***\n"); _exit (99); } /* restore default handler and re-raise so that the usual ASAN/abort diagnostics are produced */ signal (sig, SIG_DFL); raise (sig); } /** * Report a logical (non-memory-safety) finding: dump the reproducer * and abort so that the failure is impossible to overlook. */ FUZZ_UNUSED static void fuzz_report_finding (const char *what) { size_t l = strlen (what); if (l >= sizeof (fuzz_crash_msg)) l = sizeof (fuzz_crash_msg) - 1; memcpy (fuzz_crash_msg, what, l); fuzz_crash_msg[l] = '\0'; fuzz_msg ("\n*** FUZZ FINDING: "); fuzz_msg (fuzz_crash_msg); fuzz_msg (" ***\n"); fuzz_dump_current (); abort (); } /* Weak declaration: resolved when built with ASAN (gcc or clang), NULL otherwise. ASAN calls this right before it terminates the process, which is the only reliable hook when abort_on_error=0. */ extern void __sanitizer_set_death_callback (void (*cb)(void)) __attribute__ ((weak)); /** * Ignore SIGPIPE. Idempotent, so it is safe to call on every execution. * * This deliberately lives OUTSIDE the #ifndef FUZZ_NO_MAIN block below, * because it is needed by the fuzz *target*, not merely by the built-in * driver. fuzz_request writes into an AF_UNIX socketpair whose peer end * MHD may already have closed (any input that makes the daemon drop the * connection early does this), and a write() to a socket with no reader * raises SIGPIPE. * * None of the external engines does this for us: libFuzzer intercepts * SEGV/BUS/ABRT/ILL/FPE/INT/TERM/XFSZ/USR1/USR2 and has no * -handle_sigpipe flag at all, and AFL++/honggfuzz likewise leave the * default disposition in place. So without this call an OSS-Fuzz build * of fuzz_request is killed by SIGPIPE after a few dozen executions, * with no stack trace, no artifact and no report -- the target simply * stops fuzzing. Measured here: dead after ~28 execs without it, * 540000 execs in 31 s with it. */ FUZZ_UNUSED static void fuzz_ignore_sigpipe (void) { static int sigpipe_ignored; if (sigpipe_ignored) return; sigpipe_ignored = 1; (void) signal (SIGPIPE, SIG_IGN); } #ifndef FUZZ_NO_MAIN static void fuzz_install_handlers (void) { struct sigaction sa; if (NULL != __sanitizer_set_death_callback) __sanitizer_set_death_callback (&fuzz_death_callback); memset (&sa, 0, sizeof (sa)); sa.sa_handler = &fuzz_sig_handler; sigemptyset (&sa.sa_mask); sa.sa_flags = 0; (void) sigaction (SIGABRT, &sa, NULL); (void) sigaction (SIGSEGV, &sa, NULL); (void) sigaction (SIGBUS, &sa, NULL); (void) sigaction (SIGILL, &sa, NULL); (void) sigaction (SIGFPE, &sa, NULL); (void) sigaction (SIGALRM, &sa, NULL); fuzz_ignore_sigpipe (); } /** * Remember which input we are about to feed to the target, and * pre-render the name of the file it would be dumped to. */ static void fuzz_set_current (const uint8_t *data, size_t size, const char *tag) { fuzz_cur_input = data; fuzz_cur_input_len = size; fuzz_dumped = 0; (void) snprintf (fuzz_crash_path, sizeof (fuzz_crash_path), "%s/crash-%s-seed%llu-iter%llu.bin", fuzz_crash_dir, FUZZ_HARNESS_NAME, (unsigned long long) fuzz_cur_seed, (unsigned long long) fuzz_cur_iter); (void) snprintf (fuzz_crash_msg, sizeof (fuzz_crash_msg), "harness=%s seed=%llu iteration=%llu source=%s", FUZZ_HARNESS_NAME, (unsigned long long) fuzz_cur_seed, (unsigned long long) fuzz_cur_iter, tag); } /* ------------------------------------------------------------------ */ /* Generic byte-level mutator */ /* ------------------------------------------------------------------ */ static const uint8_t fuzz_interesting[] = { 0x00, 0x01, 0x07, 0x09, 0x0A, 0x0D, 0x20, 0x22, 0x25, 0x26, 0x27, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x3A, 0x3B, 0x3D, 0x3F, 0x40, 0x5C, 0x7B, 0x7D, 0x7F, 0x80, 0xC0, 0xFE, 0xFF }; static const char *const fuzz_interesting_str[] = { "\r\n", "\r\n\r\n", "\n", "%", "%%NONCE%%", ";", "=", "\"", "\\", "chunked", "Transfer-Encoding: ", "Content-Length: ", "algorithm=", "userhash=true", "Authorization: Digest ", "Authorization: Basic ", "boundary=", "multipart/form-data", "0\r\n\r\n", "?", "&", "aaaaaaaaaaaaaaaa" }; /** * Apply a single random mutation to @a buf. * * @param rng the PRNG state * @param[in,out] buf the buffer to mutate * @param len current length * @param cap capacity of @a buf * @return new length */ static size_t fuzz_mutate_once (struct fuzz_rng *rng, uint8_t *buf, size_t len, size_t cap) { uint32_t op; if (0 == len) { buf[0] = fuzz_byte (rng); return 1; } op = fuzz_below (rng, 10); switch (op) { case 0: /* bit flip */ { size_t p = fuzz_below (rng, (uint32_t) len); buf[p] = (uint8_t) (buf[p] ^ (1u << fuzz_below (rng, 8))); break; } case 1: /* random byte */ buf[fuzz_below (rng, (uint32_t) len)] = fuzz_byte (rng); break; case 2: /* interesting byte */ buf[fuzz_below (rng, (uint32_t) len)] = fuzz_interesting[fuzz_below (rng, (uint32_t) (sizeof (fuzz_interesting)))]; break; case 3: /* add/sub small value */ { size_t p = fuzz_below (rng, (uint32_t) len); buf[p] = (uint8_t) (buf[p] + (int) fuzz_below (rng, 17) - 8); break; } case 4: /* erase a run */ { size_t p = fuzz_below (rng, (uint32_t) len); size_t n = 1 + fuzz_below (rng, (uint32_t) (len - p)); memmove (buf + p, buf + p + n, len - p - n); len -= n; break; } case 5: /* insert repeated byte */ { size_t p = fuzz_below (rng, (uint32_t) len + 1); size_t n = 1 + fuzz_below (rng, 32); uint8_t v = fuzz_byte (rng); if (len + n > cap) n = cap - len; if (0 == n) break; memmove (buf + p + n, buf + p, len - p); memset (buf + p, v, n); len += n; break; } case 6: /* duplicate a chunk */ { size_t p = fuzz_below (rng, (uint32_t) len); size_t n = 1 + fuzz_below (rng, (uint32_t) (len - p)); size_t d = fuzz_below (rng, (uint32_t) len + 1); if (len + n > cap) n = cap - len; if (0 == n) break; memmove (buf + d + n, buf + d, len - d); memmove (buf + d, buf + ((p >= d) ? (p + n) : p), n); len += n; break; } case 7: /* insert an interesting token */ { const char *s = fuzz_interesting_str[fuzz_below (rng, (uint32_t) (sizeof (fuzz_interesting_str) / sizeof (fuzz_interesting_str[0])))]; size_t n = strlen (s); size_t p = fuzz_below (rng, (uint32_t) len + 1); if (len + n > cap) break; memmove (buf + p + n, buf + p, len - p); memcpy (buf + p, s, n); len += n; break; } case 8: /* swap two bytes */ { size_t a = fuzz_below (rng, (uint32_t) len); size_t b = fuzz_below (rng, (uint32_t) len); uint8_t t = buf[a]; buf[a] = buf[b]; buf[b] = t; break; } default: /* truncate */ len = 1 + fuzz_below (rng, (uint32_t) len); break; } return len; } /* ------------------------------------------------------------------ */ /* Standalone driver */ /* ------------------------------------------------------------------ */ static int fuzz_run_file (const char *path) { FILE *f; uint8_t *buf; size_t n; f = fopen (path, "rb"); if (NULL == f) { fprintf (stderr, "%s: cannot open '%s': %s\n", FUZZ_HARNESS_NAME, path, strerror (errno)); return 1; } buf = (uint8_t *) malloc (FUZZ_MAX_INPUT); if (NULL == buf) { (void) fclose (f); return 1; } n = fread (buf, 1, FUZZ_MAX_INPUT, f); (void) fclose (f); fuzz_pristine = 1; fuzz_set_current (buf, n, path); alarm (FUZZ_DEFAULT_TIMEOUT); (void) LLVMFuzzerTestOneInput (buf, n); alarm (0); free (buf); return 0; } static int fuzz_run_corpus_dir (const char *dir) { DIR *d; struct dirent *de; char path[1024]; int ret = 0; unsigned int cnt = 0; d = opendir (dir); if (NULL == d) { fprintf (stderr, "%s: cannot open corpus dir '%s': %s\n", FUZZ_HARNESS_NAME, dir, strerror (errno)); return 1; } while (NULL != (de = readdir (d))) { struct stat sb; if ('.' == de->d_name[0]) continue; (void) snprintf (path, sizeof (path), "%s/%s", dir, de->d_name); if ( (0 != stat (path, &sb)) || (! S_ISREG (sb.st_mode)) ) continue; fuzz_cur_iter = cnt++; ret |= fuzz_run_file (path); } (void) closedir (d); printf ("%s: replayed %u corpus file(s) from %s\n", FUZZ_HARNESS_NAME, cnt, dir); return ret; } static void fuzz_usage (const char *argv0) { printf ( "Usage: %s [OPTIONS] [FILE...]\n" "\n" "In-process fuzzing harness '%s' for GNU libmicrohttpd.\n" "\n" " --iterations=N number of generate/mutate iterations (default %d)\n" " --seed=N PRNG seed; runs are fully reproducible (default 1)\n" " --corpus-dir=DIR replay every regular file in DIR and exit\n" " --file=PATH replay a single input and exit (crash reproduction)\n" " --crash-dir=DIR where to write reproducers (default 'crashes')\n" " --timeout=SEC per-iteration watchdog (default %d, 0 disables)\n" " --write-corpus=DIR write the built-in seed corpus to DIR and exit\n" " --skip-seeds do not replay the built-in seed corpus first\n" " --verbose enable MHD's error log inside the harness\n" " --help this text\n" "\n" "Environment: MHD_FUZZ_ITERATIONS, MHD_FUZZ_SEED, MHD_FUZZ_TIMEOUT,\n" " MHD_FUZZ_CRASH_DIR, MHD_FUZZ_VERBOSE\n" "\n" "Bare FILE arguments are equivalent to --file=FILE (libFuzzer-style).\n", argv0, FUZZ_HARNESS_NAME, (int) FUZZ_DEFAULT_ITERATIONS, (int) FUZZ_DEFAULT_TIMEOUT); } static int fuzz_write_corpus (const char *dir) { size_t i; size_t n = fuzz_seed_count (); if ( (0 != mkdir (dir, 0755)) && (EEXIST != errno) ) { fprintf (stderr, "%s: mkdir '%s': %s\n", FUZZ_HARNESS_NAME, dir, strerror (errno)); return 1; } for (i = 0; i < n; i++) { char path[1024]; size_t len; const uint8_t *s = fuzz_seed_get (i, &len); FILE *f; (void) snprintf (path, sizeof (path), "%s/%s-%02u.bin", dir, FUZZ_HARNESS_NAME, (unsigned int) i); f = fopen (path, "wb"); if (NULL == f) { fprintf (stderr, "%s: fopen '%s': %s\n", FUZZ_HARNESS_NAME, path, strerror (errno)); return 1; } if (len != fwrite (s, 1, len, f)) { (void) fclose (f); return 1; } (void) fclose (f); } printf ("%s: wrote %u seed(s) to %s\n", FUZZ_HARNESS_NAME, (unsigned int) n, dir); return 0; } int main (int argc, char *const *argv) { uint64_t iterations = FUZZ_DEFAULT_ITERATIONS; uint64_t seed = 1; unsigned int timeout = FUZZ_DEFAULT_TIMEOUT; const char *corpus_dir = NULL; const char *single_file = NULL; const char *write_corpus = NULL; struct fuzz_rng rng; uint8_t *buf; uint64_t i; int j; const char *e; int ret = 0; e = getenv ("MHD_FUZZ_ITERATIONS"); if (NULL != e) iterations = strtoull (e, NULL, 10); e = getenv ("MHD_FUZZ_SEED"); if (NULL != e) seed = strtoull (e, NULL, 10); e = getenv ("MHD_FUZZ_TIMEOUT"); if (NULL != e) timeout = (unsigned int) strtoul (e, NULL, 10); e = getenv ("MHD_FUZZ_CRASH_DIR"); if (NULL != e) fuzz_crash_dir = e; e = getenv ("MHD_FUZZ_VERBOSE"); if (NULL != e) fuzz_verbose = (0 != atoi (e)); e = getenv ("MHD_FUZZ_SKIP_SEEDS"); if (NULL != e) fuzz_skip_seeds = (0 != atoi (e)); for (j = 1; j < argc; j++) { const char *a = argv[j]; if (0 == strncmp (a, "--iterations=", 13)) iterations = strtoull (a + 13, NULL, 10); else if (0 == strncmp (a, "--seed=", 7)) seed = strtoull (a + 7, NULL, 10); else if (0 == strncmp (a, "--corpus-dir=", 13)) corpus_dir = a + 13; else if (0 == strncmp (a, "--file=", 7)) single_file = a + 7; else if (0 == strncmp (a, "--crash-dir=", 12)) fuzz_crash_dir = a + 12; else if (0 == strncmp (a, "--timeout=", 10)) timeout = (unsigned int) strtoul (a + 10, NULL, 10); else if (0 == strncmp (a, "--write-corpus=", 15)) write_corpus = a + 15; else if (0 == strcmp (a, "--skip-seeds")) fuzz_skip_seeds = 1; else if (0 == strcmp (a, "--verbose")) fuzz_verbose = 1; else if ( (0 == strcmp (a, "--help")) || (0 == strcmp (a, "-h")) ) { fuzz_usage (argv[0]); return 0; } else if ('-' == a[0]) { fprintf (stderr, "%s: unknown option '%s'\n", FUZZ_HARNESS_NAME, a); fuzz_usage (argv[0]); return 2; } else single_file = a; } fuzz_cur_seed = seed; fuzz_install_handlers (); if (NULL != write_corpus) return fuzz_write_corpus (write_corpus); if (NULL != single_file) { printf ("%s: replaying %s\n", FUZZ_HARNESS_NAME, single_file); ret = fuzz_run_file (single_file); printf ("%s: replay finished without a finding\n", FUZZ_HARNESS_NAME); return ret; } if (NULL != corpus_dir) return fuzz_run_corpus_dir (corpus_dir); buf = (uint8_t *) malloc (FUZZ_MAX_INPUT); if (NULL == buf) return 1; fuzz_rng_seed (&rng, seed); printf ("%s: seed=%llu iterations=%llu\n", FUZZ_HARNESS_NAME, (unsigned long long) seed, (unsigned long long) iterations); fflush (stdout); for (i = 0; i < iterations; i++) { size_t len; const char *tag; uint32_t mode; fuzz_cur_iter = i; if ( (! fuzz_skip_seeds) && (i < fuzz_seed_count ()) ) { size_t sl; const uint8_t *s = fuzz_seed_get ((size_t) i, &sl); if (sl > FUZZ_MAX_INPUT) sl = FUZZ_MAX_INPUT; memcpy (buf, s, sl); len = sl; fuzz_pristine = 1; tag = "builtin-seed"; } else { mode = fuzz_below (&rng, 100); if (mode < 55) { fuzz_pristine = 1; len = fuzz_generate (&rng, buf, FUZZ_MAX_INPUT); tag = "generated"; } else { unsigned int k; unsigned int nmut; if (mode < 85) { len = fuzz_generate (&rng, buf, FUZZ_MAX_INPUT); tag = "generated+mutated"; } else { size_t sl; const uint8_t *s; if (0 == fuzz_seed_count ()) { len = fuzz_generate (&rng, buf, FUZZ_MAX_INPUT); } else { s = fuzz_seed_get (fuzz_below (&rng, (uint32_t) fuzz_seed_count ()), &sl); if (sl > FUZZ_MAX_INPUT) sl = FUZZ_MAX_INPUT; memcpy (buf, s, sl); len = sl; } tag = "seed+mutated"; } fuzz_pristine = 0; nmut = 1 + fuzz_below (&rng, 8); for (k = 0; k < nmut; k++) len = fuzz_mutate_once (&rng, buf, len, FUZZ_MAX_INPUT); } } fuzz_set_current (buf, len, tag); if (0 != timeout) alarm (timeout); (void) LLVMFuzzerTestOneInput (buf, len); if (0 != timeout) alarm (0); } free (buf); printf ("%s: %llu iterations completed, no findings\n", FUZZ_HARNESS_NAME, (unsigned long long) iterations); return ret; } #endif /* ! FUZZ_NO_MAIN */ #endif /* MHD_FUZZ_COMMON_H */ libmicrohttpd-1.0.10/src/fuzz/fuzz_memorypool.c0000664000175000017500000013660715232214516015347 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file fuzz/fuzz_memorypool.c * @brief Direct in-process fuzzer for src/microhttpd/memorypool.c * @author Christian Grothoff * * memorypool.c is the per-connection allocator: a bump allocator that * hands out "normal" blocks from the start of the pool and small, * never-reallocated blocks from its end, plus an in-place resize and a * reset that moves one surviving block back to the beginning. Every * request buffer, every header name and value of every connection lives * in it, so a single mis-computed offset here is a cross-request * information leak or a heap overflow -- and one that ASAN alone cannot * see, because the whole pool is one malloc()ed object. (It does see it * in a build where MHD_ASAN_POISON_ACTIVE is defined, i.e. where * `sanitizer/asan_interface.h` was found and memorypool.c poisons the * unallocated parts of the pool itself. The harness works either way * and knows the red zone size that mode adds between two blocks.) * * The harness therefore keeps its own model of the pool and checks it * against the allocator after every single operation: * * - every returned pointer lies inside the pool, is aligned, and does * not overlap any other live allocation; * - every live allocation carries a position-dependent byte pattern * that is re-verified later; the allocator moves data around in * MHD_pool_reallocate() and MHD_pool_reset(), and the pattern is what * proves the move was correct; * - the sum of the live allocations plus MHD_pool_get_free() never * exceeds the size of the pool, MHD_pool_get_free() never grows * across an allocation and never shrinks across a deallocation; * - the implications the rest of MHD relies on hold: * * MHD_pool_allocate (pool, MHD_pool_get_free (pool), false) must * succeed (response.c:2203 does exactly this), and more generally * an allocation must not fail while get_free() reports room for * its rounded-up size; * * if MHD_pool_is_resizable_inplace() says yes, a reallocation * that fits must succeed *and must not move the block* * (connection.c:729/750/2082/2121 assert precisely that); * * after freeing the number of bytes MHD_pool_try_alloc() asked * for in @a required_bytes, the same call must succeed -- this is * the whole point of that out parameter and the logic of * MHD_connection_alloc_memory_(). * * Documented preconditions are respected, since violating them would * only produce findings about the harness: blocks allocated "from the * end" are never passed to MHD_pool_reallocate(), MHD_pool_reset() is * never asked for more than the pool size nor for more copy_bytes than * the kept block holds, and a block is only ever deallocated with the * size it was allocated with. * * Two *open* defects of memorypool.c are reachable and would otherwise * make every run abort; each is gated behind an environment variable, * documented in full at full_dealloc_enabled and wrap_realloc_enabled * below and in README section 6.1, with a byte-exact reproducer in the * built-in seed corpus. Nothing else is gated. * * Input format: * byte 0 pool size selector (index into fz_pool_sizes[]) * byte 1 flags * 0x01 verify every live block after every operation * 0x02 prefer allocating "from the end" * rest unused * byte 2.. a stream of 3-byte operation records * [0] opcode (see enum fz_op) * [1] block selector / auxiliary nibbles * [2] size selector (see fz_size()) */ #define FUZZ_HARNESS_NAME "fuzz_memorypool" #include "fuzz_common.h" /* internal.h pulls in MHD_config.h and in the right order; including first would redefine _MHD_EXTERN. */ #include "internal.h" #include "memorypool.h" /** * Alignment of every block the pool hands out; memorypool.c aligns to * two words "as GNU libc does". */ #define FZ_ALIGN_SIZE (2 * sizeof (void *)) /** * Size of the red zone memorypool.c keeps between two blocks. It only * exists in a build with user memory poisoning, i.e. when the pool * itself is instrumented; without it the pool is packed tight. */ #ifdef MHD_ASAN_POISON_ACTIVE #define FZ_RED_ZONE_SIZE FZ_ALIGN_SIZE #else /* ! MHD_ASAN_POISON_ACTIVE */ #define FZ_RED_ZONE_SIZE ((size_t) 0) #endif /* ! MHD_ASAN_POISON_ACTIVE */ /** * Maximum number of live allocations the model tracks. An operation * that would exceed this is skipped, so the model never loses a block. */ #define FZ_MAX_BLOCKS 24 /** * Maximum number of operations executed for one input. */ #define FZ_MAX_OPS 64 /** * Number of bytes of each allocation that carry the check pattern. * Bounding this keeps the harness fast; the interesting bugs of a bump * allocator are all at the start of a block or at its (ASAN-guarded) * end. */ #define FZ_PAT_MAX 96 /** * Pool sizes to choose from. MHD uses 128..32768 in practice (the * default is 32768 and MHD_OPTION_CONNECTION_MEMORY_LIMIT can set * anything); everything at or below 32k is malloc()ed by * MHD_pool_create(), so the harness knows the exact usable size and * ASAN's redzone sits right behind the pool. The last two entries are * larger than that on purpose: they take the mmap() path of * MHD_pool_create() and the munmap() path of MHD_pool_destroy(). Both * are powers of two and therefore a multiple of any page size, so the * resulting pool is exactly that large either way and the check below * stays exact. */ static const size_t fz_pool_sizes[] = { 1, 15, 16, 17, 32, 48, 64, 96, 128, 129, 192, 256, 320, 384, 512, 768, 1024, 1400, 1500, 2048, 4096, 8192, 16384, 32768, 65536, 131072 }; #define FZ_NUM_POOL_SIZES \ (sizeof (fz_pool_sizes) / sizeof (fz_pool_sizes[0])) enum fz_op { FZ_OP_ALLOC = 0, /**< MHD_pool_allocate() */ FZ_OP_ALLOC_ALL, /**< allocate exactly MHD_pool_get_free() bytes */ FZ_OP_TRY_ALLOC, /**< MHD_pool_try_alloc() */ FZ_OP_SQUEEZE, /**< try_alloc + shrink + retry */ FZ_OP_REALLOC, /**< MHD_pool_reallocate() of a live block */ FZ_OP_REALLOC_NEW, /**< MHD_pool_reallocate() with old == NULL */ FZ_OP_DEALLOC, /**< MHD_pool_deallocate() */ FZ_OP_RESET, /**< MHD_pool_reset() */ FZ_OP_GET_FREE, /**< MHD_pool_get_free() */ FZ_OP_RESIZABLE, /**< MHD_pool_is_resizable_inplace() */ FZ_OP_VERIFY, /**< re-check every live block */ FZ_OP_RECREATE, /**< MHD_pool_destroy() + MHD_pool_create() */ FZ_OP_COUNT }; /** * One live allocation. */ struct fz_block { /** * Address returned by the pool. */ uint8_t *ptr; /** * Current size of the block, i.e. the number of bytes the harness is * allowed to touch and the size it will pass to the pool again. */ size_t size; /** * Seed of the check pattern of this block. */ uint8_t tag; /** * True if the block was allocated "from the end" (MHD_pool_allocate() * with @a from_end, or MHD_pool_try_alloc()). Such blocks must never * be passed to MHD_pool_reallocate(). */ bool from_end; }; /** * The model of one pool. */ struct fz_pool { struct MemoryPool *pool; /** * Address of the first byte of the pool, as returned by * MHD_pool_reset() for an empty pool -- that is a real MHD call site * (connection.c:3021 uses the result as the new read buffer). */ uint8_t *base; /** * Total size of the pool in bytes. */ size_t cap; struct fz_block blk[FZ_MAX_BLOCKS]; unsigned int nblk; uint8_t next_tag; /** * Verify every live block after every operation. */ bool paranoid; }; /** * F1 -- MHD_pool_deallocate() of a "from the end" block of a pool that * is *exactly* full. This is a live defect in memorypool.c and is * therefore off by default; set MHD_FUZZ_POOL_FULL_DEALLOC=1 to reach * it (seed fuzz_memorypool-15.bin is the byte-exact reproducer). * * MHD_pool_deallocate() decides whether a block came from the front or * from the end with * * if (block_offset <= pool->pos) memorypool.c:666 * * which is ambiguous when pool->pos == pool->end, i.e. when the pool has * no free space left: a "from the end" block then starts exactly at * pool->pos and is treated as a front block. With --enable-asserts * * mhd_assert ((block_offset != pool->pos) || (block_size == 0)); :655 * mhd_assert (alg_end <= pool->pos); :671 * * both fail, i.e. the process aborts; without them the block is simply * not returned to the pool (pool->end is left alone), so the memory is * lost until the pool is reset or destroyed. Reproducer: * * p = MHD_pool_create (128); * e = MHD_pool_allocate (p, 16, true); * (void) MHD_pool_allocate (p, MHD_pool_get_free (p), false); * MHD_pool_deallocate (p, e, 16); <- abort / 16 bytes lost * * Nothing in memorypool.h forbids this; MHD_pool_deallocate() documents * only that "the NULL is tolerated" and has an explicit branch for * blocks allocated from the end. MHD's own call sites never hit it, * because the three MHD_pool_deallocate() calls in connection.c and * response.c all pass the read or the write buffer, which are front * allocations -- so this is a latent defect of a supported branch of the * API rather than something reachable from the network today. A * dispatch on `block_offset < pool->end` would resolve the ambiguity. */ static int full_dealloc_enabled; /** * F2 -- MHD_pool_reallocate() reports success for a @a new_size that * wrapped. Also a live defect, off by default; set * MHD_FUZZ_POOL_WRAP_REALLOC=1 to reach it (seed * fuzz_memorypool-16.bin is the byte-exact reproducer). * * Every other entry point of memorypool.c detects a size that is too * close to SIZE_MAX explicitly: * * asize = ROUND_TO_ALIGN_PLUS_RED_ZONE (size); * if ( (0 == asize) && (0 != size) ) * return NULL; // "size too close to SIZE_MAX" * * -- MHD_pool_allocate(), MHD_pool_try_alloc() and the "need to * allocate a new block" tail of MHD_pool_reallocate() all do it. The * in-place branch of MHD_pool_reallocate() instead relies on * * const size_t new_apos = * ROUND_TO_ALIGN_PLUS_RED_ZONE (old_offset + new_size); * if ( (new_apos > pool->end) || * (new_apos < pool->pos) ) // "Value wrap" * return NULL; * * which does not catch the wrap when the wrapped value happens to land * on pool->pos. For a zero-length block sitting at the front boundary * (old_size == 0, old_offset == pool->pos, which is exactly what * MHD_pool_reset (pool, NULL, 0, 0) returns -- see connection.c:3021 -- * or MHD_pool_allocate (pool, 0, false)) and any new_size in * [SIZE_MAX - 14, SIZE_MAX], old_offset + new_size wraps to * old_offset - 1 - k, which rounds back up to exactly old_offset, i.e. * to pool->pos: neither test fires, pool->pos is left alone and the * function returns @a old, i.e. it reports success. * * p = MHD_pool_create (1024); * b = MHD_pool_reset (p, NULL, 0, 0); * r = MHD_pool_reallocate (p, b, 0, SIZE_MAX - 4); * // r == b, not NULL: the caller now believes it owns * // SIZE_MAX - 4 bytes at the start of a 1024 byte pool, * // while MHD_pool_get_free() still reports the full 1024. * * The documented contract is "@return new address of the block, or NULL * if the pool cannot support @a new_size bytes", so this is a plain * contract violation, and one that hands the caller a buffer size the * allocation does not have. No MHD call site can reach it today: every * new_size MHD passes is derived from the pool size (connection.c:1636, * 2031, 2082, 2121, 2170, 6935), so it is a latent defect rather than * something reachable from the network. Checking the addition itself, * e.g. `if (new_size > pool->size - old_offset) return NULL;`, would * close it. */ static int wrap_realloc_enabled; static int known_bugs_read; /** Statistics, printed at exit with --verbose. */ static unsigned long stat_ops; static unsigned long stat_alloc_ok; static unsigned long stat_alloc_fail; static unsigned long stat_realloc_moved; static unsigned long stat_resets; static void print_stats (void) { if (! fuzz_verbose) return; fprintf (stderr, "%s: ops=%lu allocations=%lu (failed %lu) " "moved reallocations=%lu resets=%lu\n", FUZZ_HARNESS_NAME, stat_ops, stat_alloc_ok, stat_alloc_fail, stat_realloc_moved, stat_resets); } /** * Report a finding, prefixed with the name of the operation that was * running. */ static void fz_report (const char *op, const char *what) { char msg[256]; (void) snprintf (msg, sizeof (msg), "%s: %s", op, what); fuzz_report_finding (msg); } /** * The ROUND_TO_ALIGN() of memorypool.c, wrap-around included: a size * that is too close to SIZE_MAX rounds to 0, which is how the allocator * detects it. */ static size_t fz_round (size_t n) { return (n + (FZ_ALIGN_SIZE - 1)) / FZ_ALIGN_SIZE * FZ_ALIGN_SIZE; } /** * Byte @a idx of the check pattern of a block with seed @a tag. */ static uint8_t fz_pat (uint8_t tag, size_t idx) { return (uint8_t) ((((unsigned int) tag) * 131u) + ((unsigned int) (idx * 17u)) + 0x5Au); } /** * Write the check pattern into @a ptr[from..to). */ static void fz_fill (uint8_t *ptr, uint8_t tag, size_t from, size_t to) { size_t i; if (to > FZ_PAT_MAX) to = FZ_PAT_MAX; for (i = from; i < to; i++) ptr[i] = fz_pat (tag, i); } /** * Verify that the first bytes of @a ptr still carry the pattern of * @a tag. The expected bytes are built in an exactly sized malloc()ed * buffer, so that a comparison that runs off either end is caught by * ASAN rather than silently passing. */ static void fz_verify (const uint8_t *ptr, size_t size, uint8_t tag, const char *op, const char *what) { size_t n = (size < FZ_PAT_MAX) ? size : (size_t) FZ_PAT_MAX; uint8_t *expect; size_t i; if (0 == n) return; expect = (uint8_t *) malloc (n); if (NULL == expect) abort (); for (i = 0; i < n; i++) expect[i] = fz_pat (tag, i); if (0 != memcmp (expect, ptr, n)) fz_report (op, what); free (expect); } /** * Verify every live block. */ static void fz_verify_all (struct fz_pool *st, const char *op) { unsigned int i; for (i = 0; i < st->nblk; i++) fz_verify (st->blk[i].ptr, st->blk[i].size, st->blk[i].tag, op, "the contents of a live allocation changed"); } /** * Check a pointer the pool just returned: inside the pool, aligned, and * not overlapping any block that is still live. The caller has already * removed the block being replaced (if any) from the model. */ static void fz_check_ptr (struct fz_pool *st, void *p, size_t size, const char *op) { const uint8_t *up = (const uint8_t *) p; size_t off; unsigned int i; if ( (up < st->base) || (up > st->base + st->cap) ) { fz_report (op, "returned a pointer outside of the pool"); return; } off = (size_t) (up - st->base); if ( (size > st->cap) || (off + size > st->cap) ) fz_report (op, "returned a block that extends past the end of the pool"); if (0 != (off % FZ_ALIGN_SIZE)) fz_report (op, "returned a misaligned pointer"); if (0 == size) return; for (i = 0; i < st->nblk; i++) { const uint8_t *q = st->blk[i].ptr; if (0 == st->blk[i].size) continue; if ( (up < q + st->blk[i].size) && (q < up + size) ) { fz_report (op, "returned a block overlapping another live allocation"); return; } } } /** * Invariants that must hold after every single operation. */ static void fz_check_invariants (struct fz_pool *st, const char *op) { size_t total = 0; size_t freem; unsigned int i; freem = MHD_pool_get_free (st->pool); if (freem > st->cap) fz_report (op, "MHD_pool_get_free() exceeds the size of the pool"); for (i = 0; i < st->nblk; i++) total += st->blk[i].size; if (total > st->cap) fz_report (op, "the live allocations alone exceed the size of the pool"); else if (total + freem > st->cap) fz_report (op, "the live allocations plus the free space exceed the size " "of the pool"); if (st->paranoid) fz_verify_all (st, op); } static struct fz_block * fz_add (struct fz_pool *st, void *ptr, size_t size, bool from_end) { struct fz_block *b = &st->blk[st->nblk++]; b->ptr = (uint8_t *) ptr; b->size = size; b->tag = st->next_tag++; b->from_end = from_end; fz_fill (b->ptr, b->tag, 0, size); return b; } static void fz_del (struct fz_pool *st, struct fz_block *b) { *b = st->blk[--st->nblk]; } /** * Pick a live block. * * @param st the model * @param sel selector byte * @param front_only only consider blocks that may be reallocated * @return NULL if there is no such block */ static struct fz_block * fz_pick (struct fz_pool *st, uint8_t sel, bool front_only) { unsigned int i; unsigned int n = 0; unsigned int idx; for (i = 0; i < st->nblk; i++) { if ( (! front_only) || (! st->blk[i].from_end) ) n++; } if (0 == n) return NULL; idx = ((unsigned int) sel) % n; for (i = 0; i < st->nblk; i++) { if ( (front_only) && (st->blk[i].from_end) ) continue; if (0 == idx) return &st->blk[i]; idx--; } return NULL; /* unreachable */ } /** * Turn a selector byte into a size. The four classes matter: tiny * sizes are what headers use, fractions of the pool are what the * request buffers use, sizes around the currently free amount are where * the off-by-one-block bugs live, and sizes close to SIZE_MAX exercise * the "value wrap" guards of the allocator. */ static size_t fz_size (uint8_t sel, size_t cap, size_t freem) { size_t d; switch (sel & 0x03) { case 0: return (size_t) (sel >> 2); /* 0 .. 63 */ case 1: return (((size_t) ((sel >> 2) + 1)) * cap) / 64u; case 2: d = (size_t) ((sel >> 2) & 0x07u); if (0 != (sel & 0x20)) return freem + d; return (freem > d) ? (freem - d) : 0; default: return SIZE_MAX - (size_t) (sel >> 2); } } static void fz_pool_close (struct fz_pool *st) { MHD_pool_destroy (st->pool); st->pool = NULL; st->nblk = 0; } /** * Create a pool and learn its base address and its exact size. * * @return false if the pool could not be created */ static bool fz_pool_open (struct fz_pool *st, uint8_t sel) { size_t max = fz_pool_sizes[((size_t) sel) % FZ_NUM_POOL_SIZES]; void *base; st->nblk = 0; st->pool = MHD_pool_create (max); if (NULL == st->pool) return false; st->cap = MHD_pool_get_free (st->pool) + FZ_RED_ZONE_SIZE; if (st->cap != fz_round (max)) fz_report ("MHD_pool_create", "a fresh pool does not offer the requested size rounded " "up to the alignment"); /* MHD_pool_reset() with nothing to keep returns the start of the pool; connection.c:3021 relies on exactly this call. It is the only way to learn the base address through the public interface. */ base = MHD_pool_reset (st->pool, NULL, 0, 0); if (NULL == base) { fz_report ("MHD_pool_reset", "returned NULL for an empty pool"); fz_pool_close (st); return false; } st->base = (uint8_t *) base; return true; } /* ------------------------------------------------------------------ */ /* The individual operations */ /* ------------------------------------------------------------------ */ /** * MHD_pool_allocate(), from the front or from the end. */ static void fz_op_alloc (struct fz_pool *st, const uint8_t *op, bool prefer_end) { static const char *const nm[2] = { "MHD_pool_allocate", "MHD_pool_allocate (from_end)" }; const bool from_end = (0 != (op[1] & 0x01)) || prefer_end; const char *name = nm[from_end ? 1 : 0]; size_t freem; size_t after; size_t size; void *p; if (st->nblk >= FZ_MAX_BLOCKS) return; freem = MHD_pool_get_free (st->pool); size = fz_size (op[2], st->cap, freem); p = MHD_pool_allocate (st->pool, size, from_end); after = MHD_pool_get_free (st->pool); if (NULL == p) { stat_alloc_fail++; if (after != freem) fz_report (name, "a failed allocation changed the amount of free space"); if ( (0 != fz_round (size)) && (fz_round (size) <= freem) ) fz_report (name, "allocation failed although MHD_pool_get_free() reported " "room for it"); return; } stat_alloc_ok++; if (after > freem) fz_report (name, "MHD_pool_get_free() increased across an allocation"); else if (freem - after < size) fz_report (name, "MHD_pool_get_free() dropped by less than the allocated size"); fz_check_ptr (st, p, size, name); (void) fz_add (st, p, size, from_end); } /** * Allocate exactly MHD_pool_get_free() bytes. response.c:2203 does * this and dereferences the result without a NULL check, so it must * always succeed, and it must leave the pool without any free space. */ static void fz_op_alloc_all (struct fz_pool *st, const uint8_t *op) { static const char name[] = "MHD_pool_allocate (all free)"; const bool from_end = (0 != (op[1] & 0x01)); size_t freem; void *p; if (st->nblk >= FZ_MAX_BLOCKS) return; freem = MHD_pool_get_free (st->pool); if (0 == freem) return; p = MHD_pool_allocate (st->pool, freem, from_end); if (NULL == p) { stat_alloc_fail++; fz_report (name, "allocating exactly MHD_pool_get_free() bytes failed"); return; } stat_alloc_ok++; fz_check_ptr (st, p, freem, name); if (0 != MHD_pool_get_free (st->pool)) fz_report (name, "the pool still reports free space after all of it was " "allocated"); (void) fz_add (st, p, freem, from_end); } /** * MHD_pool_try_alloc(). Checks the contract of @a required_bytes. */ static void fz_op_try_alloc (struct fz_pool *st, const uint8_t *op) { static const char name[] = "MHD_pool_try_alloc"; size_t freem; size_t after; size_t size; size_t need; void *p; if (st->nblk >= FZ_MAX_BLOCKS) return; freem = MHD_pool_get_free (st->pool); size = fz_size (op[2], st->cap, freem); need = 0x5A5A5A5Au; /* poor man's "was it written at all" */ p = MHD_pool_try_alloc (st->pool, size, &need); after = MHD_pool_get_free (st->pool); if (NULL == p) { stat_alloc_fail++; if (after != freem) fz_report (name, "a failed allocation changed the amount of free space"); if (0 == need) fz_report (name, "the allocation failed but no additional memory is " "reported to be required"); else if ( (SIZE_MAX != need) && (need > st->cap) ) fz_report (name, "more memory is reported to be required than the pool " "has in total"); if ( (0 != fz_round (size)) && (fz_round (size) <= freem) ) fz_report (name, "allocation failed although MHD_pool_get_free() reported " "room for it"); return; } stat_alloc_ok++; if (0 != need) fz_report (name, "the allocation succeeded but required_bytes was not " "cleared"); if (after > freem) fz_report (name, "MHD_pool_get_free() increased across an allocation"); else if (freem - after < size) fz_report (name, "MHD_pool_get_free() dropped by less than the allocated size"); fz_check_ptr (st, p, size, name); /* try_alloc always allocates "from the end" */ (void) fz_add (st, p, size, true); } /** * The logic of MHD_connection_alloc_memory_() (connection.c:706): when * MHD_pool_try_alloc() fails it names the number of bytes that have to * be freed in the relocatable area; freeing exactly that many bytes by * shrinking a block that is resizable in-place must make the very same * allocation succeed. If it does not, MHD returns "out of memory" for * a request it has the memory for. */ static void fz_op_squeeze (struct fz_pool *st, const uint8_t *op) { static const char name[] = "MHD_pool_try_alloc (squeeze)"; size_t size; size_t need = 0; size_t need2 = 0; void *p; unsigned int i; struct fz_block *victim = NULL; if (st->nblk >= FZ_MAX_BLOCKS) return; size = fz_size (op[2], st->cap, MHD_pool_get_free (st->pool)); p = MHD_pool_try_alloc (st->pool, size, &need); if (NULL != p) { fz_check_ptr (st, p, size, name); (void) fz_add (st, p, size, true); return; } if ( (0 == need) || (SIZE_MAX == need) ) return; for (i = 0; i < st->nblk; i++) { if (st->blk[i].from_end) continue; if (st->blk[i].size < need) continue; if (! MHD_pool_is_resizable_inplace (st->pool, st->blk[i].ptr, st->blk[i].size)) continue; victim = &st->blk[i]; break; } if (NULL == victim) return; { const size_t new_size = victim->size - need; void *shrunk = MHD_pool_reallocate (st->pool, victim->ptr, victim->size, new_size); if (NULL == shrunk) { fz_report (name, "shrinking a block that is resizable in-place failed"); return; } if (shrunk != victim->ptr) fz_report (name, "shrinking a block that is resizable in-place moved it"); victim->ptr = (uint8_t *) shrunk; victim->size = new_size; fz_verify (victim->ptr, victim->size, victim->tag, name, "shrinking a block damaged its contents"); } p = MHD_pool_try_alloc (st->pool, size, &need2); if (NULL == p) { fz_report (name, "the allocation still fails after freeing the number of " "bytes that required_bytes asked for"); return; } fz_check_ptr (st, p, size, name); (void) fz_add (st, p, size, true); } /** * MHD_pool_reallocate() of a live block that was allocated from the * front. Blocks allocated "from the end" are excluded: memorypool.c * documents ("Blocks 'from the end' must not be reallocated") and * asserts that. */ static void fz_op_realloc (struct fz_pool *st, const uint8_t *op) { static const char name[] = "MHD_pool_reallocate"; struct fz_block *b = fz_pick (st, op[1], true); struct fz_block saved; size_t freem; size_t after; size_t new_size; bool inplace; void *p; if (NULL == b) return; freem = MHD_pool_get_free (st->pool); new_size = fz_size (op[2], st->cap, freem); if ( (0 == b->size) && (new_size > SIZE_MAX - FZ_ALIGN_SIZE) && (! wrap_realloc_enabled) ) return; /* open finding F2, see above */ inplace = MHD_pool_is_resizable_inplace (st->pool, b->ptr, b->size); saved = *b; p = MHD_pool_reallocate (st->pool, b->ptr, b->size, new_size); after = MHD_pool_get_free (st->pool); if (NULL == p) { /* "old continues to be valid for old_size" */ if (after != freem) fz_report (name, "a failed reallocation changed the amount of free space"); fz_verify (saved.ptr, saved.size, saved.tag, name, "a failed reallocation damaged the old block"); if ( (inplace) && (new_size <= saved.size + freem) ) fz_report (name, "reallocation failed although the block is resizable " "in-place and the pool has the required free space"); return; } if ( (inplace) && (p != saved.ptr) ) fz_report (name, "a block that MHD_pool_is_resizable_inplace() accepted was " "moved"); if ( (new_size >= saved.size) && (after > freem) ) fz_report (name, "MHD_pool_get_free() increased across a growing " "reallocation"); /* the old location is gone as far as the model is concerned */ fz_del (st, b); if (p != saved.ptr) stat_realloc_moved++; fz_check_ptr (st, p, new_size, name); fz_verify ((const uint8_t *) p, (new_size < saved.size) ? new_size : saved.size, saved.tag, name, "reallocation did not preserve the contents of the block"); b = &st->blk[st->nblk++]; b->ptr = (uint8_t *) p; b->size = new_size; b->tag = saved.tag; b->from_end = false; if (new_size > saved.size) fz_fill (b->ptr, b->tag, saved.size, new_size); } /** * MHD_pool_reallocate() with @a old == NULL, which is the documented * way to obtain a fresh relocatable block (connection.c:2121 uses it * for the very first write buffer). */ static void fz_op_realloc_new (struct fz_pool *st, const uint8_t *op) { static const char name[] = "MHD_pool_reallocate (fresh)"; size_t freem; size_t size; void *p; if (st->nblk >= FZ_MAX_BLOCKS) return; freem = MHD_pool_get_free (st->pool); size = fz_size (op[2], st->cap, freem); p = MHD_pool_reallocate (st->pool, NULL, 0, size); if (NULL == p) { stat_alloc_fail++; if ( (0 != fz_round (size)) && (fz_round (size) <= freem) ) fz_report (name, "allocation failed although MHD_pool_get_free() reported " "room for it"); return; } stat_alloc_ok++; if (MHD_pool_get_free (st->pool) > freem) fz_report (name, "MHD_pool_get_free() increased across an allocation"); fz_check_ptr (st, p, size, name); (void) fz_add (st, p, size, false); } /** * MHD_pool_deallocate() of a live block, or of NULL ("the NULL is * tolerated"). A block is always deallocated with the size it * currently has: memorypool.c asserts that the block lies inside the * allocated area, and splitting a block is explicitly disallowed. */ static void fz_op_dealloc (struct fz_pool *st, const uint8_t *op) { static const char name[] = "MHD_pool_deallocate"; struct fz_block *b = fz_pick (st, op[1], false); size_t freem; size_t after; freem = MHD_pool_get_free (st->pool); if ( (NULL != b) && (b->from_end) && (0 != b->size) && (0 == freem) && (! full_dealloc_enabled) ) { /* See the comment on full_dealloc_enabled: this is an open finding, not a precondition of MHD_pool_deallocate(). The lowest-addressed live "from the end" block of non-zero size starts exactly at pool->end, which for a full pool is also pool->pos -- the ambiguous case. Any block above it is unaffected, so only that one block is spared. Zero-sized blocks do not count: they consume nothing, so they can sit below pool->end once a later deallocation has moved pool->end back up past them. */ unsigned int i; for (i = 0; i < st->nblk; i++) { if ( (st->blk[i].from_end) && (0 != st->blk[i].size) && (st->blk[i].ptr < b->ptr) ) break; } if (i == st->nblk) return; } if (NULL == b) { MHD_pool_deallocate (st->pool, NULL, 0); } else { fz_verify (b->ptr, b->size, b->tag, name, "the contents of the block changed before it was freed"); MHD_pool_deallocate (st->pool, b->ptr, b->size); fz_del (st, b); } after = MHD_pool_get_free (st->pool); if (after < freem) fz_report (name, "deallocation reduced the amount of free space"); } /** * MHD_pool_reset(). Preconditions: copy_bytes <= new_size, * new_size <= size of the pool, and the kept block must really hold * copy_bytes bytes. */ static void fz_op_reset (struct fz_pool *st, const uint8_t *op) { static const char name[] = "MHD_pool_reset"; struct fz_block *b = fz_pick (st, (uint8_t) (op[1] & 0x0F), false); size_t new_size; size_t copy; uint8_t tag = 0; void *p; new_size = fz_size (op[2], st->cap, MHD_pool_get_free (st->pool)); if (new_size > st->cap) new_size = st->cap; copy = 0; if (NULL != b) { copy = (b->size * ((size_t) (op[1] >> 4))) / 15u; if (copy > b->size) copy = b->size; if (copy > new_size) copy = new_size; tag = b->tag; fz_verify (b->ptr, b->size, b->tag, name, "the contents of the kept block changed before the reset"); } p = MHD_pool_reset (st->pool, (NULL != b) ? b->ptr : NULL, copy, new_size); stat_resets++; /* every allocation is gone now */ st->nblk = 0; if (NULL == p) { fz_report (name, "returned NULL"); return; } fz_check_ptr (st, p, new_size, name); fz_verify ((const uint8_t *) p, copy, tag, name, "the kept bytes did not survive the reset"); b = fz_add (st, p, new_size, false); /* fz_add() has just re-tagged and re-filled the whole block */ } /** * MHD_pool_is_resizable_inplace() on a live block, or on NULL. */ static void fz_op_resizable (struct fz_pool *st, const uint8_t *op) { static const char name[] = "MHD_pool_is_resizable_inplace"; struct fz_block *b = fz_pick (st, op[1], false); bool r; if ( (NULL == b) || (0 != (op[1] & 0x80)) ) { if (MHD_pool_is_resizable_inplace (st->pool, NULL, 0)) fz_report (name, "an unallocated block is reported as resizable"); return; } r = MHD_pool_is_resizable_inplace (st->pool, b->ptr, b->size); if ( (r) && (b->from_end) && (0 != b->size) ) fz_report (name, "a block allocated from the end is reported as resizable " "in-place"); if (! r) return; /* A block that is resizable in-place must survive a resize to its own size without moving; connection.c asserts this after every such reallocation. */ { void *p = MHD_pool_reallocate (st->pool, b->ptr, b->size, b->size); if (NULL == p) fz_report (name, "reallocating a resizable block to its own size failed"); else if (p != b->ptr) fz_report (name, "reallocating a resizable block to its own size moved it"); } } static void fz_do_op (struct fz_pool *st, const uint8_t *op, bool prefer_end) { const char *name = "operation"; stat_ops++; switch ((enum fz_op) (op[0] % (uint8_t) FZ_OP_COUNT)) { case FZ_OP_ALLOC: fz_op_alloc (st, op, prefer_end); break; case FZ_OP_ALLOC_ALL: fz_op_alloc_all (st, op); break; case FZ_OP_TRY_ALLOC: fz_op_try_alloc (st, op); break; case FZ_OP_SQUEEZE: fz_op_squeeze (st, op); break; case FZ_OP_REALLOC: fz_op_realloc (st, op); break; case FZ_OP_REALLOC_NEW: fz_op_realloc_new (st, op); break; case FZ_OP_DEALLOC: fz_op_dealloc (st, op); break; case FZ_OP_RESET: fz_op_reset (st, op); break; case FZ_OP_GET_FREE: name = "MHD_pool_get_free"; break; case FZ_OP_RESIZABLE: fz_op_resizable (st, op); break; case FZ_OP_VERIFY: name = "verify"; fz_verify_all (st, name); break; case FZ_OP_RECREATE: fz_pool_close (st); if (! fz_pool_open (st, op[1])) return; break; case FZ_OP_COUNT: default: break; } fz_check_invariants (st, name); } int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { static bool inited = false; struct fz_pool st; size_t nops; size_t i; if (size < 5) return 0; if (! inited) { inited = true; /* Sets the page size used by MHD_pool_create(); MHD does this once from MHD_start_daemon(). */ MHD_init_mem_pools_ (); (void) atexit (&print_stats); } if (! known_bugs_read) { const char *e; known_bugs_read = 1; e = getenv ("MHD_FUZZ_POOL_FULL_DEALLOC"); if (NULL != e) full_dealloc_enabled = (0 != atoi (e)); e = getenv ("MHD_FUZZ_POOL_WRAP_REALLOC"); if (NULL != e) wrap_realloc_enabled = (0 != atoi (e)); } memset (&st, 0, sizeof (st)); st.paranoid = (0 != (data[1] & 0x01)); if (! fz_pool_open (&st, data[0])) return 0; nops = (size - 2) / 3; if (nops > FZ_MAX_OPS) nops = FZ_MAX_OPS; for (i = 0; i < nops; i++) { if (NULL == st.pool) break; fz_do_op (&st, data + 2 + 3 * i, (0 != (data[1] & 0x02))); } fz_verify_all (&st, "final"); fz_pool_close (&st); /* MHD_pool_destroy() tolerates a NULL pool */ return 0; } /* ------------------------------------------------------------------ */ /* Generator */ /* ------------------------------------------------------------------ */ /** * Opcodes, weighted: the allocating operations and the reallocation are * what move the pool's internal offsets around, so they get most of the * probability mass, while the read-only queries and the destructive * reset and re-create are rarer. */ static const uint8_t gen_ops[] = { FZ_OP_ALLOC, FZ_OP_ALLOC, FZ_OP_ALLOC, FZ_OP_ALLOC, FZ_OP_ALLOC_ALL, FZ_OP_TRY_ALLOC, FZ_OP_TRY_ALLOC, FZ_OP_SQUEEZE, FZ_OP_SQUEEZE, FZ_OP_REALLOC, FZ_OP_REALLOC, FZ_OP_REALLOC, FZ_OP_REALLOC, FZ_OP_REALLOC_NEW, FZ_OP_DEALLOC, FZ_OP_DEALLOC, FZ_OP_DEALLOC, FZ_OP_RESET, FZ_OP_GET_FREE, FZ_OP_RESIZABLE, FZ_OP_RESIZABLE, FZ_OP_VERIFY, FZ_OP_RECREATE }; /** * Size selector bytes that are worth trying often: the boundary cases * (exactly the free space, one alignment unit more or less) and the * value-wrap guards. */ static uint8_t gen_size_sel (struct fuzz_rng *rng) { const uint32_t k = fuzz_below (rng, 100); uint32_t d; uint32_t sign; if (k < 35) /* tiny */ return (uint8_t) ((fuzz_below (rng, 64) << 2) | 0u); if (k < 60) /* fraction of the pool */ return (uint8_t) ((fuzz_below (rng, 64) << 2) | 1u); if (k < 95) { /* around the free space */ /* Two statements, not one expression: the order in which the operands of '|' are evaluated is unspecified, and both calls advance the PRNG, so a single expression would make the generated stream compiler-dependent. */ d = fuzz_below (rng, 8); sign = fuzz_below (rng, 2); return (uint8_t) ((d << 2) | (sign << 5) | 2u); } return (uint8_t) ((fuzz_below (rng, 64) << 2) | 3u); /* value wrap */ } static size_t fuzz_generate (struct fuzz_rng *rng, uint8_t *buf, size_t cap) { size_t len = 0; unsigned int nops; unsigned int i; unsigned int psel; uint8_t flags = 0; if (cap < 8) return 0; /* Small pools are where the interesting paths are, so bias towards them, but keep the whole table reachable. */ if (fuzz_chance (rng, 3)) psel = fuzz_below (rng, (uint32_t) FZ_NUM_POOL_SIZES); else psel = fuzz_below (rng, 16); buf[len++] = (uint8_t) psel; /* One PRNG call per statement, see gen_size_sel(). */ if (fuzz_chance (rng, 4)) flags |= 0x01; if (fuzz_chance (rng, 8)) flags |= 0x02; buf[len++] = flags; nops = 1 + fuzz_below (rng, FZ_MAX_OPS); for (i = 0; i < nops; i++) { if (len + 3 > cap) break; buf[len++] = gen_ops[fuzz_below (rng, (uint32_t) (sizeof (gen_ops)))]; buf[len++] = fuzz_byte (rng); buf[len++] = gen_size_sel (rng); } return len; } /* ------------------------------------------------------------------ */ /* Seed corpus */ /* ------------------------------------------------------------------ */ /* Size selectors, see fz_size() */ #define SZ_TINY(n) ((uint8_t) ((((unsigned int) (n)) << 2) | 0u)) #define SZ_FRAC(k) ((uint8_t) ((((unsigned int) (k)) << 2) | 1u)) #define SZ_FREE ((uint8_t) 2u) #define SZ_FREE_M(d) ((uint8_t) ((((unsigned int) (d)) << 2) | 2u)) #define SZ_FREE_P(d) ((uint8_t) ((((unsigned int) (d)) << 2) | 0x20u | 2u)) #define SZ_HUGE ((uint8_t) 3u) /* Pool size selectors, indices into fz_pool_sizes[] */ #define PS_1 0 #define PS_16 2 #define PS_32 4 #define PS_64 6 #define PS_128 8 #define PS_256 11 #define PS_512 14 #define PS_1024 16 #define PS_1500 18 #define PS_32768 23 #define OPR(o,b,s) ((uint8_t) (o)), ((uint8_t) (b)), (s) static const uint8_t seed_grow_shrink[] = { PS_512, 0x01, OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (32)), OPR (FZ_OP_REALLOC, 0x00, SZ_TINY (63)), OPR (FZ_OP_REALLOC, 0x00, SZ_TINY (8)), OPR (FZ_OP_REALLOC, 0x00, SZ_FRAC (32)), OPR (FZ_OP_VERIFY, 0x00, SZ_TINY (0)), OPR (FZ_OP_REALLOC, 0x00, SZ_TINY (1)), OPR (FZ_OP_DEALLOC, 0x00, SZ_TINY (0)) }; static const uint8_t seed_two_blocks_realloc[] = { PS_256, 0x01, OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (17)), OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (23)), /* the first block is no longer the last one: it has to move */ OPR (FZ_OP_REALLOC, 0x00, SZ_TINY (60)), OPR (FZ_OP_VERIFY, 0x00, SZ_TINY (0)), OPR (FZ_OP_REALLOC, 0x01, SZ_TINY (40)), OPR (FZ_OP_VERIFY, 0x00, SZ_TINY (0)) }; static const uint8_t seed_from_end[] = { PS_128, 0x01, OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (16)), OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (1)), OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (16)), OPR (FZ_OP_RESIZABLE, 0x00, SZ_TINY (0)), OPR (FZ_OP_DEALLOC, 0x00, SZ_TINY (0)), OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (16)) }; static const uint8_t seed_fill_exactly[] = { PS_128, 0x01, OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (16)), OPR (FZ_OP_ALLOC_ALL, 0x00, SZ_TINY (0)), OPR (FZ_OP_GET_FREE, 0x00, SZ_TINY (0)), OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (1)), OPR (FZ_OP_TRY_ALLOC, 0x00, SZ_TINY (1)) }; static const uint8_t seed_squeeze[] = { PS_512, 0x01, OPR (FZ_OP_ALLOC, 0x00, SZ_FREE), OPR (FZ_OP_SQUEEZE, 0x00, SZ_TINY (40)), OPR (FZ_OP_SQUEEZE, 0x00, SZ_TINY (7)), OPR (FZ_OP_VERIFY, 0x00, SZ_TINY (0)), OPR (FZ_OP_SQUEEZE, 0x00, SZ_FRAC (8)) }; static const uint8_t seed_squeeze_small[] = { PS_128, 0x01, OPR (FZ_OP_REALLOC_NEW, 0x00, SZ_FREE_M (2)), OPR (FZ_OP_SQUEEZE, 0x00, SZ_TINY (17)), OPR (FZ_OP_SQUEEZE, 0x00, SZ_TINY (17)), OPR (FZ_OP_SQUEEZE, 0x00, SZ_TINY (17)) }; static const uint8_t seed_reset_keep[] = { PS_1500, 0x01, OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (60)), OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (12)), OPR (FZ_OP_RESET, 0xF0, SZ_FRAC (31)), OPR (FZ_OP_VERIFY, 0x00, SZ_TINY (0)), OPR (FZ_OP_RESET, 0xF0, SZ_TINY (4)), OPR (FZ_OP_RESET, 0x00, SZ_TINY (0)) }; static const uint8_t seed_reset_full[] = { PS_256, 0x01, OPR (FZ_OP_ALLOC, 0x00, SZ_FRAC (63)), OPR (FZ_OP_RESET, 0xF0, SZ_FRAC (63)), OPR (FZ_OP_RESET, 0xF0, SZ_FREE_P (1)), OPR (FZ_OP_VERIFY, 0x00, SZ_TINY (0)) }; static const uint8_t seed_boundary[] = { PS_64, 0x01, OPR (FZ_OP_ALLOC, 0x00, SZ_FREE_M (1)), OPR (FZ_OP_ALLOC, 0x00, SZ_FREE), OPR (FZ_OP_ALLOC, 0x01, SZ_FREE_P (1)), OPR (FZ_OP_TRY_ALLOC, 0x00, SZ_FREE), OPR (FZ_OP_DEALLOC, 0x00, SZ_TINY (0)), OPR (FZ_OP_ALLOC, 0x00, SZ_FREE) }; static const uint8_t seed_wrap[] = { PS_256, 0x00, OPR (FZ_OP_ALLOC, 0x00, SZ_HUGE), OPR (FZ_OP_ALLOC, 0x01, SZ_HUGE), OPR (FZ_OP_TRY_ALLOC, 0x00, SZ_HUGE), OPR (FZ_OP_REALLOC_NEW, 0x00, SZ_HUGE), OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (16)), OPR (FZ_OP_REALLOC, 0x00, SZ_HUGE), OPR (FZ_OP_VERIFY, 0x00, SZ_TINY (0)) }; static const uint8_t seed_tiny_pool[] = { PS_1, 0x01, OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (1)), OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (1)), OPR (FZ_OP_GET_FREE, 0x00, SZ_TINY (0)), OPR (FZ_OP_RESET, 0xF0, SZ_TINY (1)), OPR (FZ_OP_DEALLOC, 0x00, SZ_TINY (0)) }; static const uint8_t seed_zero_sizes[] = { PS_32, 0x01, OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (0)), OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (0)), OPR (FZ_OP_REALLOC, 0x00, SZ_TINY (0)), OPR (FZ_OP_REALLOC, 0x00, SZ_TINY (4)), OPR (FZ_OP_DEALLOC, 0x00, SZ_TINY (0)), OPR (FZ_OP_RESET, 0x00, SZ_TINY (0)) }; static const uint8_t seed_many_small[] = { PS_1500, 0x01, OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (5)), OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (5)), OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (5)), OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (5)), OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (5)), OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (5)), OPR (FZ_OP_REALLOC, 0x00, SZ_TINY (33)), OPR (FZ_OP_REALLOC, 0x01, SZ_TINY (33)), OPR (FZ_OP_DEALLOC, 0x02, SZ_TINY (0)), OPR (FZ_OP_VERIFY, 0x00, SZ_TINY (0)), OPR (FZ_OP_ALLOC, 0x00, SZ_TINY (5)) }; static const uint8_t seed_recreate[] = { PS_32768, 0x00, OPR (FZ_OP_ALLOC, 0x00, SZ_FRAC (60)), OPR (FZ_OP_RECREATE, PS_16, SZ_TINY (0)), OPR (FZ_OP_ALLOC, 0x00, SZ_FREE), OPR (FZ_OP_RECREATE, PS_512, SZ_TINY (0)), OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (24)), OPR (FZ_OP_RESET, 0xF0, SZ_FRAC (2)) }; /* The read-buffer life cycle of a connection: allocate the read buffer, grow it to everything that is free, put the parsed headers "at the end", shrink the read buffer to what was actually received, then reset the pool keeping the received bytes -- connection.c does exactly this for every keep-alive request. */ static const uint8_t seed_connection_cycle[] = { PS_1500, 0x01, OPR (FZ_OP_REALLOC_NEW, 0x00, SZ_FRAC (31)), OPR (FZ_OP_REALLOC, 0x00, SZ_FREE), OPR (FZ_OP_TRY_ALLOC, 0x00, SZ_TINY (12)), OPR (FZ_OP_TRY_ALLOC, 0x00, SZ_TINY (20)), OPR (FZ_OP_SQUEEZE, 0x00, SZ_TINY (40)), OPR (FZ_OP_REALLOC, 0x00, SZ_TINY (60)), OPR (FZ_OP_VERIFY, 0x00, SZ_TINY (0)), OPR (FZ_OP_RESET, 0xF0, SZ_FRAC (31)), OPR (FZ_OP_REALLOC, 0x00, SZ_FREE), OPR (FZ_OP_VERIFY, 0x00, SZ_TINY (0)) }; /* The reproducer of the open finding described at full_dealloc_enabled: a 128 byte pool, one 16 byte block "from the end", the whole rest of the pool allocated from the front, then that first block released. Inert unless MHD_FUZZ_POOL_FULL_DEALLOC=1 is set. */ static const uint8_t seed_dealloc_end_full[] = { PS_128, 0x01, OPR (FZ_OP_ALLOC, 0x01, SZ_TINY (16)), OPR (FZ_OP_ALLOC_ALL, 0x00, SZ_TINY (0)), OPR (FZ_OP_DEALLOC, 0x00, SZ_TINY (0)) }; /* The reproducer of the open finding F2: MHD_pool_reset() with nothing to keep leaves a zero-length block at the front boundary, and reallocating that to SIZE_MAX wraps. Inert unless MHD_FUZZ_POOL_WRAP_REALLOC=1 is set. */ static const uint8_t seed_realloc_wrap[] = { PS_1024, 0x01, OPR (FZ_OP_RESET, 0x00, SZ_TINY (0)), OPR (FZ_OP_REALLOC, 0x00, SZ_HUGE) }; struct mp_seed { const uint8_t *bytes; size_t len; }; #define MSEED(a) { (a), sizeof (a) } static const struct mp_seed mp_seeds[] = { MSEED (seed_grow_shrink), MSEED (seed_two_blocks_realloc), MSEED (seed_from_end), MSEED (seed_fill_exactly), MSEED (seed_squeeze), MSEED (seed_squeeze_small), MSEED (seed_reset_keep), MSEED (seed_reset_full), MSEED (seed_boundary), MSEED (seed_wrap), MSEED (seed_tiny_pool), MSEED (seed_zero_sizes), MSEED (seed_many_small), MSEED (seed_recreate), MSEED (seed_connection_cycle), MSEED (seed_dealloc_end_full), MSEED (seed_realloc_wrap) }; static size_t fuzz_seed_count (void) { return sizeof (mp_seeds) / sizeof (mp_seeds[0]); } static const uint8_t * fuzz_seed_get (size_t idx, size_t *len) { *len = mp_seeds[idx].len; return mp_seeds[idx].bytes; } libmicrohttpd-1.0.10/src/fuzz/fuzz_auth_header.c0000664000175000017500000004315415232141452015406 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file fuzz/fuzz_auth_header.c * @brief Direct fuzzer for the "Authorization:" header parsers. * @author Christian Grothoff * * MHD_get_rq_dauth_params_() and MHD_get_rq_bauth_params_() are internal * (they live in gen_auth.c and are not exported), and both need a * `struct MHD_Connection`. Rather than pushing bytes through a socket, * this harness assembles the *minimal* connection object those two * functions actually touch -- a daemon pointer, a memory pool, a state * and a single "Authorization" header -- and then varies only the header * value. That makes this the fastest way to explore the parameter * parser (roughly two orders of magnitude more executions per second * than fuzz_request). * * Besides memory-safety (ASAN), the harness checks the parser output for * internal consistency: every returned parameter must be a sub-range of * the header value that was fed in. A parameter pointing outside of it * would be a parser bug that ASAN alone might not catch. * * Input format: * byte 0 scheme selector / pool size selector * byte 1.. the raw "Authorization" header value */ #define FUZZ_HARNESS_NAME "fuzz_auth_header" #include "fuzz_common.h" /* internal.h pulls in MHD_config.h and in the right order; including first would redefine _MHD_EXTERN. */ #include "internal.h" #include "memorypool.h" #include "gen_auth.h" #include "mhd_str.h" #ifdef DAUTH_SUPPORT #include "digestauth.h" #endif #ifdef BAUTH_SUPPORT #include "basicauth.h" #endif static const size_t pool_sizes[] = { 256, 512, 1024, 4096, 32768 }; /** * Exactly-sized, NUL terminated copy of @a len bytes of @a src. * * "Exactly sized" is the point: the allocation is @a len + 1 bytes and * not one byte more, so ASAN's redzone sits immediately behind the * terminator and any read past it is reported. */ static char * fuzz_dup_n (const char *src, size_t len) { char *r = (char *) malloc (len + 1); if (NULL == r) return NULL; memcpy (r, src, len); r[len] = '\0'; return r; } /** * gen_auth.c logs through MHD_DLOG(), which dereferences the daemon of * the connection, so a real (but idle) daemon is required. It is * created once and reused for the whole run. */ static struct MHD_Daemon *shared_daemon; /** Statistics, printed at exit with --verbose. */ static unsigned long stat_dauth_parsed; static unsigned long stat_dauth_failed; static unsigned long stat_bauth_parsed; static unsigned long stat_bauth_failed; static void print_stats (void) { if (! fuzz_verbose) return; fprintf (stderr, "%s: digest headers parsed=%lu rejected=%lu; " "basic headers parsed=%lu rejected=%lu\n", FUZZ_HARNESS_NAME, stat_dauth_parsed, stat_dauth_failed, stat_bauth_parsed, stat_bauth_failed); } static enum MHD_Result dummy_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; (void) connection; (void) url; (void) method; (void) version; (void) upload_data; (void) upload_data_size; (void) req_cls; return MHD_NO; } static void stop_shared_daemon (void) { if (NULL != shared_daemon) { MHD_stop_daemon (shared_daemon); shared_daemon = NULL; } } static struct MHD_Daemon * get_shared_daemon (void) { if (NULL == shared_daemon) { shared_daemon = MHD_start_daemon (MHD_USE_NO_LISTEN_SOCKET | (fuzz_verbose ? MHD_USE_ERROR_LOG : 0u), 0, NULL, NULL, &dummy_ahc, NULL, MHD_OPTION_END); if (NULL != shared_daemon) { (void) atexit (&stop_shared_daemon); (void) atexit (&print_stats); } } return shared_daemon; } #ifdef DAUTH_SUPPORT /** * Every parsed parameter must be a sub-range of the header value. */ static void check_param (const struct MHD_RqDAuthParam *pm, const char *base, size_t base_len, const char *what) { char msg[256]; if (NULL == pm->value.str) { if (0 != pm->value.len) { (void) snprintf (msg, sizeof (msg), "digest parameter '%s' has NULL string but " "non-zero length", what); fuzz_report_finding (msg); } return; } if ( (pm->value.str < base) || (pm->value.str > base + base_len) || (pm->value.len > base_len) || (pm->value.str + pm->value.len > base + base_len) ) { (void) snprintf (msg, sizeof (msg), "digest parameter '%s' points outside of the " "Authorization header value", what); fuzz_report_finding (msg); } } #endif /* DAUTH_SUPPORT */ int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { static const char hdr_name[] = MHD_HTTP_HEADER_AUTHORIZATION; struct MHD_Connection c; struct MHD_HTTP_Req_Header h; struct MemoryPool *pool; char *value; size_t vlen; unsigned int sel; size_t pool_size; if (size < 2) return 0; if (NULL == get_shared_daemon ()) return 0; sel = data[0]; vlen = size - 1; if (vlen > 4096) vlen = 4096; pool_size = pool_sizes[(sel >> 3) % (sizeof (pool_sizes) / sizeof (pool_sizes[0]))]; /* Exactly sized, zero-terminated copy of the header value, so that ASAN catches any read past its end. */ value = (char *) malloc (vlen + 1); if (NULL == value) return 0; memcpy (value, data + 1, vlen); value[vlen] = '\0'; pool = MHD_pool_create (pool_size); if (NULL == pool) { free (value); return 0; } memset (&c, 0, sizeof (c)); memset (&h, 0, sizeof (h)); h.header = hdr_name; h.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION); h.value = value; h.value_size = vlen; h.kind = MHD_HEADER_KIND; c.daemon = shared_daemon; c.pool = pool; c.rq.headers_received = &h; c.rq.headers_received_tail = &h; c.state = MHD_CONNECTION_HEADERS_PROCESSED; #ifdef DAUTH_SUPPORT if (0 == (sel & 0x01)) { const struct MHD_RqDAuth *da; da = MHD_get_rq_dauth_params_ (&c); if (NULL == da) stat_dauth_failed++; else { stat_dauth_parsed++; check_param (&da->nonce, value, vlen, "nonce"); check_param (&da->opaque, value, vlen, "opaque"); check_param (&da->response, value, vlen, "response"); check_param (&da->username, value, vlen, "username"); check_param (&da->username_ext, value, vlen, "username*"); check_param (&da->realm, value, vlen, "realm"); check_param (&da->uri, value, vlen, "uri"); check_param (&da->qop_raw, value, vlen, "qop"); check_param (&da->cnonce, value, vlen, "cnonce"); check_param (&da->nc, value, vlen, "nc"); /* The result must be stable: a second call returns the cache. */ if (da != MHD_get_rq_dauth_params_ (&c)) fuzz_report_finding ("MHD_get_rq_dauth_params_() is not idempotent"); } } #endif /* DAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT if (0 != (sel & 0x01)) { const struct MHD_RqBAuth *ba; ba = MHD_get_rq_bauth_params_ (&c); if (NULL == ba) stat_bauth_failed++; else { stat_bauth_parsed++; if (NULL != ba->token68.str) { if ( (ba->token68.str < value) || (ba->token68.str + ba->token68.len > value + vlen) ) fuzz_report_finding ("basic auth token68 points outside of the " "Authorization header value"); /* Decoding must fit into the documented maximum size. */ if (0 != ba->token68.len) { size_t need = MHD_base64_max_dec_size_ (ba->token68.len); uint8_t *bin = (uint8_t *) malloc ((0 == need) ? 1 : need); if (NULL != bin) { size_t r = MHD_base64_to_bin_n (ba->token68.str, ba->token68.len, bin, need); if (r > need) fuzz_report_finding ("MHD_base64_to_bin_n() exceeded " "MHD_base64_max_dec_size_()"); free (bin); } } } if (ba != MHD_get_rq_bauth_params_ (&c)) fuzz_report_finding ("MHD_get_rq_bauth_params_() is not idempotent"); } } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /* The connection-less digest helpers. They belong here rather than in fuzz_request because they are pure functions of their string arguments: this harness reaches roughly two orders of magnitude more executions per second, and -- more importantly -- it can hand them a username and realm taken straight from the fuzzer instead of the fixed constants fuzz_request has to use. Every output buffer is a heap allocation of *exactly* the size declared to MHD, and that size is swept down to zero, so a helper that writes its full digest into a buffer that is too small is caught immediately by ASAN's redzone rather than silently corrupting an adjacent object. That is precisely the shape of the overflow fixed in commit 5a73c1ae. */ if (0 != (sel & 0x02)) { /* Exactly one base hashing algorithm per entry. In particular MHD_DIGEST_AUTH_ALGO3_INVALID must not appear: every one of these helpers routes through digest_get_hash_size(), which asserts that precisely one of MD5 / SHA-256 / SHA-512-256 is named. Passing INVALID is an API violation on the caller's side, not something worth fuzzing. */ static const enum MHD_DigestAuthAlgo3 algo3s[] = { MHD_DIGEST_AUTH_ALGO3_MD5, MHD_DIGEST_AUTH_ALGO3_SHA256, MHD_DIGEST_AUTH_ALGO3_SHA512_256, MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION }; enum MHD_DigestAuthAlgo3 a = algo3s[(sel >> 5) % (sizeof (algo3s) / sizeof (algo3s[0]))]; size_t hs = MHD_digest_get_hash_size (a); /* Split the fuzzer-supplied header value into username / realm / password. Each gets its OWN exactly-sized allocation rather than being carved out of `value` in place: that way each string is followed by its own ASAN redzone, so a helper reading one byte past the end of the username is reported precisely instead of quietly running into the realm that would follow it in a shared buffer. */ size_t o1 = vlen / 3; size_t o2 = (2 * vlen) / 3; char *user = fuzz_dup_n (value, o1); char *realm = fuzz_dup_n (value + o1, o2 - o1); char *pass = fuzz_dup_n (value + o2, vlen - o2); if ( (NULL != user) && (NULL != realm) && (NULL != pass) ) { if ( (0 != hs) && (hs <= 64) ) { size_t claim = hs - (size_t) (data[0] % (unsigned int) (hs + 1u)); void *bin = malloc (claim); if (NULL != bin) { (void) MHD_digest_auth_calc_userdigest (a, user, realm, pass, bin, claim); (void) MHD_digest_auth_calc_userhash (a, user, realm, bin, claim); free (bin); } } { size_t need = (0 != hs) ? (2 * hs + 1) : 1; size_t claim = need - (size_t) (data[0] % (unsigned int) (need + 1u)); char *hex = (char *) malloc (claim); if (NULL != hex) { (void) MHD_digest_auth_calc_userhash_hex (a, user, realm, hex, claim); free (hex); } } } free (user); free (realm); free (pass); } #endif /* DAUTH_SUPPORT */ MHD_pool_destroy (pool); free (value); return 0; } /* ------------------------------------------------------------------ */ /* Generator */ /* ------------------------------------------------------------------ */ static const char *const gen_param_names[] = { "username", "username*", "realm", "nonce", "uri", "response", "algorithm", "qop", "nc", "cnonce", "opaque", "userhash", "charset", "domain", "unknown", "", "USERNAME", "user name" }; static const char *const gen_param_values[] = { "\"user\"", "user", "\"\"", "\"a\\\"b\"", "\"a\\\\\"", "\"\\\"", "UTF-8''a%20b", "utf-8''%41", "''", "'", "true", "false", "TRUE", "auth", "auth-int", "auth,auth-int", "\"auth\"", "MD5", "SHA-256", "SHA-512-256", "BOGUS", "\"SHA-256\"", "00000001", "ffffffff", "0123456789abcdef0123456789abcdef", "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"" }; static size_t fuzz_generate (struct fuzz_rng *rng, uint8_t *buf, size_t cap) { size_t len = 0; unsigned int nparams; unsigned int i; int basic; if (cap < 32) return 0; basic = fuzz_chance (rng, 4); buf[len++] = (uint8_t) ((fuzz_byte (rng) & 0xFE) | (basic ? 1u : 0u)); /* NB: evaluate the argument exactly once -- it usually contains a call into the PRNG. */ #define ADD(s) \ do { \ const char *s_ = (s); \ size_t l_ = strlen (s_); \ if (len + l_ >= cap) \ return len; \ memcpy (buf + len, s_, l_); \ len += l_; \ } while (0) if (basic) { unsigned int n; ADD ("Basic "); n = fuzz_below (rng, 48); for (i = 0; (i < n) && (len < cap); i++) buf[len++] = (uint8_t) "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" "0123456789+/= "[fuzz_below (rng, 66)]; return len; } ADD ("Digest "); nparams = 1 + fuzz_below (rng, 12); for (i = 0; i < nparams; i++) { if (0 != i) ADD (fuzz_chance (rng, 8) ? "," : ", "); ADD (gen_param_names[fuzz_below (rng, (uint32_t) (sizeof (gen_param_names) / sizeof (char *)))]); if (! fuzz_chance (rng, 10)) ADD (fuzz_chance (rng, 10) ? " = " : "="); ADD (gen_param_values[fuzz_below (rng, (uint32_t) (sizeof (gen_param_values) / sizeof (char *)))]); } #undef ADD return len; } /* ------------------------------------------------------------------ */ /* Seed corpus */ /* ------------------------------------------------------------------ */ struct ah_seed { const char *txt; size_t len; }; #define ASEED(t) { t, sizeof (t) - 1 } static const struct ah_seed ah_seeds[] = { ASEED ("\x00" "Digest username=\"user\", realm=\"TestRealm\", " "nonce=\"0123456789abcdef\", uri=\"/a\", qop=auth, nc=00000001, " "cnonce=\"x\", algorithm=MD5, response=\"0123456789abcdef\""), ASEED ("\x00" "Digest algorithm=BOGUS"), ASEED ("\x00" "Digest algorithm="), ASEED ("\x00" "Digest username*=UTF-8''a%20b"), ASEED ("\x00" "Digest username*=''"), ASEED ("\x00" "Digest username=\"\\\""), ASEED ("\x00" "Digest userhash=true, username=\"aaaa\""), ASEED ("\x00" "Digest response=\"" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\""), ASEED ("\x00" "Digest"), ASEED ("\x00" "Digest ,,,,,"), ASEED ("\x00" "Digest nc=\"ffffffffffffffffffffffff\""), ASEED ("\x01" "Basic dXNlcjpwYXNz"), ASEED ("\x01" "Basic "), ASEED ("\x01" "Basic ===="), ASEED ("\x01" "Basic QQ==QQ=="), /* Bit 0x02 of byte 0 additionally runs the connection-less digest helpers (MHD_digest_auth_calc_userdigest/_userhash/_userhash_hex) with the header value split into username / realm / password. Bits 5-7 pick the algorithm and byte 0 also sets the deliberately undersized output-buffer length, so the seeds below cover several algorithms at several buffer sizes. Without a seed here the branch is only reachable by a lucky bit flip in byte 0. The three *_SESSION algorithms are not seeded separately: they hash with the same primitive as their non-session counterpart, so they reach no code the entries below do not, and byte 0 is the byte a mutator flips first anyway. */ ASEED ("\x02" "user:TestRealm:pass"), ASEED ("\x22" "user:TestRealm:pass"), ASEED ("\x42" "user:TestRealm:pass"), ASEED ("\xa2" "user:TestRealm:pass"), /* Degenerate splits: empty username, empty realm, empty password. */ ASEED ("\x02" "::"), ASEED ("\x02" ""), /* Both the parser and the helpers in one execution. */ ASEED ("\x02" "Digest username=\"user\", realm=\"TestRealm\"") }; static size_t fuzz_seed_count (void) { return sizeof (ah_seeds) / sizeof (ah_seeds[0]); } static const uint8_t * fuzz_seed_get (size_t idx, size_t *len) { *len = ah_seeds[idx].len; return (const uint8_t *) ah_seeds[idx].txt; } libmicrohttpd-1.0.10/src/fuzz/fuzz_eventloop.c0000664000175000017500000017646015232414252015160 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file fuzz/fuzz_eventloop.c * @brief In-process fuzzer for MHD's external event loop and for the * scheduling of the connection life cycle. * @author Christian Grothoff * * fuzz_request.c already touches these entry points, but only as a side * channel: it picks one event-loop mode per iteration and then always * pumps in the same rhythm. The bugs this harness is after are in the * *scheduling* -- what MHD does when the application polls at adversarial * times, ignores the timeout it was given, calls MHD_run_from_select() * with descriptor sets that do not match what MHD asked for, or * suspends/resumes connections across those calls. * * The input is therefore not an HTTP request but a *schedule*: a short * configuration block followed by a program of one-byte opcodes that is * interpreted against a live `struct MHD_Daemon` with up to * #MAX_CONNS socketpair connections. Request bytes enter the program * through two of those opcodes (a fragment table and a raw literal), so * the parser is still driven, just not fuzzed. * * Input format * ------------ * * byte 0 daemon configuration * bits 0-1 MHD_OPTION_CONNECTION_TIMEOUT selector, * index into {1, 2, 0, 1} seconds * bit 2 give the daemon a real listening socket (port 0) * instead of MHD_USE_NO_LISTEN_SOCKET, so that * MHD_quiesce_daemon() has something to do and the * listen FD shows up in the descriptor sets * bit 3 pass MHD_OPTION_APP_FD_SETSIZE * bits 4-5 MHD_OPTION_CONNECTION_MEMORY_LIMIT selector, * index into {default, 256, 1024, 4096} * bit 6 MHD_OPTION_CONNECTION_LIMIT = 2, so that * MHD_add_connection() starts failing * bit 7 shrink SO_SNDBUF/SO_RCVBUF of the socketpair, so * that responses do not fit and connections stay * blocked on write * byte 1 access-handler behaviour * bits 0-1 response kind: 0 small static buffer, * 1 chunked callback (MHD_SIZE_UNKNOWN), * 2 large (128 KiB) static buffer, 3 empty * bit 2 answer 500 instead of 200 * bit 3 suspend in the handler and leave it parked * bit 4 suspend and resume immediately in the handler * bit 5 call MHD_set_connection_option() from the handler * bit 6 call MHD_get_connection_info() from the handler * bit 7 drain the client side after every run * byte 2 event-loop defaults * bits 0-2 default MHD_get_fdset*() variant * bits 3-4 default run entry point * bit 5 honour the timeout MHD returns * bit 6 query the timeouts after every run * bit 7 MHD_quiesce_daemon() before stopping * byte 3 schedule knobs * bits 0-1 number of connections opened up front (1-4) * bit 2 run the timeout oracle after every operation * bit 3 allow a real-time wait for a connection timeout * to expire (globally budgeted, see below) * bit 4 queue one more connection at the very end and * stop the daemon without running the loop again, * so that MHD has to dispose of a connection it * never started (see queue_unprocessed_conn()) * bits 5-7 unused * byte 4 artificial-clock step base * byte 5. the operation program. Each operation is one byte, * `(opcode << 4) | argument`; see enum op below. OP_SEND_RAW * is the only one with an operand: a length byte followed by * that many payload bytes. * * An input shorter than five bytes is rejected: the configuration block * is mandatory and an input that short carries no program either. * * Oracles * ------- * * Beyond ASAN/UBSAN and the MHD_set_panic_func() tripwire (any * MHD_PANIC() reached this way is a finding, including the * "MHD_stop_daemon() called while we have suspended connections" one * that answers the "the daemon must always be stoppable" requirement): * * a) the four timeout accessors must agree. MHD_get_timeout(), * MHD_get_timeout64(), MHD_get_timeout64s() and MHD_get_timeout_i() * read the same state, so either all of them report a timeout or * none of them does. Their values are read in sequence, so the * clock may advance between two of them and the value may only * *decrease*; connection_get_wait() has a documented 100 ms floor * for the "exact match" case, hence the 100 ms slack. * * b) a reported timeout must never exceed the largest connection * timeout in effect. MHD only ever derives it from * `last_activity + connection_timeout_ms`, so a larger value would * mean the deadline is somewhere the application cannot reach. * * c) MHD must never ask the application to wait forever while it has a * live, not-suspended connection with a non-zero timeout: that is * precisely the "timeout in the past" situation, i.e. a connection * that can never be reaped. Live connections are tracked through * MHD_OPTION_NOTIFY_CONNECTION, which brackets exactly the interval * in which MHD owns the connection object. * * Both inputs of (b) and (c) -- whether a connection is suspended and * what its timeout is -- are read back from MHD rather than modelled, * because both diverge from what the application asked for: * MHD_set_connection_option() silently does nothing while a * connection is suspended. A harness that models them ends up * reporting findings against its own model. * * d) MHD_get_fdset*() must not set a descriptor at or above the * FD_SETSIZE limit it was given, `*max_fd` must be at least as large * as every descriptor that was added, and `*max_fd` itself must be * one of them. * * e) after MHD_quiesce_daemon() the listening socket must be gone from * the descriptor sets. * * Two contract rules the harness has to respect (violating either makes * MHD abort on a schedule that is perfectly legal, so the harness would * only be finding its own bugs): * * * a connection is only suspended when the access handler is about to * return MHD_YES. MHD_NO asks MHD to terminate the connection, and * terminating one that the same callback just suspended trips * mhd_assert (! connection->suspended) in MHD_connection_close_(); * * * every suspended connection is resumed before MHD_stop_daemon(). * Several connections can be parked at once, so this is a set * (@e lives[i].susp), not a single slot, and @e tearing_down stops * the handler from parking anything new while the set is drained. * * MHD_suspend_connection() is additionally only called when MHD does not * already consider the connection suspended, *unless* a resume of it is * still pending -- that is the one case internal_suspend_connection_() * handles itself (it cancels the resume), and the harness mirrors the * resulting state. Calling it on an already-suspended connection would * unlink it from a list it is not on. * * One more trap: with MHD_USE_ITC -- which MHD_ALLOW_SUSPEND_RESUME * implies, so this harness always has it -- MHD_add_connection() only * *queues* the socket, and the `struct MHD_Connection` is created later, * from inside a run. There is therefore no moment at which the * application could pair its own socket up with the connection object, * and the registry of live connections has to be built purely from * MHD_OPTION_NOTIFY_CONNECTION. This is why the client sockets * (@e csock) and the connections (@e lives) are two separate arrays. * * Note on MHD_get_timeout_expiration(): no such function exists in the * MHD 1.x API. The four accessors above are the complete family; the * absolute-deadline form is a MHD 2.x addition. */ #define FUZZ_HARNESS_NAME "fuzz_eventloop" #include "fuzz_common.h" #include #include #include #include #include /** Largest number of connections a single iteration may have open. */ #define MAX_CONNS 8 /** Upper bound on the number of operations interpreted per iteration. */ #define MAX_OPS 400 /** Size of the "large response" body. */ #define BIG_BODY_LEN 131072 /** Bytes read back from the daemon are counted, never inspected. */ #define DRAIN_BUF 4096 /* ------------------------------------------------------------------ */ /* Per-iteration configuration */ /* ------------------------------------------------------------------ */ struct el_cfg { unsigned int timeout_s; /**< MHD_OPTION_CONNECTION_TIMEOUT */ int listen_sock; /**< real listening socket wanted */ int app_fd_setsize; /**< pass MHD_OPTION_APP_FD_SETSIZE */ size_t mem_limit; /**< MHD_OPTION_CONNECTION_MEMORY_LIMIT */ int conn_limit; /**< MHD_OPTION_CONNECTION_LIMIT = 2 */ int small_sockbuf; /**< shrink the socketpair buffers */ unsigned int resp_kind; /**< which response the handler queues */ int error_reply; /**< answer 500 instead of 200 */ int susp_park; /**< handler suspends and leaves it parked */ int susp_now; /**< handler suspends and resumes at once */ int hnd_connopt; /**< handler calls set_connection_option */ int hnd_info; /**< handler calls get_connection_info */ int auto_drain; /**< drain the client sockets after a run */ unsigned int fdset_var; /**< default MHD_get_fdset*() variant */ unsigned int run_var; /**< default run entry point */ int honour_timeout; /**< act on the timeout MHD returns */ int timeout_every_run; /**< query the timeouts after every run */ int quiesce_end; /**< quiesce before stopping */ unsigned int nconn_up_front; /**< connections opened before the program */ int check_always; /**< run the timeout oracle after every op */ int allow_real_wait; /**< may burn real time on a timeout expiry */ int stop_with_queued; /**< stop with a connection still queued */ uint8_t clock_seed; /**< artificial-clock step base */ }; static struct el_cfg cfg; /** Connection memory limits selectable by byte 0. */ static const size_t mem_limit_tbl[] = { 0, 256, 1024, 4096 }; /** Connection timeouts (seconds) selectable by byte 0. */ static const unsigned int timeout_tbl[] = { 1, 2, 0, 1 }; /** * FD_SETSIZE values handed to MHD_get_fdset2()/MHD_run_from_select2(). * * All of them are <= FD_SETSIZE on purpose. Passing a *larger* value * than the `fd_set` objects actually hold would let MHD write past them, * which is the application lying about its own buffers rather than * anything MHD could defend against; the interesting direction is the * smaller one, where MHD has to refuse descriptors that do not fit. */ static const unsigned int setsize_tbl[] = { (unsigned int) FD_SETSIZE, (unsigned int) FD_SETSIZE, (unsigned int) FD_SETSIZE / 2, 64, 16, 4, 1, (unsigned int) FD_SETSIZE }; /* ------------------------------------------------------------------ */ /* Per-iteration state */ /* ------------------------------------------------------------------ */ /** * The client end of one socketpair. Deliberately *not* tied to a * `struct MHD_Connection`: with MHD_USE_ITC (which * MHD_ALLOW_SUSPEND_RESUME implies) MHD_add_connection() only queues the * socket and the connection object is created later, from inside a run. * There is therefore no moment at which the harness could pair the two * up, and trying to would silently mistrack every connection. */ static int csock[MAX_CONNS]; static unsigned int nconns; static unsigned int cur_conn; /** * A connection MHD currently owns. * * The registry is maintained purely from MHD_OPTION_NOTIFY_CONNECTION, * which brackets exactly the interval in which the object exists: after * MHD_CONNECTION_NOTIFY_CLOSED nothing may reference it any more, in * particular not a deferred resume and not the "is there a live * connection" oracle. */ struct live_conn { struct MHD_Connection *mc; /**< NULL if the slot is free */ int susp; /**< suspended by us, not resumed yet */ }; /** A few more slots than connections, so the registry cannot overflow. */ #define MAX_LIVE (MAX_CONNS + 4) static struct live_conn lives[MAX_LIVE]; /** Daemon of the current iteration. */ static struct MHD_Daemon *cur_daemon; /** * Set once the iteration only wants to drain the daemon. The handler * then stops parking connections, which is what makes the flush loop in * the teardown terminate. */ static int tearing_down; /** Listening socket returned by MHD_quiesce_daemon(), ours to close. */ static MHD_socket quiesced_fd = MHD_INVALID_SOCKET; /** Artificial clock; only the harness's own scheduling depends on it. */ static uint64_t clk_ms; static uint64_t deadline_ms; static int deadline_valid; /** Descriptor sets collected by the last OP_FDSET. */ static fd_set g_rs; static fd_set g_ws; static fd_set g_es; static MHD_socket g_max_fd = MHD_INVALID_SOCKET; static unsigned int g_setsize = (unsigned int) FD_SETSIZE; static int g_have_sets; /** The large response body, filled once. */ static char big_body[BIG_BODY_LEN]; static int big_body_ready; /** * Budget for iterations that are allowed to wait in real time for a * connection timeout to expire. MHD_OPTION_CONNECTION_TIMEOUT has a * resolution of one second, so the expiry path cannot be reached without * actually burning about that much wall clock; the budget keeps the * whole run in the "couple of seconds" range while still exercising it. * Override with MHD_FUZZ_EXPIRY_BUDGET. */ static int expiry_budget = 2; static int expiry_budget_read; /** Statistics, printed at exit with --verbose. */ static unsigned long stat_daemons; static unsigned long stat_handler_calls; static unsigned long stat_fdset_v1; static unsigned long stat_fdset_v2; static unsigned long stat_rfs_v1; static unsigned long stat_rfs_v2; static unsigned long stat_run; static unsigned long stat_run_wait; static unsigned long stat_timeouts; static unsigned long stat_quiesce; static unsigned long stat_suspend; static unsigned long stat_resume; static unsigned long stat_expiry_waits; static unsigned long stat_queued_at_stop; static int stats_registered; static void print_stats (void) { if (! fuzz_verbose) return; fprintf (stderr, "%s: daemons=%lu handler=%lu get_fdset=%lu get_fdset2=%lu " "run_from_select=%lu run_from_select2=%lu run=%lu run_wait=%lu " "timeout queries=%lu quiesce=%lu suspend=%lu resume=%lu " "expiry waits=%lu queued at stop=%lu\n", FUZZ_HARNESS_NAME, stat_daemons, stat_handler_calls, stat_fdset_v1, stat_fdset_v2, stat_rfs_v1, stat_rfs_v2, stat_run, stat_run_wait, stat_timeouts, stat_quiesce, stat_suspend, stat_resume, stat_expiry_waits, stat_queued_at_stop); } /* ------------------------------------------------------------------ */ /* Callbacks */ /* ------------------------------------------------------------------ */ static void panic_cb (void *cls, const char *file, unsigned int line, const char *reason) { char msg[512]; (void) cls; (void) snprintf (msg, sizeof (msg), "MHD_PANIC() reached from an event-loop schedule " "at %s:%u: %s", (NULL != file) ? file : "?", line, (NULL != reason) ? reason : "?"); fuzz_report_finding (msg); } /** * Find the registry slot of @a c, or -1. */ static int slot_of (const struct MHD_Connection *c) { unsigned int i; for (i = 0; i < MAX_LIVE; i++) if ( (NULL != lives[i].mc) && (lives[i].mc == c) ) return (int) i; return -1; } static void notify_conn_cb (void *cls, struct MHD_Connection *connection, void **socket_context, enum MHD_ConnectionNotificationCode toe) { unsigned int i; int idx; (void) cls; (void) socket_context; if (MHD_CONNECTION_NOTIFY_STARTED == toe) { for (i = 0; i < MAX_LIVE; i++) { if (NULL != lives[i].mc) continue; lives[i].mc = connection; lives[i].susp = 0; return; } return; } /* MHD_CONNECTION_NOTIFY_CLOSED: the object is about to be freed. */ idx = slot_of (connection); if (0 <= idx) { lives[idx].mc = NULL; lives[idx].susp = 0; } } /* ------------------------------------------------------------------ */ /* Suspend / resume bookkeeping */ /* ------------------------------------------------------------------ */ /** * Ask MHD whether it considers slot @a i suspended. */ static int mhd_thinks_suspended (unsigned int i) { const union MHD_ConnectionInfo *ci; if (NULL == lives[i].mc) return 0; ci = MHD_get_connection_info (lives[i].mc, MHD_CONNECTION_INFO_CONNECTION_SUSPENDED); if (NULL == ci) return 0; return (MHD_YES == ci->suspended); } /** * Suspend slot @a i, if that is legal right now. * * MHD_suspend_connection() unlinks the connection from the timeout and * connection lists, so calling it on a connection MHD already has on the * suspended list corrupts those lists. The one exception is a * connection with a resume still pending: internal_suspend_connection_() * detects that itself and merely cancels the resume, leaving the * connection suspended -- which is why @e susp is set in both branches. */ static void do_suspend (unsigned int i) { int mhd_susp; if ( (i >= MAX_LIVE) || (NULL == lives[i].mc) ) return; mhd_susp = mhd_thinks_suspended (i); if (mhd_susp && lives[i].susp) return; /* really suspended already */ MHD_suspend_connection (lives[i].mc); lives[i].susp = 1; stat_suspend++; } static void do_resume (unsigned int i) { if ( (i >= MAX_LIVE) || (NULL == lives[i].mc) || (! lives[i].susp) ) return; /* Clear first: MHD_resume_connection() may end up running the handler later, which is allowed to suspend the very same connection again. */ lives[i].susp = 0; MHD_resume_connection (lives[i].mc); stat_resume++; } /** * Resume everything still parked. * * @return non-zero if at least one connection was resumed, so that the * caller knows the daemon needs another round to act on it */ static int resume_all (void) { unsigned int i; int any = 0; for (i = 0; i < MAX_LIVE; i++) { if ( (NULL == lives[i].mc) || (! lives[i].susp) ) continue; lives[i].susp = 0; MHD_resume_connection (lives[i].mc); stat_resume++; any = 1; } return any; } /** * Summarise the connections MHD currently owns. * * Both properties are read back from MHD rather than modelled: a * connection leaves the timeout lists exactly when MHD sets * `connection->suspended`, and its timeout is exactly what * MHD_set_connection_option() left there -- which is *not* what the * application passed if the connection happened to be suspended at the * time. Modelling either of them means the oracle eventually fires on * the model rather than on MHD. * * @param[out] max_ms largest timeout, in milliseconds, of the * connections that are in a timeout list right now * @return non-zero if at least one such connection exists, i.e. if MHD * must report a timeout */ static int scan_live_timeouts (uint64_t *max_ms) { unsigned int i; int any = 0; *max_ms = 0; for (i = 0; i < MAX_LIVE; i++) { const union MHD_ConnectionInfo *ci; uint64_t ms; if (NULL == lives[i].mc) continue; ci = MHD_get_connection_info (lives[i].mc, MHD_CONNECTION_INFO_CONNECTION_SUSPENDED); if ( (NULL != ci) && (MHD_YES == ci->suspended) ) continue; /* not in any timeout list */ ci = MHD_get_connection_info (lives[i].mc, MHD_CONNECTION_INFO_CONNECTION_TIMEOUT); if (NULL == ci) continue; ms = ((uint64_t) ci->connection_timeout) * 1000; if (0 == ms) continue; /* in a list, but exempt from timeouts */ any = 1; if (ms > *max_ms) *max_ms = ms; } return any; } /* ------------------------------------------------------------------ */ /* The access handler */ /* ------------------------------------------------------------------ */ struct crc_state { uint64_t total; unsigned int pattern; }; static ssize_t crc_cb (void *cls, uint64_t pos, char *buf, size_t max) { struct crc_state *st = (struct crc_state *) cls; size_t n; size_t i; if (pos >= st->total) return MHD_CONTENT_READER_END_OF_STREAM; n = (size_t) (st->total - pos); if (n > max) n = max; if (0 == n) return MHD_CONTENT_READER_END_OF_STREAM; for (i = 0; i < n; i++) buf[i] = (char) ('a' + (int) ((pos + i + st->pattern) % 26)); return (ssize_t) n; } static void crc_free (void *cls) { free (cls); } static struct MHD_Response * make_response (void) { struct crc_state *st; struct MHD_Response *r; switch (cfg.resp_kind) { case 1: st = (struct crc_state *) calloc (1, sizeof (struct crc_state)); if (NULL == st) return NULL; st->total = 700; st->pattern = cfg.clock_seed; r = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 128, &crc_cb, st, &crc_free); if (NULL == r) free (st); return r; case 2: /* Large enough not to fit into the socket buffers, so that the connection stays blocked on write and MHD has to schedule it through the write descriptor set over several rounds. */ return MHD_create_response_from_buffer_static (BIG_BODY_LEN, big_body); case 3: return MHD_create_response_empty (MHD_RF_NONE); default: return MHD_create_response_from_buffer_static (2, "ok"); } } static enum MHD_Result ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *resp; enum MHD_Result ret; int idx; (void) cls; (void) url; (void) method; (void) version; (void) upload_data; if (NULL == *req_cls) { *req_cls = (void *) (intptr_t) 1; return MHD_YES; } stat_handler_calls++; if (0 != *upload_data_size) { *upload_data_size = 0; return MHD_YES; } idx = slot_of (connection); if (cfg.hnd_connopt) { /* Moves the connection between the "normal" and the "manual" timeout list, i.e. changes which connection MHD_get_timeout*() reports. */ unsigned int nt = (0 == cfg.timeout_s) ? 1u : (cfg.timeout_s + 1u); (void) MHD_set_connection_option (connection, MHD_CONNECTION_OPTION_TIMEOUT, nt); } if (cfg.hnd_info) { volatile size_t sink = 0; const union MHD_ConnectionInfo *ci; ci = MHD_get_connection_info (connection, MHD_CONNECTION_INFO_CONNECTION_FD); if (NULL != ci) sink += (size_t) (ci->connect_fd + 1); ci = MHD_get_connection_info (connection, MHD_CONNECTION_INFO_CONNECTION_TIMEOUT); if (NULL != ci) sink += (size_t) ci->connection_timeout; (void) sink; } resp = make_response (); if (NULL == resp) return MHD_NO; ret = MHD_queue_response (connection, cfg.error_reply ? MHD_HTTP_INTERNAL_SERVER_ERROR : MHD_HTTP_OK, resp); MHD_destroy_response (resp); if (MHD_YES != ret) return ret; /* Only once the response was accepted: returning MHD_NO tells MHD to terminate the connection, and terminating one that this very callback suspended trips mhd_assert (! connection->suspended) in MHD_connection_close_(). */ if (tearing_down || (0 > idx)) return ret; if (cfg.susp_now) { MHD_suspend_connection (connection); MHD_resume_connection (connection); stat_suspend++; stat_resume++; } else if (cfg.susp_park && (! lives[idx].susp)) { MHD_suspend_connection (connection); lives[idx].susp = 1; stat_suspend++; } return ret; } /* ------------------------------------------------------------------ */ /* Oracles */ /* ------------------------------------------------------------------ */ /** * Query all four timeout accessors and cross-check them. * * The values are read one after the other, so the monotonic clock may * advance in between and a later reading may be *smaller*. It may never * be larger, except for the 100 ms floor connection_get_wait() falls back * to when the elapsed time exactly matches the timeout. */ static void check_timeouts (struct MHD_Daemon *d) { MHD_UNSIGNED_LONG_LONG tl = 0; uint64_t t64 = 0; int64_t t64s; int ti; enum MHD_Result r1; enum MHD_Result r2; int have[4]; uint64_t val[4]; unsigned int k; uint64_t max_ms; int any_timed; char msg[256]; stat_timeouts++; r1 = MHD_get_timeout (d, &tl); r2 = MHD_get_timeout64 (d, &t64); t64s = MHD_get_timeout64s (d); ti = MHD_get_timeout_i (d); have[0] = (MHD_YES == r1); have[1] = (MHD_YES == r2); have[2] = (0 <= t64s); have[3] = (0 <= ti); val[0] = (uint64_t) tl; val[1] = t64; val[2] = (uint64_t) (t64s < 0 ? 0 : t64s); val[3] = (uint64_t) (ti < 0 ? 0 : ti); for (k = 1; k < 4; k++) if (have[k] != have[0]) fuzz_report_finding ( "MHD_get_timeout*(): the four accessors disagree about whether " "a timeout is in effect"); any_timed = scan_live_timeouts (&max_ms); if (! have[0]) { /* An indefinite wait while a live, not-suspended connection has a non-zero timeout means that connection can never be reaped: its deadline is already unreachable for the application. */ if (any_timed) fuzz_report_finding ( "MHD_get_timeout*() reported no timeout although the daemon has a " "live, not suspended connection with a non-zero timeout"); deadline_valid = 0; return; } for (k = 0; k < 4; k++) { if (val[k] <= max_ms) continue; (void) snprintf (msg, sizeof (msg), "MHD_get_timeout*() [accessor %u] returned %llu ms, " "larger than the largest connection timeout in effect " "(%llu ms)", k, (unsigned long long) val[k], (unsigned long long) max_ms); fuzz_report_finding (msg); } for (k = 1; k < 4; k++) if ( (val[k] > val[k - 1]) && (val[k] > 100) ) fuzz_report_finding ( "MHD_get_timeout*(): a later accessor reported a larger timeout " "than an earlier one, although the deadline cannot have moved"); deadline_ms = clk_ms + val[1]; deadline_valid = 1; } /** * Check the descriptor sets that the last MHD_get_fdset*() produced. * * @param setsize the FD_SETSIZE limit that was passed to MHD * @param max_fd the reported maximum, #MHD_INVALID_SOCKET if none * @param had_max whether a @a max_fd pointer was passed at all * @param with_es whether an except set was passed */ static void check_fdsets (unsigned int setsize, MHD_socket max_fd, int had_max, int with_es) { int f; int hi = -1; int max_seen = 0; for (f = 0; f < (int) FD_SETSIZE; f++) { int in_set = FD_ISSET (f, &g_rs) || FD_ISSET (f, &g_ws); if (with_es && FD_ISSET (f, &g_es)) in_set = 1; if (! in_set) continue; if ((unsigned int) f >= setsize) fuzz_report_finding ( "MHD_get_fdset*() added a descriptor at or above the FD_SETSIZE " "limit it was given"); if (f > hi) hi = f; if ( (had_max) && (MHD_INVALID_SOCKET != max_fd) && (f == (int) max_fd) ) max_seen = 1; } if (! had_max) return; if (0 > hi) { if (MHD_INVALID_SOCKET != max_fd) fuzz_report_finding ( "MHD_get_fdset*() set max_fd although it added no descriptor"); return; } if (MHD_INVALID_SOCKET == max_fd) fuzz_report_finding ( "MHD_get_fdset*() added descriptors but left max_fd unset"); if (hi > (int) max_fd) fuzz_report_finding ( "MHD_get_fdset*() added a descriptor larger than the max_fd it " "reported"); if ((unsigned int) max_fd >= setsize) fuzz_report_finding ( "MHD_get_fdset*() reported a max_fd at or above the FD_SETSIZE " "limit it was given"); if (! max_seen) fuzz_report_finding ( "MHD_get_fdset*() reported a max_fd that is not in any of the sets"); } /* ------------------------------------------------------------------ */ /* Event-loop primitives */ /* ------------------------------------------------------------------ */ /** * Collect the descriptor sets. * * Variant 0 goes through the *real* v1 entry point. microhttpd.h also * defines MHD_get_fdset as a macro forwarding to MHD_get_fdset2 with * FD_SETSIZE, so the name has to be parenthesised or the v1 function is * never reached at all. Same trick for MHD_run_from_select below. */ static void op_fdset (struct MHD_Daemon *d, unsigned int var) { MHD_socket max_fd = MHD_INVALID_SOCKET; unsigned int setsize = (unsigned int) FD_SETSIZE; int had_max = 1; int with_es = 1; FD_ZERO (&g_rs); FD_ZERO (&g_ws); FD_ZERO (&g_es); switch (var % 5) { case 0: stat_fdset_v1++; (void) (MHD_get_fdset) (d, &g_rs, &g_ws, &g_es, &max_fd); break; case 1: stat_fdset_v2++; (void) MHD_get_fdset2 (d, &g_rs, &g_ws, &g_es, &max_fd, (unsigned int) FD_SETSIZE); break; case 2: stat_fdset_v2++; setsize = setsize_tbl[(var + cfg.clock_seed) % (sizeof (setsize_tbl) / sizeof (setsize_tbl[0]))]; (void) MHD_get_fdset2 (d, &g_rs, &g_ws, &g_es, &max_fd, setsize); break; case 3: /* max_fd is documented as optional */ stat_fdset_v2++; had_max = 0; (void) MHD_get_fdset2 (d, &g_rs, &g_ws, &g_es, NULL, (unsigned int) FD_SETSIZE); break; default: /* no except set: deprecated, but shipped API */ stat_fdset_v2++; with_es = 0; (void) MHD_get_fdset2 (d, &g_rs, &g_ws, NULL, &max_fd, (unsigned int) FD_SETSIZE); break; } check_fdsets (setsize, max_fd, had_max, with_es); g_max_fd = max_fd; g_setsize = setsize; g_have_sets = 1; if ( (MHD_INVALID_SOCKET != quiesced_fd) && ((unsigned int) quiesced_fd < (unsigned int) FD_SETSIZE) && FD_ISSET (quiesced_fd, &g_rs) ) fuzz_report_finding ( "MHD_get_fdset*() still watches the listening socket after " "MHD_quiesce_daemon() handed it back to the application"); } /** * select() on the sets collected last, with a zero timeout. * * The harness is single threaded and everything MHD could be waiting for * has already been written into the socketpairs, so blocking would only * burn wall clock; select() is called purely to fill in the readiness. */ static void op_poll (void) { struct timeval tv; if ( (! g_have_sets) || (MHD_INVALID_SOCKET == g_max_fd) ) return; tv.tv_sec = 0; tv.tv_usec = 0; (void) select ((int) g_max_fd + 1, &g_rs, &g_ws, &g_es, &tv); } /** * Drain whatever the daemon has produced on slot @a i, so that a large * response can make progress. */ static void drain_conn (unsigned int i) { char tmp[DRAIN_BUF]; if ( (i >= MAX_CONNS) || (0 > csock[i]) ) return; for (;;) { ssize_t n = recv (csock[i], tmp, sizeof (tmp), MSG_DONTWAIT); if (0 >= n) break; } } static void drain_all (void) { unsigned int i; for (i = 0; i < MAX_CONNS; i++) drain_conn (i); } /** * Advance the daemon once. * * @param d the daemon * @param var which entry point to use * @param flavour which descriptor sets to hand over: * 0 the ones MHD asked for, 1 all-zero, 2 all-ones, * 3 only the read set as collected */ static void op_run (struct MHD_Daemon *d, unsigned int var, unsigned int flavour) { fd_set rs; fd_set ws; fd_set es; switch (flavour % 4) { case 1: FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); break; case 2: /* Every descriptor number reported ready. MHD only tests the bits of the sockets it owns, so this is an application that lies about readiness, not an invalid descriptor. */ memset (&rs, 0xFF, sizeof (rs)); memset (&ws, 0xFF, sizeof (ws)); memset (&es, 0xFF, sizeof (es)); break; case 3: rs = g_rs; FD_ZERO (&ws); FD_ZERO (&es); break; default: rs = g_rs; ws = g_ws; es = g_es; break; } switch (var % 4) { case 0: stat_rfs_v1++; (void) (MHD_run_from_select) (d, &rs, &ws, &es); break; case 1: stat_rfs_v2++; (void) MHD_run_from_select2 (d, &rs, &ws, &es, (g_setsize > (unsigned int) FD_SETSIZE) ? (unsigned int) FD_SETSIZE : g_setsize); break; case 2: stat_run++; (void) MHD_run (d); break; default: stat_run_wait++; (void) MHD_run_wait (d, 0); break; } deadline_valid = 0; if (cfg.auto_drain) drain_all (); if (cfg.timeout_every_run) check_timeouts (d); } /* ------------------------------------------------------------------ */ /* Connections */ /* ------------------------------------------------------------------ */ static int new_connection (struct MHD_Daemon *d) { int sv[2]; struct sockaddr_in sa; unsigned int idx; if (nconns >= MAX_CONNS) return -1; idx = nconns; if (0 != socketpair (AF_UNIX, SOCK_STREAM, 0, sv)) return -1; if (cfg.small_sockbuf) { int bs = 2048; (void) setsockopt (sv[0], SOL_SOCKET, SO_RCVBUF, &bs, sizeof (bs)); (void) setsockopt (sv[1], SOL_SOCKET, SO_SNDBUF, &bs, sizeof (bs)); } memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (44444); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); csock[idx] = sv[0]; if (MHD_YES != MHD_add_connection (d, (MHD_socket) sv[1], (const struct sockaddr *) &sa, (socklen_t) sizeof (sa))) { /* MHD has already closed sv[1] in that case. */ (void) close (sv[0]); csock[idx] = -1; return -1; } nconns++; cur_conn = idx; return (int) idx; } /** * Hand the daemon one more connection and do not run the loop again. * * MHD_add_connection() on a thread-safe daemon does not build the * `struct MHD_Connection` right away; it puts the socket on * `daemon->new_connections_head` and leaves the rest to the next run. * Stopping the daemon before that run is the only way to reach * new_connection_close_() in daemon.c, which is where MHD disposes of a * connection it accepted but never started. The ordinary teardown below * always calls MHD_run() once more, which is why 1.6 billion executions * left that function at zero coverage. * * The socket pair is deliberately kept out of the harness's own * connection table: nothing is ever sent on it, no notify callback fires * for it, and by this point the teardown has already closed every * tracked slot. Our end is returned so that the caller can close it * after MHD_stop_daemon(). * * @param d the daemon, about to be stopped * @return our end of the socket pair, or -1 if nothing was queued */ static int queue_unprocessed_conn (struct MHD_Daemon *d) { int sv[2]; struct sockaddr_in sa; if (0 != socketpair (AF_UNIX, SOCK_STREAM, 0, sv)) return -1; memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (44444); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (MHD_YES != MHD_add_connection (d, (MHD_socket) sv[1], (const struct sockaddr *) &sa, (socklen_t) sizeof (sa))) { /* MHD has closed sv[1] already. */ (void) close (sv[0]); return -1; } stat_queued_at_stop++; return sv[0]; } /** * Drop our end of connection @a i. * * @param graceful non-zero to shut the write side down first (an orderly * client close), zero to just close (an abrupt one, which MHD sees * as a reset) */ static void close_conn (unsigned int i, int graceful) { if ( (i >= MAX_CONNS) || (0 > csock[i]) ) return; if (graceful) (void) shutdown (csock[i], SHUT_WR); (void) close (csock[i]); csock[i] = -1; } static void send_bytes (unsigned int i, const void *buf, size_t len) { const char *p = (const char *) buf; size_t off = 0; unsigned int tries = 0; if ( (i >= MAX_CONNS) || (0 > csock[i]) || (0 == len) ) return; while ( (off < len) && (tries < 4) ) { ssize_t s = send (csock[i], p + off, len - off, MSG_DONTWAIT); if (0 < s) { off += (size_t) s; continue; } tries++; /* The peer's receive buffer is full because MHD has not run yet, or MHD is gone. One round is enough to tell the two apart; the rest of the fragment is simply dropped, which is a split point like any other. */ if (NULL != cur_daemon) (void) MHD_run (cur_daemon); if ( (0 > s) && (EAGAIN != errno) && (EWOULDBLOCK != errno) && (EINTR != errno) ) break; } } /** * Request fragments. Whole requests, halves of requests and pipelines, * so that a schedule can leave a connection in any parser state while it * plays with the event loop. */ static const char *const frag_tbl[16] = { "GET / HTTP/1.1\r\nHost: x\r\n\r\n", "GET /a HTTP/1.1\r\nHost: x\r\n", "\r\n", "POST /p HTTP/1.1\r\nHost: x\r\nContent-Length: 10\r\n\r\n", "0123456789", "POST /c HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n", "5\r\nabcde\r\n", "0\r\n\r\n", "GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n", "GET / HTTP/1.0\r\n\r\n", "HEAD / HTTP/1.1\r\nHost: x\r\n\r\n", "GET / HTTP/1.1\r\nHost: x\r\n\r\nGET /2 HTTP/1.1\r\nHost: x\r\n\r\n", "G", "ET / HTTP/1.1\r\n", "Host: x\r\n\r\n", "\r\n\r\n" }; /* ------------------------------------------------------------------ */ /* The operation program */ /* ------------------------------------------------------------------ */ enum op { OP_SEND_FRAG = 0, OP_SEND_RAW = 1, OP_FDSET = 2, OP_RUN = 3, OP_TIMEOUT = 4, OP_CLOCK = 5, OP_SUSPEND = 6, OP_RESUME = 7, OP_NEWCONN = 8, OP_CLOSECONN = 9, OP_SWITCH = 10, OP_QUIESCE = 11, OP_DRAIN = 12, OP_CONNOPT = 13, OP_INFO = 14, OP_POLL = 15 }; /** * Wait in real time until the connection timeout of the current daemon * has certainly expired, so that the expiry path is actually reached. * * MHD_OPTION_CONNECTION_TIMEOUT has a resolution of one second, so this * costs about that much wall clock and is therefore globally budgeted. */ static void wait_for_expiry (struct MHD_Daemon *d) { struct timeval tv; if ( (! cfg.allow_real_wait) || (1 != cfg.timeout_s) || (0 >= expiry_budget) ) return; expiry_budget--; stat_expiry_waits++; tv.tv_sec = 1; tv.tv_usec = 50000; (void) select (0, NULL, NULL, NULL, &tv); clk_ms += 1050; /* Everything parked has to come back first, or the expiry cannot be observed for it at all. */ (void) resume_all (); (void) MHD_run (d); (void) MHD_run (d); } static void op_quiesce (struct MHD_Daemon *d) { MHD_socket ls; stat_quiesce++; ls = MHD_quiesce_daemon (d); if (MHD_INVALID_SOCKET == ls) return; if (MHD_INVALID_SOCKET != quiesced_fd) { /* MHD_quiesce_daemon() is documented to hand the socket over once and to answer MHD_INVALID_SOCKET afterwards. */ (void) close (ls); fuzz_report_finding ( "MHD_quiesce_daemon() handed out the listening socket twice"); return; } quiesced_fd = ls; } static void op_info (struct MHD_Daemon *d, unsigned int arg) { const union MHD_DaemonInfo *di; const union MHD_ConnectionInfo *ci; volatile size_t sink = 0; unsigned int i = arg % MAX_LIVE; di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_CURRENT_CONNECTIONS); if (NULL != di) sink += (size_t) di->num_connections; di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL != di) sink += (size_t) di->flags; if (NULL != lives[i].mc) { ci = MHD_get_connection_info (lives[i].mc, MHD_CONNECTION_INFO_CONNECTION_SUSPENDED); if (NULL != ci) sink += (size_t) ci->suspended; ci = MHD_get_connection_info (lives[i].mc, MHD_CONNECTION_INFO_DAEMON); if (NULL != ci) sink += (NULL != ci->daemon) ? 1u : 0u; } (void) sink; } static void op_connopt (unsigned int i, unsigned int val) { if ( (i >= MAX_LIVE) || (NULL == lives[i].mc) ) return; /* Note that MHD skips the whole update while connection->suspended is set, so this is not necessarily the timeout the connection ends up with -- which is why the oracle reads it back instead. */ (void) MHD_set_connection_option (lives[i].mc, MHD_CONNECTION_OPTION_TIMEOUT, val); } /* ------------------------------------------------------------------ */ /* The fuzz target */ /* ------------------------------------------------------------------ */ int LLVMFuzzerTestOneInput (const uint8_t *data, size_t size) { struct MHD_Daemon *d; struct MHD_OptionItem opts[8]; unsigned int nopt = 0; unsigned int flags; size_t pos; unsigned int nops = 0; unsigned int i; int queued_fd = -1; /**< see queue_unprocessed_conn() */ /* Must happen before the first write() into a socketpair. The built-in driver also does this, but that code is compiled out under -DFUZZ_NO_MAIN, which is exactly the build every external fuzzing engine uses; the call is idempotent. See fuzz_ignore_sigpipe() in fuzz_common.h for why the process dies without it. */ fuzz_ignore_sigpipe (); if (size < 5) return 0; if (! big_body_ready) { big_body_ready = 1; for (i = 0; i < BIG_BODY_LEN; i++) big_body[i] = (char) ('a' + (i % 26)); } if (! expiry_budget_read) { const char *e = getenv ("MHD_FUZZ_EXPIRY_BUDGET"); expiry_budget_read = 1; if (NULL != e) expiry_budget = atoi (e); } memset (&cfg, 0, sizeof (cfg)); /* Must never carry over: everything these point at belonged to the previous iteration's daemon and is long gone. */ memset (lives, 0, sizeof (lives)); for (i = 0; i < MAX_CONNS; i++) csock[i] = -1; nconns = 0; cur_conn = 0; tearing_down = 0; quiesced_fd = MHD_INVALID_SOCKET; clk_ms = 0; deadline_ms = 0; deadline_valid = 0; g_have_sets = 0; g_max_fd = MHD_INVALID_SOCKET; g_setsize = (unsigned int) FD_SETSIZE; cfg.timeout_s = timeout_tbl[data[0] & 0x03]; cfg.listen_sock = (0 != (data[0] & 0x04)); cfg.app_fd_setsize = (0 != (data[0] & 0x08)); cfg.mem_limit = mem_limit_tbl[(data[0] >> 4) & 0x03]; cfg.conn_limit = (0 != (data[0] & 0x40)); cfg.small_sockbuf = (0 != (data[0] & 0x80)); cfg.resp_kind = (unsigned int) (data[1] & 0x03); cfg.error_reply = (0 != (data[1] & 0x04)); cfg.susp_park = (0 != (data[1] & 0x08)); cfg.susp_now = (0 != (data[1] & 0x10)); cfg.hnd_connopt = (0 != (data[1] & 0x20)); cfg.hnd_info = (0 != (data[1] & 0x40)); cfg.auto_drain = (0 != (data[1] & 0x80)); cfg.fdset_var = (unsigned int) (data[2] & 0x07); cfg.run_var = (unsigned int) ((data[2] >> 3) & 0x03); cfg.honour_timeout = (0 != (data[2] & 0x20)); cfg.timeout_every_run = (0 != (data[2] & 0x40)); cfg.quiesce_end = (0 != (data[2] & 0x80)); cfg.nconn_up_front = 1u + (unsigned int) (data[3] & 0x03); cfg.check_always = (0 != (data[3] & 0x04)); cfg.allow_real_wait = (0 != (data[3] & 0x08)); cfg.stop_with_queued = (0 != (data[3] & 0x10)); cfg.clock_seed = data[4]; if (0 != cfg.mem_limit) { opts[nopt].option = MHD_OPTION_CONNECTION_MEMORY_LIMIT; opts[nopt].value = (intptr_t) cfg.mem_limit; opts[nopt].ptr_value = NULL; nopt++; } opts[nopt].option = MHD_OPTION_CONNECTION_TIMEOUT; opts[nopt].value = (intptr_t) cfg.timeout_s; opts[nopt].ptr_value = NULL; nopt++; if (cfg.conn_limit) { opts[nopt].option = MHD_OPTION_CONNECTION_LIMIT; opts[nopt].value = (intptr_t) 2; opts[nopt].ptr_value = NULL; nopt++; } if (cfg.app_fd_setsize) { opts[nopt].option = MHD_OPTION_APP_FD_SETSIZE; opts[nopt].value = (intptr_t) FD_SETSIZE; opts[nopt].ptr_value = NULL; nopt++; } opts[nopt].option = MHD_OPTION_END; opts[nopt].value = 0; opts[nopt].ptr_value = NULL; /* MHD_ALLOW_SUSPEND_RESUME is always on: it is what this harness is about, and it implies MHD_USE_ITC, whose descriptor is one more thing MHD_get_fdset*() has to report correctly. */ flags = MHD_ALLOW_SUSPEND_RESUME; if (! cfg.listen_sock) flags |= MHD_USE_NO_LISTEN_SOCKET; if (fuzz_verbose) flags |= MHD_USE_ERROR_LOG; MHD_set_panic_func (&panic_cb, NULL); d = MHD_start_daemon (flags, 0, NULL, NULL, &ahc, NULL, MHD_OPTION_ARRAY, opts, /* through the varargs rather than the option array: storing a function pointer in the array's intptr_t member is not strictly conforming C */ MHD_OPTION_NOTIFY_CONNECTION, ¬ify_conn_cb, NULL, MHD_OPTION_END); if ( (NULL == d) && cfg.listen_sock) { /* No networking available: fall back to the socketpair-only daemon rather than losing the whole iteration. */ cfg.listen_sock = 0; flags |= MHD_USE_NO_LISTEN_SOCKET; d = MHD_start_daemon (flags, 0, NULL, NULL, &ahc, NULL, MHD_OPTION_ARRAY, opts, MHD_OPTION_NOTIFY_CONNECTION, ¬ify_conn_cb, NULL, MHD_OPTION_END); } if (NULL == d) return 0; cur_daemon = d; stat_daemons++; if (! stats_registered) { stats_registered = 1; (void) atexit (&print_stats); } for (i = 0; i < cfg.nconn_up_front; i++) if (0 > new_connection (d)) break; pos = 5; while ( (pos < size) && (nops < MAX_OPS) ) { const unsigned int b = data[pos++]; const unsigned int opc = b >> 4; const unsigned int arg = b & 0x0F; nops++; switch (opc) { case OP_SEND_FRAG: { const char *f = frag_tbl[arg]; send_bytes (cur_conn, f, strlen (f)); break; } case OP_SEND_RAW: { size_t l; if (pos >= size) break; l = data[pos++]; if (l > size - pos) l = size - pos; send_bytes (cur_conn, data + pos, l); pos += l; break; } case OP_FDSET: op_fdset (d, (0 != (arg & 0x08)) ? cfg.fdset_var : arg); break; case OP_RUN: op_run (d, arg & 0x03, (arg >> 2) & 0x03); break; case OP_TIMEOUT: check_timeouts (d); if ( (cfg.honour_timeout) && (deadline_valid) && (deadline_ms <= clk_ms) ) op_run (d, cfg.run_var, 0); break; case OP_CLOCK: if (15 == arg) wait_for_expiry (d); else { clk_ms += (uint64_t) (1u + arg) * (uint64_t) (1u + cfg.clock_seed % 64u) ; if ( (cfg.honour_timeout) && (deadline_valid) && (deadline_ms <= clk_ms) ) op_run (d, cfg.run_var, 0); } break; case OP_SUSPEND: do_suspend (arg % MAX_LIVE); break; case OP_RESUME: do_resume (arg % MAX_LIVE); break; case OP_NEWCONN: (void) new_connection (d); break; case OP_CLOSECONN: close_conn ((0 != (arg & 0x08)) ? cur_conn : (arg % MAX_CONNS), (0 != (arg & 0x04))); break; case OP_SWITCH: if ( (arg % MAX_CONNS) < nconns) cur_conn = arg % MAX_CONNS; break; case OP_QUIESCE: op_quiesce (d); break; case OP_DRAIN: if (0 != (arg & 0x08)) drain_all (); else drain_conn (arg % MAX_CONNS); break; case OP_CONNOPT: op_connopt (arg % MAX_LIVE, (arg >> 3) & 0x01); break; case OP_INFO: op_info (d, arg); break; default: op_poll (); break; } if (cfg.check_always) check_timeouts (d); } /* ---- teardown ---- */ tearing_down = 1; queued_fd = -1; for (i = 0; i < MAX_CONNS; i++) close_conn (i, 1); /* A connection left suspended makes MHD_stop_daemon() MHD_PANIC() ("called while we have suspended connections"), and MHD_resume_connection() alone is not enough: it only raises a flag, and the connection leaves the suspended list in MHD_run(). So flush and run until nothing is parked any more. tearing_down keeps the handler from parking anything new, which is what bounds this loop; the cap is only a backstop. */ for (i = 0; i < MAX_CONNS + 2u; i++) { if (! resume_all ()) break; (void) MHD_run (d); } (void) MHD_run (d); if (cfg.quiesce_end) op_quiesce (d); /* Last, so that no run can drain the list again. */ if (cfg.stop_with_queued) queued_fd = queue_unprocessed_conn (d); MHD_stop_daemon (d); cur_daemon = NULL; if (0 <= queued_fd) { (void) close (queued_fd); queued_fd = -1; } if (MHD_INVALID_SOCKET != quiesced_fd) { (void) close (quiesced_fd); quiesced_fd = MHD_INVALID_SOCKET; } for (i = 0; i < MAX_CONNS; i++) close_conn (i, 0); memset (lives, 0, sizeof (lives)); return 0; } /* ------------------------------------------------------------------ */ /* Structure-aware schedule generator */ /* ------------------------------------------------------------------ */ struct sbuf { uint8_t *p; size_t len; size_t cap; }; static void sb_byte (struct sbuf *b, uint8_t v) { if (b->len < b->cap) b->p[b->len++] = v; } static void sb_op (struct sbuf *b, unsigned int opc, unsigned int arg) { sb_byte (b, (uint8_t) ((opc << 4) | (arg & 0x0F))); } /** * Fragment indices, weighted towards the ones that complete a request: * a schedule that never reaches the access handler exercises very little * of the connection life cycle. */ static const unsigned char gen_frag_bias[] = { 0, 0, 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11, 1, 2, 12, 13, 14, 15 }; static unsigned int gen_frag (struct fuzz_rng *rng) { if (fuzz_chance (rng, 4)) return fuzz_below (rng, 16); return gen_frag_bias[fuzz_below (rng, (uint32_t) sizeof (gen_frag_bias))]; } /** * Emit "collect the descriptors, poll, run" -- the shape a real external * event loop has -- with a randomly chosen variant of each step. */ static void gen_loop_round (struct fuzz_rng *rng, struct sbuf *b) { unsigned int v; unsigned int fl; if (! fuzz_chance (rng, 5)) sb_op (b, OP_FDSET, fuzz_below (rng, 16)); if (! fuzz_chance (rng, 3)) sb_op (b, OP_POLL, 0); if (fuzz_chance (rng, 3)) sb_op (b, OP_TIMEOUT, fuzz_below (rng, 16)); v = fuzz_below (rng, 4); /* Half the runs use the descriptor sets MHD actually asked for, so that requests make progress; the other half are the adversarial ones (all-zero, all-ones, read set only). */ fl = fuzz_chance (rng, 2) ? 0u : fuzz_below (rng, 4); sb_op (b, OP_RUN, v | (fl << 2)); } static size_t fuzz_generate (struct fuzz_rng *rng, uint8_t *buf, size_t cap) { struct sbuf b; unsigned int nrounds; unsigned int i; unsigned int r; b.p = buf; b.len = 0; b.cap = cap; /* --- configuration block --- */ sb_byte (&b, fuzz_byte (rng)); sb_byte (&b, fuzz_byte (rng)); sb_byte (&b, fuzz_byte (rng)); sb_byte (&b, fuzz_byte (rng)); sb_byte (&b, fuzz_byte (rng)); nrounds = 3u + fuzz_below (rng, 40); for (i = 0; i < nrounds; i++) { switch (fuzz_below (rng, 24)) { case 0: case 1: case 2: case 3: case 4: case 5: /* feed the current connection */ sb_op (&b, OP_SEND_FRAG, gen_frag (rng)); gen_loop_round (rng, &b); break; case 6: /* raw literal, so that a mutator has somewhere to put bytes */ { unsigned int n = fuzz_below (rng, 24); unsigned int k; sb_op (&b, OP_SEND_RAW, 0); sb_byte (&b, (uint8_t) n); for (k = 0; k < n; k++) sb_byte (&b, fuzz_byte (rng)); break; } case 7: case 8: gen_loop_round (rng, &b); break; case 9: r = fuzz_below (rng, 16); sb_op (&b, OP_SUSPEND, r); break; case 10: r = fuzz_below (rng, 16); sb_op (&b, OP_RESUME, r); break; case 11: sb_op (&b, OP_NEWCONN, 0); sb_op (&b, OP_SEND_FRAG, gen_frag (rng)); break; case 12: r = fuzz_below (rng, 16); sb_op (&b, OP_CLOSECONN, r); break; case 13: r = fuzz_below (rng, 16); sb_op (&b, OP_SWITCH, r); break; case 14: sb_op (&b, OP_QUIESCE, 0); break; case 15: r = fuzz_below (rng, 16); sb_op (&b, OP_DRAIN, r); break; case 16: r = fuzz_below (rng, 16); sb_op (&b, OP_CONNOPT, r); break; case 17: r = fuzz_below (rng, 16); sb_op (&b, OP_INFO, r); break; case 18: r = fuzz_below (rng, 16); sb_op (&b, OP_TIMEOUT, r); break; case 19: /* an artificial clock jump, occasionally the real one that lets a connection time out */ r = fuzz_chance (rng, 40) ? 15u : fuzz_below (rng, 15); sb_op (&b, OP_CLOCK, r); break; case 20: /* a run without ever asking MHD what it wanted */ r = fuzz_below (rng, 16); sb_op (&b, OP_RUN, r); break; case 21: sb_op (&b, OP_POLL, 0); break; default: sb_op (&b, OP_SEND_FRAG, gen_frag (rng)); break; } } /* Make sure most schedules end with the daemon actually run, so that the interesting states are reached rather than only set up. */ gen_loop_round (rng, &b); return b.len; } /* ------------------------------------------------------------------ */ /* Built-in seed corpus */ /* ------------------------------------------------------------------ */ /** * A seed is the five configuration bytes plus a literal operation * program. Programs are short on purpose: each one is meant to pin down * one entry point or one life-cycle transition, and libFuzzer's -merge * keeps the shortest input reaching a given edge. */ struct seed_def { const char *name; unsigned char cfg[5]; unsigned char ops[24]; unsigned char nops; }; #define OPB(o,a) (unsigned char) (((o) << 4) | (a)) static const struct seed_def seeds[] = { /* MHD_get_fdset() (the real v1 entry point) + select() + MHD_run_from_select() (also v1) */ { "fdset-v1-run-from-select-v1", { 0x00, 0x80, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_FDSET, 0), OPB (OP_POLL, 0), OPB (OP_RUN, 0), OPB (OP_TIMEOUT, 0), OPB (OP_FDSET, 0), OPB (OP_POLL, 0), OPB (OP_RUN, 0) }, 8 }, /* MHD_get_fdset2() + MHD_run_from_select2() */ { "fdset2-run-from-select2", { 0x00, 0x80, 0x09, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_FDSET, 1), OPB (OP_POLL, 0), OPB (OP_RUN, 1), OPB (OP_TIMEOUT, 0), OPB (OP_FDSET, 1), OPB (OP_POLL, 0), OPB (OP_RUN, 1) }, 8 }, /* a small FD_SETSIZE limit, which MHD has to refuse descriptors for */ { "fdset2-small-setsize", { 0x00, 0x80, 0x02, 0x00, 0x04 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_FDSET, 2), OPB (OP_RUN, 1), OPB (OP_FDSET, 2), OPB (OP_TIMEOUT, 0), OPB (OP_RUN, 1) }, 6 }, /* max_fd == NULL and except_fd_set == NULL, both documented shapes */ { "fdset2-null-args", { 0x00, 0x80, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_FDSET, 3), OPB (OP_RUN, 1), OPB (OP_FDSET, 4), OPB (OP_RUN, 1), OPB (OP_TIMEOUT, 0) }, 6 }, /* MHD_run() and MHD_run_wait() */ { "run-and-run-wait", { 0x00, 0x80, 0x10, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_RUN, 2), OPB (OP_RUN, 3), OPB (OP_TIMEOUT, 0), OPB (OP_RUN, 2) }, 5 }, /* descriptor sets MHD never asked for: all-zero and all-ones */ { "run-from-select-bogus-sets", { 0x00, 0x80, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_RUN, 0x04), OPB (OP_RUN, 0x08), OPB (OP_RUN, 0x05), OPB (OP_RUN, 0x09), OPB (OP_TIMEOUT, 0), OPB (OP_RUN, 0x0C) }, 7 }, /* stale sets: collect, close the connection, then run with them */ { "run-from-select-stale-sets", { 0x00, 0x80, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 1), OPB (OP_FDSET, 1), OPB (OP_CLOSECONN, 0), OPB (OP_RUN, 0), OPB (OP_RUN, 1), OPB (OP_TIMEOUT, 0) }, 6 }, /* suspend from the pump loop, across a full fdset/poll/run round */ { "suspend-across-loop", { 0x00, 0x80, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 1), OPB (OP_RUN, 2), OPB (OP_SUSPEND, 0), OPB (OP_FDSET, 1), OPB (OP_TIMEOUT, 0), OPB (OP_POLL, 0), OPB (OP_RUN, 1), OPB (OP_RESUME, 0), OPB (OP_RUN, 2) }, 9 }, /* the handler parks the connection; several are parked at once */ { "handler-parks-two-connections", { 0x00, 0x88, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_RUN, 2), OPB (OP_NEWCONN, 0), OPB (OP_SEND_FRAG, 0), OPB (OP_RUN, 2), OPB (OP_TIMEOUT, 0), OPB (OP_RESUME, 0), OPB (OP_RUN, 2) }, 8 }, /* suspend while a resume is still pending (cancels the resume) */ { "suspend-cancels-pending-resume", { 0x00, 0x80, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 1), OPB (OP_RUN, 2), OPB (OP_SUSPEND, 0), OPB (OP_RESUME, 0), OPB (OP_SUSPEND, 0), OPB (OP_TIMEOUT, 0), OPB (OP_RESUME, 0), OPB (OP_RUN, 2) }, 8 }, /* quiesce a daemon that really has a listening socket, then check that it is gone from the descriptor sets */ { "quiesce-listening-daemon", { 0x04, 0x80, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_FDSET, 1), OPB (OP_RUN, 1), OPB (OP_QUIESCE, 0), OPB (OP_FDSET, 1), OPB (OP_TIMEOUT, 0), OPB (OP_RUN, 1), OPB (OP_QUIESCE, 0) }, 8 }, /* a large response on a small socket buffer: the connection stays blocked on write over many rounds */ { "blocked-write-scheduling", { 0x80, 0x02, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_FDSET, 1), OPB (OP_POLL, 0), OPB (OP_RUN, 1), OPB (OP_FDSET, 1), OPB (OP_POLL, 0), OPB (OP_RUN, 1), OPB (OP_DRAIN, 8), OPB (OP_FDSET, 1), OPB (OP_RUN, 1), OPB (OP_TIMEOUT, 0) }, 11 }, /* a real connection-timeout expiry */ { "connection-timeout-expiry", { 0x00, 0x80, 0x00, 0x08, 0x00 }, { OPB (OP_SEND_FRAG, 1), OPB (OP_RUN, 2), OPB (OP_TIMEOUT, 0), OPB (OP_CLOCK, 15), OPB (OP_TIMEOUT, 0), OPB (OP_RUN, 2) }, 6 }, /* per-connection timeouts, which move the connection to the "manual" timeout list that MHD_get_timeout*() has to scan separately */ { "manual-timeout-list", { 0x00, 0x80, 0x00, 0x03, 0x00 }, { OPB (OP_SEND_FRAG, 1), OPB (OP_CONNOPT, 8), OPB (OP_TIMEOUT, 0), OPB (OP_CONNOPT, 1), OPB (OP_TIMEOUT, 0), OPB (OP_RUN, 2), OPB (OP_TIMEOUT, 0) }, 7 }, /* pipelined requests plus a chunked upload, driven one run at a time */ { "pipelined-and-chunked", { 0x00, 0x81, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 11), OPB (OP_RUN, 2), OPB (OP_SEND_FRAG, 5), OPB (OP_RUN, 2), OPB (OP_SEND_FRAG, 6), OPB (OP_RUN, 2), OPB (OP_SEND_FRAG, 7), OPB (OP_RUN, 2), OPB (OP_TIMEOUT, 0) }, 9 }, /* never poll, never ask for descriptors, only run from empty sets */ { "never-poll", { 0x00, 0x80, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_RUN, 0x04), OPB (OP_RUN, 0x04), OPB (OP_RUN, 0x04), OPB (OP_RUN, 0x04), OPB (OP_TIMEOUT, 0) }, 6 }, /* abrupt close in the middle of a request, with the descriptor sets collected before it */ { "abrupt-close-mid-request", { 0x00, 0x80, 0x00, 0x00, 0x00 }, { OPB (OP_SEND_FRAG, 3), OPB (OP_FDSET, 1), OPB (OP_CLOSECONN, 0), OPB (OP_RUN, 1), OPB (OP_TIMEOUT, 0), OPB (OP_RUN, 2) }, 6 }, /* connection limit of two, so that MHD_add_connection() starts to fail */ { "connection-limit", { 0x40, 0x80, 0x00, 0x03, 0x00 }, { OPB (OP_NEWCONN, 0), OPB (OP_NEWCONN, 0), OPB (OP_SEND_FRAG, 0), OPB (OP_RUN, 2), OPB (OP_TIMEOUT, 0) }, 5 }, /* no connection timeout at all: MHD_get_timeout*() must report that an indefinite wait is fine */ { "no-timeout-configured", { 0x02, 0x80, 0x00, 0x04, 0x00 }, { OPB (OP_SEND_FRAG, 1), OPB (OP_TIMEOUT, 0), OPB (OP_RUN, 2), OPB (OP_TIMEOUT, 0), OPB (OP_SEND_FRAG, 2), OPB (OP_RUN, 2) }, 6 }, /* byte 3 bit 4: after the program has run and everything has been torn down, hand MHD one more connection and stop it without another run, so that it has to dispose of a connection it never started. That is new_connection_close_() in daemon.c, which nothing else reaches. */ { "stop-with-queued-connection", { 0x00, 0x80, 0x00, 0x10, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_RUN, 2), OPB (OP_TIMEOUT, 0) }, 3 }, /* the same after MHD_quiesce_daemon() on a daemon that really has a listening socket, which is the other order the two can happen in */ { "stop-with-queued-after-quiesce", { 0x04, 0x80, 0x80, 0x10, 0x00 }, { OPB (OP_SEND_FRAG, 0), OPB (OP_RUN, 2) }, 2 } }; static uint8_t seed_render_buf[64]; static size_t fuzz_seed_count (void) { return sizeof (seeds) / sizeof (seeds[0]); } static const uint8_t * fuzz_seed_get (size_t idx, size_t *len) { const struct seed_def *sd = &seeds[idx]; size_t n = sd->nops; if (n > sizeof (sd->ops)) n = sizeof (sd->ops); if (n + sizeof (sd->cfg) > sizeof (seed_render_buf)) n = sizeof (seed_render_buf) - sizeof (sd->cfg); memcpy (seed_render_buf, sd->cfg, sizeof (sd->cfg)); memcpy (seed_render_buf + sizeof (sd->cfg), sd->ops, n); *len = sizeof (sd->cfg) + n; return seed_render_buf; } libmicrohttpd-1.0.10/src/fuzz/Makefile.am0000664000175000017500000001335115232414252013744 # This Makefile.am is in the public domain # In-process fuzzing harnesses. See README in this directory. # # The harnesses are built only with --enable-fuzzing (see # BUILD-INTEGRATION.md). They are ordinary check_PROGRAMS with a # built-in deterministic driver, so they need neither clang nor # libFuzzer nor AFL++; with those available the very same sources can be # compiled into libFuzzer/AFL++ targets (again, see the README). SUBDIRS = . # Number of generate/mutate iterations per harness during "make check". # Raise for a real fuzzing session, e.g. # make MHD_FUZZ_ITERATIONS=1000000 MHD_FUZZ_SEED=42 check # The whole suite takes about three seconds under ASAN+UBSAN at this value. MHD_FUZZ_ITERATIONS = 50000 # PRNG seed; every run is exactly reproducible from (harness, seed). MHD_FUZZ_SEED = 1 # Lower bound for MHD_OPTION_CLIENT_DISCIPLINE_LVL in fuzz_request. # -3 is the full range: it includes the deliberately non-conformant # parsing modes, which is where the most interesting inputs live. MHD_FUZZ_MIN_DISCIPLINE = -3 # Lower bound for MHD_OPTION_CONNECTION_MEMORY_LIMIT in fuzz_request. # 0 is the full range, including the tiny pools needed to reach the # read-buffer "shift back" code path. MHD_FUZZ_MIN_MEM_LIMIT = 0 # Where reproducers for failing inputs are written. MHD_FUZZ_CRASH_DIR = crashes AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ $(CPPFLAGS_ac) AM_CFLAGS = $(CFLAGS_ac) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) \ MHD_FUZZ_ITERATIONS="$(MHD_FUZZ_ITERATIONS)" ; \ export MHD_FUZZ_ITERATIONS ; \ MHD_FUZZ_SEED="$(MHD_FUZZ_SEED)" ; export MHD_FUZZ_SEED ; \ MHD_FUZZ_MIN_DISCIPLINE="$(MHD_FUZZ_MIN_DISCIPLINE)" ; \ export MHD_FUZZ_MIN_DISCIPLINE ; \ MHD_FUZZ_MIN_MEM_LIMIT="$(MHD_FUZZ_MIN_MEM_LIMIT)" ; \ export MHD_FUZZ_MIN_MEM_LIMIT ; \ MHD_FUZZ_CRASH_DIR="$(MHD_FUZZ_CRASH_DIR)" ; \ export MHD_FUZZ_CRASH_DIR ; if USE_COVERAGE AM_CFLAGS += -fprofile-arcs -ftest-coverage endif # fuzz_str and fuzz_auth_header call functions that are internal to the # library (mhd_str.c, gen_auth.c, memorypool.c) and therefore hidden in # the shared object; link them against the static archive. This # requires a build with --enable-static (the default). LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la check_PROGRAMS = \ fuzz_request \ fuzz_options \ fuzz_eventloop \ fuzz_str \ fuzz_memorypool \ fuzz_postprocessor if HAVE_ANYAUTH check_PROGRAMS += \ fuzz_auth_header endif # fuzz_tls needs a TLS backend, and it links GnuTLS directly of its own # accord: it drives a real client through the handshake rather than # feeding bytes at MHD, which is what makes MHD's own TLS plumbing -- # rather than GnuTLS's record parser -- the thing under test. if ENABLE_HTTPS check_PROGRAMS += \ fuzz_tls endif .NOTPARALLEL: TESTS = $(check_PROGRAMS) fuzz_request_SOURCES = \ fuzz_request.c fuzz_common.h fuzz_request_LDFLAGS = $(AM_LDFLAGS) -static fuzz_options_SOURCES = \ fuzz_options.c fuzz_common.h fuzz_options_LDFLAGS = $(AM_LDFLAGS) -static fuzz_eventloop_SOURCES = \ fuzz_eventloop.c fuzz_common.h fuzz_eventloop_LDFLAGS = $(AM_LDFLAGS) -static fuzz_tls_SOURCES = \ fuzz_tls.c fuzz_common.h fuzz_tls_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) fuzz_tls_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) -static fuzz_tls_LDADD = $(LDADD) $(MHD_TLS_LIBDEPS) fuzz_str_SOURCES = \ fuzz_str.c fuzz_common.h fuzz_str_LDFLAGS = $(AM_LDFLAGS) -static fuzz_auth_header_SOURCES = \ fuzz_auth_header.c fuzz_common.h fuzz_auth_header_LDFLAGS = $(AM_LDFLAGS) -static fuzz_memorypool_SOURCES = \ fuzz_memorypool.c fuzz_common.h fuzz_memorypool_LDFLAGS = $(AM_LDFLAGS) -static fuzz_postprocessor_SOURCES = \ fuzz_postprocessor.c fuzz_common.h fuzz_postprocessor_LDFLAGS = $(AM_LDFLAGS) -static # The whole corpus directory is distributed as-is. EXTRA_DIST = \ README \ BUILD-INTEGRATION.md \ corpus CLEANFILES = \ $(MHD_FUZZ_CRASH_DIR)/*.bin # Regenerate the on-disk seed corpus from the built-in one. .PHONY: refresh-corpus refresh-corpus: $(check_PROGRAMS) for p in $(check_PROGRAMS) ; do \ ./$$p --write-corpus=$(srcdir)/corpus || exit 1 ; \ done # Replay the whole on-disk corpus through every harness; this is what a # CI regression run should do after a crash has been fixed. # # corpus/known-findings/ and corpus/distilled/ are listed separately # because --corpus-dir does not recurse. # # known-findings/ holds the reproducers of the findings in README # section 6; all of them are fixed, so anything failing there is a # regression. The one intended exception is a reproducer committed while # its finding is still open: that fails here until the fix lands, which # is what a regression test for an unfixed bug is supposed to do. # # distilled/ is the edge-minimal residue of a fuzzing campaign; see # corpus/README. It is the slowest part of check-corpus by file count # and the most valuable part by coverage. # # Note that these only bite on a tree configured with --enable-asserts; # without it mhd_assert() compiles away and most of these reproducers # pass whether MHD is fixed or not. CORPUS_DIRS = \ $(srcdir)/corpus \ $(srcdir)/corpus/known-findings \ $(srcdir)/corpus/distilled .PHONY: check-corpus check-corpus: $(check_PROGRAMS) for p in $(check_PROGRAMS) ; do \ for d in $(CORPUS_DIRS) ; do \ MHD_FUZZ_MIN_DISCIPLINE="$(MHD_FUZZ_MIN_DISCIPLINE)" \ MHD_FUZZ_MIN_MEM_LIMIT="$(MHD_FUZZ_MIN_MEM_LIMIT)" \ ./$$p --corpus-dir=$$d || exit 1 ; \ done ; \ done libmicrohttpd-1.0.10/src/tools/0000775000175000017500000000000015235437006012134 5libmicrohttpd-1.0.10/src/tools/perf_replies.c0000664000175000017500000017053115223425213014700 /* This file is part of GNU libmicrohttpd Copyright (C) 2023 Evgeny Grin (Karlson2k) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice unmodified, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file tools/perf_replies.c * @brief Implementation of HTTP server optimised for fast replies * based on MHD. * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include #include "microhttpd.h" #include "mhd_tool_str_to_uint.h" #include "mhd_tool_get_cpu_count.h" #if defined(MHD_REAL_CPU_COUNT) #if MHD_REAL_CPU_COUNT == 0 #undef MHD_REAL_CPU_COUNT #endif /* MHD_REAL_CPU_COUNT == 0 */ #endif /* MHD_REAL_CPU_COUNT */ #define PERF_RPL_ERR_CODE_BAD_PARAM 65 #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /* Static constants */ static const char *const tool_copyright = "Copyright (C) 2023 Evgeny Grin (Karlson2k)"; /* Package or build specific string, like "Debian 1.2.3-4" or "RevX, built by MSYS2" */ static const char *const build_revision = "" #ifdef MHD_BUILD_REV_STR MHD_BUILD_REV_STR #endif /* MHD_BUILD_REV_STR */ ; #define PERF_REPL_PORT_FALLBACK 48080 /* Dynamic variables */ static char self_name[500] = "perf_replies"; static uint16_t mhd_port = 0; static void set_self_name (int argc, char *const *argv) { if ((argc >= 1) && (NULL != argv[0])) { const char *last_dir_sep; last_dir_sep = strrchr (argv[0], '/'); #ifdef _WIN32 if (1) { const char *last_w32_dir_sep; last_w32_dir_sep = strrchr (argv[0], '\\'); if ((NULL == last_dir_sep) || ((NULL != last_w32_dir_sep) && (last_w32_dir_sep > last_dir_sep))) last_dir_sep = last_w32_dir_sep; } #endif /* _WIN32 */ if (NULL != last_dir_sep) { size_t name_len; name_len = strlen (last_dir_sep + 1); if ((0 != name_len) && ((sizeof(self_name) / sizeof(char)) > name_len)) { strcpy (self_name, last_dir_sep + 1); return; } } } /* Set default name */ strcpy (self_name, "perf_replies"); return; } static unsigned int detect_cpu_core_count (void) { int sys_cpu_count; sys_cpu_count = mhd_tool_get_system_cpu_count (); if (0 >= sys_cpu_count) { int proc_cpu_count; fprintf (stderr, "Failed to detect the number of logical CPU cores " "available on the system.\n"); proc_cpu_count = mhd_tool_get_proc_cpu_count (); if (0 < proc_cpu_count) { fprintf (stderr, "The number of CPU cores available for this process " "is used as a fallback.\n"); sys_cpu_count = proc_cpu_count; } #ifdef MHD_REAL_CPU_COUNT if (0 >= sys_cpu_count) { fprintf (stderr, "configure-detected hardcoded number is used " "as a fallback.\n"); sys_cpu_count = MHD_REAL_CPU_COUNT; } #endif if (0 >= sys_cpu_count) sys_cpu_count = 1; printf ("Assuming %d logical CPU core%s on this system.\n", sys_cpu_count, (1 == sys_cpu_count) ? "" : "s"); } else { printf ("Detected %d logical CPU core%s on this system.\n", sys_cpu_count, (1 == sys_cpu_count) ? "" : "s"); } return (unsigned int) sys_cpu_count; } static unsigned int get_cpu_core_count (void) { static unsigned int num_cpu_cores = 0; if (0 == num_cpu_cores) num_cpu_cores = detect_cpu_core_count (); return num_cpu_cores; } static unsigned int detect_process_cpu_core_count (void) { unsigned int num_proc_cpu_cores; unsigned int sys_cpu_cores; int res; sys_cpu_cores = get_cpu_core_count (); res = mhd_tool_get_proc_cpu_count (); if (0 > res) { fprintf (stderr, "Cannot detect the number of logical CPU cores available " "for this process.\n"); if (1 != sys_cpu_cores) printf ("Assuming all %u system logical CPU cores are available to run " "threads of this process.\n", sys_cpu_cores); else printf ("Assuming single logical CPU core available for this process.\n"); num_proc_cpu_cores = sys_cpu_cores; } else { printf ("Detected %d logical CPU core%s available to run threads " "of this process.\n", res, (1 == res) ? "" : "s"); num_proc_cpu_cores = (unsigned int) res; } if (num_proc_cpu_cores > sys_cpu_cores) { fprintf (stderr, "WARNING: Detected number of CPU cores available " "for this process (%u) is larger than detected number " "of CPU cores on the system (%u).\n", num_proc_cpu_cores, sys_cpu_cores); num_proc_cpu_cores = sys_cpu_cores; fprintf (stderr, "Using %u as the number of logical CPU cores available " "for this process.\n", num_proc_cpu_cores); } return num_proc_cpu_cores; } static unsigned int get_process_cpu_core_count (void) { static unsigned int proc_num_cpu_cores = 0; if (0 == proc_num_cpu_cores) proc_num_cpu_cores = detect_process_cpu_core_count (); return proc_num_cpu_cores; } static unsigned int num_threads = 0; static unsigned int get_num_threads (void) { #if 0 /* disabled code */ static const unsigned int max_threads = 32; #endif /* disabled code */ if (0 < num_threads) return num_threads; num_threads = get_cpu_core_count () / 2; if (0 == num_threads) num_threads = 1; else { unsigned int num_proc_cpus; num_proc_cpus = get_process_cpu_core_count (); if (num_proc_cpus >= num_threads) { printf ("Using half of all available CPU cores, assuming the other half " "is used by client / requests generator.\n"); } else { printf ("Using all CPU cores available for this process as more than " "half of CPU cores on this system are still available for use " "by client / requests generator.\n"); num_threads = num_proc_cpus; } } #if 0 /* disabled code */ if (max_threads < num_threads) { printf ("Number of threads is limited to %u as more threads " "are unlikely to improve performance.\n", max_threads); num_threads = max_threads; } #endif /* disabled code */ return num_threads; } /** * The result of short parameters processing */ enum PerfRepl_param_result { PERF_RPL_PARAM_ERROR, /**< Error processing parameter */ PERF_RPL_PARAM_ONE_CHAR, /**< Processed exactly one character */ PERF_RPL_PARAM_FULL_STR, /**< Processed current parameter completely */ PERF_RPL_PARAM_STR_PLUS_NEXT /**< Current parameter completely and next parameter processed */ }; /** * Extract parameter value * @param param_name the name of the parameter * @param param_tail the pointer to the character after parameter name in * the parameter string * @param next_param the pointer to the next parameter (if any) or NULL * @param[out] param_value the pointer where to store resulting value * @return enum value, the PERF_PERPL_SPARAM_ONE_CHAR is not used by * this function */ static enum PerfRepl_param_result get_param_value (const char *param_name, const char *param_tail, const char *next_param, unsigned int *param_value) { const char *value_str; size_t digits; if (0 != param_tail[0]) { if ('=' != param_tail[0]) value_str = param_tail; else value_str = param_tail + 1; } else value_str = next_param; if (NULL != value_str) digits = mhd_tool_str_to_uint (value_str, param_value); else digits = 0; if ((0 == digits) || (0 != value_str[digits])) { fprintf (stderr, "Parameter '%s' is not followed by valid number.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (0 != param_tail[0]) return PERF_RPL_PARAM_FULL_STR; return PERF_RPL_PARAM_STR_PLUS_NEXT; } static void show_help (void) { printf ("Usage: %s [OPTIONS] [PORT_NUMBER]\n", self_name); printf ("Start MHD-based web-server optimised for fast replies.\n"); printf ("\n"); printf ("Threading options (mutually exclusive):\n"); printf (" -A, --all-cpus use all available CPU cores (for \n" " testing with remote client)\n"); printf (" -t NUM, --threads=NUM use NUM threads\n"); printf (" -P, --thread-per-conn use thread-per-connection mode,\n" " the number of threads is limited only\n" " by the number of connection\n"); printf ("\n"); printf ("Force polling function (mutually exclusive):\n"); if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_EPOLL)) printf (" -e, --epoll use 'epoll' functionality\n"); if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_POLL)) printf (" -p, --poll use poll() function\n"); printf (" -s, --select use select() function\n"); printf ("\n"); printf ("Response body size options (mutually exclusive):\n"); printf (" -E, --empty empty response, 0 bytes\n"); printf (" -T, --tiny tiny response, 3 bytes (default)\n"); printf (" -M, --medium medium response, 8 KiB\n"); printf (" -L, --large large response, 1 MiB\n"); printf (" -X, --xlarge extra large response, 8 MiB\n"); printf (" -J, --jumbo jumbo response, 101 MiB\n"); printf ("\n"); printf ("Response use options (mutually exclusive):\n"); printf (" -S, --shared pool of pre-generated shared response\n" " objects (default)\n"); printf (" -I, --single single pre-generated response object\n" " used for all requests\n"); printf (" -U, --unique response object generated for every\n" " request and used one time only\n"); printf ("\n"); printf ("Other options:\n"); printf (" -c NUM, --connections=NUM reject more than NUM client \n" " connections\n"); printf (" -O NUM, --timeout=NUM set connection timeout to NUM seconds,\n" " zero means no timeout\n"); printf (" --date-header use the 'Date:' header in every\n" " reply\n"); printf (" --help display this help and exit\n"); printf (" -V, --version output version information and exit\n"); printf ("\n"); printf ("This tool is part of GNU libmicrohttpd suite.\n"); printf ("%s\n", tool_copyright); } struct PerfRepl_parameters { int all_cpus; unsigned int threads; int thread_per_conn; int epoll; int poll; int select; int empty; int tiny; int medium; int large; int xlarge; int jumbo; int shared; int single; int unique; unsigned int connections; unsigned int timeout; int date_header; int help; int version; }; static struct PerfRepl_parameters tool_params; static enum PerfRepl_param_result process_param__all_cpus (const char *param_name) { if (0 != tool_params.threads) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-t' or '--threads'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.thread_per_conn) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-P' or '--thread-per-conn'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.all_cpus = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } /** * Process parameter '-t' or '--threads' * @param param_name the name of the parameter as specified in command line * @param param_tail the pointer to the character after parameter name in * the parameter string * @param next_param the pointer to the next parameter (if any) or NULL * @return enum value, the PERF_PERPL_SPARAM_ONE_CHAR is not used by * this function */ static enum PerfRepl_param_result process_param__threads (const char *param_name, const char *param_tail, const char *next_param) { unsigned int param_value; enum PerfRepl_param_result value_res; if (tool_params.all_cpus) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-A' or '--all-cpus'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.thread_per_conn) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-P' or '--thread-per-conn'.\n", param_name); return PERF_RPL_PARAM_ERROR; } value_res = get_param_value (param_name, param_tail, next_param, ¶m_value); if (PERF_RPL_PARAM_ERROR == value_res) return value_res; if (0 == param_value) { fprintf (stderr, "'0' is not valid value for parameter '%s'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.threads = param_value; return value_res; } static enum PerfRepl_param_result process_param__thread_per_conn (const char *param_name) { if (tool_params.all_cpus) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-A' or '--all-cpus'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (0 != tool_params.threads) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-t' or '--threads'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.thread_per_conn = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__epoll (const char *param_name) { if (tool_params.poll) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-p' or '--poll'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.select) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-s' or '--select'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.epoll = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__poll (const char *param_name) { if (tool_params.epoll) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-e' or '--epoll'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.select) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-s' or '--select'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.poll = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__select (const char *param_name) { if (tool_params.epoll) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-e' or '--epoll'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.poll) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-p' or '--poll'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.select = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__empty (const char *param_name) { if (tool_params.tiny) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-T' or '--tiny'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.medium) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-M' or '--medium'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.large) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-L' or '--large'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.xlarge) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-X' or '--xlarge'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.jumbo) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-J' or '--jumbo'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.empty = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__tiny (const char *param_name) { if (tool_params.empty) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-E' or '--empty'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.medium) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-M' or '--medium'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.large) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-L' or '--large'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.xlarge) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-X' or '--xlarge'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.jumbo) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-J' or '--jumbo'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.tiny = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__medium (const char *param_name) { if (tool_params.empty) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-E' or '--empty'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.tiny) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-T' or '--tiny'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.large) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-L' or '--large'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.xlarge) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-X' or '--xlarge'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.jumbo) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-J' or '--jumbo'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.medium = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__large (const char *param_name) { if (tool_params.empty) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-E' or '--empty'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.tiny) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-T' or '--tiny'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.medium) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-M' or '--medium'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.xlarge) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-X' or '--xlarge'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.jumbo) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-J' or '--jumbo'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.large = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__xlarge (const char *param_name) { if (tool_params.empty) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-E' or '--empty'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.tiny) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-T' or '--tiny'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.medium) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-M' or '--medium'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.large) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-L' or '--large'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.jumbo) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-J' or '--jumbo'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.xlarge = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__jumbo (const char *param_name) { if (tool_params.empty) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-E' or '--empty'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.tiny) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-T' or '--tiny'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.medium) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-M' or '--medium'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.large) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-L' or '--large'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.xlarge) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-X' or '--xlarge'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.jumbo = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__shared (const char *param_name) { if (tool_params.single) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-I' or '--single'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.unique) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-U' or '--unique'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.shared = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__single (const char *param_name) { if (tool_params.shared) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-S' or '--shared'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.unique) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-U' or '--unique'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.single = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__unique (const char *param_name) { if (tool_params.shared) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-S' or '--shared'.\n", param_name); return PERF_RPL_PARAM_ERROR; } if (tool_params.single) { fprintf (stderr, "Parameter '%s' cannot be used together " "with '-I' or '--single'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.unique = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } /** * Process parameter '-c' or '--connections' * @param param_name the name of the parameter as specified in command line * @param param_tail the pointer to the character after parameter name in * the parameter string * @param next_param the pointer to the next parameter (if any) or NULL * @return enum value, the PERF_PERPL_SPARAM_ONE_CHAR is not used by * this function */ static enum PerfRepl_param_result process_param__connections (const char *param_name, const char *param_tail, const char *next_param) { unsigned int param_value; enum PerfRepl_param_result value_res; value_res = get_param_value (param_name, param_tail, next_param, ¶m_value); if (PERF_RPL_PARAM_ERROR == value_res) return value_res; if (0 == param_value) { fprintf (stderr, "'0' is not valid value for parameter '%s'.\n", param_name); return PERF_RPL_PARAM_ERROR; } tool_params.connections = param_value; return value_res; } /** * Process parameter '-O' or '--timeout' * @param param_name the name of the parameter as specified in command line * @param param_tail the pointer to the character after parameter name in * the parameter string * @param next_param the pointer to the next parameter (if any) or NULL * @return enum value, the PERF_PERPL_SPARAM_ONE_CHAR is not used by * this function */ static enum PerfRepl_param_result process_param__timeout (const char *param_name, const char *param_tail, const char *next_param) { unsigned int param_value; enum PerfRepl_param_result value_res; value_res = get_param_value (param_name, param_tail, next_param, ¶m_value); if (PERF_RPL_PARAM_ERROR == value_res) return value_res; tool_params.timeout = param_value; return value_res; } static enum PerfRepl_param_result process_param__date_header (const char *param_name) { tool_params.date_header = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__help (const char *param_name) { /* Use only one of help | version */ if (! tool_params.version) tool_params.help = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } static enum PerfRepl_param_result process_param__version (const char *param_name) { /* Use only one of help | version */ if (! tool_params.help) tool_params.version = ! 0; return '-' == param_name[1] ? PERF_RPL_PARAM_FULL_STR :PERF_RPL_PARAM_ONE_CHAR; } /** * Process "short" (one character) parameter. * @param param the pointer to character after "-" or after another valid * parameter * @param next_param the pointer to the next parameter (if any) or * NULL if no next parameter * @return enum value with result */ static enum PerfRepl_param_result process_short_param (const char *param, const char *next_param) { const char param_chr = param[0]; if ('A' == param_chr) return process_param__all_cpus ("-A"); else if ('t' == param_chr) return process_param__threads ("-t", param + 1, next_param); else if ('P' == param_chr) return process_param__thread_per_conn ("-P"); else if ('e' == param_chr) return process_param__epoll ("-e"); else if ('p' == param_chr) return process_param__poll ("-p"); else if ('s' == param_chr) return process_param__select ("-s"); else if ('E' == param_chr) return process_param__empty ("-E"); else if ('T' == param_chr) return process_param__tiny ("-T"); else if ('M' == param_chr) return process_param__medium ("-M"); else if ('L' == param_chr) return process_param__large ("-L"); else if ('X' == param_chr) return process_param__xlarge ("-X"); else if ('J' == param_chr) return process_param__jumbo ("-J"); else if ('S' == param_chr) return process_param__shared ("-S"); else if ('I' == param_chr) return process_param__single ("-I"); else if ('U' == param_chr) return process_param__unique ("-U"); else if ('c' == param_chr) return process_param__connections ("-c", param + 1, next_param); else if ('O' == param_chr) return process_param__timeout ("-O", param + 1, next_param); else if ('V' == param_chr) return process_param__version ("-V"); fprintf (stderr, "Unrecognised parameter: -%c.\n", param_chr); return PERF_RPL_PARAM_ERROR; } /** * Process string of "short" (one character) parameters. * @param params_str the pointer to first character after "-" * @param next_param the pointer to the next parameter (if any) or * NULL if no next parameter * @return enum value with result */ static enum PerfRepl_param_result process_short_params_str (const char *params_str, const char *next_param) { if (0 == params_str[0]) { fprintf (stderr, "Unrecognised parameter: -\n"); return PERF_RPL_PARAM_ERROR; } do { enum PerfRepl_param_result param_res; param_res = process_short_param (params_str, next_param); if (PERF_RPL_PARAM_ONE_CHAR != param_res) return param_res; } while (0 != (++params_str)[0]); return PERF_RPL_PARAM_FULL_STR; } /** * Process "long" (--something) parameters. * @param param the pointer to first character after "--" * @param next_param the pointer to the next parameter (if any) or * NULL if no next parameter * @return enum value, the PERF_PERPL_SPARAM_ONE_CHAR is not used by * this function */ static enum PerfRepl_param_result process_long_param (const char *param, const char *next_param) { const size_t param_len = strlen (param); if ((MHD_STATICSTR_LEN_ ("all-cpus") == param_len) && (0 == memcmp (param, "all-cpus", MHD_STATICSTR_LEN_ ("all-cpus")))) return process_param__all_cpus ("--all-cpus"); else if ((MHD_STATICSTR_LEN_ ("threads") <= param_len) && (0 == memcmp (param, "threads", MHD_STATICSTR_LEN_ ("threads")))) return process_param__threads ("--threads", param + MHD_STATICSTR_LEN_ ("threads"), next_param); else if ((MHD_STATICSTR_LEN_ ("thread-per-conn") == param_len) && (0 == memcmp (param, "thread-per-conn", MHD_STATICSTR_LEN_ ("thread-per-conn")))) return process_param__thread_per_conn ("--thread-per-conn"); else if ((MHD_STATICSTR_LEN_ ("epoll") == param_len) && (0 == memcmp (param, "epoll", MHD_STATICSTR_LEN_ ("epoll")))) return process_param__epoll ("--epoll"); else if ((MHD_STATICSTR_LEN_ ("poll") == param_len) && (0 == memcmp (param, "poll", MHD_STATICSTR_LEN_ ("poll")))) return process_param__poll ("--poll"); else if ((MHD_STATICSTR_LEN_ ("select") == param_len) && (0 == memcmp (param, "select", MHD_STATICSTR_LEN_ ("select")))) return process_param__select ("--select"); else if ((MHD_STATICSTR_LEN_ ("empty") == param_len) && (0 == memcmp (param, "empty", MHD_STATICSTR_LEN_ ("empty")))) return process_param__empty ("--empty"); else if ((MHD_STATICSTR_LEN_ ("tiny") == param_len) && (0 == memcmp (param, "tiny", MHD_STATICSTR_LEN_ ("tiny")))) return process_param__tiny ("--tiny"); else if ((MHD_STATICSTR_LEN_ ("medium") == param_len) && (0 == memcmp (param, "medium", MHD_STATICSTR_LEN_ ("medium")))) return process_param__medium ("--medium"); else if ((MHD_STATICSTR_LEN_ ("large") == param_len) && (0 == memcmp (param, "large", MHD_STATICSTR_LEN_ ("large")))) return process_param__large ("--large"); else if ((MHD_STATICSTR_LEN_ ("xlarge") == param_len) && (0 == memcmp (param, "xlarge", MHD_STATICSTR_LEN_ ("xlarge")))) return process_param__xlarge ("--xlarge"); else if ((MHD_STATICSTR_LEN_ ("jumbo") == param_len) && (0 == memcmp (param, "jumbo", MHD_STATICSTR_LEN_ ("jumbo")))) return process_param__jumbo ("--jumbo"); else if ((MHD_STATICSTR_LEN_ ("shared") == param_len) && (0 == memcmp (param, "shared", MHD_STATICSTR_LEN_ ("shared")))) return process_param__shared ("--shared"); else if ((MHD_STATICSTR_LEN_ ("single") == param_len) && (0 == memcmp (param, "single", MHD_STATICSTR_LEN_ ("single")))) return process_param__single ("--single"); else if ((MHD_STATICSTR_LEN_ ("unique") == param_len) && (0 == memcmp (param, "unique", MHD_STATICSTR_LEN_ ("unique")))) return process_param__unique ("--unique"); else if ((MHD_STATICSTR_LEN_ ("connections") <= param_len) && (0 == memcmp (param, "connections", MHD_STATICSTR_LEN_ ("connections")))) return process_param__connections ("--connections", param + MHD_STATICSTR_LEN_ ("connections"), next_param); else if ((MHD_STATICSTR_LEN_ ("timeout") <= param_len) && (0 == memcmp (param, "timeout", MHD_STATICSTR_LEN_ ("timeout")))) return process_param__timeout ("--timeout", param + MHD_STATICSTR_LEN_ ("timeout"), next_param); else if ((MHD_STATICSTR_LEN_ ("date-header") == param_len) && (0 == memcmp (param, "date-header", MHD_STATICSTR_LEN_ ("date-header")))) return process_param__date_header ("--date-header"); else if ((MHD_STATICSTR_LEN_ ("help") == param_len) && (0 == memcmp (param, "help", MHD_STATICSTR_LEN_ ("help")))) return process_param__help ("--help"); else if ((MHD_STATICSTR_LEN_ ("version") == param_len) && (0 == memcmp (param, "version", MHD_STATICSTR_LEN_ ("version")))) return process_param__version ("--version"); fprintf (stderr, "Unrecognised parameter: --%s.\n", param); return PERF_RPL_PARAM_ERROR; } static int process_params (int argc, char *const *argv) { int proc_dash_param = ! 0; int i; for (i = 1; i < argc; ++i) { /** * The currently processed argument */ const char *const p = argv[i]; const char *const p_next = (argc == (i + 1)) ? NULL : (argv[i + 1]); if (NULL == p) { fprintf (stderr, "The NULL in the parameter number %d. " "The error in the C library?\n", i); continue; } else if (0 == p[0]) continue; /* Empty */ else if (proc_dash_param && ('-' == p[0])) { enum PerfRepl_param_result param_res; if ('-' == p[1]) { if (0 == p[2]) { proc_dash_param = 0; /* The '--' parameter */ continue; } param_res = process_long_param (p + 2, p_next); } else param_res = process_short_params_str (p + 1, p_next); if (PERF_RPL_PARAM_ERROR == param_res) return PERF_RPL_ERR_CODE_BAD_PARAM; if (PERF_RPL_PARAM_STR_PLUS_NEXT == param_res) ++i; else if (PERF_RPL_PARAM_ONE_CHAR == param_res) abort (); continue; } else if (('0' <= p[0]) && ('9' >= p[0])) { /* Process the port number */ unsigned int read_port; size_t num_digits; num_digits = mhd_tool_str_to_uint (p, &read_port); if (0 != p[num_digits]) { fprintf (stderr, "Error in specified port number: %s\n", p); return PERF_RPL_ERR_CODE_BAD_PARAM; } else if (65535 < read_port) { fprintf (stderr, "Wrong port number: %s\n", p); return PERF_RPL_ERR_CODE_BAD_PARAM; } mhd_port = (uint16_t) read_port; } else { fprintf (stderr, "Unrecognised parameter: %s\n\n", p); return PERF_RPL_ERR_CODE_BAD_PARAM; } } return 0; } static void print_version (void) { printf ("%s (GNU libmicrohttpd", self_name); if (0 != build_revision[0]) printf ("; %s", build_revision); printf (") %s\n", MHD_get_version ()); printf ("%s\n", tool_copyright); } static void print_all_cores_used (void) { printf ("No CPU cores on this machine are left unused and available " "for the client / requests generator. " "Testing with remote client is recommended.\n"); } static void check_param_port (void) { if (0 != mhd_port) return; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) mhd_port = PERF_REPL_PORT_FALLBACK; } /** * Apply parameter '-A' or '--all-cpus' */ static void check_apply_param__all_cpus (void) { if (! tool_params.all_cpus) return; num_threads = get_process_cpu_core_count (); printf ("Requested use of all available CPU cores for MHD threads.\n"); if (get_cpu_core_count () == num_threads) print_all_cores_used (); } /** * Apply parameter '-t' or '--threads' */ static void check_apply_param__threads (void) { if (0 == tool_params.threads) return; num_threads = tool_params.threads; if (get_process_cpu_core_count () < num_threads) { fprintf (stderr, "WARNING: The requested number of threads (%u) is " "higher than the number of detected available CPU cores (%u).\n", num_threads, get_process_cpu_core_count ()); fprintf (stderr, "This decreases the performance. " "Consider using fewer threads.\n"); } if (get_cpu_core_count () == num_threads) { printf ("The requested number of threads is equal to the number of " "detected CPU cores.\n"); print_all_cores_used (); } } /** * Apply parameter '-P' or '--thread-per-conn' * @return non-zero - OK, zero - error */ static int check_apply_param__thread_per_conn (void) { if (! tool_params.thread_per_conn) return ! 0; if (tool_params.epoll) { fprintf (stderr, "'Thread-per-connection' mode cannot be used together " "with 'epoll'.\n"); return 0; } num_threads = 1; return ! 0; } /* non-zero - OK, zero - error */ static int check_param__epoll (void) { if (! tool_params.epoll) return ! 0; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { fprintf (stderr, "'epoll' was requested, but this MHD build does not " "support 'epoll' functionality.\n"); return 0; } return ! 0; } /* non-zero - OK, zero - error */ static int check_param__poll (void) { if (! tool_params.poll) return ! 0; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_POLL)) { fprintf (stderr, "poll() was requested, but this MHD build does not " "support polling by poll().\n"); return 0; } return ! 0; } static void check_param__empty_tiny_medium_large_xlarge_jumbo (void) { if (0 == (tool_params.empty | tool_params.tiny | tool_params.medium | tool_params.large | tool_params.xlarge | tool_params.jumbo)) tool_params.tiny = ! 0; } static void check_param__shared_single_unique (void) { if (0 == (tool_params.shared | tool_params.single | tool_params.unique)) tool_params.shared = ! 0; } /* Must be called after 'check_apply_param__threads()' and 'check_apply_param__all_cpus()' */ /* non-zero - OK, zero - error */ static int check_param__connections (void) { if (0 == tool_params.connections) return ! 0; if (get_num_threads () > tool_params.connections) { fprintf (stderr, "The connections number limit (%u) is less than number " "of threads used (%u). Use higher value for connections limit.\n", tool_params.connections, get_num_threads ()); return 0; } return ! 0; } /** * Apply decoded parameters * @return 0 if success, * positive error code if case of error, * -1 to exit program with success (0) error code. */ static int check_apply_params (void) { if (tool_params.help) { show_help (); return -1; } else if (tool_params.version) { print_version (); return -1; } check_param_port (); check_apply_param__all_cpus (); check_apply_param__threads (); if (! check_apply_param__thread_per_conn ()) return PERF_RPL_ERR_CODE_BAD_PARAM; if (! check_param__epoll ()) return PERF_RPL_ERR_CODE_BAD_PARAM; if (! check_param__poll ()) return PERF_RPL_ERR_CODE_BAD_PARAM; check_param__empty_tiny_medium_large_xlarge_jumbo (); check_param__shared_single_unique (); if (! check_param__connections ()) return PERF_RPL_ERR_CODE_BAD_PARAM; return 0; } static uint64_t mini_rnd (void) { /* Simple xoshiro256+ implementation */ static uint64_t s[4] = { 0xE220A8397B1DCDAFuLL, 0x6E789E6AA1B965F4uLL, 0x06C45D188009454FuLL, 0xF88BB8A8724C81ECuLL }; /* Good enough for static initialisation */ const uint64_t ret = s[0] + s[3]; const uint64_t t = s[1] << 17; s[2] ^= s[0]; s[3] ^= s[1]; s[1] ^= s[2]; s[0] ^= s[3]; s[2] ^= t; s[3] = ((s[3] << 45u) | (s[3] >> (64u - 45u))); return ret; } /* The pool of shared responses */ static struct MHD_Response **resps = NULL; static unsigned int num_resps = 0; /* The single response */ static struct MHD_Response *resp_single = NULL; /* Use the same memory area to avoid multiple copies. The system will keep it in cache. */ static const char tiny_body[] = "Hi!"; static char *body_dyn = NULL; /* Non-static body data */ static size_t body_dyn_size; /* Non-zero - success, zero - failure */ static int init_response_body_data (void) { if (0 != body_dyn_size) { body_dyn = (char *) malloc (body_dyn_size); if (NULL == body_dyn) { fprintf (stderr, "Failed to allocate memory.\n"); return 0; } if (16u * 1024u >= body_dyn_size) { /* Fill the body with HTML-like content */ size_t pos; size_t filler_pos; static const char body_header[] = "\n" "\nSample page title\n\n" "\n"; static const char body_filler[] = "The quick brown fox jumps over the lazy dog.
\n"; static const char body_footer[] = "\n" "\n"; pos = 0; memcpy (body_dyn + pos, body_header, MHD_STATICSTR_LEN_ (body_header)); pos += MHD_STATICSTR_LEN_ (body_header); for (filler_pos = 0; filler_pos < (body_dyn_size - (MHD_STATICSTR_LEN_ (body_header) + MHD_STATICSTR_LEN_ (body_footer))); ++filler_pos) { body_dyn[pos + filler_pos] = body_filler[filler_pos % MHD_STATICSTR_LEN_ (body_filler)]; } pos += filler_pos; memcpy (body_dyn + pos, body_footer, MHD_STATICSTR_LEN_ (body_footer)); } else if (2u * 1024u * 1024u >= body_dyn_size) { /* Fill the body with binary-like content */ size_t pos; for (pos = 0; pos < body_dyn_size; ++pos) { body_dyn[pos] = (char) (unsigned char) (255U - pos % 256U); } } else { /* Fill the body with pseudo-random binary-like content */ size_t pos; uint64_t rnd_data; for (pos = 0; pos < body_dyn_size - body_dyn_size % 8; pos += 8) { rnd_data = mini_rnd (); body_dyn[pos + 0] = (char) (unsigned char) (rnd_data >> 0); body_dyn[pos + 1] = (char) (unsigned char) (rnd_data >> 8); body_dyn[pos + 2] = (char) (unsigned char) (rnd_data >> 16); body_dyn[pos + 3] = (char) (unsigned char) (rnd_data >> 24); body_dyn[pos + 4] = (char) (unsigned char) (rnd_data >> 32); body_dyn[pos + 5] = (char) (unsigned char) (rnd_data >> 40); body_dyn[pos + 6] = (char) (unsigned char) (rnd_data >> 48); body_dyn[pos + 7] = (char) (unsigned char) (rnd_data >> 56); } rnd_data = mini_rnd (); for ((void) pos; pos < body_dyn_size; ++pos) { body_dyn[pos] = (char) (unsigned char) (rnd_data); rnd_data >>= 8u; } } } return ! 0; } static struct MHD_Response * create_response_object (void) { #if MHD_VERSION >= 0x00097701 if (NULL != body_dyn) return MHD_create_response_from_buffer_static (body_dyn_size, body_dyn); else if (tool_params.empty) return MHD_create_response_empty (MHD_RF_NONE); return MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (tiny_body), tiny_body); #else /* MHD_VERSION < 0x00097701 */ if (NULL != body_dyn) return MHD_create_response_from_buffer (body_dyn_size, (void *) body_dyn, MHD_RESPMEM_PERSISTENT); else if (tool_params.empty) return MHD_create_response_from_buffer (0, (void *) tiny_body, MHD_RESPMEM_PERSISTENT); return MHD_create_response_from_buffer (MHD_STATICSTR_LEN_ (tiny_body), (void *) tiny_body, MHD_RESPMEM_PERSISTENT); #endif /* MHD_VERSION < 0x00097701 */ } static int init_data (void) { unsigned int i; if (tool_params.medium) body_dyn_size = 8U * 1024U; else if (tool_params.large) body_dyn_size = 1024U * 1024U; else if (tool_params.xlarge) body_dyn_size = 8U * 1024U * 1024U; else if (tool_params.jumbo) body_dyn_size = 101U * 1024U * 1024U; else body_dyn_size = 0; if (! init_response_body_data ()) return 25; if (tool_params.unique) return 0; /* Responses are generated on-fly */ if (tool_params.single) { resp_single = create_response_object (); if (NULL == resp_single) { fprintf (stderr, "Failed to create response.\n"); return 25; } return 0; } /* Use more responses to minimise waiting in threads while the response used by other thread. */ if (! tool_params.thread_per_conn) num_resps = 16 * get_num_threads (); else num_resps = 16 * get_cpu_core_count (); resps = (struct MHD_Response **) malloc ((sizeof(struct MHD_Response *)) * num_resps); if (NULL == resps) { if (NULL != body_dyn) { free (body_dyn); body_dyn = NULL; } fprintf (stderr, "Failed to allocate memory.\n"); return 25; } for (i = 0; i < num_resps; ++i) { resps[i] = create_response_object (); if (NULL == resps[i]) { fprintf (stderr, "Failed to create responses.\n"); break; } } if (i == num_resps) return 0; /* Success */ /* Cleanup */ while (i-- != 0) MHD_destroy_response (resps[i]); free (resps); resps = NULL; num_resps = 0; if (NULL != body_dyn) free (body_dyn); body_dyn = NULL; return 32; } static void deinit_data (void) { if (NULL != resp_single) MHD_destroy_response (resp_single); resp_single = NULL; if (NULL != resps) { unsigned int i; for (i = 0; i < num_resps; ++i) MHD_destroy_response (resps[i]); num_resps = 0; free (resps); } resps = NULL; if (NULL != body_dyn) free (body_dyn); body_dyn = NULL; } static enum MHD_Result answer_shared_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker = 0; unsigned int resp_index; static volatile unsigned int last_index = 0; (void) cls; /* Unused */ (void) url; (void) version; /* Unused */ (void) upload_data; (void) upload_data_size; /* Unused */ if (NULL == *req_cls) { /* The first call */ *req_cls = (void *) ▮ /* Do not send reply yet. No error. */ return MHD_YES; } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return MHD_NO; /* Unsupported method, close connection */ /* This kind of operation does not guarantee that numbers are not reused in parallel threads, when processed simultaneously, but this should not be a big problem, as it just slow down replies a bit due to response locking. */ resp_index = (last_index++) % num_resps; return MHD_queue_response (connection, MHD_HTTP_OK, resps[resp_index]); } static enum MHD_Result answer_single_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker = 0; (void) cls; /* Unused */ (void) url; (void) version; /* Unused */ (void) upload_data; (void) upload_data_size; /* Unused */ if (NULL == *req_cls) { /* The first call */ *req_cls = (void *) ▮ /* Do not send reply yet. No error. */ return MHD_YES; } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return MHD_NO; /* Unsupported method, close connection */ return MHD_queue_response (connection, MHD_HTTP_OK, resp_single); } static enum MHD_Result answer_unique_empty_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker = 0; struct MHD_Response *r; enum MHD_Result ret; (void) cls; /* Unused */ (void) url; (void) version; /* Unused */ (void) upload_data; (void) upload_data_size; /* Unused */ if (NULL == *req_cls) { /* The first call */ *req_cls = (void *) ▮ /* Do not send reply yet. No error. */ return MHD_YES; } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return MHD_NO; /* Unsupported method, close connection */ #if MHD_VERSION >= 0x00097701 r = MHD_create_response_empty (MHD_RF_NONE); #else /* MHD_VERSION < 0x00097701 */ r = MHD_create_response_from_buffer (0, NULL, MHD_RESPMEM_PERSISTENT); #endif /* MHD_VERSION < 0x00097701 */ ret = MHD_queue_response (connection, MHD_HTTP_OK, r); MHD_destroy_response (r); return ret; } static enum MHD_Result answer_unique_tiny_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker = 0; struct MHD_Response *r; enum MHD_Result ret; (void) cls; /* Unused */ (void) url; (void) version; /* Unused */ (void) upload_data; (void) upload_data_size; /* Unused */ if (NULL == *req_cls) { /* The first call */ *req_cls = (void *) ▮ /* Do not send reply yet. No error. */ return MHD_YES; } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return MHD_NO; /* Unsupported method, close connection */ #if MHD_VERSION >= 0x00097701 r = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (tiny_body), tiny_body); #else /* MHD_VERSION < 0x00097701 */ r = MHD_create_response_from_buffer (MHD_STATICSTR_LEN_ (tiny_body), (void *) tiny_body, MHD_RESPMEM_PERSISTENT); #endif /* MHD_VERSION < 0x00097701 */ ret = MHD_queue_response (connection, MHD_HTTP_OK, r); MHD_destroy_response (r); return ret; } static enum MHD_Result answer_unique_dyn_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker = 0; struct MHD_Response *r; enum MHD_Result ret; (void) cls; /* Unused */ (void) url; (void) version; /* Unused */ (void) upload_data; (void) upload_data_size; /* Unused */ if (NULL == *req_cls) { /* The first call */ *req_cls = (void *) ▮ /* Do not send reply yet. No error. */ return MHD_YES; } if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return MHD_NO; /* Unsupported method, close connection */ #if MHD_VERSION >= 0x00097701 r = MHD_create_response_from_buffer_static (body_dyn_size, body_dyn); #else /* MHD_VERSION < 0x00097701 */ r = MHD_create_response_from_buffer (body_dyn_size, (void *) body_dyn, MHD_RESPMEM_PERSISTENT); #endif /* MHD_VERSION < 0x00097701 */ ret = MHD_queue_response (connection, MHD_HTTP_OK, r); MHD_destroy_response (r); return ret; } static void print_perf_warnings (void) { int newline_needed = 0; #if defined (_DEBUG) fprintf (stderr, "WARNING: Running with debug asserts enabled, " "the performance is suboptimal.\n"); newline_needed |= ! 0; #endif /* _DEBUG */ #if defined(__GNUC__) && ! defined (__OPTIMIZE__) fprintf (stderr, "WARNING: This tool is compiled without enabled compiler " "optimisations, the performance is suboptimal.\n"); newline_needed |= ! 0; #endif /* __GNUC__ && ! __OPTIMIZE__ */ #if defined(__GNUC__) && defined (__OPTIMIZE_SIZE__) fprintf (stderr, "WARNING: This tool is compiled with size-optimisations, " "the performance is suboptimal.\n"); #endif /* __GNUC__ && ! __OPTIMIZE__ */ #if MHD_VERSION >= 0x00097701 if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_DEBUG_BUILD)) { fprintf (stderr, "WARNING: The libmicrohttpd is compiled with " "debug asserts enabled, the performance is suboptimal.\n"); newline_needed |= ! 0; } #endif /* MHD_VERSION >= 0x00097701 */ if (newline_needed) printf ("\n"); } /* Borrowed from daemon.c */ /* TODO: run-time detection */ /** * Default connection limit. */ #ifdef MHD_POSIX_SOCKETS #define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 4) #else #define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 2) #endif static unsigned int get_mhd_conn_limit (struct MHD_Daemon *d) { /* TODO: implement run-time detection */ (void) d; /* Unused */ if (0 != tool_params.connections) return tool_params.connections; return (unsigned int) MHD_MAX_CONNECTIONS_DEFAULT; } static const char * get_mhd_response_size (void) { if (tool_params.empty) return "0 bytes (empty)"; else if (tool_params.tiny) return "3 bytes (tiny)"; else if (tool_params.medium) return "8 KiB (medium)"; else if (tool_params.large) return "1 MiB (large)"; else if (tool_params.xlarge) return "8 MiB (xlarge)"; else if (tool_params.jumbo) return "101 MiB (jumbo)"; return "!!internal error!!"; } static int run_mhd (void) { MHD_AccessHandlerCallback reply_func; struct MHD_Daemon *d; unsigned int use_num_threads; unsigned int flags = MHD_NO_FLAG; struct MHD_OptionItem opt_arr[16]; size_t opt_count = 0; const union MHD_DaemonInfo *d_info; const char *poll_mode; uint16_t port; if (tool_params.thread_per_conn) use_num_threads = 0; else use_num_threads = get_num_threads (); printf ("\n"); print_perf_warnings (); printf ("Responses:\n"); printf (" Sharing: "); if (tool_params.shared) { reply_func = &answer_shared_response; printf ("pre-generated shared pool with %u objects\n", num_resps); } else if (tool_params.single) { reply_func = &answer_single_response; printf ("single pre-generated reused response object\n"); } else { /* Unique responses */ if (tool_params.empty) reply_func = &answer_unique_empty_response; else if (tool_params.tiny) reply_func = &answer_unique_tiny_response; else reply_func = &answer_unique_dyn_response; printf ("one-time response object generated for every request\n"); } printf (" Body size: %s\n", get_mhd_response_size ()); flags |= MHD_USE_ERROR_LOG; flags |= MHD_USE_INTERNAL_POLLING_THREAD; if (tool_params.epoll) flags |= MHD_USE_EPOLL; else if (tool_params.poll) flags |= MHD_USE_POLL; else if (tool_params.select) (void) flags; /* No special additional flag */ else flags |= MHD_USE_AUTO; if (tool_params.thread_per_conn) flags |= MHD_USE_THREAD_PER_CONNECTION; if (! tool_params.date_header) flags |= MHD_USE_SUPPRESS_DATE_NO_CLOCK; if (0 != tool_params.connections) { opt_arr[opt_count].option = MHD_OPTION_CONNECTION_LIMIT; opt_arr[opt_count].value = (intptr_t) tool_params.connections; opt_arr[opt_count].ptr_value = NULL; ++opt_count; } if (1 < use_num_threads) { opt_arr[opt_count].option = MHD_OPTION_THREAD_POOL_SIZE; opt_arr[opt_count].value = (intptr_t) use_num_threads; opt_arr[opt_count].ptr_value = NULL; ++opt_count; } if (1) { opt_arr[opt_count].option = MHD_OPTION_CONNECTION_TIMEOUT; opt_arr[opt_count].value = (intptr_t) tool_params.timeout; opt_arr[opt_count].ptr_value = NULL; ++opt_count; } if (1) { struct MHD_OptionItem option = { MHD_OPTION_END, 0, NULL }; if (opt_count >= (sizeof(opt_arr) / sizeof(opt_arr[0]))) abort (); opt_arr[opt_count] = option; } d = MHD_start_daemon (flags, mhd_port, NULL, NULL, reply_func, NULL, MHD_OPTION_ARRAY, opt_arr, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Error starting MHD daemon.\n"); return 15; } d_info = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == d_info) abort (); flags = (unsigned int) d_info->flags; if (0 != (flags & MHD_USE_POLL)) poll_mode = "poll()"; else if (0 != (flags & MHD_USE_EPOLL)) poll_mode = "epoll"; else poll_mode = "select()"; d_info = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == d_info) abort (); port = d_info->port; if (0 == port) fprintf (stderr, "Cannot detect port number. Consider specifying " "port number explicitly.\n"); printf ("MHD is running.\n"); printf (" Bind port: %u\n", (unsigned int) port); printf (" Polling function: %s\n", poll_mode); printf (" Threading: "); if (MHD_USE_THREAD_PER_CONNECTION == (flags & MHD_USE_THREAD_PER_CONNECTION)) printf ("thread per connection\n"); else if (1 == get_num_threads ()) printf ("one MHD thread\n"); else printf ("%u MHD threads in thread pool\n", get_num_threads ()); printf (" Connections limit: %u\n", get_mhd_conn_limit (d)); printf (" Connection timeout: %u%s\n", tool_params.timeout, 0 == tool_params.timeout ? " (no timeout)" : ""); printf (" 'Date:' header: %s\n", tool_params.date_header ? "Yes" : "No"); printf ("To test with remote client use " "http://HOST_IP:%u/\n", (unsigned int) port); printf ("To test with client on the same host use " "http://127.0.0.1:%u/\n", (unsigned int) port); printf ("\nPress ENTER to stop.\n"); if (1) { char buf[10]; (void) fgets (buf, sizeof(buf), stdin); } MHD_stop_daemon (d); return 0; } int main (int argc, char *const *argv) { int ret; set_self_name (argc, argv); ret = process_params (argc, argv); if (0 != ret) return ret; ret = check_apply_params (); if (0 > ret) return 0; if (0 != ret) return ret; ret = init_data (); if (0 != ret) return ret; ret = run_mhd (); deinit_data (); return ret; } libmicrohttpd-1.0.10/src/tools/mhd_tool_get_cpu_count.h0000644000175000017500000000357014760713577016767 /* This file is part of GNU libmicrohttpd Copyright (C) 2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file tools/mhd_tool_get_cpu_count.h * @brief Declaration of functions to detect the number of available * CPU cores. * @author Karlson2k (Evgeny Grin) */ #ifndef SRC_TOOLS_MHD_TOOL_GET_CPU_COUNT_H_ #define SRC_TOOLS_MHD_TOOL_GET_CPU_COUNT_H_ 1 /** * Detect the number of logical CPU cores available for the process. * The number of cores available for this process could be different from * value of cores available on the system. The OS may have limit on number * assigned/allowed cores for single process and process may have limited * CPU affinity. * @return the number of logical CPU cores available for the process or * -1 if failed to detect */ int mhd_tool_get_proc_cpu_count (void); /** * Try to detect the number of logical CPU cores available for the system. * The number of available logical CPU cores could be changed any time due to * CPU hotplug. * @return the number of logical CPU cores available, * -1 if failed to detect. */ int mhd_tool_get_system_cpu_count (void); #endif /* SRC_TOOLS_MHD_TOOL_GET_CPU_COUNT_H_ */ libmicrohttpd-1.0.10/src/tools/mhd_tool_get_cpu_count.c0000644000175000017500000007205015035214301016732 /* This file is part of GNU libmicrohttpd Copyright (C) 2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file tools/mhd_tool_get_cpu_count.c * @brief Implementation of functions to detect the number of available * CPU cores. * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "mhd_tool_get_cpu_count.h" #ifdef HAVE_SYS_TYPES_H # include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_SYS_PARAM_H # include #endif /* HAVE_SYS_PARAM_H */ #ifdef HAVE_SYS__CPUSET_H # include #endif /* HAVE_SYS_PARAM_H */ #ifdef HAVE_STDDEF_H # include #endif /* HAVE_STDDEF_H */ #ifdef HAVE_STRING_H # include #endif /* HAVE_STRING_H */ #ifdef HAVE_SYS_SYSCTL_H # include #endif /* HAVE_SYS_SYSCTL_H */ #ifdef HAVE_FEATURES_H # include #endif /* HAVE_FEATURES_H */ #ifdef HAVE_UNISTD_H # include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_VXCPULIB_H # include #endif #ifdef HAVE_WINDOWS_H # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif /* ! WIN32_LEAN_AND_MEAN */ # include # ifndef ALL_PROCESSOR_GROUPS # define ALL_PROCESSOR_GROUPS 0xFFFFu # endif /* ALL_PROCESSOR_GROUPS */ #elif defined(_WIN32) && ! defined (__CYGWIN__) # error Windows headers are required for Windows build #endif /* HAVE_WINDOWS_H */ #ifdef HAVE_SCHED_H # include #endif /* HAVE_SCHED_H */ #ifdef HAVE_SYS_CPUSET_H # include #endif /* HAVE_SYS_CPUSET_H */ #ifdef HAVE_STDBOOL_H # include #endif /* HAVE_STDBOOL_H */ #if ! defined(HAS_DECL_CPU_SETSIZE) && ! defined(CPU_SETSIZE) # define CPU_SETSIZE (1024) # define CPU_SETSIZE_SAFE (64) #else /* HAS_DECL_CPU_SETSIZE || CPU_SETSIZE */ # define CPU_SETSIZE_SAFE CPU_SETSIZE #endif /* HAS_DECL_CPU_SETSIZE || CPU_SETSIZE */ /* Check and fix possible missing macros */ #if ! defined(HAS_DECL_CTL_HW) && defined(CTL_HW) # define HAS_DECL_CTL_HW 1 #endif /* ! HAS_DECL_CTL_HW && CTL_HW */ #if ! defined(HAS_DECL_HW_NCPUONLINE) && defined(HW_NCPUONLINE) # define HAS_DECL_HW_NCPUONLINE 1 #endif /* ! HAS_DECL_HW_NCPUONLINE && HW_NCPUONLINE */ #if ! defined(HAS_DECL_HW_AVAILCPU) && defined(HW_AVAILCPU) # define HAS_DECL_HW_AVAILCPU 1 #endif /* ! HAS_DECL_HW_AVAILCPU && HW_AVAILCPU */ #if ! defined(HAS_DECL_HW_NCPU) && defined(HW_NCPU) # define HAS_DECL_HW_NCPU 1 #endif /* ! HAS_DECL_HW_NCPU && HW_NCPU */ #if ! defined(HAS_DECL__SC_NPROCESSORS_ONLN) && defined(_SC_NPROCESSORS_ONLN) # define HAS_DECL__SC_NPROCESSORS_ONLN 1 #endif /* ! HAS_DECL__SC_NPROCESSORS_ONLN && _SC_NPROCESSORS_ONLN */ #if ! defined(HAS_DECL__SC_NPROC_ONLN) && defined(_SC_NPROC_ONLN) # define HAS_DECL__SC_NPROC_ONLN 1 #endif /* ! HAS_DECL__SC_NPROC_ONLN && _SC_NPROC_ONLN */ #if ! defined(HAS_DECL__SC_CRAY_NCPU) && defined(_SC_CRAY_NCPU) # define HAS_DECL__SC_CRAY_NCPU 1 #endif /* ! HAS_DECL__SC_CRAY_NCPU && _SC_CRAY_NCPU */ #if ! defined(HAS_DECL__SC_NPROCESSORS_CONF) && defined(_SC_NPROCESSORS_CONF) # define HAS_DECL__SC_NPROCESSORS_CONF 1 #endif /* ! HAVE_DECL__SC_NPROCESSORS_CONF && _SC_NPROCESSORS_CONF */ /* Forward declarations */ static int mhd_tool_get_sys_cpu_count_sysctl_ (void); /** * Detect the number of logical CPU cores available for the process by * sched_getaffinity() (and related) function. * @return the number of detected logical CPU cores or * -1 if failed to detect (or this function unavailable). */ static int mhd_tool_get_proc_cpu_count_sched_getaffinity_ (void) { int ret = -1; #if defined(HAVE_SCHED_GETAFFINITY) && defined(HAVE_GETPID) /* Glibc style */ if (0 >= ret) { cpu_set_t cur_set; if (0 == sched_getaffinity (getpid (), sizeof (cur_set), &cur_set)) { #ifdef HAVE_CPU_COUNT ret = CPU_COUNT (&cur_set); #else /* ! HAVE_CPU_COUNT */ unsigned int i; ret = 0; for (i = 0; i < CPU_SETSIZE_SAFE; ++i) { if (CPU_ISSET (i, &cur_set)) ++ret; } if (0 == ret) ret = -1; #endif /* ! HAVE_CPU_COUNT */ } } #ifdef HAVE_CPU_COUNT_S if (0 >= ret) { /* Use 256 times larger size than size for default maximum CPU number. Hopefully it would be enough even for exotic situations. */ static const unsigned int set_size_cpus = 256 * CPU_SETSIZE; const size_t set_size_bytes = CPU_ALLOC_SIZE (set_size_cpus); cpu_set_t *p_set; p_set = CPU_ALLOC (set_size_cpus); if (NULL != p_set) { if (0 == sched_getaffinity (getpid (), set_size_bytes, p_set)) { #ifndef MHD_FUNC_CPU_COUNT_S_GETS_CPUS ret = CPU_COUNT_S (set_size_bytes, p_set); #else /* MHD_FUNC_CPU_COUNT_S_GETS_CPUS */ ret = CPU_COUNT_S (set_size_cpus, p_set); #endif /* MHD_FUNC_CPU_COUNT_S_GETS_CPUS */ } CPU_FREE (p_set); } } #endif /* HAVE_CPU_COUNT_S */ #endif /* HAVE_SCHED_GETAFFINITY && HAVE_GETPID */ if (0 >= ret) return -1; return ret; } /** * Detect the number of logical CPU cores available for the process by * cpuset_getaffinity() function. * @return the number of detected logical CPU cores or * -1 if failed to detect (or this function unavailable). */ static int mhd_tool_get_proc_cpu_count_cpuset_getaffinity_ (void) { int ret = -1; #if defined(HAVE_CPUSET_GETAFFINITY) /* FreeBSD style */ if (0 >= ret) { cpuset_t cur_mask; /* The should get "anonymous" mask/set. The anonymous mask is always a subset of the assigned set (which is a subset of the root set). */ if (0 == cpuset_getaffinity (CPU_LEVEL_WHICH, CPU_WHICH_PID, (id_t) -1, sizeof (cur_mask), &cur_mask)) { #ifdef HAVE_CPU_COUNT ret = CPU_COUNT (&cur_mask); #else /* ! HAVE_CPU_COUNT */ unsigned int i; ret = 0; for (i = 0; i < CPU_SETSIZE_SAFE; ++i) { if (CPU_ISSET (i, &cur_mask)) ++ret; } if (0 == ret) ret = -1; #endif /* ! HAVE_CPU_COUNT */ } } #ifdef HAVE_CPU_COUNT_S if (0 >= ret) { /* Use 256 times larger size than size for default maximum CPU number. Hopefully it would be enough even for exotic situations. */ static const unsigned int mask_size_cpus = 256 * CPU_SETSIZE; const size_t mask_size_bytes = CPU_ALLOC_SIZE (mask_size_cpus); cpuset_t *p_mask; p_mask = CPU_ALLOC (mask_size_cpus); if (NULL != p_mask) { if (0 == cpuset_getaffinity (CPU_LEVEL_WHICH, CPU_WHICH_PID, (id_t) -1, mask_size_bytes, p_mask)) { #ifndef MHD_FUNC_CPU_COUNT_S_GETS_CPUS ret = CPU_COUNT_S (mask_size_bytes, p_mask); #else /* MHD_FUNC_CPU_COUNT_S_GETS_CPUS */ ret = CPU_COUNT_S (mask_size_cpus, p_mask); #endif /* MHD_FUNC_CPU_COUNT_S_GETS_CPUS */ } CPU_FREE (p_mask); } } #endif /* HAVE_CPU_COUNT_S */ #endif /* HAVE_CPUSET_GETAFFINITY */ if (0 >= ret) return -1; return ret; } /** * Detect the number of logical CPU cores available for the process by * sched_getaffinity_np() (and related) function. * @return the number of detected logical CPU cores or * -1 if failed to detect (or this function unavailable). */ static int mhd_tool_get_proc_cpu_count_sched_getaffinity_np_ (void) { int ret = -1; #if defined(HAVE_SCHED_GETAFFINITY_NP) && defined(HAVE_GETPID) /* NetBSD style */ cpuset_t *cpuset_ptr; cpuset_ptr = cpuset_create (); if (NULL != cpuset_ptr) { if (0 == sched_getaffinity_np (getpid (), cpuset_size (cpuset_ptr), cpuset_ptr)) { cpuid_t cpu_num; #if defined(HAVE_SYSCONF) && defined(HAVE_DECL__SC_NPROCESSORS_CONF) unsigned int max_num = 0; long sc_value; sc_value = sysconf (_SC_NPROCESSORS_ONLN); if (0 < sc_value) max_num = (unsigned int) sc_value; if (0 < max_num) { ret = 0; for (cpu_num = 0; cpu_num < max_num; ++cpu_num) if (0 < cpuset_isset (cpu_num, cpuset_ptr)) ++ret; } else /* Combined with the next 'if' */ #endif /* HAVE_SYSCONF && HAVE_DECL__SC_NPROCESSORS_CONF */ if (1) { int res; cpu_num = 0; ret = 0; do { res = cpuset_isset (cpu_num++, cpuset_ptr); if (0 < res) ++ret; } while (0 <= res); } #ifdef __NetBSD__ if (0 == ret) { /* On NetBSD "unset" affinity (exactly zero CPUs) means "all CPUs are available". */ ret = mhd_tool_get_sys_cpu_count_sysctl_ (); } #endif /* __NetBSD__ */ } cpuset_destroy (cpuset_ptr); } #endif /* HAVE_SCHED_GETAFFINITY_NP && HAVE_GETPID */ if (0 >= ret) return -1; return ret; } /** * Detect the number of logical CPU cores available for the process by * W32 API functions. * @return the number of detected logical CPU cores or * -1 if failed to detect (or this function unavailable). */ static int mhd_tool_get_proc_cpu_count_w32_ (void) { int ret = -1; #if defined(_WIN32) && ! defined(__CYGWIN__) /* W32 Native */ /** * Maximum used number of CPU groups. * Improvement: Implement dynamic allocation when it would be reasonable */ #define MHDT_MAX_GROUP_COUNT 128 /** * The count of logical CPUs as returned by GetProcessAffinityMask() */ int count_by_proc_aff_mask; count_by_proc_aff_mask = -1; if (1) { DWORD_PTR proc_aff; DWORD_PTR sys_aff; if (GetProcessAffinityMask (GetCurrentProcess (), &proc_aff, &sys_aff)) { /* Count all set bits */ for (count_by_proc_aff_mask = 0; 0 != proc_aff; proc_aff &= proc_aff - 1) ++count_by_proc_aff_mask; } } if (0 < count_by_proc_aff_mask) { HMODULE k32hndl; k32hndl = LoadLibraryA ("kernel32.dll"); if (NULL != k32hndl) { typedef BOOL (WINAPI *GPGA_PTR)(HANDLE hProcess, PUSHORT GroupCount, PUSHORT GroupArray); GPGA_PTR ptrGetProcessGroupAffinity; ptrGetProcessGroupAffinity = (GPGA_PTR) (void *) GetProcAddress (k32hndl, "GetProcessGroupAffinity"); if (NULL == ptrGetProcessGroupAffinity) { /* Windows version before Win7 */ /* No processor groups supported, the process affinity mask gives full picture */ ret = count_by_proc_aff_mask; } else { /* Windows version Win7 or later */ /* Processor groups are supported */ USHORT arr_elements = MHDT_MAX_GROUP_COUNT; USHORT groups_arr[MHDT_MAX_GROUP_COUNT]; /* Hopefully should be enough */ /* Improvement: Implement dynamic allocation when it would be reasonable */ /** * Exactly one processor group is assigned to the process */ bool single_cpu_group_assigned; /**< Exactly one processor group is assigned to the process */ struct mhdt_GR_AFFINITY { KAFFINITY Mask; WORD Group; WORD Reserved[3]; }; typedef BOOL (WINAPI *GPDCSM_PTR)(HANDLE Process, struct mhdt_GR_AFFINITY *CpuSetMasks, USHORT CpuSetMaskCount, USHORT *RequiredMaskCount); GPDCSM_PTR ptrGetProcessDefaultCpuSetMasks; bool win_fe_or_later; bool cpu_set_mask_assigned; single_cpu_group_assigned = false; if (ptrGetProcessGroupAffinity (GetCurrentProcess (), &arr_elements, groups_arr)) { if (1 == arr_elements) { /* Exactly one processor group assigned to the process */ single_cpu_group_assigned = true; #if 0 /* Disabled code */ /* The value returned by GetThreadGroupAffinity() is not relevant as for the new threads the process affinity mask is used. */ ULONG_PTR proc_aff2; typedef BOOL (WINAPI *GTGA_PTR)(HANDLE hThread, struct mhdt_GR_AFFINITY * GroupAffinity); GTGA_PTR ptrGetThreadGroupAffinity; ptrGetThreadGroupAffinity = (GTGA_PTR) (void *) GetProcAddress (k32hndl, "GetThreadGroupAffinity"); if (NULL != ptrGetThreadGroupAffinity) { struct mhdt_GR_AFFINITY thr_gr_aff; if (ptrGetThreadGroupAffinity (GetCurrentThread (), &thr_gr_aff)) proc_aff2 = (ULONG_PTR) thr_gr_aff.Mask; } #endif /* Disabled code */ } } ptrGetProcessDefaultCpuSetMasks = (GPDCSM_PTR) (void *) GetProcAddress (k32hndl, "GetProcessDefaultCpuSetMasks"); if (NULL != ptrGetProcessDefaultCpuSetMasks) { /* This is Iron Release / Codename Fe (also know as Windows 11 and Windows Server 2022) or later version */ struct mhdt_GR_AFFINITY gr_affs[MHDT_MAX_GROUP_COUNT]; /* Hopefully should be enough */ /* Improvement: Implement dynamic allocation when it would be reasonable */ USHORT num_elm; win_fe_or_later = true; if (ptrGetProcessDefaultCpuSetMasks (GetCurrentProcess (), gr_affs, sizeof (gr_affs) / sizeof (gr_affs[0]), &num_elm)) { if (0 == num_elm) { /* No group mask set */ cpu_set_mask_assigned = false; } else cpu_set_mask_assigned = true; } else cpu_set_mask_assigned = true; /* Assume the worst case */ } else { win_fe_or_later = false; cpu_set_mask_assigned = false; } if (! win_fe_or_later) { /* The OS is not capable of distributing threads across different processor groups. Results reported by GetProcessAffinityMask() are relevant for the main processor group for the process. */ ret = count_by_proc_aff_mask; } else { /* The of is capable of automatic threads distribution across processor groups. */ if (cpu_set_mask_assigned) { /* Assigned Default CpuSet Masks combines with "classic" affinity in the not fully clear way. The combination is not documented and this functionality could be changed any moment. */ ret = -1; } else { if (! single_cpu_group_assigned) { /* This is a multi processor group process on Win11 (or later). Each processor group may have different affinity and the OS has not API to get it. For example, affinity to the main processor group could be assigned by SetProcessAffinityMask() function, which converts the process to the single-processor-group type, but if SetThreadGroupAffinity() is called later and bind the thread to another processor group, the process becomes multi-processor- group again, however the initial affinity mask is still used for the initial (main) processor group. There is no API to read it. It is also possible that processor groups have different number of processors. */ ret = -1; } else { /* Single-processor-group process on Win11 (or later) without assigned Default CpuSet Masks. */ ret = count_by_proc_aff_mask; } } } } FreeLibrary (k32hndl); } } #endif /* _WIN32 && ! __CYGWIN__ */ if (0 >= ret) return -1; return ret; } /** * Detect the number of logical CPU cores available for the process. * The number of cores available for this process could be different from * value of cores available on the system. The OS may have limit on number * assigned/allowed cores for single process and process may have limited * CPU affinity. * @return the number of logical CPU cores available for the process or * -1 if failed to detect */ int mhd_tool_get_proc_cpu_count (void) { int res; #if defined(__linux__) || defined(__GLIBC__) /* On Linux kernel try first 'sched_getaffinity()' as it should be the native API. Also try it first on other kernels if Glibc is used. */ res = mhd_tool_get_proc_cpu_count_sched_getaffinity_ (); if (0 < res) return res; res = mhd_tool_get_proc_cpu_count_cpuset_getaffinity_ (); if (0 < res) return res; #else /* ! __linux__ && ! __GLIBC__ */ /* On non-Linux kernels 'cpuset_getaffinity()' could be the native API, while 'sched_getaffinity()' could be implemented in compatibility layer. */ res = mhd_tool_get_proc_cpu_count_cpuset_getaffinity_ (); if (0 < res) return res; res = mhd_tool_get_proc_cpu_count_sched_getaffinity_ (); if (0 < res) return res; #endif /* ! __linux__ && ! __GLIBC__ */ res = mhd_tool_get_proc_cpu_count_sched_getaffinity_np_ (); if (0 < res) return res; res = mhd_tool_get_proc_cpu_count_w32_ (); if (0 < res) return res; return -1; } /** * Detect the number of processors by special API functions * @return number of processors as returned by special API functions or * -1 in case of error or special API functions unavailable */ static int mhd_tool_get_sys_cpu_count_special_api_ (void) { int ret = -1; #ifdef HAVE_PSTAT_GETDYNAMIC if (0 >= ret) { /* HP-UX things */ struct pst_dynamic psd_data; memset ((void *) &psd_data, 0, sizeof (psd_data)); if (1 == pstat_getdynamic (&psd_data, sizeof (psd_data), (size_t) 1, 0)) { if (0 < psd_data.psd_proc_cnt) ret = (int) psd_data.psd_proc_cnt; } } #endif /* HAVE_PSTAT_GETDYNAMIC */ #ifdef HAVE_VXCPUENABLEDGET if (0 >= ret) { /* VxWorks */ cpuset_t enb_set; enb_set = vxCpuEnabledGet (); /* Count set bits */ for (ret = 0; 0 != enb_set; enb_set &= enb_set - 1) ++ret; } #endif /* HAVE_VXCPUENABLEDGET */ #if defined(_WIN32) && ! defined (__CYGWIN__) if (0 >= ret) { /* Native W32 */ HMODULE k32hndl; k32hndl = LoadLibraryA ("kernel32.dll"); if (NULL != k32hndl) { typedef DWORD (WINAPI *GAPC_PTR)(WORD GroupNumber); GAPC_PTR ptrGetActiveProcessorCount; /* Available on W7 or later */ ptrGetActiveProcessorCount = (GAPC_PTR) (void *) GetProcAddress (k32hndl, "GetActiveProcessorCount"); if (NULL != ptrGetActiveProcessorCount) { DWORD res; res = ptrGetActiveProcessorCount (ALL_PROCESSOR_GROUPS); ret = (int) res; if (res != (DWORD) ret) ret = -1; /* Overflow */ } } if ((0 >= ret) && (NULL != k32hndl)) { typedef void (WINAPI *GNSI_PTR)(SYSTEM_INFO *pSysInfo); GNSI_PTR ptrGetNativeSystemInfo; /* May give incorrect (low) result on versions from W7 to W11 when more then 64 CPUs are available */ ptrGetNativeSystemInfo = (GNSI_PTR) (void *) GetProcAddress (k32hndl, "GetNativeSystemInfo"); if (NULL != ptrGetNativeSystemInfo) { SYSTEM_INFO sysInfo; memset ((void *) &sysInfo, 0, sizeof (sysInfo)); ptrGetNativeSystemInfo (&sysInfo); ret = (int) sysInfo.dwNumberOfProcessors; if (sysInfo.dwNumberOfProcessors != (DWORD) ret) ret = -1; /* Overflow */ } } if (NULL != k32hndl) FreeLibrary (k32hndl); } if (0 >= ret) { /* May give incorrect (low) result on versions from W7 to W11 when more then 64 CPUs are available */ SYSTEM_INFO sysInfo; memset ((void *) &sysInfo, 0, sizeof (sysInfo)); GetSystemInfo (&sysInfo); ret = (int) sysInfo.dwNumberOfProcessors; if (sysInfo.dwNumberOfProcessors != (DWORD) ret) ret = -1; /* Overflow */ } #endif /* _WIN32 && ! __CYGWIN__ */ if (0 >= ret) return -1; return ret; } /** * Detect the number of processors by sysctl*() functions in reliable way. * * This function uses reliable identificators that coreponds to actual * number of CPU cores online currently. * @return number of processors as returned by 'sysctl*' functions or * -1 in case of error or the number cannot be detected * by these functions */ static int mhd_tool_get_sys_cpu_count_sysctl_ (void) { int ret = -1; /* Do not use sysctl() function on GNU/Linux even if sysctl() is available */ #ifndef __linux__ #ifdef HAVE_SYSCTLBYNAME if (0 >= ret) { size_t value_size = sizeof (ret); /* Darwin: The number of available logical CPUs */ if ((0 != sysctlbyname ("hw.logicalcpu", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } if (0 >= ret) { size_t value_size = sizeof (ret); /* FreeBSD: The number of online CPUs */ if ((0 != sysctlbyname ("kern.smp.cpus", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } if (0 >= ret) { size_t value_size = sizeof (ret); /* Darwin: The current number of CPUs available to run threads */ if ((0 != sysctlbyname ("hw.activecpu", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } if (0 >= ret) { size_t value_size = sizeof (ret); /* OpenBSD, NetBSD: The number of online CPUs */ if ((0 != sysctlbyname ("hw.ncpuonline", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } if (0 >= ret) { size_t value_size = sizeof (ret); /* Darwin: The old/alternative name for "hw.activecpu" */ if ((0 != sysctlbyname ("hw.availcpu", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } #endif /* HAVE_SYSCTLBYNAME */ #if defined(HAVE_SYSCTL) && \ defined(HAS_DECL_CTL_HW) && \ defined(HAS_DECL_HW_NCPUONLINE) if (0 >= ret) { /* OpenBSD, NetBSD: The number of online CPUs */ int mib[2] = {CTL_HW, HW_NCPUONLINE}; size_t value_size = sizeof (ret); if ((0 != sysctl (mib, 2, &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } #endif /* HAVE_SYSCTL && HAS_DECL_CTL_HW && HAS_DECL_HW_NCPUONLINE */ #if defined(HAVE_SYSCTL) && \ defined(HAS_DECL_CTL_HW) && \ defined(HAS_DECL_HW_AVAILCPU) if (0 >= ret) { /* Darwin: The MIB name for "hw.activecpu" */ int mib[2] = {CTL_HW, HW_AVAILCPU}; size_t value_size = sizeof (ret); if ((0 != sysctl (mib, 2, &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } #endif /* HAVE_SYSCTL && HAS_DECL_CTL_HW && HAS_DECL_HW_AVAILCPU */ #endif /* ! __linux__ */ if (0 >= ret) return -1; return ret; } /** * Detect the number of processors by sysctl*() functions, using fallback way. * * This function uses less reliable (compared to * #mhd_tool_get_sys_cpu_count_sysctl_()) ways to detect the number of * available CPU cores and may return values corresponding to the number of * physically available (but possibly not used by the kernel) CPU logical cores. * @return number of processors as returned by 'sysctl*' functions or * -1 in case of error or the number cannot be detected * by these functions */ static int mhd_tool_get_sys_cpu_count_sysctl_fallback_ (void) { int ret = -1; /* Do not use sysctl() function on GNU/Linux even if sysctl() is available */ #ifndef __linux__ #ifdef HAVE_SYSCTLBYNAME if (0 >= ret) { size_t value_size = sizeof (ret); /* FreeBSD, OpenBSD, NetBSD, Darwin (and others?): The number of CPUs */ if ((0 != sysctlbyname ("hw.ncpu", &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } #endif /* HAVE_SYSCTLBYNAME */ #if defined(HAVE_SYSCTL) && \ defined(HAS_DECL_CTL_HW) && \ defined(HAS_DECL_HW_NCPU) if (0 >= ret) { /* FreeBSD, OpenBSD, NetBSD, Darwin (and others?): The number of CPUs */ int mib[2] = {CTL_HW, HW_NCPU}; size_t value_size = sizeof (ret); if ((0 != sysctl (mib, 2, &ret, &value_size, NULL, 0)) || (sizeof (ret) != value_size)) ret = -1; } #endif /* HAVE_SYSCTL && HAS_DECL_CTL_HW && HAS_DECL_HW_NCPU */ #endif /* ! __linux__ */ if (0 >= ret) return -1; return ret; } /** * Detect the number of processors by sysconf() function in reliable way. * * This function uses reliable identificators that coreponds to actual * number of CPU cores online currently. * @return number of processors as returned by 'sysconf' function or * -1 in case of error or 'sysconf' unavailable */ static int mhd_tool_get_sys_cpu_count_sysconf_ (void) { int ret = -1; #if defined(HAVE_SYSCONF) && \ (defined(HAS_DECL__SC_NPROCESSORS_ONLN) || defined(HAS_DECL__SC_NPROC_ONLN)) long value = -1; #ifdef HAS_DECL__SC_NPROCESSORS_ONLN if (0 >= value) value = sysconf (_SC_NPROCESSORS_ONLN); #endif /* HAS_DECL__SC_NPROCESSORS_ONLN */ #ifdef HAS_DECL__SC_NPROC_ONLN if (0 >= value) value = sysconf (_SC_NPROC_ONLN); #endif /* HAS_DECL__SC_NPROC_ONLN */ if (0 >= value) return -1; ret = (int) value; if ((long) ret != value) return -1; /* Overflow */ #endif /* HAVE_SYSCONF && (HAS_DECL__SC_NPROCESSORS_ONLN || HAS_DECL__SC_NPROC_ONLN) */ return ret; } /** * Detect the number of processors by sysconf() function, using fallback way. * * This function uses less reliable (compared to * #mhd_tool_get_sys_cpu_count_sysconf_()) ways to detect the number of * available CPU cores and may return values corresponding to the number of * physically available (but possibly not used by the kernel) CPU logical cores. * @return number of processors as returned by 'sysconf' function or * -1 in case of error or 'sysconf' unavailable */ static int mhd_tool_get_sys_cpu_count_sysconf_fallback_ (void) { int ret = -1; #if defined(HAVE_SYSCONF) && \ (defined(HAS_DECL__SC_CRAY_NCPU) || defined(HAS_DECL__SC_NPROCESSORS_CONF)) long value = -1; #ifdef HAS_DECL__SC_CRAY_NCPU if (0 >= value) value = sysconf (_SC_CRAY_NCPU); #endif /* HAS_DECL__SC_CRAY_NCPU */ #ifdef HAS_DECL__SC_NPROCESSORS_CONF if (0 >= value) value = sysconf (_SC_NPROCESSORS_CONF); #endif /* HAS_DECL__SC_NPROCESSORS_CONF */ if (0 >= value) return -1; ret = (int) value; if ((long) ret != value) return -1; /* Overflow */ #endif /* HAVE_SYSCONF && (HAS_DECL__SC_CRAY_NCPU || HAS_DECL__SC_NPROCESSORS_CONF) */ return ret; } /** * Try to detect the number of logical CPU cores available for the system. * The number of available logical CPU cores could be changed any time due to * CPU hotplug. * @return the number of logical CPU cores available, * -1 if failed to detect. */ int mhd_tool_get_system_cpu_count (void) { int res; /* Try specialised APIs first */ res = mhd_tool_get_sys_cpu_count_special_api_ (); if (0 < res) return res; /* Try sysctl*(). This is typically a direct interface to kernel values. */ res = mhd_tool_get_sys_cpu_count_sysctl_ (); if (0 < res) return res; /* Try sysconf() as the last resort as this is a generic interface which can be implemented by parsing system files. */ res = mhd_tool_get_sys_cpu_count_sysconf_ (); #if ! defined(__linux__) && ! defined(__GLIBC__) if (0 < res) return res; #else /* __linux__ || __GLIBC__ */ if (2 < res) return res; if (0 < res) { /* '1' or '2' could a be fallback number. * See get_nprocs_fallback() in glibc sysdeps/unix/sysv/linux/getsysstats.c */ int proc_cpu_count; proc_cpu_count = mhd_tool_get_proc_cpu_count (); if (proc_cpu_count == res) { /* The detected number of CPUs available for the process is equal to the detected number of system CPUs. Assume detected number is correct. */ return res; } } #endif /* __linux__ || __GLIBC__ */ /* Try available fallbacks */ res = mhd_tool_get_sys_cpu_count_sysctl_fallback_ (); if (0 < res) return res; res = mhd_tool_get_sys_cpu_count_sysconf_fallback_ (); #if ! defined(__linux__) && ! defined(__GLIBC__) if (0 < res) return res; #else /* __linux__ || __GLIBC__ */ if (2 < res) return res; #endif /* __linux__ || __GLIBC__ */ return -1; /* Cannot detect */ } libmicrohttpd-1.0.10/src/tools/Makefile.in0000664000175000017500000006437615235436271014144 # Makefile.in generated by automake 1.17 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2024 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) am__rm_f = rm -f $(am__rm_f_notfound) am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = --coverage noinst_PROGRAMS = $(am__EXEEXT_1) @USE_THREADS_TRUE@am__append_2 = \ @USE_THREADS_TRUE@ perf_replies subdir = src/tools ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @USE_THREADS_TRUE@am__EXEEXT_1 = perf_replies$(EXEEXT) PROGRAMS = $(noinst_PROGRAMS) am_perf_replies_OBJECTS = perf_replies.$(OBJEXT) \ mhd_tool_get_cpu_count.$(OBJEXT) perf_replies_OBJECTS = $(am_perf_replies_OBJECTS) perf_replies_LDADD = $(LDADD) perf_replies_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/mhd_tool_get_cpu_count.Po \ ./$(DEPDIR)/perf_replies.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(perf_replies_SOURCES) DIST_SOURCES = $(perf_replies_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ am__xargs_n = @am__xargs_n@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -DMHD_REAL_CPU_COUNT=@MHD_REAL_CPU_COUNT@ \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) \ -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ $(am__append_1) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la perf_replies_SOURCES = \ perf_replies.c mhd_tool_str_to_uint.h \ mhd_tool_get_cpu_count.h mhd_tool_get_cpu_count.c all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/tools/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/tools/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstPROGRAMS: $(am__rm_f) $(noinst_PROGRAMS) test -z "$(EXEEXT)" || $(am__rm_f) $(noinst_PROGRAMS:$(EXEEXT)=) perf_replies$(EXEEXT): $(perf_replies_OBJECTS) $(perf_replies_DEPENDENCIES) $(EXTRA_perf_replies_DEPENDENCIES) @rm -f perf_replies$(EXEEXT) $(AM_V_CCLD)$(LINK) $(perf_replies_OBJECTS) $(perf_replies_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd_tool_get_cpu_count.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/perf_replies.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @: >>$@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(PROGRAMS) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -$(am__rm_f) $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool clean-noinstPROGRAMS \ mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/mhd_tool_get_cpu_count.Po -rm -f ./$(DEPDIR)/perf_replies.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/mhd_tool_get_cpu_count.Po -rm -f ./$(DEPDIR)/perf_replies.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-am clean clean-generic clean-libtool \ clean-noinstPROGRAMS cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am .PRECIOUS: Makefile $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: # Tell GNU make to disable its built-in pattern rules. %:: %,v %:: RCS/%,v %:: RCS/% %:: s.% %:: SCCS/s.% libmicrohttpd-1.0.10/src/tools/mhd_tool_str_to_uint.h0000644000175000017500000000370614760713577016503 /* This file is part of GNU libmicrohttpd Copyright (C) 2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file tools/mhd_tool_str_to_uint.h * @brief Function to decode the value of decimal string number. * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_TOOL_STR_TO_UINT_H_ #define MHD_TOOL_STR_TO_UINT_H_ 1 #include /** * Convert decimal string to unsigned int. * Function stops at the end of the string or on first non-digit character. * @param str the string to convert * @param[out] value the pointer to put the result * @return return the number of digits converted or * zero if no digits found or result would overflow the output * variable (the output set to UINT_MAX in this case). */ static size_t mhd_tool_str_to_uint (const char *str, unsigned int *value) { size_t i; unsigned int v = 0; *value = 0; for (i = 0; 0 != str[i]; ++i) { const char chr = str[i]; unsigned int digit; if (('0' > chr) || ('9' < chr)) break; digit = (unsigned char) (chr - '0'); if ((((0U - 1) / 10) < v) || ((v * 10 + digit) < v)) { /* Overflow */ *value = 0U - 1; return 0; } v *= 10; v += digit; } *value = v; return i; } #endif /* MHD_TOOL_STR_TO_UINT_H_ */ libmicrohttpd-1.0.10/src/tools/Makefile.am0000644000175000017500000000167615035214301014105 # This Makefile.am is in the public domain SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -DMHD_REAL_CPU_COUNT=@MHD_REAL_CPU_COUNT@ \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) \ -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) if USE_COVERAGE AM_CFLAGS += --coverage endif LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tools noinst_PROGRAMS = if USE_THREADS noinst_PROGRAMS += \ perf_replies endif perf_replies_SOURCES = \ perf_replies.c mhd_tool_str_to_uint.h \ mhd_tool_get_cpu_count.h mhd_tool_get_cpu_count.c libmicrohttpd-1.0.10/src/include/0000775000175000017500000000000015235437005012416 5libmicrohttpd-1.0.10/src/include/autoinit_funcs.h0000644000175000017500000003021415035214301015525 /* * AutoinitFuncs: Automatic Initialization and Deinitialization Functions * Copyright(C) 2014-2023 Karlson2k (Evgeny Grin) * * This header is free software; you can redistribute it and / or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This header is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this header; if not, see * . */ /* General usage is simple: include this header, declare or define two functions with zero parameters (void) and any return type: one for initialisation and one for deinitialisation, add _SET_INIT_AND_DEINIT_FUNCS(FuncInitName, FuncDeInitName) to the code and functions will be automatically called during application startup and shutdown. This is useful for libraries as libraries don't have direct access to main() functions. Example: ------------------------------------------------- #include #include "autoinit_funcs.h" int someVar; void* somePtr; void libInit(void) { someVar = 3; somePtr = malloc(100); } void libDeinit(void) { free(somePtr); } _SET_INIT_AND_DEINIT_FUNCS(libInit,libDeinit); ------------------------------------------------- If initialiser or deinitialiser function is not needed, just define it as empty function. This header should work with GCC, clang, MSVC (2010 or later) and SunPro / Sun Studio / Oracle Solaris Studio / Oracle Developer Studio compiler. Supported C and C++ languages; application, static and dynamic (DLL) libraries; non-optimized (Debug) and optimised (Release) compilation and linking. For more information see header code and comments in code. */ #ifndef AUTOINIT_FUNCS_INCLUDED #define AUTOINIT_FUNCS_INCLUDED 1 /** * Current version of the header in packed BCD form. * 0x01093001 = 1.9.30-1. */ #define AUTOINIT_FUNCS_VERSION 0x01001000 #if defined(__GNUC__) || defined(__clang__) /* if possible - check for supported attribute */ #ifdef __has_attribute #if ! __has_attribute (constructor) || ! __has_attribute (destructor) #define _GNUC_ATTR_CONSTR_NOT_SUPPORTED 1 #endif /* !__has_attribute(constructor) || !__has_attribute(destructor) */ #endif /* __has_attribute */ #endif /* __GNUC__ */ /* "__has_attribute__ ((constructor))" is supported by GCC, clang and Sun/Oracle compiler starting from version 12.1. */ #if ((defined(__GNUC__) || defined(__clang__)) && \ ! defined(_GNUC_ATTR_CONSTR_NOT_SUPPORTED)) || \ (defined(__SUNPRO_C) && __SUNPRO_C + 0 >= 0x5100) #define GNUC_SET_INIT_AND_DEINIT(FI,FD) \ void __attribute__ ((constructor)) _GNUC_init_helper_ ## FI (void); \ void __attribute__ ((destructor)) _GNUC_deinit_helper_ ## FD (void); \ void __attribute__ ((constructor)) _GNUC_init_helper_ ## FI (void) \ { (void) (FI) (); } \ void __attribute__ ((destructor)) _GNUC_deinit_helper_ ## FD (void) \ { (void) (FD) (); } \ struct _GNUC_dummy_str_ ## FI {int i;} #define _SET_INIT_AND_DEINIT_FUNCS(FI,FD) GNUC_SET_INIT_AND_DEINIT (FI,FD) #define _AUTOINIT_FUNCS_ARE_SUPPORTED 1 #elif defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1600 /* Make sure that your project/sources define: _LIB if building a static library (_LIB is ignored if _CONSOLE is defined); _USRDLL if building DLL-library; not defined both _LIB and _USRDLL if building an application */ /* Define AUTOINIT_FUNCS_DECLARE_STATIC_REG if you need macro declaration for registering static initialisation functions even if you building DLL */ /* Define AUTOINIT_FUNCS_FORCE_STATIC_REG if you want to set main macro _SET_INIT_AND_DEINIT_FUNCS to static version even if building a DLL */ /* Stringify macros */ #define _INSTRMACRO(a) #a #define _STRMACRO(a) _INSTRMACRO (a) #if ! defined(_USRDLL) || defined(AUTOINIT_FUNCS_DECLARE_STATIC_REG) \ || defined(AUTOINIT_FUNCS_FORCE_STATIC_REG) /* Use "C" linkage for variable to simplify variable decoration */ #ifdef __cplusplus #define W32_INITVARDECL extern "C" #else #define W32_INITVARDECL extern #endif /* How variable is decorated by compiler */ #if (defined(_WIN32) || defined(_WIN64)) \ && ! defined(_M_IX86) && ! defined(_X86_) #if ! defined(_M_X64) && ! defined(_M_AMD64) && ! defined(_x86_64_) \ && ! defined(_M_ARM) && ! defined(_M_ARM64) #pragma message(__FILE__ "(" _STRMACRO(__LINE__) ") : warning AIFW001 : " \ "Untested architecture, linker may fail with unresolved symbol") #endif /* ! _M_X64 && ! _M_AMD64 && ! _x86_64_ && ! _M_ARM && ! _M_ARM64 */ #define W32_VARDECORPREFIX #define W32_DECORVARNAME(v) v #define W32_VARDECORPREFIXSTR "" #elif defined(_WIN32) && (defined(_M_IX86) || defined(_X86_)) #define W32_VARDECORPREFIX _ #define W32_DECORVARNAME(v) _ ## v #define W32_VARDECORPREFIXSTR "_" #else #error Do not know how to decorate symbols for this architecture #endif /* Internal variable prefix (can be any) */ #define W32_INITHELPERVARNAME(f) _initHelperDummy_ ## f #define W32_INITHELPERVARNAMEDECORSTR(f) \ W32_VARDECORPREFIXSTR _STRMACRO (W32_INITHELPERVARNAME (f)) /* Declare section (segment), put variable pointing to init function to chosen segment, force linker to always include variable to avoid omitting by optimiser */ /* Initialisation function must be declared as void __cdecl FuncName(void) */ /* "extern" with initialisation value means that variable is declared AND defined. */ #define W32_VFPTR_IN_SEG(S,F) \ __pragma (section (S,long,read)) \ __pragma (comment (linker, "/INCLUDE:" W32_INITHELPERVARNAMEDECORSTR (F))) \ W32_INITVARDECL __declspec(allocate (S))void \ (__cdecl * W32_INITHELPERVARNAME (F))(void) = &F /* Sections (segments) for pointers to initialisers/deinitialisers */ /* Semi-officially suggested section for early initialisers (called before C++ objects initialisers), "void" return type */ #define W32_SEG_INIT_EARLY ".CRT$XCT" /* Semi-officially suggested section for late initialisers (called after C++ objects initialisers), "void" return type */ #define W32_SEG_INIT_LATE ".CRT$XCV" /* Unsafe sections (segments) for pointers to initialisers/deinitialisers */ /* C++ lib initialisers, "void" return type (reserved by the system!) */ #define W32_SEG_INIT_CXX_LIB ".CRT$XCL" /* C++ user initialisers, "void" return type (reserved by the system!) */ #define W32_SEG_INIT_CXX_USER ".CRT$XCU" /* Declare section (segment), put variable pointing to init function to chosen segment, force linker to always include variable to avoid omitting by optimiser */ /* Initialisation function must be declared as int __cdecl FuncName(void) */ /* Startup process is aborted if initialiser returns non-zero */ /* "extern" with initialisation value means that variable is declared AND defined. */ #define W32_IFPTR_IN_SEG(S,F) \ __pragma (section (S,long,read)) \ __pragma (comment (linker, "/INCLUDE:" W32_INITHELPERVARNAMEDECORSTR (F))) \ W32_INITVARDECL __declspec(allocate (S))int \ (__cdecl * W32_INITHELPERVARNAME (F))(void) = &F /* Unsafe sections (segments) for pointers to initialisers with "int" return type */ /* C lib initialisers, "int" return type (reserved by the system!). These initialisers are called before others. */ #define W32_SEG_INIT_C_LIB ".CRT$XIL" /* C user initialisers, "int" return type (reserved by the system!). These initialisers are called before others. */ #define W32_SEG_INIT_C_USER ".CRT$XIU" /* Declare macro for different initialisers sections */ /* Macro can be used several times to register several initialisers */ /* Once function is registered as initialiser, it will be called automatically during application startup */ #define W32_REG_INIT_EARLY(F) W32_VFPTR_IN_SEG (W32_SEG_INIT_EARLY,F) #define W32_REG_INIT_LATE(F) W32_VFPTR_IN_SEG (W32_SEG_INIT_LATE,F) /* Not recommended / unsafe */ /* "lib" initialisers are called before "user" initialisers */ /* "C" initialisers are called before "C++" initialisers */ #define W32_REG_INIT_C_USER(F) W32_FPTR_IN_SEG (W32_SEG_INIT_C_USER,F) #define W32_REG_INIT_C_LIB(F) W32_FPTR_IN_SEG (W32_SEG_INIT_C_LIB,F) #define W32_REG_INIT_CXX_USER(F) W32_FPTR_IN_SEG (W32_SEG_INIT_CXX_USER,F) #define W32_REG_INIT_CXX_LIB(F) W32_FPTR_IN_SEG (W32_SEG_INIT_CXX_LIB,F) /* Choose main register macro based on language and program type */ /* Assuming that _LIB or _USRDLL is defined for static or DLL-library */ /* Macro can be used several times to register several initialisers */ /* Once function is registered as initialiser, it will be called automatically during application startup */ /* Define AUTOINIT_FUNCS_FORCE_EARLY_INIT to force register as early initialiser */ /* Define AUTOINIT_FUNCS_FORCE_LATE_INIT to force register as late initialiser */ /* By default C++ static or DLL-library code and any C code and will be registered as early initialiser, while C++ non-library code will be registered as late initialiser */ #if (! defined(__cplusplus) || \ ((defined(_LIB) && ! defined(_CONSOLE)) || defined(_USRDLL)) || \ defined(AUTOINIT_FUNCS_FORCE_EARLY_INIT)) && \ ! defined(AUTOINIT_FUNCS_FORCE_LATE_INIT) #define W32_REGISTER_INIT(F) W32_REG_INIT_EARLY(F) #else #define W32_REGISTER_INIT(F) W32_REG_INIT_LATE(F) #endif #endif /* ! _USRDLL || ! AUTOINIT_FUNCS_DECLARE_STATIC_REG || AUTOINIT_FUNCS_FORCE_STATIC_REG */ #if ! defined(_USRDLL) || defined(AUTOINIT_FUNCS_FORCE_STATIC_REG) #include /* required for atexit() */ #define W32_SET_INIT_AND_DEINIT(FI,FD) \ void __cdecl _W32_init_helper_ ## FI (void); \ void __cdecl _W32_deinit_helper_ ## FD (void); \ void __cdecl _W32_init_helper_ ## FI (void) \ { (void) (FI) (); atexit (_W32_deinit_helper_ ## FD); } \ void __cdecl _W32_deinit_helper_ ## FD (void) \ { (void) (FD) (); } \ W32_REGISTER_INIT (_W32_init_helper_ ## FI) #else /* _USRDLL */ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* WIN32_LEAN_AND_MEAN */ #include /* Required for DllMain */ /* If DllMain is already present in code, define AUTOINIT_FUNCS_CALL_USR_DLLMAIN and rename DllMain to usr_DllMain */ #ifndef AUTOINIT_FUNCS_CALL_USR_DLLMAIN #define W32_SET_INIT_AND_DEINIT(FI,FD) \ BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused); \ BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused) \ { (void) hinst; (void) unused; \ if (DLL_PROCESS_ATTACH==reason) {(void) (FI) ();} \ else if (DLL_PROCESS_DETACH==reason) {(void) (FD) ();} \ return TRUE; \ } struct _W32_dummy_strc_ ## FI {int i;} #else /* AUTOINIT_FUNCS_CALL_USR_DLLMAIN */ #define W32_SET_INIT_AND_DEINIT(FI,FD) \ BOOL WINAPI usr_DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused); \ BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused); \ BOOL WINAPI DllMain (HINSTANCE hinst,DWORD reason,LPVOID unused) \ { if (DLL_PROCESS_ATTACH==reason) {(void) (FI) ();} \ else if (DLL_PROCESS_DETACH==reason) {(void) (FD) ();} \ return usr_DllMain (hinst,reason,unused); \ } struct _W32_dummy_strc_ ## FI {int i;} #endif /* AUTOINIT_FUNCS_CALL_USR_DLLMAIN */ #endif /* _USRDLL */ #define _SET_INIT_AND_DEINIT_FUNCS(FI,FD) W32_SET_INIT_AND_DEINIT (FI,FD) /* Indicate that automatic initialisers/deinitialisers are supported */ #define _AUTOINIT_FUNCS_ARE_SUPPORTED 1 #else /* !__GNUC__ && !_MSC_FULL_VER */ /* Define EMIT_ERROR_IF_AUTOINIT_FUNCS_ARE_NOT_SUPPORTED before inclusion of header to abort compilation if automatic initialisers/deinitialisers are not supported */ #ifdef EMIT_ERROR_IF_AUTOINIT_FUNCS_ARE_NOT_SUPPORTED #error \ Compiler/platform does not support automatic calls of user-defined initializer and deinitializer #endif /* EMIT_ERROR_IF_AUTOINIT_FUNCS_ARE_NOT_SUPPORTED */ /* Do nothing */ #define _SET_INIT_AND_DEINIT_FUNCS(FI,FD) /* Indicate that automatic initialisers/deinitialisers are not supported */ #define _AUTOINIT_FUNCS_ARE_NOT_SUPPORTED 1 #endif /* !__GNUC__ && !_MSC_FULL_VER */ #endif /* !AUTOINIT_FUNCS_INCLUDED */ libmicrohttpd-1.0.10/src/include/microhttpd.h0000664000175000017500000076677015235436721014717 /* This file is part of libmicrohttpd Copyright (C) 2006-2021 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd.h * @brief public interface to libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) * @author Chris GauthierDickey * * All symbols defined in this header start with MHD. MHD is a small * HTTP daemon library. As such, it does not have any API for logging * errors (you can only enable or disable logging to stderr). Also, * it may not support all of the HTTP features directly, where * applicable, portions of HTTP may have to be handled by clients of * the library. * * The library is supposed to handle everything that it must handle * (because the API would not allow clients to do this), such as basic * connection management; however, detailed interpretations of headers * -- such as range requests -- and HTTP methods are left to clients. * The library does understand HEAD and will only send the headers of * the response and not the body, even if the client supplied a body. * The library also understands headers that control connection * management (specifically, "Connection: close" and "Expect: 100 * continue" are understood and handled automatically). * * MHD understands POST data and is able to decode certain formats * (at the moment only "application/x-www-form-urlencoded" and * "multipart/formdata"). Unsupported encodings and large POST * submissions may require the application to manually process * the stream, which is provided to the main application (and thus can be * processed, just not conveniently by MHD). * * The header file defines various constants used by the HTTP protocol. * This does not mean that MHD actually interprets all of these * values. The provided constants are exported as a convenience * for users of the library. MHD does not verify that transmitted * HTTP headers are part of the standard specification; users of the * library are free to define their own extensions of the HTTP * standard and use those with MHD. * * All functions are guaranteed to be completely reentrant and * thread-safe (with the exception of #MHD_set_connection_value, * which must only be used in a particular context). * * * @defgroup event event-loop control * MHD API to start and stop the HTTP server and manage the event loop. * @defgroup response generation of responses * MHD API used to generate responses. * @defgroup request handling of requests * MHD API used to access information about requests. * @defgroup authentication HTTP authentication * MHD API related to basic and digest HTTP authentication. * @defgroup logging logging * MHD API to manage logging and error handling * @defgroup specialized misc. specialized functions * This group includes functions that do not fit into any particular * category and that are rarely used. */ #ifndef MHD_MICROHTTPD_H #define MHD_MICROHTTPD_H #ifndef __cplusplus # define MHD_C_DECLRATIONS_START_HERE_ /* Empty */ # define MHD_C_DECLRATIONS_FINISH_HERE_ /* Empty */ #else /* __cplusplus */ /* *INDENT-OFF* */ # define MHD_C_DECLRATIONS_START_HERE_ extern "C" { # define MHD_C_DECLRATIONS_FINISH_HERE_ } /* *INDENT-ON* */ #endif /* __cplusplus */ MHD_C_DECLRATIONS_START_HERE_ /** * Current version of the library in packed BCD form. * @note Version number components are coded as Simple Binary-Coded Decimal * (also called Natural BCD or BCD 8421). While they are hexadecimal numbers, * they are parsed as decimal numbers. * Example: 0x01093001 = 1.9.30-1. */ #define MHD_VERSION 0x01001000 /* If generic headers don't work on your platform, include headers which define 'va_list', 'size_t', 'ssize_t', 'intptr_t', 'off_t', 'uint8_t', 'uint16_t', 'int32_t', 'uint32_t', 'int64_t', 'uint64_t', 'struct sockaddr', 'socklen_t', 'fd_set' and "#define MHD_PLATFORM_H" before including "microhttpd.h". Then the following "standard" includes won't be used (which might be a good idea, especially on platforms where they do not exist). */ #ifndef MHD_PLATFORM_H #if defined(_WIN32) && ! defined(__CYGWIN__) && \ ! defined(_CRT_DECLARE_NONSTDC_NAMES) /* Declare POSIX-compatible names */ #define _CRT_DECLARE_NONSTDC_NAMES 1 #endif /* _WIN32 && ! __CYGWIN__ && ! _CRT_DECLARE_NONSTDC_NAMES */ #include #include #include #if ! defined(_WIN32) || defined(__CYGWIN__) #include #include #include #else /* _WIN32 && ! __CYGWIN__ */ #include #if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED) #define _SSIZE_T_DEFINED typedef intptr_t ssize_t; #endif /* !_SSIZE_T_DEFINED */ #endif /* _WIN32 && ! __CYGWIN__ */ #endif #if defined(__CYGWIN__) && ! defined(_SYS_TYPES_FD_SET) /* Do not define __USE_W32_SOCKETS under Cygwin! */ #error Cygwin with winsock fd_set is not supported #endif #ifdef __has_attribute #if __has_attribute (flag_enum) #define _MHD_FLAGS_ENUM __attribute__((flag_enum)) #endif /* flag_enum */ #if __has_attribute (enum_extensibility) #define _MHD_FIXED_ENUM __attribute__((enum_extensibility (closed))) #endif /* enum_extensibility */ #endif /* __has_attribute */ #ifndef _MHD_FLAGS_ENUM #define _MHD_FLAGS_ENUM #endif /* _MHD_FLAGS_ENUM */ #ifndef _MHD_FIXED_ENUM #define _MHD_FIXED_ENUM #endif /* _MHD_FIXED_ENUM */ #define _MHD_FIXED_FLAGS_ENUM _MHD_FIXED_ENUM _MHD_FLAGS_ENUM /** * Operational results from MHD calls. */ enum MHD_Result { /** * MHD result code for "NO". */ MHD_NO = 0, /** * MHD result code for "YES". */ MHD_YES = 1 } _MHD_FIXED_ENUM; /** * Constant used to indicate unknown size (use when * creating a response). */ #ifdef UINT64_MAX #define MHD_SIZE_UNKNOWN UINT64_MAX #else #define MHD_SIZE_UNKNOWN ((uint64_t) -1LL) #endif #define MHD_CONTENT_READER_END_OF_STREAM ((ssize_t) -1) #define MHD_CONTENT_READER_END_WITH_ERROR ((ssize_t) -2) #ifndef _MHD_EXTERN #if defined(_WIN32) && defined(MHD_W32LIB) #define _MHD_EXTERN extern #elif defined(_WIN32) && defined(MHD_W32DLL) /* Define MHD_W32DLL when using MHD as W32 .DLL to speed up linker a little */ #define _MHD_EXTERN __declspec(dllimport) #else #define _MHD_EXTERN extern #endif #endif #ifndef MHD_SOCKET_DEFINED /** * MHD_socket is type for socket FDs */ #if ! defined(_WIN32) || defined(_SYS_TYPES_FD_SET) #define MHD_POSIX_SOCKETS 1 typedef int MHD_socket; #define MHD_INVALID_SOCKET (-1) #else /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */ #define MHD_WINSOCK_SOCKETS 1 #include typedef SOCKET MHD_socket; #define MHD_INVALID_SOCKET (INVALID_SOCKET) #endif /* !defined(_WIN32) || defined(_SYS_TYPES_FD_SET) */ #define MHD_SOCKET_DEFINED 1 #endif /* MHD_SOCKET_DEFINED */ /** * Define MHD_NO_DEPRECATION before including "microhttpd.h" to disable deprecation messages */ #ifdef MHD_NO_DEPRECATION #define _MHD_DEPR_MACRO(msg) #define _MHD_NO_DEPR_IN_MACRO 1 #define _MHD_DEPR_IN_MACRO(msg) #define _MHD_NO_DEPR_FUNC 1 #define _MHD_DEPR_FUNC(msg) #endif /* MHD_NO_DEPRECATION */ #ifndef _MHD_DEPR_MACRO #if defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1500 /* VS 2008 or later */ /* Stringify macros */ #define _MHD_INSTRMACRO(a) #a #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) /* deprecation message */ #define _MHD_DEPR_MACRO(msg) \ __pragma \ (message (__FILE__ "(" _MHD_STRMACRO ( __LINE__) "): warning: " msg)) #define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg) #elif defined(__clang__) || defined(__GNUC_PATCHLEVEL__) /* clang or GCC since 3.0 */ #define _MHD_GCC_PRAG(x) _Pragma(#x) #if (defined(__clang__) && \ (__clang_major__ + 0 >= 5 || \ (! defined(__apple_build_version__) && \ (__clang_major__ + 0 > 3 || \ (__clang_major__ + 0 == 3 && __clang_minor__ >= 3))))) || \ __GNUC__ + 0 > 4 || (__GNUC__ + 0 == 4 && __GNUC_MINOR__ + 0 >= 8) /* clang >= 3.3 (or XCode's clang >= 5.0) or GCC >= 4.8 */ #define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG (GCC warning msg) #define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg) #else /* older clang or GCC */ /* clang < 3.3, XCode's clang < 5.0, 3.0 <= GCC < 4.8 */ #define _MHD_DEPR_MACRO(msg) _MHD_GCC_PRAG (message msg) #if (defined(__clang__) && \ (__clang_major__ + 0 > 2 || \ (__clang_major__ + 0 == 2 && __clang_minor__ >= 9))) /* clang >= 2.9 */ /* clang handles inline pragmas better than GCC */ #define _MHD_DEPR_IN_MACRO(msg) _MHD_DEPR_MACRO (msg) #endif /* clang >= 2.9 */ #endif /* older clang or GCC */ /* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */ #endif /* clang || GCC >= 3.0 */ #endif /* !_MHD_DEPR_MACRO */ #ifndef _MHD_DEPR_MACRO #define _MHD_DEPR_MACRO(msg) #endif /* !_MHD_DEPR_MACRO */ #ifndef _MHD_DEPR_IN_MACRO #define _MHD_NO_DEPR_IN_MACRO 1 #define _MHD_DEPR_IN_MACRO(msg) #endif /* !_MHD_DEPR_IN_MACRO */ #ifndef _MHD_DEPR_FUNC #if defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1400 /* VS 2005 or later */ #define _MHD_DEPR_FUNC(msg) __declspec(deprecated (msg)) #elif defined(_MSC_FULL_VER) && _MSC_VER + 0 >= 1310 /* VS .NET 2003 deprecation does not support custom messages */ #define _MHD_DEPR_FUNC(msg) __declspec(deprecated) #elif (__GNUC__ + 0 >= 5) || (defined(__clang__) && \ (__clang_major__ + 0 > 2 || \ (__clang_major__ + 0 == 2 && __clang_minor__ >= 9))) /* GCC >= 5.0 or clang >= 2.9 */ #define _MHD_DEPR_FUNC(msg) __attribute__((deprecated (msg))) #elif defined(__clang__) || __GNUC__ + 0 > 3 || \ (__GNUC__ + 0 == 3 && __GNUC_MINOR__ + 0 >= 1) /* 3.1 <= GCC < 5.0 or clang < 2.9 */ /* old GCC-style deprecation does not support custom messages */ #define _MHD_DEPR_FUNC(msg) __attribute__((__deprecated__)) /* #elif defined(SOMEMACRO) */ /* add compiler-specific macros here if required */ #endif /* clang < 2.9 || GCC >= 3.1 */ #endif /* !_MHD_DEPR_FUNC */ #ifndef _MHD_DEPR_FUNC #define _MHD_NO_DEPR_FUNC 1 #define _MHD_DEPR_FUNC(msg) #endif /* !_MHD_DEPR_FUNC */ /** * Not all architectures and `printf()`'s support the `long long` type. * This gives the ability to replace `long long` with just a `long`, * standard `int` or a `short`. */ #ifndef MHD_LONG_LONG /** * @deprecated use #MHD_UNSIGNED_LONG_LONG instead! */ #define MHD_LONG_LONG long long #define MHD_UNSIGNED_LONG_LONG unsigned long long #else /* MHD_LONG_LONG */ _MHD_DEPR_MACRO ( \ "Macro MHD_LONG_LONG is deprecated, use MHD_UNSIGNED_LONG_LONG") #endif /** * Format string for printing a variable of type #MHD_LONG_LONG. * You should only redefine this if you also define #MHD_LONG_LONG. */ #ifndef MHD_LONG_LONG_PRINTF /** * @deprecated use #MHD_UNSIGNED_LONG_LONG_PRINTF instead! */ #define MHD_LONG_LONG_PRINTF "ll" #define MHD_UNSIGNED_LONG_LONG_PRINTF "%llu" #else /* MHD_LONG_LONG_PRINTF */ _MHD_DEPR_MACRO ( \ "Macro MHD_LONG_LONG_PRINTF is deprecated, use MHD_UNSIGNED_LONG_LONG_PRINTF") #endif /** * @defgroup httpcode HTTP response codes. * These are the status codes defined for HTTP responses. * See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * Registry export date: 2023-09-29 * @{ */ /* 100 "Continue". RFC9110, Section 15.2.1. */ #define MHD_HTTP_CONTINUE 100 /* 101 "Switching Protocols". RFC9110, Section 15.2.2. */ #define MHD_HTTP_SWITCHING_PROTOCOLS 101 /* 102 "Processing". RFC2518. */ #define MHD_HTTP_PROCESSING 102 /* 103 "Early Hints". RFC8297. */ #define MHD_HTTP_EARLY_HINTS 103 /* 200 "OK". RFC9110, Section 15.3.1. */ #define MHD_HTTP_OK 200 /* 201 "Created". RFC9110, Section 15.3.2. */ #define MHD_HTTP_CREATED 201 /* 202 "Accepted". RFC9110, Section 15.3.3. */ #define MHD_HTTP_ACCEPTED 202 /* 203 "Non-Authoritative Information". RFC9110, Section 15.3.4. */ #define MHD_HTTP_NON_AUTHORITATIVE_INFORMATION 203 /* 204 "No Content". RFC9110, Section 15.3.5. */ #define MHD_HTTP_NO_CONTENT 204 /* 205 "Reset Content". RFC9110, Section 15.3.6. */ #define MHD_HTTP_RESET_CONTENT 205 /* 206 "Partial Content". RFC9110, Section 15.3.7. */ #define MHD_HTTP_PARTIAL_CONTENT 206 /* 207 "Multi-Status". RFC4918. */ #define MHD_HTTP_MULTI_STATUS 207 /* 208 "Already Reported". RFC5842. */ #define MHD_HTTP_ALREADY_REPORTED 208 /* 226 "IM Used". RFC3229. */ #define MHD_HTTP_IM_USED 226 /* 300 "Multiple Choices". RFC9110, Section 15.4.1. */ #define MHD_HTTP_MULTIPLE_CHOICES 300 /* 301 "Moved Permanently". RFC9110, Section 15.4.2. */ #define MHD_HTTP_MOVED_PERMANENTLY 301 /* 302 "Found". RFC9110, Section 15.4.3. */ #define MHD_HTTP_FOUND 302 /* 303 "See Other". RFC9110, Section 15.4.4. */ #define MHD_HTTP_SEE_OTHER 303 /* 304 "Not Modified". RFC9110, Section 15.4.5. */ #define MHD_HTTP_NOT_MODIFIED 304 /* 305 "Use Proxy". RFC9110, Section 15.4.6. */ #define MHD_HTTP_USE_PROXY 305 /* 306 "Switch Proxy". Not used! RFC9110, Section 15.4.7. */ #define MHD_HTTP_SWITCH_PROXY 306 /* 307 "Temporary Redirect". RFC9110, Section 15.4.8. */ #define MHD_HTTP_TEMPORARY_REDIRECT 307 /* 308 "Permanent Redirect". RFC9110, Section 15.4.9. */ #define MHD_HTTP_PERMANENT_REDIRECT 308 /* 400 "Bad Request". RFC9110, Section 15.5.1. */ #define MHD_HTTP_BAD_REQUEST 400 /* 401 "Unauthorized". RFC9110, Section 15.5.2. */ #define MHD_HTTP_UNAUTHORIZED 401 /* 402 "Payment Required". RFC9110, Section 15.5.3. */ #define MHD_HTTP_PAYMENT_REQUIRED 402 /* 403 "Forbidden". RFC9110, Section 15.5.4. */ #define MHD_HTTP_FORBIDDEN 403 /* 404 "Not Found". RFC9110, Section 15.5.5. */ #define MHD_HTTP_NOT_FOUND 404 /* 405 "Method Not Allowed". RFC9110, Section 15.5.6. */ #define MHD_HTTP_METHOD_NOT_ALLOWED 405 /* 406 "Not Acceptable". RFC9110, Section 15.5.7. */ #define MHD_HTTP_NOT_ACCEPTABLE 406 /* 407 "Proxy Authentication Required". RFC9110, Section 15.5.8. */ #define MHD_HTTP_PROXY_AUTHENTICATION_REQUIRED 407 /* 408 "Request Timeout". RFC9110, Section 15.5.9. */ #define MHD_HTTP_REQUEST_TIMEOUT 408 /* 409 "Conflict". RFC9110, Section 15.5.10. */ #define MHD_HTTP_CONFLICT 409 /* 410 "Gone". RFC9110, Section 15.5.11. */ #define MHD_HTTP_GONE 410 /* 411 "Length Required". RFC9110, Section 15.5.12. */ #define MHD_HTTP_LENGTH_REQUIRED 411 /* 412 "Precondition Failed". RFC9110, Section 15.5.13. */ #define MHD_HTTP_PRECONDITION_FAILED 412 /* 413 "Content Too Large". RFC9110, Section 15.5.14. */ #define MHD_HTTP_CONTENT_TOO_LARGE 413 /* 414 "URI Too Long". RFC9110, Section 15.5.15. */ #define MHD_HTTP_URI_TOO_LONG 414 /* 415 "Unsupported Media Type". RFC9110, Section 15.5.16. */ #define MHD_HTTP_UNSUPPORTED_MEDIA_TYPE 415 /* 416 "Range Not Satisfiable". RFC9110, Section 15.5.17. */ #define MHD_HTTP_RANGE_NOT_SATISFIABLE 416 /* 417 "Expectation Failed". RFC9110, Section 15.5.18. */ #define MHD_HTTP_EXPECTATION_FAILED 417 /* 421 "Misdirected Request". RFC9110, Section 15.5.20. */ #define MHD_HTTP_MISDIRECTED_REQUEST 421 /* 422 "Unprocessable Content". RFC9110, Section 15.5.21. */ #define MHD_HTTP_UNPROCESSABLE_CONTENT 422 /* 423 "Locked". RFC4918. */ #define MHD_HTTP_LOCKED 423 /* 424 "Failed Dependency". RFC4918. */ #define MHD_HTTP_FAILED_DEPENDENCY 424 /* 425 "Too Early". RFC8470. */ #define MHD_HTTP_TOO_EARLY 425 /* 426 "Upgrade Required". RFC9110, Section 15.5.22. */ #define MHD_HTTP_UPGRADE_REQUIRED 426 /* 428 "Precondition Required". RFC6585. */ #define MHD_HTTP_PRECONDITION_REQUIRED 428 /* 429 "Too Many Requests". RFC6585. */ #define MHD_HTTP_TOO_MANY_REQUESTS 429 /* 431 "Request Header Fields Too Large". RFC6585. */ #define MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE 431 /* 451 "Unavailable For Legal Reasons". RFC7725. */ #define MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS 451 /* 500 "Internal Server Error". RFC9110, Section 15.6.1. */ #define MHD_HTTP_INTERNAL_SERVER_ERROR 500 /* 501 "Not Implemented". RFC9110, Section 15.6.2. */ #define MHD_HTTP_NOT_IMPLEMENTED 501 /* 502 "Bad Gateway". RFC9110, Section 15.6.3. */ #define MHD_HTTP_BAD_GATEWAY 502 /* 503 "Service Unavailable". RFC9110, Section 15.6.4. */ #define MHD_HTTP_SERVICE_UNAVAILABLE 503 /* 504 "Gateway Timeout". RFC9110, Section 15.6.5. */ #define MHD_HTTP_GATEWAY_TIMEOUT 504 /* 505 "HTTP Version Not Supported". RFC9110, Section 15.6.6. */ #define MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED 505 /* 506 "Variant Also Negotiates". RFC2295. */ #define MHD_HTTP_VARIANT_ALSO_NEGOTIATES 506 /* 507 "Insufficient Storage". RFC4918. */ #define MHD_HTTP_INSUFFICIENT_STORAGE 507 /* 508 "Loop Detected". RFC5842. */ #define MHD_HTTP_LOOP_DETECTED 508 /* 510 "Not Extended". (OBSOLETED) RFC2774; status-change-http-experiments-to-historic. */ #define MHD_HTTP_NOT_EXTENDED 510 /* 511 "Network Authentication Required". RFC6585. */ #define MHD_HTTP_NETWORK_AUTHENTICATION_REQUIRED 511 /* Not registered non-standard codes */ /* 449 "Reply With". MS IIS extension. */ #define MHD_HTTP_RETRY_WITH 449 /* 450 "Blocked by Windows Parental Controls". MS extension. */ #define MHD_HTTP_BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS 450 /* 509 "Bandwidth Limit Exceeded". Apache extension. */ #define MHD_HTTP_BANDWIDTH_LIMIT_EXCEEDED 509 /* Deprecated names and codes */ /** @deprecated */ #define MHD_HTTP_METHOD_NOT_ACCEPTABLE _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_METHOD_NOT_ACCEPTABLE is deprecated, use MHD_HTTP_NOT_ACCEPTABLE" \ ) 406 /** @deprecated */ #define MHD_HTTP_REQUEST_ENTITY_TOO_LARGE _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_REQUEST_ENTITY_TOO_LARGE is deprecated, use MHD_HTTP_CONTENT_TOO_LARGE" \ ) 413 /** @deprecated */ #define MHD_HTTP_PAYLOAD_TOO_LARGE _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_PAYLOAD_TOO_LARGE is deprecated use MHD_HTTP_CONTENT_TOO_LARGE" \ ) 413 /** @deprecated */ #define MHD_HTTP_REQUEST_URI_TOO_LONG _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_REQUEST_URI_TOO_LONG is deprecated, use MHD_HTTP_URI_TOO_LONG" \ ) 414 /** @deprecated */ #define MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_REQUESTED_RANGE_NOT_SATISFIABLE is deprecated, use MHD_HTTP_RANGE_NOT_SATISFIABLE" \ ) 416 /** @deprecated */ #define MHD_HTTP_UNPROCESSABLE_ENTITY _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_UNPROCESSABLE_ENTITY is deprecated, use MHD_HTTP_UNPROCESSABLE_CONTENT" \ ) 422 /** @deprecated */ #define MHD_HTTP_UNORDERED_COLLECTION _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_UNORDERED_COLLECTION is deprecated as it was removed from RFC" \ ) 425 /** @deprecated */ #define MHD_HTTP_NO_RESPONSE _MHD_DEPR_IN_MACRO ( \ "Value MHD_HTTP_NO_RESPONSE is deprecated as it is nginx internal code for logs only" \ ) 444 /** @} */ /* end of group httpcode */ /** * Returns the string reason phrase for a response code. * * If message string is not available for a status code, * "Unknown" string will be returned. */ _MHD_EXTERN const char * MHD_get_reason_phrase_for (unsigned int code); /** * Returns the length of the string reason phrase for a response code. * * If message string is not available for a status code, * 0 is returned. */ _MHD_EXTERN size_t MHD_get_reason_phrase_len_for (unsigned int code); /** * Flag to be or-ed with MHD_HTTP status code for * SHOUTcast. This will cause the response to begin * with the SHOUTcast "ICY" line instead of "HTTP/1.x". * @ingroup specialized */ #define MHD_ICY_FLAG ((uint32_t) (((uint32_t) 1) << 31)) /** * @defgroup headers HTTP headers * The standard headers found in HTTP requests and responses. * See: https://www.iana.org/assignments/http-fields/http-fields.xhtml * Registry export date: 2023-10-02 * @{ */ /* Main HTTP headers. */ /* Permanent. RFC9110, Section 12.5.1: HTTP Semantics */ #define MHD_HTTP_HEADER_ACCEPT "Accept" /* Deprecated. RFC9110, Section 12.5.2: HTTP Semantics */ #define MHD_HTTP_HEADER_ACCEPT_CHARSET "Accept-Charset" /* Permanent. RFC9110, Section 12.5.3: HTTP Semantics */ #define MHD_HTTP_HEADER_ACCEPT_ENCODING "Accept-Encoding" /* Permanent. RFC9110, Section 12.5.4: HTTP Semantics */ #define MHD_HTTP_HEADER_ACCEPT_LANGUAGE "Accept-Language" /* Permanent. RFC9110, Section 14.3: HTTP Semantics */ #define MHD_HTTP_HEADER_ACCEPT_RANGES "Accept-Ranges" /* Permanent. RFC9111, Section 5.1: HTTP Caching */ #define MHD_HTTP_HEADER_AGE "Age" /* Permanent. RFC9110, Section 10.2.1: HTTP Semantics */ #define MHD_HTTP_HEADER_ALLOW "Allow" /* Permanent. RFC9110, Section 11.6.3: HTTP Semantics */ #define MHD_HTTP_HEADER_AUTHENTICATION_INFO "Authentication-Info" /* Permanent. RFC9110, Section 11.6.2: HTTP Semantics */ #define MHD_HTTP_HEADER_AUTHORIZATION "Authorization" /* Permanent. RFC9111, Section 5.2 */ #define MHD_HTTP_HEADER_CACHE_CONTROL "Cache-Control" /* Permanent. RFC9112, Section 9.6: HTTP/1.1 */ #define MHD_HTTP_HEADER_CLOSE "Close" /* Permanent. RFC9110, Section 7.6.1: HTTP Semantics */ #define MHD_HTTP_HEADER_CONNECTION "Connection" /* Permanent. RFC9110, Section 8.4: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_ENCODING "Content-Encoding" /* Permanent. RFC9110, Section 8.5: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_LANGUAGE "Content-Language" /* Permanent. RFC9110, Section 8.6: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_LENGTH "Content-Length" /* Permanent. RFC9110, Section 8.7: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_LOCATION "Content-Location" /* Permanent. RFC9110, Section 14.4: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_RANGE "Content-Range" /* Permanent. RFC9110, Section 8.3: HTTP Semantics */ #define MHD_HTTP_HEADER_CONTENT_TYPE "Content-Type" /* Permanent. RFC9110, Section 6.6.1: HTTP Semantics */ #define MHD_HTTP_HEADER_DATE "Date" /* Permanent. RFC9110, Section 8.8.3: HTTP Semantics */ #define MHD_HTTP_HEADER_ETAG "ETag" /* Permanent. RFC9110, Section 10.1.1: HTTP Semantics */ #define MHD_HTTP_HEADER_EXPECT "Expect" /* Permanent. RFC9111, Section 5.3: HTTP Caching */ #define MHD_HTTP_HEADER_EXPIRES "Expires" /* Permanent. RFC9110, Section 10.1.2: HTTP Semantics */ #define MHD_HTTP_HEADER_FROM "From" /* Permanent. RFC9110, Section 7.2: HTTP Semantics */ #define MHD_HTTP_HEADER_HOST "Host" /* Permanent. RFC9110, Section 13.1.1: HTTP Semantics */ #define MHD_HTTP_HEADER_IF_MATCH "If-Match" /* Permanent. RFC9110, Section 13.1.3: HTTP Semantics */ #define MHD_HTTP_HEADER_IF_MODIFIED_SINCE "If-Modified-Since" /* Permanent. RFC9110, Section 13.1.2: HTTP Semantics */ #define MHD_HTTP_HEADER_IF_NONE_MATCH "If-None-Match" /* Permanent. RFC9110, Section 13.1.5: HTTP Semantics */ #define MHD_HTTP_HEADER_IF_RANGE "If-Range" /* Permanent. RFC9110, Section 13.1.4: HTTP Semantics */ #define MHD_HTTP_HEADER_IF_UNMODIFIED_SINCE "If-Unmodified-Since" /* Permanent. RFC9110, Section 8.8.2: HTTP Semantics */ #define MHD_HTTP_HEADER_LAST_MODIFIED "Last-Modified" /* Permanent. RFC9110, Section 10.2.2: HTTP Semantics */ #define MHD_HTTP_HEADER_LOCATION "Location" /* Permanent. RFC9110, Section 7.6.2: HTTP Semantics */ #define MHD_HTTP_HEADER_MAX_FORWARDS "Max-Forwards" /* Permanent. RFC9112, Appendix B.1: HTTP/1.1 */ #define MHD_HTTP_HEADER_MIME_VERSION "MIME-Version" /* Deprecated. RFC9111, Section 5.4: HTTP Caching */ #define MHD_HTTP_HEADER_PRAGMA "Pragma" /* Permanent. RFC9110, Section 11.7.1: HTTP Semantics */ #define MHD_HTTP_HEADER_PROXY_AUTHENTICATE "Proxy-Authenticate" /* Permanent. RFC9110, Section 11.7.3: HTTP Semantics */ #define MHD_HTTP_HEADER_PROXY_AUTHENTICATION_INFO "Proxy-Authentication-Info" /* Permanent. RFC9110, Section 11.7.2: HTTP Semantics */ #define MHD_HTTP_HEADER_PROXY_AUTHORIZATION "Proxy-Authorization" /* Permanent. RFC9110, Section 14.2: HTTP Semantics */ #define MHD_HTTP_HEADER_RANGE "Range" /* Permanent. RFC9110, Section 10.1.3: HTTP Semantics */ #define MHD_HTTP_HEADER_REFERER "Referer" /* Permanent. RFC9110, Section 10.2.3: HTTP Semantics */ #define MHD_HTTP_HEADER_RETRY_AFTER "Retry-After" /* Permanent. RFC9110, Section 10.2.4: HTTP Semantics */ #define MHD_HTTP_HEADER_SERVER "Server" /* Permanent. RFC9110, Section 10.1.4: HTTP Semantics */ #define MHD_HTTP_HEADER_TE "TE" /* Permanent. RFC9110, Section 6.6.2: HTTP Semantics */ #define MHD_HTTP_HEADER_TRAILER "Trailer" /* Permanent. RFC9112, Section 6.1: HTTP Semantics */ #define MHD_HTTP_HEADER_TRANSFER_ENCODING "Transfer-Encoding" /* Permanent. RFC9110, Section 7.8: HTTP Semantics */ #define MHD_HTTP_HEADER_UPGRADE "Upgrade" /* Permanent. RFC9110, Section 10.1.5: HTTP Semantics */ #define MHD_HTTP_HEADER_USER_AGENT "User-Agent" /* Permanent. RFC9110, Section 12.5.5: HTTP Semantics */ #define MHD_HTTP_HEADER_VARY "Vary" /* Permanent. RFC9110, Section 7.6.3: HTTP Semantics */ #define MHD_HTTP_HEADER_VIA "Via" /* Permanent. RFC9110, Section 11.6.1: HTTP Semantics */ #define MHD_HTTP_HEADER_WWW_AUTHENTICATE "WWW-Authenticate" /* Permanent. RFC9110, Section 12.5.5: HTTP Semantics */ #define MHD_HTTP_HEADER_ASTERISK "*" /* Additional HTTP headers. */ /* Permanent. RFC 3229: Delta encoding in HTTP */ #define MHD_HTTP_HEADER_A_IM "A-IM" /* Permanent. RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) */ #define MHD_HTTP_HEADER_ACCEPT_ADDITIONS "Accept-Additions" /* Permanent. RFC 8942, Section 3.1: HTTP Client Hints */ #define MHD_HTTP_HEADER_ACCEPT_CH "Accept-CH" /* Permanent. RFC 7089: HTTP Framework for Time-Based Access to Resource States -- Memento */ #define MHD_HTTP_HEADER_ACCEPT_DATETIME "Accept-Datetime" /* Permanent. RFC 2295: Transparent Content Negotiation in HTTP */ #define MHD_HTTP_HEADER_ACCEPT_FEATURES "Accept-Features" /* Permanent. RFC 5789: PATCH Method for HTTP */ #define MHD_HTTP_HEADER_ACCEPT_PATCH "Accept-Patch" /* Permanent. Linked Data Platform 1.0 */ #define MHD_HTTP_HEADER_ACCEPT_POST "Accept-Post" /* Permanent. RFC-ietf-httpbis-message-signatures-19, Section 5.1: HTTP Message Signatures */ #define MHD_HTTP_HEADER_ACCEPT_SIGNATURE "Accept-Signature" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS \ "Access-Control-Allow-Credentials" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_HEADERS \ "Access-Control-Allow-Headers" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_METHODS \ "Access-Control-Allow-Methods" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN \ "Access-Control-Allow-Origin" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS \ "Access-Control-Expose-Headers" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_MAX_AGE "Access-Control-Max-Age" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_REQUEST_HEADERS \ "Access-Control-Request-Headers" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_ACCESS_CONTROL_REQUEST_METHOD \ "Access-Control-Request-Method" /* Permanent. RFC 7639, Section 2: The ALPN HTTP Header Field */ #define MHD_HTTP_HEADER_ALPN "ALPN" /* Permanent. RFC 7838: HTTP Alternative Services */ #define MHD_HTTP_HEADER_ALT_SVC "Alt-Svc" /* Permanent. RFC 7838: HTTP Alternative Services */ #define MHD_HTTP_HEADER_ALT_USED "Alt-Used" /* Permanent. RFC 2295: Transparent Content Negotiation in HTTP */ #define MHD_HTTP_HEADER_ALTERNATES "Alternates" /* Permanent. RFC 4437: Web Distributed Authoring and Versioning (WebDAV) Redirect Reference Resources */ #define MHD_HTTP_HEADER_APPLY_TO_REDIRECT_REF "Apply-To-Redirect-Ref" /* Permanent. RFC 8053, Section 4: HTTP Authentication Extensions for Interactive Clients */ #define MHD_HTTP_HEADER_AUTHENTICATION_CONTROL "Authentication-Control" /* Permanent. RFC9211: The Cache-Status HTTP Response Header Field */ #define MHD_HTTP_HEADER_CACHE_STATUS "Cache-Status" /* Permanent. RFC 8607, Section 5.1: Calendaring Extensions to WebDAV (CalDAV): Managed Attachments */ #define MHD_HTTP_HEADER_CAL_MANAGED_ID "Cal-Managed-ID" /* Permanent. RFC 7809, Section 7.1: Calendaring Extensions to WebDAV (CalDAV): Time Zones by Reference */ #define MHD_HTTP_HEADER_CALDAV_TIMEZONES "CalDAV-Timezones" /* Permanent. RFC9297 */ #define MHD_HTTP_HEADER_CAPSULE_PROTOCOL "Capsule-Protocol" /* Permanent. RFC9213: Targeted HTTP Cache Control */ #define MHD_HTTP_HEADER_CDN_CACHE_CONTROL "CDN-Cache-Control" /* Permanent. RFC 8586: Loop Detection in Content Delivery Networks (CDNs) */ #define MHD_HTTP_HEADER_CDN_LOOP "CDN-Loop" /* Permanent. RFC 8739, Section 3.3: Support for Short-Term, Automatically Renewed (STAR) Certificates in the Automated Certificate Management Environment (ACME) */ #define MHD_HTTP_HEADER_CERT_NOT_AFTER "Cert-Not-After" /* Permanent. RFC 8739, Section 3.3: Support for Short-Term, Automatically Renewed (STAR) Certificates in the Automated Certificate Management Environment (ACME) */ #define MHD_HTTP_HEADER_CERT_NOT_BEFORE "Cert-Not-Before" /* Permanent. Clear Site Data */ #define MHD_HTTP_HEADER_CLEAR_SITE_DATA "Clear-Site-Data" /* Permanent. RFC9440, Section 2: Client-Cert HTTP Header Field */ #define MHD_HTTP_HEADER_CLIENT_CERT "Client-Cert" /* Permanent. RFC9440, Section 2: Client-Cert HTTP Header Field */ #define MHD_HTTP_HEADER_CLIENT_CERT_CHAIN "Client-Cert-Chain" /* Permanent. RFC-ietf-httpbis-digest-headers-13, Section 2: Digest Fields */ #define MHD_HTTP_HEADER_CONTENT_DIGEST "Content-Digest" /* Permanent. RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP) */ #define MHD_HTTP_HEADER_CONTENT_DISPOSITION "Content-Disposition" /* Permanent. The HTTP Distribution and Replication Protocol */ #define MHD_HTTP_HEADER_CONTENT_ID "Content-ID" /* Permanent. Content Security Policy Level 3 */ #define MHD_HTTP_HEADER_CONTENT_SECURITY_POLICY "Content-Security-Policy" /* Permanent. Content Security Policy Level 3 */ #define MHD_HTTP_HEADER_CONTENT_SECURITY_POLICY_REPORT_ONLY \ "Content-Security-Policy-Report-Only" /* Permanent. RFC 6265: HTTP State Management Mechanism */ #define MHD_HTTP_HEADER_COOKIE "Cookie" /* Permanent. HTML */ #define MHD_HTTP_HEADER_CROSS_ORIGIN_EMBEDDER_POLICY \ "Cross-Origin-Embedder-Policy" /* Permanent. HTML */ #define MHD_HTTP_HEADER_CROSS_ORIGIN_EMBEDDER_POLICY_REPORT_ONLY \ "Cross-Origin-Embedder-Policy-Report-Only" /* Permanent. HTML */ #define MHD_HTTP_HEADER_CROSS_ORIGIN_OPENER_POLICY "Cross-Origin-Opener-Policy" /* Permanent. HTML */ #define MHD_HTTP_HEADER_CROSS_ORIGIN_OPENER_POLICY_REPORT_ONLY \ "Cross-Origin-Opener-Policy-Report-Only" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_CROSS_ORIGIN_RESOURCE_POLICY \ "Cross-Origin-Resource-Policy" /* Permanent. RFC 5323: Web Distributed Authoring and Versioning (WebDAV) SEARCH */ #define MHD_HTTP_HEADER_DASL "DASL" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_DAV "DAV" /* Permanent. RFC 3229: Delta encoding in HTTP */ #define MHD_HTTP_HEADER_DELTA_BASE "Delta-Base" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_DEPTH "Depth" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_DESTINATION "Destination" /* Permanent. The HTTP Distribution and Replication Protocol */ #define MHD_HTTP_HEADER_DIFFERENTIAL_ID "Differential-ID" /* Permanent. RFC9449: OAuth 2.0 Demonstrating Proof of Possession (DPoP) */ #define MHD_HTTP_HEADER_DPOP "DPoP" /* Permanent. RFC9449: OAuth 2.0 Demonstrating Proof of Possession (DPoP) */ #define MHD_HTTP_HEADER_DPOP_NONCE "DPoP-Nonce" /* Permanent. RFC 8470: Using Early Data in HTTP */ #define MHD_HTTP_HEADER_EARLY_DATA "Early-Data" /* Permanent. RFC9163: Expect-CT Extension for HTTP */ #define MHD_HTTP_HEADER_EXPECT_CT "Expect-CT" /* Permanent. RFC 7239: Forwarded HTTP Extension */ #define MHD_HTTP_HEADER_FORWARDED "Forwarded" /* Permanent. RFC 7486, Section 6.1.1: HTTP Origin-Bound Authentication (HOBA) */ #define MHD_HTTP_HEADER_HOBAREG "Hobareg" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_IF "If" /* Permanent. RFC 6338: Scheduling Extensions to CalDAV */ #define MHD_HTTP_HEADER_IF_SCHEDULE_TAG_MATCH "If-Schedule-Tag-Match" /* Permanent. RFC 3229: Delta encoding in HTTP */ #define MHD_HTTP_HEADER_IM "IM" /* Permanent. RFC 8473: Token Binding over HTTP */ #define MHD_HTTP_HEADER_INCLUDE_REFERRED_TOKEN_BINDING_ID \ "Include-Referred-Token-Binding-ID" /* Permanent. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_KEEP_ALIVE "Keep-Alive" /* Permanent. RFC 3253: Versioning Extensions to WebDAV: (Web Distributed Authoring and Versioning) */ #define MHD_HTTP_HEADER_LABEL "Label" /* Permanent. HTML */ #define MHD_HTTP_HEADER_LAST_EVENT_ID "Last-Event-ID" /* Permanent. RFC 8288: Web Linking */ #define MHD_HTTP_HEADER_LINK "Link" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_LOCK_TOKEN "Lock-Token" /* Permanent. RFC 7089: HTTP Framework for Time-Based Access to Resource States -- Memento */ #define MHD_HTTP_HEADER_MEMENTO_DATETIME "Memento-Datetime" /* Permanent. RFC 2227: Simple Hit-Metering and Usage-Limiting for HTTP */ #define MHD_HTTP_HEADER_METER "Meter" /* Permanent. RFC 2295: Transparent Content Negotiation in HTTP */ #define MHD_HTTP_HEADER_NEGOTIATE "Negotiate" /* Permanent. Network Error Logging */ #define MHD_HTTP_HEADER_NEL "NEL" /* Permanent. OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_ODATA_ENTITYID "OData-EntityId" /* Permanent. OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_ODATA_ISOLATION "OData-Isolation" /* Permanent. OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_ODATA_MAXVERSION "OData-MaxVersion" /* Permanent. OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_ODATA_VERSION "OData-Version" /* Permanent. RFC 8053, Section 3: HTTP Authentication Extensions for Interactive Clients */ #define MHD_HTTP_HEADER_OPTIONAL_WWW_AUTHENTICATE "Optional-WWW-Authenticate" /* Permanent. RFC 3648: Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol */ #define MHD_HTTP_HEADER_ORDERING_TYPE "Ordering-Type" /* Permanent. RFC 6454: The Web Origin Concept */ #define MHD_HTTP_HEADER_ORIGIN "Origin" /* Permanent. HTML */ #define MHD_HTTP_HEADER_ORIGIN_AGENT_CLUSTER "Origin-Agent-Cluster" /* Permanent. RFC 8613, Section 11.1: Object Security for Constrained RESTful Environments (OSCORE) */ #define MHD_HTTP_HEADER_OSCORE "OSCORE" /* Permanent. OASIS Project Specification 01; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_OSLC_CORE_VERSION "OSLC-Core-Version" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_OVERWRITE "Overwrite" /* Permanent. HTML */ #define MHD_HTTP_HEADER_PING_FROM "Ping-From" /* Permanent. HTML */ #define MHD_HTTP_HEADER_PING_TO "Ping-To" /* Permanent. RFC 3648: Web Distributed Authoring and Versioning (WebDAV) Ordered Collections Protocol */ #define MHD_HTTP_HEADER_POSITION "Position" /* Permanent. RFC 7240: Prefer Header for HTTP */ #define MHD_HTTP_HEADER_PREFER "Prefer" /* Permanent. RFC 7240: Prefer Header for HTTP */ #define MHD_HTTP_HEADER_PREFERENCE_APPLIED "Preference-Applied" /* Permanent. RFC9218: Extensible Prioritization Scheme for HTTP */ #define MHD_HTTP_HEADER_PRIORITY "Priority" /* Permanent. RFC9209: The Proxy-Status HTTP Response Header Field */ #define MHD_HTTP_HEADER_PROXY_STATUS "Proxy-Status" /* Permanent. RFC 7469: Public Key Pinning Extension for HTTP */ #define MHD_HTTP_HEADER_PUBLIC_KEY_PINS "Public-Key-Pins" /* Permanent. RFC 7469: Public Key Pinning Extension for HTTP */ #define MHD_HTTP_HEADER_PUBLIC_KEY_PINS_REPORT_ONLY \ "Public-Key-Pins-Report-Only" /* Permanent. RFC 4437: Web Distributed Authoring and Versioning (WebDAV) Redirect Reference Resources */ #define MHD_HTTP_HEADER_REDIRECT_REF "Redirect-Ref" /* Permanent. HTML */ #define MHD_HTTP_HEADER_REFRESH "Refresh" /* Permanent. RFC 8555, Section 6.5.1: Automatic Certificate Management Environment (ACME) */ #define MHD_HTTP_HEADER_REPLAY_NONCE "Replay-Nonce" /* Permanent. RFC-ietf-httpbis-digest-headers-13, Section 3: Digest Fields */ #define MHD_HTTP_HEADER_REPR_DIGEST "Repr-Digest" /* Permanent. RFC 6638: Scheduling Extensions to CalDAV */ #define MHD_HTTP_HEADER_SCHEDULE_REPLY "Schedule-Reply" /* Permanent. RFC 6338: Scheduling Extensions to CalDAV */ #define MHD_HTTP_HEADER_SCHEDULE_TAG "Schedule-Tag" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_SEC_PURPOSE "Sec-Purpose" /* Permanent. RFC 8473: Token Binding over HTTP */ #define MHD_HTTP_HEADER_SEC_TOKEN_BINDING "Sec-Token-Binding" /* Permanent. RFC 6455: The WebSocket Protocol */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_ACCEPT "Sec-WebSocket-Accept" /* Permanent. RFC 6455: The WebSocket Protocol */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_EXTENSIONS "Sec-WebSocket-Extensions" /* Permanent. RFC 6455: The WebSocket Protocol */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_KEY "Sec-WebSocket-Key" /* Permanent. RFC 6455: The WebSocket Protocol */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_PROTOCOL "Sec-WebSocket-Protocol" /* Permanent. RFC 6455: The WebSocket Protocol */ #define MHD_HTTP_HEADER_SEC_WEBSOCKET_VERSION "Sec-WebSocket-Version" /* Permanent. Server Timing */ #define MHD_HTTP_HEADER_SERVER_TIMING "Server-Timing" /* Permanent. RFC 6265: HTTP State Management Mechanism */ #define MHD_HTTP_HEADER_SET_COOKIE "Set-Cookie" /* Permanent. RFC-ietf-httpbis-message-signatures-19, Section 4.2: HTTP Message Signatures */ #define MHD_HTTP_HEADER_SIGNATURE "Signature" /* Permanent. RFC-ietf-httpbis-message-signatures-19, Section 4.1: HTTP Message Signatures */ #define MHD_HTTP_HEADER_SIGNATURE_INPUT "Signature-Input" /* Permanent. RFC 5023: The Atom Publishing Protocol */ #define MHD_HTTP_HEADER_SLUG "SLUG" /* Permanent. Simple Object Access Protocol (SOAP) 1.1 */ #define MHD_HTTP_HEADER_SOAPACTION "SoapAction" /* Permanent. RFC 2518: HTTP Extensions for Distributed Authoring -- WEBDAV */ #define MHD_HTTP_HEADER_STATUS_URI "Status-URI" /* Permanent. RFC 6797: HTTP Strict Transport Security (HSTS) */ #define MHD_HTTP_HEADER_STRICT_TRANSPORT_SECURITY "Strict-Transport-Security" /* Permanent. RFC 8594: The Sunset HTTP Header Field */ #define MHD_HTTP_HEADER_SUNSET "Sunset" /* Permanent. Edge Architecture Specification */ #define MHD_HTTP_HEADER_SURROGATE_CAPABILITY "Surrogate-Capability" /* Permanent. Edge Architecture Specification */ #define MHD_HTTP_HEADER_SURROGATE_CONTROL "Surrogate-Control" /* Permanent. RFC 2295: Transparent Content Negotiation in HTTP */ #define MHD_HTTP_HEADER_TCN "TCN" /* Permanent. RFC 4918: HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV) */ #define MHD_HTTP_HEADER_TIMEOUT "Timeout" /* Permanent. RFC 8030, Section 5.4: Generic Event Delivery Using HTTP Push */ #define MHD_HTTP_HEADER_TOPIC "Topic" /* Permanent. Trace Context */ #define MHD_HTTP_HEADER_TRACEPARENT "Traceparent" /* Permanent. Trace Context */ #define MHD_HTTP_HEADER_TRACESTATE "Tracestate" /* Permanent. RFC 8030, Section 5.2: Generic Event Delivery Using HTTP Push */ #define MHD_HTTP_HEADER_TTL "TTL" /* Permanent. RFC 8030, Section 5.3: Generic Event Delivery Using HTTP Push */ #define MHD_HTTP_HEADER_URGENCY "Urgency" /* Permanent. RFC 2295: Transparent Content Negotiation in HTTP */ #define MHD_HTTP_HEADER_VARIANT_VARY "Variant-Vary" /* Permanent. RFC-ietf-httpbis-digest-headers-13, Section 4: Digest Fields */ #define MHD_HTTP_HEADER_WANT_CONTENT_DIGEST "Want-Content-Digest" /* Permanent. RFC-ietf-httpbis-digest-headers-13, Section 4: Digest Fields */ #define MHD_HTTP_HEADER_WANT_REPR_DIGEST "Want-Repr-Digest" /* Permanent. Fetch */ #define MHD_HTTP_HEADER_X_CONTENT_TYPE_OPTIONS "X-Content-Type-Options" /* Permanent. HTML */ #define MHD_HTTP_HEADER_X_FRAME_OPTIONS "X-Frame-Options" /* Provisional. AMP-Cache-Transform HTTP request header */ #define MHD_HTTP_HEADER_AMP_CACHE_TRANSFORM "AMP-Cache-Transform" /* Provisional. OSLC Configuration Management Version 1.0. Part 3: Configuration Specification */ #define MHD_HTTP_HEADER_CONFIGURATION_CONTEXT "Configuration-Context" /* Provisional. RFC 6017: Electronic Data Interchange - Internet Integration (EDIINT) Features Header Field */ #define MHD_HTTP_HEADER_EDIINT_FEATURES "EDIINT-Features" /* Provisional. OData Version 4.01 Part 1: Protocol; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_ISOLATION "Isolation" /* Provisional. Permissions Policy */ #define MHD_HTTP_HEADER_PERMISSIONS_POLICY "Permissions-Policy" /* Provisional. Repeatable Requests Version 1.0; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_REPEATABILITY_CLIENT_ID "Repeatability-Client-ID" /* Provisional. Repeatable Requests Version 1.0; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_REPEATABILITY_FIRST_SENT "Repeatability-First-Sent" /* Provisional. Repeatable Requests Version 1.0; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_REPEATABILITY_REQUEST_ID "Repeatability-Request-ID" /* Provisional. Repeatable Requests Version 1.0; OASIS; Chet_Ensign */ #define MHD_HTTP_HEADER_REPEATABILITY_RESULT "Repeatability-Result" /* Provisional. Reporting API */ #define MHD_HTTP_HEADER_REPORTING_ENDPOINTS "Reporting-Endpoints" /* Provisional. Global Privacy Control (GPC) */ #define MHD_HTTP_HEADER_SEC_GPC "Sec-GPC" /* Provisional. Resource Timing Level 1 */ #define MHD_HTTP_HEADER_TIMING_ALLOW_ORIGIN "Timing-Allow-Origin" /* Deprecated. PEP - an Extension Mechanism for HTTP; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_C_PEP_INFO "C-PEP-Info" /* Deprecated. White Paper: Joint Electronic Payment Initiative */ #define MHD_HTTP_HEADER_PROTOCOL_INFO "Protocol-Info" /* Deprecated. White Paper: Joint Electronic Payment Initiative */ #define MHD_HTTP_HEADER_PROTOCOL_QUERY "Protocol-Query" /* Obsoleted. Access Control for Cross-site Requests */ #define MHD_HTTP_HEADER_ACCESS_CONTROL "Access-Control" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_C_EXT "C-Ext" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_C_MAN "C-Man" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_C_OPT "C-Opt" /* Obsoleted. PEP - an Extension Mechanism for HTTP; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_C_PEP "C-PEP" /* Obsoleted. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1; RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_CONTENT_BASE "Content-Base" /* Obsoleted. RFC 2616, Section 14.15: Hypertext Transfer Protocol -- HTTP/1.1; RFC 7231, Appendix B: Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content */ #define MHD_HTTP_HEADER_CONTENT_MD5 "Content-MD5" /* Obsoleted. HTML 4.01 Specification */ #define MHD_HTTP_HEADER_CONTENT_SCRIPT_TYPE "Content-Script-Type" /* Obsoleted. HTML 4.01 Specification */ #define MHD_HTTP_HEADER_CONTENT_STYLE_TYPE "Content-Style-Type" /* Obsoleted. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_CONTENT_VERSION "Content-Version" /* Obsoleted. RFC 2965: HTTP State Management Mechanism; RFC 6265: HTTP State Management Mechanism */ #define MHD_HTTP_HEADER_COOKIE2 "Cookie2" /* Obsoleted. HTML 4.01 Specification */ #define MHD_HTTP_HEADER_DEFAULT_STYLE "Default-Style" /* Obsoleted. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_DERIVED_FROM "Derived-From" /* Obsoleted. RFC 3230: Instance Digests in HTTP; RFC-ietf-httpbis-digest-headers-13, Section 1.3: Digest Fields */ #define MHD_HTTP_HEADER_DIGEST "Digest" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_EXT "Ext" /* Obsoleted. Implementation of OPS Over HTTP */ #define MHD_HTTP_HEADER_GETPROFILE "GetProfile" /* Obsoleted. RFC 7540, Section 3.2.1: Hypertext Transfer Protocol Version 2 (HTTP/2) */ #define MHD_HTTP_HEADER_HTTP2_SETTINGS "HTTP2-Settings" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_MAN "Man" /* Obsoleted. Access Control for Cross-site Requests */ #define MHD_HTTP_HEADER_METHOD_CHECK "Method-Check" /* Obsoleted. Access Control for Cross-site Requests */ #define MHD_HTTP_HEADER_METHOD_CHECK_EXPIRES "Method-Check-Expires" /* Obsoleted. RFC 2774: An HTTP Extension Framework; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_OPT "Opt" /* Obsoleted. The Platform for Privacy Preferences 1.0 (P3P1.0) Specification */ #define MHD_HTTP_HEADER_P3P "P3P" /* Obsoleted. PEP - an Extension Mechanism for HTTP */ #define MHD_HTTP_HEADER_PEP "PEP" /* Obsoleted. PEP - an Extension Mechanism for HTTP */ #define MHD_HTTP_HEADER_PEP_INFO "Pep-Info" /* Obsoleted. PICS Label Distribution Label Syntax and Communication Protocols */ #define MHD_HTTP_HEADER_PICS_LABEL "PICS-Label" /* Obsoleted. Implementation of OPS Over HTTP */ #define MHD_HTTP_HEADER_PROFILEOBJECT "ProfileObject" /* Obsoleted. PICS Label Distribution Label Syntax and Communication Protocols */ #define MHD_HTTP_HEADER_PROTOCOL "Protocol" /* Obsoleted. PICS Label Distribution Label Syntax and Communication Protocols */ #define MHD_HTTP_HEADER_PROTOCOL_REQUEST "Protocol-Request" /* Obsoleted. Notification for Proxy Caches */ #define MHD_HTTP_HEADER_PROXY_FEATURES "Proxy-Features" /* Obsoleted. Notification for Proxy Caches */ #define MHD_HTTP_HEADER_PROXY_INSTRUCTION "Proxy-Instruction" /* Obsoleted. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_PUBLIC "Public" /* Obsoleted. Access Control for Cross-site Requests */ #define MHD_HTTP_HEADER_REFERER_ROOT "Referer-Root" /* Obsoleted. RFC 2310: The Safe Response Header Field; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_SAFE "Safe" /* Obsoleted. RFC 2660: The Secure HyperText Transfer Protocol; status-change-http-experiments-to-historic */ #define MHD_HTTP_HEADER_SECURITY_SCHEME "Security-Scheme" /* Obsoleted. RFC 2965: HTTP State Management Mechanism; RFC 6265: HTTP State Management Mechanism */ #define MHD_HTTP_HEADER_SET_COOKIE2 "Set-Cookie2" /* Obsoleted. Implementation of OPS Over HTTP */ #define MHD_HTTP_HEADER_SETPROFILE "SetProfile" /* Obsoleted. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1 */ #define MHD_HTTP_HEADER_URI "URI" /* Obsoleted. RFC 3230: Instance Digests in HTTP; RFC-ietf-httpbis-digest-headers-13, Section 1.3: Digest Fields */ #define MHD_HTTP_HEADER_WANT_DIGEST "Want-Digest" /* Obsoleted. RFC9111, Section 5.5: HTTP Caching */ #define MHD_HTTP_HEADER_WARNING "Warning" /* Headers removed from the registry. Do not use! */ /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_COMPLIANCE "Compliance" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_CONTENT_TRANSFER_ENCODING "Content-Transfer-Encoding" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_COST "Cost" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_MESSAGE_ID "Message-ID" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_NON_COMPLIANCE "Non-Compliance" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_OPTIONAL "Optional" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_RESOLUTION_HINT "Resolution-Hint" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_RESOLVER_LOCATION "Resolver-Location" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_SUBOK "SubOK" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_SUBST "Subst" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_TITLE "Title" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_UA_COLOR "UA-Color" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_UA_MEDIA "UA-Media" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_UA_PIXELS "UA-Pixels" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_UA_RESOLUTION "UA-Resolution" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_UA_WINDOWPIXELS "UA-Windowpixels" /* Obsoleted. RFC4229 */ #define MHD_HTTP_HEADER_VERSION "Version" /* Obsoleted. W3C Mobile Web Best Practices Working Group */ #define MHD_HTTP_HEADER_X_DEVICE_ACCEPT "X-Device-Accept" /* Obsoleted. W3C Mobile Web Best Practices Working Group */ #define MHD_HTTP_HEADER_X_DEVICE_ACCEPT_CHARSET "X-Device-Accept-Charset" /* Obsoleted. W3C Mobile Web Best Practices Working Group */ #define MHD_HTTP_HEADER_X_DEVICE_ACCEPT_ENCODING "X-Device-Accept-Encoding" /* Obsoleted. W3C Mobile Web Best Practices Working Group */ #define MHD_HTTP_HEADER_X_DEVICE_ACCEPT_LANGUAGE "X-Device-Accept-Language" /* Obsoleted. W3C Mobile Web Best Practices Working Group */ #define MHD_HTTP_HEADER_X_DEVICE_USER_AGENT "X-Device-User-Agent" /** @} */ /* end of group headers */ /** * @defgroup versions HTTP versions * These strings should be used to match against the first line of the * HTTP header. * @{ */ #define MHD_HTTP_VERSION_1_0 "HTTP/1.0" #define MHD_HTTP_VERSION_1_1 "HTTP/1.1" /** @} */ /* end of group versions */ /** * @defgroup methods HTTP methods * HTTP methods (as strings). * See: https://www.iana.org/assignments/http-methods/http-methods.xml * Registry export date: 2023-10-02 * @{ */ /* Main HTTP methods. */ /* Safe. Idempotent. RFC9110, Section 9.3.1. */ #define MHD_HTTP_METHOD_GET "GET" /* Safe. Idempotent. RFC9110, Section 9.3.2. */ #define MHD_HTTP_METHOD_HEAD "HEAD" /* Not safe. Not idempotent. RFC9110, Section 9.3.3. */ #define MHD_HTTP_METHOD_POST "POST" /* Not safe. Idempotent. RFC9110, Section 9.3.4. */ #define MHD_HTTP_METHOD_PUT "PUT" /* Not safe. Idempotent. RFC9110, Section 9.3.5. */ #define MHD_HTTP_METHOD_DELETE "DELETE" /* Not safe. Not idempotent. RFC9110, Section 9.3.6. */ #define MHD_HTTP_METHOD_CONNECT "CONNECT" /* Safe. Idempotent. RFC9110, Section 9.3.7. */ #define MHD_HTTP_METHOD_OPTIONS "OPTIONS" /* Safe. Idempotent. RFC9110, Section 9.3.8. */ #define MHD_HTTP_METHOD_TRACE "TRACE" /* Additional HTTP methods. */ /* Not safe. Idempotent. RFC3744, Section 8.1. */ #define MHD_HTTP_METHOD_ACL "ACL" /* Not safe. Idempotent. RFC3253, Section 12.6. */ #define MHD_HTTP_METHOD_BASELINE_CONTROL "BASELINE-CONTROL" /* Not safe. Idempotent. RFC5842, Section 4. */ #define MHD_HTTP_METHOD_BIND "BIND" /* Not safe. Idempotent. RFC3253, Section 4.4, Section 9.4. */ #define MHD_HTTP_METHOD_CHECKIN "CHECKIN" /* Not safe. Idempotent. RFC3253, Section 4.3, Section 8.8. */ #define MHD_HTTP_METHOD_CHECKOUT "CHECKOUT" /* Not safe. Idempotent. RFC4918, Section 9.8. */ #define MHD_HTTP_METHOD_COPY "COPY" /* Not safe. Idempotent. RFC3253, Section 8.2. */ #define MHD_HTTP_METHOD_LABEL "LABEL" /* Not safe. Idempotent. RFC2068, Section 19.6.1.2. */ #define MHD_HTTP_METHOD_LINK "LINK" /* Not safe. Not idempotent. RFC4918, Section 9.10. */ #define MHD_HTTP_METHOD_LOCK "LOCK" /* Not safe. Idempotent. RFC3253, Section 11.2. */ #define MHD_HTTP_METHOD_MERGE "MERGE" /* Not safe. Idempotent. RFC3253, Section 13.5. */ #define MHD_HTTP_METHOD_MKACTIVITY "MKACTIVITY" /* Not safe. Idempotent. RFC4791, Section 5.3.1; RFC8144, Section 2.3. */ #define MHD_HTTP_METHOD_MKCALENDAR "MKCALENDAR" /* Not safe. Idempotent. RFC4918, Section 9.3; RFC5689, Section 3; RFC8144, Section 2.3. */ #define MHD_HTTP_METHOD_MKCOL "MKCOL" /* Not safe. Idempotent. RFC4437, Section 6. */ #define MHD_HTTP_METHOD_MKREDIRECTREF "MKREDIRECTREF" /* Not safe. Idempotent. RFC3253, Section 6.3. */ #define MHD_HTTP_METHOD_MKWORKSPACE "MKWORKSPACE" /* Not safe. Idempotent. RFC4918, Section 9.9. */ #define MHD_HTTP_METHOD_MOVE "MOVE" /* Not safe. Idempotent. RFC3648, Section 7. */ #define MHD_HTTP_METHOD_ORDERPATCH "ORDERPATCH" /* Not safe. Not idempotent. RFC5789, Section 2. */ #define MHD_HTTP_METHOD_PATCH "PATCH" /* Safe. Idempotent. RFC9113, Section 3.4. */ #define MHD_HTTP_METHOD_PRI "PRI" /* Safe. Idempotent. RFC4918, Section 9.1; RFC8144, Section 2.1. */ #define MHD_HTTP_METHOD_PROPFIND "PROPFIND" /* Not safe. Idempotent. RFC4918, Section 9.2; RFC8144, Section 2.2. */ #define MHD_HTTP_METHOD_PROPPATCH "PROPPATCH" /* Not safe. Idempotent. RFC5842, Section 6. */ #define MHD_HTTP_METHOD_REBIND "REBIND" /* Safe. Idempotent. RFC3253, Section 3.6; RFC8144, Section 2.1. */ #define MHD_HTTP_METHOD_REPORT "REPORT" /* Safe. Idempotent. RFC5323, Section 2. */ #define MHD_HTTP_METHOD_SEARCH "SEARCH" /* Not safe. Idempotent. RFC5842, Section 5. */ #define MHD_HTTP_METHOD_UNBIND "UNBIND" /* Not safe. Idempotent. RFC3253, Section 4.5. */ #define MHD_HTTP_METHOD_UNCHECKOUT "UNCHECKOUT" /* Not safe. Idempotent. RFC2068, Section 19.6.1.3. */ #define MHD_HTTP_METHOD_UNLINK "UNLINK" /* Not safe. Idempotent. RFC4918, Section 9.11. */ #define MHD_HTTP_METHOD_UNLOCK "UNLOCK" /* Not safe. Idempotent. RFC3253, Section 7.1. */ #define MHD_HTTP_METHOD_UPDATE "UPDATE" /* Not safe. Idempotent. RFC4437, Section 7. */ #define MHD_HTTP_METHOD_UPDATEREDIRECTREF "UPDATEREDIRECTREF" /* Not safe. Idempotent. RFC3253, Section 3.5. */ #define MHD_HTTP_METHOD_VERSION_CONTROL "VERSION-CONTROL" /* Not safe. Not idempotent. RFC9110, Section 18.2. */ #define MHD_HTTP_METHOD_ASTERISK "*" /** @} */ /* end of group methods */ /** * @defgroup postenc HTTP POST encodings * See also: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4 * @{ */ #define MHD_HTTP_POST_ENCODING_FORM_URLENCODED \ "application/x-www-form-urlencoded" #define MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA "multipart/form-data" /** @} */ /* end of group postenc */ /** * @brief Handle for the daemon (listening on a socket for HTTP traffic). * @ingroup event */ struct MHD_Daemon; /** * @brief Handle for a connection / HTTP request. * * With HTTP/1.1, multiple requests can be run over the same * connection. However, MHD will only show one request per TCP * connection to the client at any given time. * @ingroup request */ struct MHD_Connection; /** * @brief Handle for a response. * @ingroup response */ struct MHD_Response; /** * @brief Handle for POST processing. * @ingroup response */ struct MHD_PostProcessor; /** * @brief Flags for the `struct MHD_Daemon`. * * Note that MHD will run automatically in background thread(s) only * if #MHD_USE_INTERNAL_POLLING_THREAD is used. Otherwise caller (application) * must use #MHD_run() or #MHD_run_from_select() to have MHD processed * network connections and data. * * Starting the daemon may also fail if a particular option is not * implemented or not supported on the target platform (i.e. no * support for TLS, epoll or IPv6). */ enum MHD_FLAG { /** * No options selected. */ MHD_NO_FLAG = 0, /** * Print errors messages to custom error logger or to `stderr` if * custom error logger is not set. * @sa ::MHD_OPTION_EXTERNAL_LOGGER */ MHD_USE_ERROR_LOG = 1, /** * Run in debug mode. If this flag is used, the library should * print error messages and warnings to `stderr`. */ MHD_USE_DEBUG = 1, /** * Run in HTTPS mode. The modern protocol is called TLS. */ MHD_USE_TLS = 2, /** @deprecated */ MHD_USE_SSL = 2, #if 0 /* let's do this later once versions that define MHD_USE_TLS a more widely deployed. */ #define MHD_USE_SSL \ _MHD_DEPR_IN_MACRO ("Value MHD_USE_SSL is deprecated, use MHD_USE_TLS") \ MHD_USE_TLS #endif /** * Run using one thread per connection. * Must be used only with #MHD_USE_INTERNAL_POLLING_THREAD. * * If #MHD_USE_ITC is also not used, closed and expired connections may only * be cleaned up internally when a new connection is received. * Consider adding of #MHD_USE_ITC flag to have faster internal cleanups * at very minor increase in system resources usage. */ MHD_USE_THREAD_PER_CONNECTION = 4, /** * Run using an internal thread (or thread pool) for sockets sending * and receiving and data processing. Without this flag MHD will not * run automatically in background thread(s). * If this flag is set, #MHD_run() and #MHD_run_from_select() couldn't * be used. * This flag is set explicitly by #MHD_USE_POLL_INTERNAL_THREAD and * by #MHD_USE_EPOLL_INTERNAL_THREAD. * When this flag is not set, MHD run in "external" polling mode. */ MHD_USE_INTERNAL_POLLING_THREAD = 8, /** @deprecated */ MHD_USE_SELECT_INTERNALLY = 8, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_SELECT_INTERNALLY \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_SELECT_INTERNALLY is deprecated, use MHD_USE_INTERNAL_POLLING_THREAD instead") \ MHD_USE_INTERNAL_POLLING_THREAD #endif /* 0 */ /** * Run using the IPv6 protocol (otherwise, MHD will just support * IPv4). If you want MHD to support IPv4 and IPv6 using a single * socket, pass #MHD_USE_DUAL_STACK, otherwise, if you only pass * this option, MHD will try to bind to IPv6-only (resulting in * no IPv4 support). */ MHD_USE_IPv6 = 16, /** * Be pedantic about the protocol (as opposed to as tolerant as * possible). * This flag is equivalent to setting 1 as #MHD_OPTION_CLIENT_DISCIPLINE_LVL * value. * @sa #MHD_OPTION_CLIENT_DISCIPLINE_LVL */ MHD_USE_PEDANTIC_CHECKS = 32, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_PEDANTIC_CHECKS \ _MHD_DEPR_IN_MACRO ( \ "Flag MHD_USE_PEDANTIC_CHECKS is deprecated, " \ "use option MHD_OPTION_CLIENT_DISCIPLINE_LVL instead") \ 32 #endif /* 0 */ /** * Use `poll()` instead of `select()` for polling sockets. * This allows sockets with `fd >= FD_SETSIZE`. * This option is not compatible with an "external" polling mode * (as there is no API to get the file descriptors for the external * poll() from MHD) and must also not be used in combination * with #MHD_USE_EPOLL. * @sa ::MHD_FEATURE_POLL, #MHD_USE_POLL_INTERNAL_THREAD */ MHD_USE_POLL = 64, /** * Run using an internal thread (or thread pool) doing `poll()`. * @sa ::MHD_FEATURE_POLL, #MHD_USE_POLL, #MHD_USE_INTERNAL_POLLING_THREAD */ MHD_USE_POLL_INTERNAL_THREAD = MHD_USE_POLL | MHD_USE_INTERNAL_POLLING_THREAD, /** @deprecated */ MHD_USE_POLL_INTERNALLY = MHD_USE_POLL | MHD_USE_INTERNAL_POLLING_THREAD, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_POLL_INTERNALLY \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_POLL_INTERNALLY is deprecated, use MHD_USE_POLL_INTERNAL_THREAD instead") \ MHD_USE_POLL_INTERNAL_THREAD #endif /* 0 */ /** * Suppress (automatically) adding the 'Date:' header to HTTP responses. * This option should ONLY be used on systems that do not have a clock * and that DO provide other mechanisms for cache control. See also * RFC 2616, section 14.18 (exception 3). */ MHD_USE_SUPPRESS_DATE_NO_CLOCK = 128, /** @deprecated */ MHD_SUPPRESS_DATE_NO_CLOCK = 128, #if 0 /* Will be marked for real deprecation later. */ #define MHD_SUPPRESS_DATE_NO_CLOCK \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_SUPPRESS_DATE_NO_CLOCK is deprecated, use MHD_USE_SUPPRESS_DATE_NO_CLOCK instead") \ MHD_USE_SUPPRESS_DATE_NO_CLOCK #endif /* 0 */ /** * Run without a listen socket. This option only makes sense if * #MHD_add_connection is to be used exclusively to connect HTTP * clients to the HTTP server. This option is incompatible with * using a thread pool; if it is used, #MHD_OPTION_THREAD_POOL_SIZE * is ignored. */ MHD_USE_NO_LISTEN_SOCKET = 256, /** * Use `epoll()` instead of `select()` or `poll()` for the event loop. * This option is only available on some systems; using the option on * systems without epoll will cause #MHD_start_daemon to fail. Using * this option is not supported with #MHD_USE_THREAD_PER_CONNECTION. * @sa ::MHD_FEATURE_EPOLL */ MHD_USE_EPOLL = 512, /** @deprecated */ MHD_USE_EPOLL_LINUX_ONLY = 512, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_EPOLL_LINUX_ONLY \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_EPOLL_LINUX_ONLY is deprecated, use MHD_USE_EPOLL") \ MHD_USE_EPOLL #endif /* 0 */ /** * Run using an internal thread (or thread pool) doing `epoll` polling. * This option is only available on certain platforms; using the option on * platform without `epoll` support will cause #MHD_start_daemon to fail. * @sa ::MHD_FEATURE_EPOLL, #MHD_USE_EPOLL, #MHD_USE_INTERNAL_POLLING_THREAD */ MHD_USE_EPOLL_INTERNAL_THREAD = MHD_USE_EPOLL | MHD_USE_INTERNAL_POLLING_THREAD, /** @deprecated */ MHD_USE_EPOLL_INTERNALLY = MHD_USE_EPOLL | MHD_USE_INTERNAL_POLLING_THREAD, /** @deprecated */ MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY = MHD_USE_EPOLL | MHD_USE_INTERNAL_POLLING_THREAD, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_EPOLL_INTERNALLY \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_EPOLL_INTERNALLY is deprecated, use MHD_USE_EPOLL_INTERNAL_THREAD") \ MHD_USE_EPOLL_INTERNAL_THREAD /** @deprecated */ #define MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_EPOLL_INTERNALLY_LINUX_ONLY is deprecated, use MHD_USE_EPOLL_INTERNAL_THREAD") \ MHD_USE_EPOLL_INTERNAL_THREAD #endif /* 0 */ /** * Use inter-thread communication channel. * #MHD_USE_ITC can be used with #MHD_USE_INTERNAL_POLLING_THREAD * and is ignored with any "external" sockets polling. * It's required for use of #MHD_quiesce_daemon * or #MHD_add_connection. * This option is enforced by #MHD_ALLOW_SUSPEND_RESUME or * #MHD_USE_NO_LISTEN_SOCKET. * Note that while this flag has no effect of its own with "external" * sockets polling, the channel implied by #MHD_ALLOW_SUSPEND_RESUME * is created and used in that mode as well: #MHD_get_fdset() adds it * to the read set, so that #MHD_resume_connection() called from * another thread interrupts a blocking select()/poll() of the * application. See #MHD_resume_connection(). * #MHD_USE_ITC is always used automatically on platforms * where select()/poll()/other ignore shutdown of listen * socket. */ MHD_USE_ITC = 1024, /** @deprecated */ MHD_USE_PIPE_FOR_SHUTDOWN = 1024, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_PIPE_FOR_SHUTDOWN \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_PIPE_FOR_SHUTDOWN is deprecated, use MHD_USE_ITC") \ MHD_USE_ITC #endif /* 0 */ /** * Use a single socket for IPv4 and IPv6. */ MHD_USE_DUAL_STACK = MHD_USE_IPv6 | 2048, /** * Enable `turbo`. Disables certain calls to `shutdown()`, * enables aggressive non-blocking optimistic reads and * other potentially unsafe optimizations. * Most effects only happen with #MHD_USE_EPOLL. */ MHD_USE_TURBO = 4096, /** @deprecated */ MHD_USE_EPOLL_TURBO = 4096, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_EPOLL_TURBO \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_EPOLL_TURBO is deprecated, use MHD_USE_TURBO") \ MHD_USE_TURBO #endif /* 0 */ /** * Enable suspend/resume functions, which also implies setting up * ITC to signal resume. */ MHD_ALLOW_SUSPEND_RESUME = 8192 | MHD_USE_ITC, /** @deprecated */ MHD_USE_SUSPEND_RESUME = 8192 | MHD_USE_ITC, #if 0 /* Will be marked for real deprecation later. */ #define MHD_USE_SUSPEND_RESUME \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_USE_SUSPEND_RESUME is deprecated, use MHD_ALLOW_SUSPEND_RESUME instead") \ MHD_ALLOW_SUSPEND_RESUME #endif /* 0 */ /** * Enable TCP_FASTOPEN option. This option is only available on Linux with a * kernel >= 3.6. On other systems, using this option cases #MHD_start_daemon * to fail. */ MHD_USE_TCP_FASTOPEN = 16384, /** * You need to set this option if you want to use HTTP "Upgrade". * "Upgrade" may require usage of additional internal resources, * which we do not want to use unless necessary. */ MHD_ALLOW_UPGRADE = 32768, /** * Automatically use best available polling function. * Choice of polling function is also depend on other daemon options. * If #MHD_USE_INTERNAL_POLLING_THREAD is specified then epoll, poll() or * select() will be used (listed in decreasing preference order, first * function available on system will be used). * If #MHD_USE_THREAD_PER_CONNECTION is specified then poll() or select() * will be used. * If those flags are not specified then epoll or select() will be * used (as the only suitable for MHD_get_fdset()) */ MHD_USE_AUTO = 65536, /** * Run using an internal thread (or thread pool) with best available on * system polling function. * This is combination of #MHD_USE_AUTO and #MHD_USE_INTERNAL_POLLING_THREAD * flags. */ MHD_USE_AUTO_INTERNAL_THREAD = MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, /** * Flag set to enable post-handshake client authentication * (only useful in combination with #MHD_USE_TLS). */ MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT = 1U << 17, /** * Flag set to enable TLS 1.3 early data. This has * security implications, be VERY careful when using this. */ MHD_USE_INSECURE_TLS_EARLY_DATA = 1U << 18, /** * Indicates that MHD daemon will be used by application in single-threaded * mode only. When this flag is set then application must call any MHD * function only within a single thread. * This flag turns off some internal thread-safety and allows MHD making * some of the internal optimisations suitable only for single-threaded * environment. * Not compatible with #MHD_USE_INTERNAL_POLLING_THREAD. * @note Available since #MHD_VERSION 0x00097707 */ MHD_USE_NO_THREAD_SAFETY = 1U << 19 }; /** * Type of a callback function used for logging by MHD. * * @param cls closure * @param fm format string (`printf()`-style) * @param ap arguments to @a fm * @ingroup logging */ typedef void (*MHD_LogCallback)(void *cls, const char *fm, va_list ap); /** * Function called to lookup the pre shared key (@a psk) for a given * HTTP connection based on the @a username. * * @param cls closure * @param connection the HTTPS connection * @param username the user name claimed by the other side * @param[out] psk to be set to the pre-shared-key; should be allocated with malloc(), * will be freed by MHD * @param[out] psk_size to be set to the number of bytes in @a psk; * must be at least 16 (RFC 4279 section 7.1), otherwise * MHD discards the key and fails the authentication * @return 0 on success, -1 on errors */ typedef int (*MHD_PskServerCredentialsCallback)(void *cls, const struct MHD_Connection *connection, const char *username, void **psk, size_t *psk_size); /** * Values for #MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE. * * These values can limit the scope of validity of MHD-generated nonces. * Values can be combined with bitwise OR. * Any value, except #MHD_DAUTH_BIND_NONCE_NONE, enforce function * #MHD_digest_auth_check3() (and similar functions) to check nonce by * re-generating it again with the same parameters, which is CPU-intensive * operation. * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DAuthBindNonce { /** * Generated nonces are valid for any request from any client until expired. * This is default and recommended value. * #MHD_digest_auth_check3() (and similar functions) would check only whether * the nonce value that is used by client has been generated by MHD and not * expired yet. * It is recommended because RFC 7616 allows clients to use the same nonce * for any request in the same "protection space". * When checking client's authorisation requests CPU is loaded less if this * value is used. * This mode gives MHD maximum flexibility for nonces generation and can * prevent possible nonce collisions (and corresponding log warning messages) * when clients' requests are intensive. * This value cannot be biwise-OR combined with other values. */ MHD_DAUTH_BIND_NONCE_NONE = 0, /** * Generated nonces are valid only for the same realm. */ MHD_DAUTH_BIND_NONCE_REALM = 1 << 0, /** * Generated nonces are valid only for the same URI (excluding parameters * after '?' in URI) and request method (GET, POST etc). * Not recommended unless "protection space" is limited to a single URI as * RFC 7616 allows clients to re-use server-generated nonces for any URI * in the same "protection space" which by default consists of all server * URIs. * Before #MHD_VERSION 0x00097701 this was default (and only supported) * nonce bind type. */ MHD_DAUTH_BIND_NONCE_URI = 1 << 1, /** * Generated nonces are valid only for the same URI including URI parameters * and request method (GET, POST etc). * This value implies #MHD_DAUTH_BIND_NONCE_URI. * Not recommended for that same reasons as #MHD_DAUTH_BIND_NONCE_URI. */ MHD_DAUTH_BIND_NONCE_URI_PARAMS = 1 << 2, /** * Generated nonces are valid only for the single client's IP. * While it looks like security improvement, in practice the same client may * jump from one IP to another (mobile or Wi-Fi handover, DHCP re-assignment, * Multi-NAT, different proxy chain and other reasons), while IP address * spoofing could be used relatively easily. */ MHD_DAUTH_BIND_NONCE_CLIENT_IP = 1 << 3 } _MHD_FLAGS_ENUM; /** * @brief MHD options. * * Passed in the varargs portion of #MHD_start_daemon. */ enum MHD_OPTION { /** * No more options / last option. This is used * to terminate the VARARGs list. */ MHD_OPTION_END = 0, /** * Maximum memory size per connection (followed by a `size_t`). * Default is 32 kb (#MHD_POOL_SIZE_DEFAULT). * Values above 128k are unlikely to result in much benefit, as half * of the memory will be typically used for IO, and TCP buffers are * unlikely to support window sizes above 64k on most systems. * Values below 64 bytes are completely unusable. * Since #MHD_VERSION 0x00097710 silently ignored if followed by zero value. */ MHD_OPTION_CONNECTION_MEMORY_LIMIT = 1, /** * Maximum number of concurrent connections to * accept (followed by an `unsigned int`). */ MHD_OPTION_CONNECTION_LIMIT = 2, /** * After how many seconds of inactivity should a * connection automatically be timed out? (followed * by an `unsigned int`; use zero for no timeout). * Values larger than (UINT64_MAX / 2000 - 1) will * be clipped to this number. */ MHD_OPTION_CONNECTION_TIMEOUT = 3, /** * Register a function that should be called whenever a request has * been completed (this can be used for application-specific clean * up). Requests that have never been presented to the application * (via #MHD_AccessHandlerCallback) will not result in * notifications. * * This option should be followed by TWO pointers. First a pointer * to a function of type #MHD_RequestCompletedCallback and second a * pointer to a closure to pass to the request completed callback. * The second pointer may be NULL. */ MHD_OPTION_NOTIFY_COMPLETED = 4, /** * Limit on the number of (concurrent) connections made to the * server from the same IP address. Can be used to prevent one * IP from taking over all of the allowed connections. If the * same IP tries to establish more than the specified number of * connections, they will be immediately rejected. The option * should be followed by an `unsigned int`. The default is * zero, which means no limit on the number of connections * from the same IP address. */ MHD_OPTION_PER_IP_CONNECTION_LIMIT = 5, /** * Bind daemon to the supplied `struct sockaddr`. This option should * be followed by a `struct sockaddr *`. If #MHD_USE_IPv6 is * specified, the `struct sockaddr*` should point to a `struct * sockaddr_in6`, otherwise to a `struct sockaddr_in`. * Silently ignored if followed by NULL pointer. * @deprecated Use #MHD_OPTION_SOCK_ADDR_LEN */ MHD_OPTION_SOCK_ADDR = 6, /** * Specify a function that should be called before parsing the URI from * the client. The specified callback function can be used for processing * the URI (including the options) before it is parsed. The URI after * parsing will no longer contain the options, which maybe inconvenient for * logging. This option should be followed by two arguments, the first * one must be of the form * * void * my_logger(void *cls, const char *uri, struct MHD_Connection *con) * * where the return value will be passed as * (`* req_cls`) in calls to the #MHD_AccessHandlerCallback * when this request is processed later; returning a * value of NULL has no special significance (however, * note that if you return non-NULL, you can no longer * rely on the first call to the access handler having * `NULL == *req_cls` on entry;) * "cls" will be set to the second argument following * #MHD_OPTION_URI_LOG_CALLBACK. Finally, uri will * be the 0-terminated URI of the request. * * Note that during the time of this call, most of the connection's * state is not initialized (as we have not yet parsed the headers). * However, information about the connecting client (IP, socket) * is available. * * The specified function is called only once per request, therefore some * programmers may use it to instantiate their own request objects, freeing * them in the notifier #MHD_OPTION_NOTIFY_COMPLETED. */ MHD_OPTION_URI_LOG_CALLBACK = 7, /** * Memory pointer for the private key (key.pem) to be used by the * HTTPS daemon. This option should be followed by a * `const char *` argument. * This should be used in conjunction with #MHD_OPTION_HTTPS_MEM_CERT. */ MHD_OPTION_HTTPS_MEM_KEY = 8, /** * Memory pointer for the certificate (cert.pem) to be used by the * HTTPS daemon. This option should be followed by a * `const char *` argument. * This should be used in conjunction with #MHD_OPTION_HTTPS_MEM_KEY. */ MHD_OPTION_HTTPS_MEM_CERT = 9, /** * Daemon credentials type. * Followed by an argument of type * `gnutls_credentials_type_t`. */ MHD_OPTION_HTTPS_CRED_TYPE = 10, /** * Memory pointer to a `const char *` specifying the GnuTLS priorities string. * If this options is not specified, then MHD will try the following strings: * * "@LIBMICROHTTPD" (application-specific system-wide configuration) * * "@SYSTEM" (system-wide configuration) * * default GnuTLS priorities string * * "NORMAL" * The first configuration accepted by GnuTLS will be used. * For more details see GnuTLS documentation for "Application-specific * priority strings". */ MHD_OPTION_HTTPS_PRIORITIES = 11, /** * Pass a listen socket for MHD to use (systemd-style). If this * option is used, MHD will not open its own listen socket(s). The * argument passed must be of type `MHD_socket` and refer to an * existing socket that has been bound to a port and is listening. * If followed by MHD_INVALID_SOCKET value, MHD ignores this option * and creates socket by itself. */ MHD_OPTION_LISTEN_SOCKET = 12, /** * Use the given function for logging error messages. This option * must be followed by two arguments; the first must be a pointer to * a function of type #MHD_LogCallback and the second a pointer * `void *` which will be passed as the first argument to the log * callback. * Should be specified as the first option, otherwise some messages * may be printed by standard MHD logger during daemon startup. * * Note that MHD will not generate any log messages * if it was compiled without the "--enable-messages" * flag being set. */ MHD_OPTION_EXTERNAL_LOGGER = 13, /** * Number (`unsigned int`) of threads in thread pool. Enable * thread pooling by setting this value to to something * greater than 1. * Can be used only for daemons started with #MHD_USE_INTERNAL_POLLING_THREAD. * Ignored if followed by zero value. */ MHD_OPTION_THREAD_POOL_SIZE = 14, /** * Additional options given in an array of `struct MHD_OptionItem`. * The array must be terminated with an entry `{MHD_OPTION_END, 0, NULL}`. * An example for code using #MHD_OPTION_ARRAY is: * * struct MHD_OptionItem ops[] = { * { MHD_OPTION_CONNECTION_LIMIT, 100, NULL }, * { MHD_OPTION_CONNECTION_TIMEOUT, 10, NULL }, * { MHD_OPTION_END, 0, NULL } * }; * d = MHD_start_daemon (0, 8080, NULL, NULL, dh, NULL, * MHD_OPTION_ARRAY, ops, * MHD_OPTION_END); * * For options that expect a single pointer argument, the * 'value' member of the `struct MHD_OptionItem` is ignored. * For options that expect two pointer arguments, the first * argument must be cast to `intptr_t`. */ MHD_OPTION_ARRAY = 15, /** * Specify a function that should be called for unescaping escape * sequences in URIs and URI arguments. Note that this function * will NOT be used by the `struct MHD_PostProcessor`. If this * option is not specified, the default method will be used which * decodes escape sequences of the form "%HH". This option should * be followed by two arguments, the first one must be of the form * * size_t my_unescaper(void *cls, * struct MHD_Connection *c, * char *s) * * where the return value must be the length of the value left in * "s" (without the 0-terminator) and "s" should be updated. Note * that the unescape function must not lengthen "s" (the result must * be shorter than the input and must still be 0-terminated). * However, it may also include binary zeros before the * 0-termination. "cls" will be set to the second argument * following #MHD_OPTION_UNESCAPE_CALLBACK. */ MHD_OPTION_UNESCAPE_CALLBACK = 16, /** * Memory pointer for the random values to be used by the Digest * Auth module. This option should be followed by two arguments. * First an integer of type `size_t` which specifies the size * of the buffer pointed to by the second argument in bytes. * The recommended size is between 8 and 32. If size is four or less * then security could be lowered. Sizes more then 32 (or, probably * more than 16 - debatable) will not increase security. * Note that the application must ensure that the buffer of the * second argument remains allocated and unmodified while the * daemon is running. * @sa #MHD_OPTION_DIGEST_AUTH_RANDOM_COPY */ MHD_OPTION_DIGEST_AUTH_RANDOM = 17, /** * Size of the internal array holding the map of the nonce and * the nonce counter. This option should be followed by an `unsigned int` * argument. * The map size is 4 by default, which is enough to communicate with * a single client at any given moment of time, but not enough to * handle several clients simultaneously. * If Digest Auth is not used, this option can be set to zero to minimise * memory allocation. */ MHD_OPTION_NONCE_NC_SIZE = 18, /** * Desired size of the stack for threads created by MHD. Followed * by an argument of type `size_t`. Use 0 for system default. */ MHD_OPTION_THREAD_STACK_SIZE = 19, /** * Memory pointer for the certificate (ca.pem) to be used by the * HTTPS daemon for client authentication. * This option should be followed by a `const char *` argument. */ MHD_OPTION_HTTPS_MEM_TRUST = 20, /** * Increment to use for growing the read buffer (followed by a * `size_t`). * Must not be higher than 1/4 of #MHD_OPTION_CONNECTION_MEMORY_LIMIT. * Since #MHD_VERSION 0x00097710 silently ignored if followed by zero value. */ MHD_OPTION_CONNECTION_MEMORY_INCREMENT = 21, /** * Use a callback to determine which X.509 certificate should be * used for a given HTTPS connection. This option should be * followed by a argument of type `gnutls_certificate_retrieve_function2 *`. * This option provides an * alternative to #MHD_OPTION_HTTPS_MEM_KEY, * #MHD_OPTION_HTTPS_MEM_CERT. You must use this version if * multiple domains are to be hosted at the same IP address using * TLS's Server Name Indication (SNI) extension. In this case, * the callback is expected to select the correct certificate * based on the SNI information provided. The callback is expected * to access the SNI data using `gnutls_server_name_get()`. * Using this option requires GnuTLS 3.0 or higher. */ MHD_OPTION_HTTPS_CERT_CALLBACK = 22, /** * When using #MHD_USE_TCP_FASTOPEN, this option changes the default TCP * fastopen queue length of 50. Note that having a larger queue size can * cause resource exhaustion attack as the TCP stack has to now allocate * resources for the SYN packet along with its DATA. This option should be * followed by an `unsigned int` argument. */ MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE = 23, /** * Memory pointer for the Diffie-Hellman parameters (dh.pem) to be used by the * HTTPS daemon for key exchange. * This option must be followed by a `const char *` argument. */ MHD_OPTION_HTTPS_MEM_DHPARAMS = 24, /** * If present and set to true, allow reusing address:port socket * (by using SO_REUSEPORT on most platform, or platform-specific ways). * If present and set to false, disallow reusing address:port socket * (does nothing on most platform, but uses SO_EXCLUSIVEADDRUSE on Windows). * This option must be followed by a `unsigned int` argument. */ MHD_OPTION_LISTENING_ADDRESS_REUSE = 25, /** * Memory pointer for a password that decrypts the private key (key.pem) * to be used by the HTTPS daemon. This option should be followed by a * `const char *` argument. * This should be used in conjunction with #MHD_OPTION_HTTPS_MEM_KEY. * @sa ::MHD_FEATURE_HTTPS_KEY_PASSWORD */ MHD_OPTION_HTTPS_KEY_PASSWORD = 26, /** * Register a function that should be called whenever a connection is * started or closed. * * This option should be followed by TWO pointers. First a pointer * to a function of type #MHD_NotifyConnectionCallback and second a * pointer to a closure to pass to the request completed callback. * The second pointer may be NULL. */ MHD_OPTION_NOTIFY_CONNECTION = 27, /** * Allow to change maximum length of the queue of pending connections on * listen socket. If not present than default platform-specific SOMAXCONN * value is used. This option should be followed by an `unsigned int` * argument. */ MHD_OPTION_LISTEN_BACKLOG_SIZE = 28, /** * If set to 1 - be strict about the protocol. Use -1 to be * as tolerant as possible. * * The more flexible option #MHD_OPTION_CLIENT_DISCIPLINE_LVL is recommended * instead of this option. * * The values mapping table: * #MHD_OPTION_STRICT_FOR_CLIENT | #MHD_OPTION_CLIENT_DISCIPLINE_LVL * -----------------------------:|:--------------------------------- * 1 | 1 * 0 | 0 * -1 | -3 * * This option should be followed by an `int` argument. * @sa #MHD_OPTION_CLIENT_DISCIPLINE_LVL */ MHD_OPTION_STRICT_FOR_CLIENT = 29, /** * This should be a pointer to callback of type * gnutls_psk_server_credentials_function that will be given to * gnutls_psk_set_server_credentials_function. It is used to * retrieve the shared key for a given username. */ MHD_OPTION_GNUTLS_PSK_CRED_HANDLER = 30, /** * Use a callback to determine which X.509 certificate should be * used for a given HTTPS connection. This option should be * followed by a argument of type `gnutls_certificate_retrieve_function3 *`. * This option provides an * alternative/extension to #MHD_OPTION_HTTPS_CERT_CALLBACK. * You must use this version if you want to use OCSP stapling. * Using this option requires GnuTLS 3.6.3 or higher. */ MHD_OPTION_HTTPS_CERT_CALLBACK2 = 31, /** * Allows the application to disable certain sanity precautions * in MHD. With these, the client can break the HTTP protocol, * so this should never be used in production. The options are, * however, useful for testing HTTP clients against "broken" * server implementations. * This argument must be followed by an "unsigned int", corresponding * to an `enum MHD_DisableSanityCheck`. */ MHD_OPTION_SERVER_INSANITY = 32, /** * If followed by value '1' informs MHD that SIGPIPE is suppressed or * handled by application. Allows MHD to use network functions that could * generate SIGPIPE, like `sendfile()`. * Valid only for daemons without #MHD_USE_INTERNAL_POLLING_THREAD as * MHD automatically suppresses SIGPIPE for threads started by MHD. * This option should be followed by an `int` argument. * @note Available since #MHD_VERSION 0x00097205 */ MHD_OPTION_SIGPIPE_HANDLED_BY_APP = 33, /** * If followed by 'int' with value '1' disables usage of ALPN for TLS * connections even if supported by TLS library. * Valid only for daemons with #MHD_USE_TLS. * This option should be followed by an `int` argument. * @note Available since #MHD_VERSION 0x00097207 */ MHD_OPTION_TLS_NO_ALPN = 34, /** * Memory pointer for the random values to be used by the Digest * Auth module. This option should be followed by two arguments. * First an integer of type `size_t` which specifies the size * of the buffer pointed to by the second argument in bytes. * The recommended size is between 8 and 32. If size is four or less * then security could be lowered. Sizes more then 32 (or, probably * more than 16 - debatable) will not increase security. * An internal copy of the buffer will be made, the data do not * need to be static. * @sa #MHD_OPTION_DIGEST_AUTH_RANDOM * @note Available since #MHD_VERSION 0x00097701 */ MHD_OPTION_DIGEST_AUTH_RANDOM_COPY = 35, /** * Allow to controls the scope of validity of MHD-generated nonces. * This regulates how "nonces" are generated and how "nonces" are checked by * #MHD_digest_auth_check3() and similar functions. * This option should be followed by an 'unsigned int` argument with value * formed as bitwise OR combination of #MHD_DAuthBindNonce values. * When not specified, default value #MHD_DAUTH_BIND_NONCE_NONE is used. * @note Available since #MHD_VERSION 0x00097701 */ MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE = 36, /** * Memory pointer to a `const char *` specifying the GnuTLS priorities to be * appended to default priorities. * This allow some specific options to be enabled/disabled, while leaving * the rest of the settings to their defaults. * The string does not have to start with a colon ':' character. * See #MHD_OPTION_HTTPS_PRIORITIES description for details of automatic * default priorities. * @note Available since #MHD_VERSION 0x00097701 */ MHD_OPTION_HTTPS_PRIORITIES_APPEND = 37, /** * Sets specified client discipline level (i.e. HTTP protocol parsing * strictness level). * * The following basic values are supported: * 0 - default MHD level, a balance between extra security and broader * compatibility, as allowed by RFCs for HTTP servers; * 1 - more strict protocol interpretation, within the limits set by * RFCs for HTTP servers; * -1 - more lenient protocol interpretation, within the limits set by * RFCs for HTTP servers. * The following extended values could be used as well: * 2 - stricter protocol interpretation, even stricter then allowed * by RFCs for HTTP servers, however it should be absolutely compatible * with clients following at least RFCs' "MUST" type of requirements * for HTTP clients; * 3 - strictest protocol interpretation, even stricter then allowed * by RFCs for HTTP servers, however it should be absolutely compatible * with clients following RFCs' "SHOULD" and "MUST" types of requirements * for HTTP clients; * -2 - more relaxed protocol interpretation, violating RFCs' "SHOULD" type * of requirements for HTTP servers; * -3 - the most flexible protocol interpretation, beyond RFCs' "MUST" type of * requirements for HTTP server. * Values higher than "3" or lower than "-3" are interpreted as "3" or "-3" * respectively. * * Higher values are more secure, lower values are more compatible with * various HTTP clients. * * The default value ("0") could be used in most cases. * Value "1" is suitable for highly loaded public servers. * Values "2" and "3" are generally recommended only for testing of HTTP * clients against MHD. * Value "2" may be used for security-centric application, however it is * slight violation of RFCs' requirements. * Negative values are not recommended for public servers. * Values "-1" and "-2" could be used for servers in isolated environment. * Value "-3" is not recommended unless it is absolutely necessary to * communicate with some client(s) with badly broken HTTP implementation. * * This option should be followed by an `int` argument. * @note Available since #MHD_VERSION 0x00097701 */ MHD_OPTION_CLIENT_DISCIPLINE_LVL = 38, /** * Specifies value of FD_SETSIZE used by application. Only For external * polling modes (without MHD internal threads). * Some platforms (FreeBSD, Solaris, W32 etc.) allow overriding of FD_SETSIZE * value. When polling by select() is used, MHD rejects sockets with numbers * equal or higher than FD_SETSIZE. If this option is used, MHD treats this * value as a limitation for socket number instead of FD_SETSIZE value which * was used for building MHD. * When external polling is used with #MHD_get_fdset2() (or #MHD_get_fdset() * macro) and #MHD_run_from_select() interfaces, it is recommended to always * use this option. * It is safe to use this option on platforms with fixed FD_SETSIZE (like * GNU/Linux) if system value of FD_SETSIZE is used as the argument. * Can be used only for daemons without #MHD_USE_INTERNAL_POLLING_THREAD, i.e. * only when external sockets polling is used. * On W32 it is silently ignored, as W32 does not limit the socket number in * fd_sets. * This option should be followed by a positive 'int' argument. * @note Available since #MHD_VERSION 0x00097705 */ MHD_OPTION_APP_FD_SETSIZE = 39, /** * Bind daemon to the supplied 'struct sockaddr'. This option should * be followed by two parameters: 'socklen_t' the size of memory at the next * pointer and the pointer 'const struct sockaddr *'. * Note: the order of the arguments is not the same as for system bind() and * other network functions. * If #MHD_USE_IPv6 is specified, the 'struct sockaddr*' should * point to a 'struct sockaddr_in6'. * The socket domain (protocol family) is detected from provided * 'struct sockaddr'. IP, IPv6 and UNIX sockets are supported (if supported * by the platform). Other types may work occasionally. * Silently ignored if followed by zero size and NULL pointer. * @note Available since #MHD_VERSION 0x00097706 */ MHD_OPTION_SOCK_ADDR_LEN = 40 , /** * Default nonce timeout value used for Digest Auth. * This option should be followed by an 'unsigned int' argument. * Silently ignored if followed by zero value. * @see #MHD_digest_auth_check3(), MHD_digest_auth_check_digest3() * @note Available since #MHD_VERSION 0x00097709 */ MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT = 41 , /** * Default maximum nc (nonce count) value used for Digest Auth. * This option should be followed by an 'uint32_t' argument. * Silently ignored if followed by zero value. * @see #MHD_digest_auth_check3(), MHD_digest_auth_check_digest3() * @note Available since #MHD_VERSION 0x00097709 */ MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC = 42 , /** * Default maximum nc (nonce count) value used for Digest Auth. * This option must be followed by an 'int' argument. * If followed by '0' (default) then: * + requests are rejected if request URI has binary zero (the result * of %00 decoding) in the path part of the URI. * If followed by '1' then: * + binary zero is allowed in request URI path; * + #MHD_AccessHandlerCallback called with NULL in @a url parameter when * request URI path has binary zero, the full @a url is available only * via #MHD_get_connection_URI_path_n() * If followed by '2' (unsafe!) then: * + binary zero is allowed in request URI path; * + #MHD_AccessHandlerCallback called with truncated (unsafe!) @a url * parameter when request URI path has binary zero. * @see #MHD_get_connection_URI_path_n() * @note Available since #MHD_VERSION 0x01000201 */ MHD_OPTION_ALLOW_BIN_ZERO_IN_URI_PATH = 43 } _MHD_FIXED_ENUM; /** * Bitfield for the #MHD_OPTION_SERVER_INSANITY specifying * which santiy checks should be disabled. */ enum MHD_DisableSanityCheck { /** * All sanity checks are enabled. */ MHD_DSC_SANE = 0 } _MHD_FIXED_FLAGS_ENUM; /** * Entry in an #MHD_OPTION_ARRAY. */ struct MHD_OptionItem { /** * Which option is being given. Use #MHD_OPTION_END * to terminate the array. */ enum MHD_OPTION option; /** * Option value (for integer arguments, and for options requiring * two pointer arguments); should be 0 for options that take no * arguments or only a single pointer argument. */ intptr_t value; /** * Pointer option value (use NULL for options taking no arguments * or only an integer option). */ void *ptr_value; }; /** * The `enum MHD_ValueKind` specifies the source of * the key-value pairs in the HTTP protocol. */ enum MHD_ValueKind { /** * Response header * @deprecated */ MHD_RESPONSE_HEADER_KIND = 0, #define MHD_RESPONSE_HEADER_KIND \ _MHD_DEPR_IN_MACRO ( \ "Value MHD_RESPONSE_HEADER_KIND is deprecated and not used") \ MHD_RESPONSE_HEADER_KIND /** * HTTP header (request/response). */ MHD_HEADER_KIND = 1, /** * Cookies. Note that the original HTTP header containing * the cookie(s) will still be available and intact. */ MHD_COOKIE_KIND = 2, /** * POST data. This is available only if a content encoding * supported by MHD is used (currently only URL encoding), * and only if the posted content fits within the available * memory pool. Note that in that case, the upload data * given to the #MHD_AccessHandlerCallback will be * empty (since it has already been processed). */ MHD_POSTDATA_KIND = 4, /** * GET (URI) arguments. */ MHD_GET_ARGUMENT_KIND = 8, /** * HTTP footer (only for HTTP 1.1 chunked encodings). */ MHD_FOOTER_KIND = 16 } _MHD_FIXED_ENUM; /** * The `enum MHD_RequestTerminationCode` specifies reasons * why a request has been terminated (or completed). * @ingroup request */ enum MHD_RequestTerminationCode { /** * We finished sending the response. * @ingroup request */ MHD_REQUEST_TERMINATED_COMPLETED_OK = 0, /** * Error handling the connection (resources * exhausted, application error accepting request, * decrypt error (for HTTPS), connection died when * sending the response etc.) * @ingroup request */ MHD_REQUEST_TERMINATED_WITH_ERROR = 1, /** * No activity on the connection for the number * of seconds specified using * #MHD_OPTION_CONNECTION_TIMEOUT. * @ingroup request */ MHD_REQUEST_TERMINATED_TIMEOUT_REACHED = 2, /** * We had to close the session since MHD was being * shut down. * @ingroup request */ MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN = 3, /** * We tried to read additional data, but the connection became broken or * the other side hard closed the connection. * This error is similar to #MHD_REQUEST_TERMINATED_WITH_ERROR, but * specific to the case where the connection died before request completely * received. * @ingroup request */ MHD_REQUEST_TERMINATED_READ_ERROR = 4, /** * The client terminated the connection by closing the socket * for writing (TCP half-closed) while still sending request. * @ingroup request */ MHD_REQUEST_TERMINATED_CLIENT_ABORT = 5 } _MHD_FIXED_ENUM; /** * The `enum MHD_ConnectionNotificationCode` specifies types * of connection notifications. * @ingroup request */ enum MHD_ConnectionNotificationCode { /** * A new connection has been started. * @ingroup request */ MHD_CONNECTION_NOTIFY_STARTED = 0, /** * A connection is closed. * @ingroup request */ MHD_CONNECTION_NOTIFY_CLOSED = 1 } _MHD_FIXED_ENUM; /** * Information about a connection. */ union MHD_ConnectionInfo { /** * Cipher algorithm used, of type "enum gnutls_cipher_algorithm". */ int /* enum gnutls_cipher_algorithm */ cipher_algorithm; /** * Protocol used, of type "enum gnutls_protocol". */ int /* enum gnutls_protocol */ protocol; /** * The suspended status of a connection. */ int /* MHD_YES or MHD_NO */ suspended; /** * Amount of second that connection could spend in idle state * before automatically disconnected. * Zero for no timeout (unlimited idle time). */ unsigned int connection_timeout; /** * HTTP status queued with the response, for #MHD_CONNECTION_INFO_HTTP_STATUS. */ unsigned int http_status; /** * Connect socket */ MHD_socket connect_fd; /** * Size of the client's HTTP header. * It includes the request line, all request headers, the header section * terminating empty line, with all CRLF (or LF) characters. */ size_t header_size; /** * GNUtls session handle, of type "gnutls_session_t". */ void * /* gnutls_session_t */ tls_session; /** * GNUtls client certificate handle, of type "gnutls_x509_crt_t". */ void * /* gnutls_x509_crt_t */ client_cert; /** * Address information for the client. */ struct sockaddr *client_addr; /** * Which daemon manages this connection (useful in case there are many * daemons running). */ struct MHD_Daemon *daemon; /** * Socket-specific client context. Points to the same address as * the "socket_context" of the #MHD_NotifyConnectionCallback. */ void *socket_context; }; /** * I/O vector type. Provided for use with #MHD_create_response_from_iovec(). * @note Available since #MHD_VERSION 0x00097204 */ struct MHD_IoVec { /** * The pointer to the memory region for I/O. */ const void *iov_base; /** * The size in bytes of the memory region for I/O. */ size_t iov_len; }; /** * Values of this enum are used to specify what * information about a connection is desired. * @ingroup request */ enum MHD_ConnectionInfoType { /** * What cipher algorithm is being used. * Takes no extra arguments. * @ingroup request */ MHD_CONNECTION_INFO_CIPHER_ALGO, /** * * Takes no extra arguments. * @ingroup request */ MHD_CONNECTION_INFO_PROTOCOL, /** * Obtain IP address of the client. Takes no extra arguments. * Returns essentially a `struct sockaddr **` (since the API returns * a `union MHD_ConnectionInfo *` and that union contains a `struct * sockaddr *`). * @ingroup request */ MHD_CONNECTION_INFO_CLIENT_ADDRESS, /** * Get the gnuTLS session handle. * @ingroup request */ MHD_CONNECTION_INFO_GNUTLS_SESSION, /** * Get the gnuTLS client certificate handle. Dysfunctional (never * implemented, deprecated). Use #MHD_CONNECTION_INFO_GNUTLS_SESSION * to get the `gnutls_session_t` and then call * gnutls_certificate_get_peers(). */ MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT, /** * Get the `struct MHD_Daemon *` responsible for managing this connection. * @ingroup request */ MHD_CONNECTION_INFO_DAEMON, /** * Request the file descriptor for the connection socket. * MHD sockets are always in non-blocking mode. * No extra arguments should be passed. * @ingroup request */ MHD_CONNECTION_INFO_CONNECTION_FD, /** * Returns the client-specific pointer to a `void *` that was (possibly) * set during a #MHD_NotifyConnectionCallback when the socket was * first accepted. * Note that this is NOT the same as the "req_cls" argument of * the #MHD_AccessHandlerCallback. The "req_cls" is fresh for each * HTTP request, while the "socket_context" is fresh for each socket. */ MHD_CONNECTION_INFO_SOCKET_CONTEXT, /** * Check whether the connection is suspended. * @ingroup request */ MHD_CONNECTION_INFO_CONNECTION_SUSPENDED, /** * Get connection timeout * @ingroup request */ MHD_CONNECTION_INFO_CONNECTION_TIMEOUT, /** * Return length of the client's HTTP request header. * @ingroup request */ MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE, /** * Return HTTP status queued with the response. NULL * if no HTTP response has been queued yet. */ MHD_CONNECTION_INFO_HTTP_STATUS } _MHD_FIXED_ENUM; /** * Values of this enum are used to specify what * information about a daemon is desired. */ enum MHD_DaemonInfoType { /** * No longer supported (will return NULL). */ MHD_DAEMON_INFO_KEY_SIZE, /** * No longer supported (will return NULL). */ MHD_DAEMON_INFO_MAC_KEY_SIZE, /** * Request the file descriptor for the listening socket. * No extra arguments should be passed. */ MHD_DAEMON_INFO_LISTEN_FD, /** * Request the file descriptor for the "external" sockets polling * when 'epoll' mode is used. * No extra arguments should be passed. * * Waiting on epoll FD must not block longer than value * returned by #MHD_get_timeout() otherwise connections * will "hung" with unprocessed data in network buffers * and timed-out connections will not be closed. * * @sa #MHD_get_timeout(), #MHD_run() */ MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY, MHD_DAEMON_INFO_EPOLL_FD = MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY, /** * Request the number of current connections handled by the daemon. * No extra arguments should be passed. * Note: when using MHD in "external" polling mode, this type of request * could be used only when #MHD_run()/#MHD_run_from_select is not * working in other thread at the same time. */ MHD_DAEMON_INFO_CURRENT_CONNECTIONS, /** * Request the daemon flags. * No extra arguments should be passed. * Note: flags may differ from original 'flags' specified for * daemon, especially if #MHD_USE_AUTO was set. */ MHD_DAEMON_INFO_FLAGS, /** * Request the port number of daemon's listen socket. * No extra arguments should be passed. * Note: if port '0' was specified for #MHD_start_daemon(), returned * value will be real port number. */ MHD_DAEMON_INFO_BIND_PORT } _MHD_FIXED_ENUM; /** * Callback for serious error condition. The default action is to print * an error message and `abort()`. * * @param cls user specified value * @param file where the error occurred, may be NULL if MHD was built without * messages support * @param line where the error occurred * @param reason error detail, may be NULL * @ingroup logging */ typedef void (*MHD_PanicCallback) (void *cls, const char *file, unsigned int line, const char *reason); /** * Allow or deny a client to connect. * * @param cls closure * @param addr address information from the client * @param addrlen length of @a addr * @return #MHD_YES if connection is allowed, #MHD_NO if not */ typedef enum MHD_Result (*MHD_AcceptPolicyCallback)(void *cls, const struct sockaddr *addr, socklen_t addrlen); /** * A client has requested the given @a url using the given @a method * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT, #MHD_HTTP_METHOD_DELETE, * #MHD_HTTP_METHOD_POST, etc). * * The callback must call MHD function MHD_queue_response() to provide content * to give back to the client and return an HTTP status code (i.e. * #MHD_HTTP_OK, #MHD_HTTP_NOT_FOUND, etc.). The response can be created * in this callback or prepared in advance. * Alternatively, callback may call MHD_suspend_connection() to temporarily * suspend data processing for this connection. * * As soon as response is provided this callback will not be called anymore * for the current request. * * For each HTTP request this callback is called several times: * * after request headers are fully received and decoded, * * for each received part of request body (optional, if request has body), * * when request is fully received. * * If response is provided before request is fully received, the rest * of the request is discarded and connection is automatically closed * after sending response. * * If the request is fully received, but response hasn't been provided and * connection is not suspended, the callback can be called again immediately. * * The response cannot be queued when this callback is called to process * the client upload data (when @a upload_data is not NULL). * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param connection the connection handle * @param url the requested url, can be truncated or can be NULL, depending * on #MHD_OPTION_ALLOW_BIN_ZERO_IN_URI_PATH option, * see #MHD_get_connection_URI_path_n() * @param method the HTTP method used (#MHD_HTTP_METHOD_GET, * #MHD_HTTP_METHOD_PUT, etc.) * @param version the HTTP version string (i.e. * #MHD_HTTP_VERSION_1_1) * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of #MHD_get_connection_values; very large POST * data *will* be made available incrementally in * @a upload_data) * @param[in,out] upload_data_size set initially to the size of the * @a upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param[in,out] req_cls pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global #MHD_RequestCompletedCallback (which * can be set with the #MHD_OPTION_NOTIFY_COMPLETED). * Initially, `*req_cls` will be NULL. * @return #MHD_YES if the connection was handled successfully, * #MHD_NO if the socket must be closed due to a serious * error while handling the request * * @sa #MHD_queue_response(), #MHD_get_connection_URI_path_n() */ typedef enum MHD_Result (*MHD_AccessHandlerCallback)(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls); /** * Signature of the callback used by MHD to notify the * application about completed requests. * * @param cls client-defined closure * @param connection connection handle * @param req_cls value as set by the last call to * the #MHD_AccessHandlerCallback * @param toe reason for request termination * @see #MHD_OPTION_NOTIFY_COMPLETED * @ingroup request */ typedef void (*MHD_RequestCompletedCallback) (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe); /** * Signature of the callback used by MHD to notify the * application about started/stopped connections * * @param cls client-defined closure * @param connection connection handle * @param socket_context socket-specific pointer where the * client can associate some state specific * to the TCP connection; note that this is * different from the "req_cls" which is per * HTTP request. The client can initialize * during #MHD_CONNECTION_NOTIFY_STARTED and * cleanup during #MHD_CONNECTION_NOTIFY_CLOSED * and access in the meantime using * #MHD_CONNECTION_INFO_SOCKET_CONTEXT. * @param toe reason for connection notification * @see #MHD_OPTION_NOTIFY_CONNECTION * @ingroup request */ typedef void (*MHD_NotifyConnectionCallback) (void *cls, struct MHD_Connection *connection, void **socket_context, enum MHD_ConnectionNotificationCode toe); /** * Iterator over key-value pairs. This iterator * can be used to iterate over all of the cookies, * headers, or POST-data fields of a request, and * also to iterate over the headers that have been * added to a response. * * @param cls closure * @param kind kind of the header we are looking at * @param key key for the value, can be an empty string * @param value corresponding value, can be NULL * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration * @ingroup request */ typedef enum MHD_Result (*MHD_KeyValueIterator)(void *cls, enum MHD_ValueKind kind, const char *key, const char *value); /** * Iterator over key-value pairs with size parameters. * This iterator can be used to iterate over all of * the cookies, headers, or POST-data fields of a * request, and also to iterate over the headers that * have been added to a response. * @note Available since #MHD_VERSION 0x00096303 * * @param cls closure * @param kind kind of the header we are looking at * @param key key for the value, can be an empty string * @param value corresponding value, can be NULL * @param value_size number of bytes in @a value; * for C-strings, the length excludes the 0-terminator * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration * @ingroup request */ typedef enum MHD_Result (*MHD_KeyValueIteratorN)(void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size); /** * Callback used by libmicrohttpd in order to obtain content. * * The callback is to copy at most @a max bytes of content into @a buf. * The total number of bytes that has been placed into @a buf should be * returned. * * Note that returning zero will cause libmicrohttpd to try again. * Thus, returning zero should only be used in conjunction * with MHD_suspend_connection() to avoid busy waiting. * * @param cls extra argument to the callback * @param pos position in the datastream to access; * note that if a `struct MHD_Response` object is re-used, * it is possible for the same content reader to * be queried multiple times for the same data; * however, if a `struct MHD_Response` is not re-used, * libmicrohttpd guarantees that "pos" will be * the sum of all non-negative return values * obtained from the content reader so far. * @param buf where to copy the data * @param max maximum number of bytes to copy to @a buf (size of @a buf) * @return number of bytes written to @a buf; * 0 is legal unless MHD is started in "internal" sockets polling mode * (since this would cause busy-waiting); 0 in "external" sockets * polling mode will cause this function to be called again once * any MHD_run*() function is called; * #MHD_CONTENT_READER_END_OF_STREAM (-1) for the regular * end of transmission (with chunked encoding, MHD will then * terminate the chunk and send any HTTP footers that might be * present; without chunked encoding and given an unknown * response size, MHD will simply close the connection; note * that while returning #MHD_CONTENT_READER_END_OF_STREAM is not technically * legal if a response size was specified, MHD accepts this * and treats it just as #MHD_CONTENT_READER_END_WITH_ERROR; * #MHD_CONTENT_READER_END_WITH_ERROR (-2) to indicate a server * error generating the response; this will cause MHD to simply * close the connection immediately. If a response size was * given or if chunked encoding is in use, this will indicate * an error to the client. Note, however, that if the client * does not know a response size and chunked encoding is not in * use, then clients will not be able to tell the difference between * #MHD_CONTENT_READER_END_WITH_ERROR and #MHD_CONTENT_READER_END_OF_STREAM. * This is not a limitation of MHD but rather of the HTTP protocol. */ typedef ssize_t (*MHD_ContentReaderCallback) (void *cls, uint64_t pos, char *buf, size_t max); /** * This method is called by libmicrohttpd if we * are done with a content reader. It should * be used to free resources associated with the * content reader. * * @param cls closure * @ingroup response */ typedef void (*MHD_ContentReaderFreeCallback) (void *cls); /** * Iterator over key-value pairs where the value * may be made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value, always #MHD_POSTDATA_KIND when called from MHD * @param key 0-terminated key for the value, NULL if not known. This value * is never NULL for url-encoded POST data. * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to @a size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in @a data available * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration */ typedef enum MHD_Result (*MHD_PostDataIterator)(void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size); /* **************** Daemon handling functions ***************** */ /** * Start a webserver on the given port. * * @param flags combination of `enum MHD_FLAG` values * @param port port to bind to (in host byte order), * use '0' to bind to random free port, * ignored if MHD_OPTION_SOCK_ADDR or * MHD_OPTION_LISTEN_SOCKET is provided * or MHD_USE_NO_LISTEN_SOCKET is specified * @param apc callback to call to check which clients * will be allowed to connect; you can pass NULL * in which case connections from any IP will be * accepted * @param apc_cls extra argument to apc * @param dh handler called for all requests (repeatedly) * @param dh_cls extra argument to @a dh * @param ap list of options (type-value pairs, * terminated with #MHD_OPTION_END). * @return NULL on error, handle to daemon on success * @ingroup event */ _MHD_EXTERN struct MHD_Daemon * MHD_start_daemon_va (unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, va_list ap); /** * Start a webserver on the given port. Variadic version of * #MHD_start_daemon_va. * * @param flags combination of `enum MHD_FLAG` values * @param port port to bind to (in host byte order), * use '0' to bind to random free port, * ignored if MHD_OPTION_SOCK_ADDR or * MHD_OPTION_LISTEN_SOCKET is provided * or MHD_USE_NO_LISTEN_SOCKET is specified * @param apc callback to call to check which clients * will be allowed to connect; you can pass NULL * in which case connections from any IP will be * accepted * @param apc_cls extra argument to apc * @param dh handler called for all requests (repeatedly) * @param dh_cls extra argument to @a dh * @return NULL on error, handle to daemon on success * @ingroup event */ _MHD_EXTERN struct MHD_Daemon * MHD_start_daemon (unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, ...); /** * Stop accepting connections from the listening socket. Allows * clients to continue processing, but stops accepting new * connections. Note that the caller is responsible for closing the * returned socket; however, if MHD is run using threads (anything but * "external" sockets polling mode), it must not be closed until AFTER * #MHD_stop_daemon has been called (as it is theoretically possible * that an existing thread is still using it). * * Note that some thread modes require the caller to have passed * #MHD_USE_ITC when using this API. If this daemon is * in one of those modes and this option was not given to * #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET. * * @param daemon daemon to stop accepting new connections for * @return old listen socket on success, #MHD_INVALID_SOCKET if * the daemon was already not listening anymore * @ingroup specialized */ _MHD_EXTERN MHD_socket MHD_quiesce_daemon (struct MHD_Daemon *daemon); /** * Shutdown an HTTP daemon. * * @param daemon daemon to stop * @ingroup event */ _MHD_EXTERN void MHD_stop_daemon (struct MHD_Daemon *daemon); /** * Add another client connection to the set of connections managed by * MHD. This API is usually not needed (since MHD will accept inbound * connections on the server socket). Use this API in special cases, * for example if your HTTP server is behind NAT and needs to connect * out to the HTTP client, or if you are building a proxy. * * If you use this API in conjunction with an "internal" socket polling, * you must set the option #MHD_USE_ITC to ensure that the freshly added * connection is immediately processed by MHD. * * The given client socket will be managed (and closed!) by MHD after * this call and must no longer be used directly by the application * afterwards. * * @param daemon daemon that manages the connection * @param client_socket socket to manage (MHD will expect * to receive an HTTP request from this socket next). * @param addr IP address of the client * @param addrlen number of bytes in @a addr * @return #MHD_YES on success, #MHD_NO if this daemon could * not handle the connection (i.e. `malloc()` failed, etc). * The socket will be closed in any case; `errno` is * set to indicate further details about the error. * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_add_connection (struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr *addr, socklen_t addrlen); /** * Obtain the `select()` sets for this daemon. * Daemon's FDs will be added to fd_sets. To get only * daemon FDs in fd_sets, call FD_ZERO for each fd_set * before calling this function. FD_SETSIZE is assumed * to be platform's default. * * This function should be called only when MHD is configured to * use "external" sockets polling with 'select()' or with 'epoll'. * In the latter case, it will only add the single 'epoll' file * descriptor used by MHD to the sets. * It's necessary to use #MHD_get_timeout() to get maximum timeout * value for `select()`. Usage of `select()` with indefinite timeout * (or timeout larger than returned by #MHD_get_timeout()) will * violate MHD API and may results in pending unprocessed data. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_fdset (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd); /** * Obtain the `select()` sets for this daemon. * Daemon's FDs will be added to fd_sets. To get only * daemon FDs in fd_sets, call FD_ZERO for each fd_set * before calling this function. * * Passing custom FD_SETSIZE as @a fd_setsize allow usage of * larger/smaller than platform's default fd_sets. * * This function should be called only when MHD is configured to * use "external" sockets polling with 'select()' or with 'epoll'. * In the latter case, it will only add the single 'epoll' file * descriptor used by MHD to the sets. * It's necessary to use #MHD_get_timeout() to get maximum timeout * value for `select()`. Usage of `select()` with indefinite timeout * (or timeout larger than returned by #MHD_get_timeout()) will * violate MHD API and may results in pending unprocessed data. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @param fd_setsize value of FD_SETSIZE * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_fdset2 (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd, unsigned int fd_setsize); /** * Obtain the `select()` sets for this daemon. * Daemon's FDs will be added to fd_sets. To get only * daemon FDs in fd_sets, call FD_ZERO for each fd_set * before calling this function. Size of fd_set is * determined by current value of FD_SETSIZE. * * This function should be called only when MHD is configured to * use "external" sockets polling with 'select()' or with 'epoll'. * In the latter case, it will only add the single 'epoll' file * descriptor used by MHD to the sets. * It's necessary to use #MHD_get_timeout() to get maximum timeout * value for `select()`. Usage of `select()` with indefinite timeout * (or timeout larger than returned by #MHD_get_timeout()) will * violate MHD API and may results in pending unprocessed data. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ #define MHD_get_fdset(daemon,read_fd_set,write_fd_set,except_fd_set,max_fd) \ MHD_get_fdset2 ((daemon),(read_fd_set),(write_fd_set),(except_fd_set), \ (max_fd),FD_SETSIZE) /** * Obtain timeout value for polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function. Smaller timeout values can be used for * polling function if it is required for any reason, but using larger * timeout value or no timeout (indefinite timeout) when this function * return #MHD_YES will break MHD processing logic and result in "hung" * connections with data pending in network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout64(), * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select()) * must be called right after return from polling function, regardless of * the states of MHD FDs. * * In practice, if #MHD_YES is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than @a timeout * millisecond even if no activity is detected on sockets by sockets * polling function. * * @param daemon daemon to query for timeout * @param[out] timeout set to the timeout (in milliseconds) * @return #MHD_YES on success, #MHD_NO if timeouts are * not used and no data processing is pending. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_timeout (struct MHD_Daemon *daemon, MHD_UNSIGNED_LONG_LONG *timeout); /** * Free the memory allocated by MHD. * * If any MHD function explicitly mentions that returned pointer must be * freed by this function, then no other method must be used to free * the memory. * * @param ptr the pointer to free. * @sa #MHD_digest_auth_get_username(), #MHD_basic_auth_get_username_password3() * @sa #MHD_basic_auth_get_username_password() * @note Available since #MHD_VERSION 0x00095600 * @ingroup specialized */ _MHD_EXTERN void MHD_free (void *ptr); /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function. Smaller timeout values can be used for * polling function if it is required for any reason, but using larger * timeout value or no timeout (indefinite timeout) when this function * return #MHD_YES will break MHD processing logic and result in "hung" * connections with data pending in network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select()) * must be called right after return from polling function, regardless of * the states of MHD FDs. * * In practice, if #MHD_YES is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than @a timeout * millisecond even if no activity is detected on sockets by sockets * polling function. * * @param daemon daemon to query for timeout * @param[out] timeout64 the pointer to the variable to be set to the * timeout (in milliseconds) * @return #MHD_YES if timeout value has been set, * #MHD_NO if timeouts are not used and no data processing is pending. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_timeout64 (struct MHD_Daemon *daemon, uint64_t *timeout); /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function (if returned value is non-negative). * Smaller timeout values can be used for polling function if it is required * for any reason, but using larger timeout value or no timeout (indefinite * timeout) when this function returns non-negative value will break MHD * processing logic and result in "hung" connections with data pending in * network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns non-negative value then #MHD_run() (or * #MHD_run_from_select()) must be called right after return from polling * function, regardless of the states of MHD FDs. * * In practice, if zero or positive value is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than returned amount of * millisecond even if no activity is detected on sockets by sockets * polling function. * * @param daemon the daemon to query for timeout * @return -1 if connections' timeouts are not set and no data processing * is pending, so external polling function may wait for sockets * activity for indefinite amount of time, * otherwise returned value is the the maximum amount of millisecond * that external polling function must wait for the activity of FDs. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN int64_t MHD_get_timeout64s (struct MHD_Daemon *daemon); /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function (if returned value is non-negative). * Smaller timeout values can be used for polling function if it is required * for any reason, but using larger timeout value or no timeout (indefinite * timeout) when this function returns non-negative value will break MHD * processing logic and result in "hung" connections with data pending in * network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64(), #MHD_get_timeout64s() functions) when "external" * polling is used. * If this function returns non-negative value then #MHD_run() (or * #MHD_run_from_select()) must be called right after return from polling * function, regardless of the states of MHD FDs. * * In practice, if zero or positive value is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than returned amount of * millisecond even if no activity is detected on sockets by sockets * polling function. * * @param daemon the daemon to query for timeout * @return -1 if connections' timeouts are not set and no data processing * is pending, so external polling function may wait for sockets * activity for indefinite amount of time, * otherwise returned value is the the maximum amount of millisecond * (capped at INT_MAX) that external polling function must wait * for the activity of FDs. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN int MHD_get_timeout_i (struct MHD_Daemon *daemon); /** * Run webserver operations (without blocking unless in client callbacks). * * This method should be called by clients in combination with * #MHD_get_fdset() (or #MHD_get_daemon_info() with MHD_DAEMON_INFO_EPOLL_FD * if epoll is used) and #MHD_get_timeout() if the client-controlled * connection polling method is used (i.e. daemon was started without * #MHD_USE_INTERNAL_POLLING_THREAD flag). * * This function is a convenience method, which is useful if the * fd_sets from #MHD_get_fdset were not directly passed to `select()`; * with this function, MHD will internally do the appropriate `select()` * call itself again. While it is acceptable to call #MHD_run (if * #MHD_USE_INTERNAL_POLLING_THREAD is not set) at any moment, you should * call #MHD_run_from_select() if performance is important (as it saves an * expensive call to `select()`). * * If #MHD_get_timeout() returned #MHD_YES, than this function must be called * right after polling function returns regardless of detected activity on * the daemon's FDs. * * @param daemon daemon to run * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run (struct MHD_Daemon *daemon); /** * Run websever operation with possible blocking. * * This function does the following: waits for any network event not more than * specified number of milliseconds, processes all incoming and outgoing data, * processes new connections, processes any timed-out connection, and does * other things required to run webserver. * Once all connections are processed, function returns. * * This function is useful for quick and simple (lazy) webserver implementation * if application needs to run a single thread only and does not have any other * network activity. * * This function calls MHD_get_timeout() internally and use returned value as * maximum wait time if it less than value of @a millisec parameter. * * It is expected that the "external" socket polling function is not used in * conjunction with this function unless the @a millisec is set to zero. * * @param daemon the daemon to run * @param millisec the maximum time in milliseconds to wait for network and * other events. Note: there is no guarantee that function * blocks for the specified amount of time. The real processing * time can be shorter (if some data or connection timeout * comes earlier) or longer (if data processing requires more * time, especially in user callbacks). * If set to '0' then function does not block and processes * only already available data (if any). * If set to '-1' then function waits for events * indefinitely (blocks until next network activity or * connection timeout). * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or some serious * unrecoverable error occurs. * @note Available since #MHD_VERSION 0x00097206 * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_wait (struct MHD_Daemon *daemon, int32_t millisec); /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * * You can use this function instead of #MHD_run if you called * `select()` on the result from #MHD_get_fdset. File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run is more efficient as MHD will * not have to call `select()` again to determine which operations are * ready. * * If #MHD_get_timeout() returned #MHD_YES, than this function must be * called right after `select()` returns regardless of detected activity * on the daemon's FDs. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to run select loop for * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @return #MHD_NO on serious errors, #MHD_YES on success * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set); /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * This function specifies FD_SETSIZE used when provided fd_sets were * created. It is important on platforms where FD_SETSIZE can be * overridden. * * You can use this function instead of #MHD_run if you called * 'select()' on the result from #MHD_get_fdset2(). File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run() is more efficient as MHD will * not have to call 'select()' again to determine which operations are * ready. * * If #MHD_get_timeout() returned #MHD_YES, than this function must be * called right after 'select()' returns regardless of detected activity * on the daemon's FDs. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon the daemon to run select loop for * @param read_fd_set the read set * @param write_fd_set the write set * @param except_fd_set the except set * @param fd_setsize the value of FD_SETSIZE * @return #MHD_NO on serious errors, #MHD_YES on success * @sa #MHD_get_fdset2(), #MHD_OPTION_APP_FD_SETSIZE * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_from_select2 (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set, unsigned int fd_setsize); /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * This macro automatically substitutes current FD_SETSIZE value. * It is important on platforms where FD_SETSIZE can be overridden. * * You can use this function instead of #MHD_run if you called * 'select()' on the result from #MHD_get_fdset2(). File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run() is more efficient as MHD will * not have to call 'select()' again to determine which operations are * ready. * * If #MHD_get_timeout() returned #MHD_YES, than this function must be * called right after 'select()' returns regardless of detected activity * on the daemon's FDs. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon the daemon to run select loop for * @param read_fd_set the read set * @param write_fd_set the write set * @param except_fd_set the except set * @param fd_setsize the value of FD_SETSIZE * @return #MHD_NO on serious errors, #MHD_YES on success * @sa #MHD_get_fdset2(), #MHD_OPTION_APP_FD_SETSIZE * @ingroup event */ #define MHD_run_from_select(d,r,w,e) \ MHD_run_from_select2 ((d),(r),(w),(e),(unsigned int) (FD_SETSIZE)) /* **************** Connection handling functions ***************** */ /** * Get request URI path (the request target without query part). * * The value obtained by this function is the same value as @a url provided * for #MHD_AccessHandlerCallback callback, but this function also provides * the size of the string. * * This function is critically important when binary zero is allowed by daemon * option #MHD_OPTION_ALLOW_BIN_ZERO_IN_URI_PATH as this is the only way to * get the non-truncated request URI. * * Returned @a uri pointer is valid until response is started or connection * is terminated. * * @param connection the connection to URI from * @param[out] uri set to the request URI without query part, may contain * binary zeros (NUL) characters, never set to NULL on * success; can be NULL * @param[out] uri_size set to the size of the @a uri in bytes, not including * final zero-termination; can be NULL * @return #MHD_NO if failed (request is not yet processed or response has * been queued already); * #MHD_YES on success (*uri set to valid pointer) * @note Available since #MHD_VERSION 0x01000201 * @sa #MHD_OPTION_ALLOW_BIN_ZERO_IN_URI_PATH, #MHD_AccessHandlerCallback * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_get_connection_URI_path_n (struct MHD_Connection *connection, const char **uri, size_t *uri_size); /** * Get all of the headers from the request. * * @param connection connection to get values from * @param kind types of values to iterate over, can be a bitmask * @param iterator callback to call on each header; * may be NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over, * -1 if connection is NULL. * @ingroup request */ _MHD_EXTERN int MHD_get_connection_values (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIterator iterator, void *iterator_cls); /** * Get all of the headers from the request. * * @param connection connection to get values from * @param kind types of values to iterate over, can be a bitmask * @param iterator callback to call on each header; * may be NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over, * -1 if connection is NULL. * @note Available since #MHD_VERSION 0x00096400 * @ingroup request */ _MHD_EXTERN int MHD_get_connection_values_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIteratorN iterator, void *iterator_cls); /** * This function can be used to add an entry to the HTTP headers of a * connection (so that the #MHD_get_connection_values function will * return them -- and the `struct MHD_PostProcessor` will also see * them). This maybe required in certain situations (see Mantis * #1399) where (broken) HTTP implementations fail to supply values * needed by the post processor (or other parts of the application). * * This function MUST only be called from within the * #MHD_AccessHandlerCallback (otherwise, access maybe improperly * synchronized). Furthermore, the client must guarantee that the key * and value arguments are 0-terminated strings that are NOT freed * until the connection is closed. (The easiest way to do this is by * passing only arguments to permanently allocated strings.). * * @param connection the connection for which a * value should be set * @param kind kind of the value * @param key key for the value * @param value the value itself * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_set_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, const char *value); /** * This function can be used to add an arbitrary entry to connection. * This function could add entry with binary zero, which is allowed * for #MHD_GET_ARGUMENT_KIND. For other kind on entries it is * recommended to use #MHD_set_connection_value. * * This function MUST only be called from within the * #MHD_AccessHandlerCallback (otherwise, access maybe improperly * synchronized). Furthermore, the client must guarantee that the key * and value arguments are 0-terminated strings that are NOT freed * until the connection is closed. (The easiest way to do this is by * passing only arguments to permanently allocated strings.). * * @param connection the connection for which a * value should be set * @param kind kind of the value * @param key key for the value, must be zero-terminated * @param key_size number of bytes in @a key (excluding 0-terminator) * @param value the value itself, must be zero-terminated * @param value_size number of bytes in @a value (excluding 0-terminator) * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @note Available since #MHD_VERSION 0x00096400 * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_set_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size); /** * Sets the global error handler to a different implementation. * * @a cb will only be called in the case of typically fatal, serious internal * consistency issues or serious system failures like failed lock of mutex. * * These issues should only arise in the case of serious memory corruption or * similar problems with the architecture, there is no safe way to continue * even for closing of the application. * * The default implementation that is used if no panic function is set simply * prints an error message and calls `abort()`. * Alternative implementations might call `exit()` or other similar functions. * * @param cb new error handler or NULL to use default handler * @param cls passed to @a cb * @ingroup logging */ _MHD_EXTERN void MHD_set_panic_func (MHD_PanicCallback cb, void *cls); /** * Process escape sequences ('%HH') Updates val in place; the * result cannot be larger than the input. * The result is still be 0-terminated. * * @param val value to unescape (modified in the process) * @return length of the resulting val (`strlen(val)` may be * shorter afterwards due to elimination of escape sequences) */ _MHD_EXTERN size_t MHD_http_unescape (char *val); /** * Get a particular header value. If multiple * values match the kind, return any one of them. * * @param connection connection to get values from * @param kind what kind of value are we looking for * @param key the header to look for, NULL to lookup 'trailing' value without a key * @return NULL if no such item was found * @ingroup request */ _MHD_EXTERN const char * MHD_lookup_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key); /** * Get a particular header value. If multiple * values match the kind, return any one of them. * @note Since MHD_VERSION 0x00096304 * * @param connection connection to get values from * @param kind what kind of value are we looking for * @param key the header to look for, NULL to lookup 'trailing' value without a key * @param key_size the length of @a key in bytes * @param[out] value_ptr the pointer to variable, which will be set to found value, * will not be updated if key not found, * could be NULL to just check for presence of @a key * @param[out] value_size_ptr the pointer variable, which will set to found value, * will not be updated if key not found, * could be NULL * @return #MHD_YES if key is found, * #MHD_NO otherwise. * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_lookup_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char **value_ptr, size_t *value_size_ptr); /** * Queue a response to be transmitted to the client (as soon as * possible but after #MHD_AccessHandlerCallback returns). * * For any active connection this function must be called * only by #MHD_AccessHandlerCallback callback. * * For suspended connection this function can be called at any moment (this * behaviour is deprecated and will be removed!). Response will be sent * as soon as connection is resumed. * * For single thread environment, when MHD is used in "external polling" mode * (without MHD_USE_SELECT_INTERNALLY) this function can be called any * time (this behaviour is deprecated and will be removed!). * * If HTTP specifications require use no body in reply, like @a status_code with * value 1xx, the response body is automatically not sent even if it is present * in the response. No "Content-Length" or "Transfer-Encoding" headers are * generated and added. * * When the response is used to respond HEAD request or used with @a status_code * #MHD_HTTP_NOT_MODIFIED, then response body is not sent, but "Content-Length" * header is added automatically based the size of the body in the response. * If body size it set to #MHD_SIZE_UNKNOWN or chunked encoding is enforced * then "Transfer-Encoding: chunked" header (for HTTP/1.1 only) is added instead * of "Content-Length" header. For example, if response with zero-size body is * used for HEAD request, then "Content-Length: 0" is added automatically to * reply headers. * @sa #MHD_RF_HEAD_ONLY_RESPONSE * * In situations, where reply body is required, like answer for the GET request * with @a status_code #MHD_HTTP_OK, headers "Content-Length" (for known body * size) or "Transfer-Encoding: chunked" (for #MHD_SIZE_UNKNOWN with HTTP/1.1) * are added automatically. * In practice, the same response object can be used to respond to both HEAD and * GET requests. * * @param connection the connection identifying the client * @param status_code HTTP status code (i.e. #MHD_HTTP_OK) * @param response response to transmit, the NULL is tolerated * @return #MHD_NO on error (reply already sent, response is NULL), * #MHD_YES on success or if message has been queued * @ingroup response * @sa #MHD_AccessHandlerCallback */ _MHD_EXTERN enum MHD_Result MHD_queue_response (struct MHD_Connection *connection, unsigned int status_code, struct MHD_Response *response); /** * Suspend handling of network data for a given connection. * This can be used to dequeue a connection from MHD's event loop * (not applicable to thread-per-connection!) for a while. * * If you use this API in conjunction with an "internal" socket polling, * you must set the option #MHD_USE_ITC to ensure that a resumed * connection is immediately processed by MHD. * * Suspended connections continue to count against the total number of * connections allowed (per daemon, as well as per IP, if such limits * are set). Suspended connections will NOT time out; timeouts will * restart when the connection handling is resumed. While a * connection is suspended, MHD will not detect disconnects by the * client. * * The only safe way to call this function is to call it from the * #MHD_AccessHandlerCallback or #MHD_ContentReaderCallback. * * Finally, it is an API violation to call #MHD_stop_daemon while * having suspended connections (this will at least create memory and * socket leaks or lead to undefined behavior). You must explicitly * resume all connections before stopping the daemon. * * @param connection the connection to suspend * * @sa #MHD_AccessHandlerCallback */ _MHD_EXTERN void MHD_suspend_connection (struct MHD_Connection *connection); /** * Resume handling of network data for suspended connection. It is * safe to resume a suspended connection at any time. Calling this * function on a connection that was not previously suspended will * result in undefined behavior. * * If you are using this function in "external" sockets polling mode, you must * make sure to run #MHD_run() and #MHD_get_timeout() afterwards (before * again calling #MHD_get_fdset()), as otherwise the change may not be * reflected in the set returned by #MHD_get_fdset() and you may end up * with a connection that is stuck until the next network activity. * * This function may be called from any thread. In "external" sockets * polling mode it writes to the inter-thread communication channel that * #MHD_ALLOW_SUSPEND_RESUME sets up, and as #MHD_get_fdset() puts the * reading end of that channel into the read set, a call from another * thread interrupts a select()/poll() that the application is blocked * in. This matters because #MHD_get_timeout() reports no timeout at * all while every connection is suspended, so the application would * otherwise block indefinitely. The channel is level triggered, hence * a resume issued between #MHD_get_fdset() and select() cannot be lost. * * @param connection the connection to resume */ _MHD_EXTERN void MHD_resume_connection (struct MHD_Connection *connection); /* **************** Response manipulation functions ***************** */ /** * Flags for special handling of responses. */ enum MHD_ResponseFlags { /** * Default: no special flags. * @note Available since #MHD_VERSION 0x00093701 */ MHD_RF_NONE = 0, /** * Only respond in conservative (dumb) HTTP/1.0-compatible mode. * Response still use HTTP/1.1 version in header, but always close * the connection after sending the response and do not use chunked * encoding for the response. * You can also set the #MHD_RF_HTTP_1_0_SERVER flag to force * HTTP/1.0 version in the response. * Responses are still compatible with HTTP/1.1. * This option can be used to communicate with some broken client, which * does not implement HTTP/1.1 features, but advertises HTTP/1.1 support. * @note Available since #MHD_VERSION 0x00097308 */ MHD_RF_HTTP_1_0_COMPATIBLE_STRICT = 1 << 0, /** * The same as #MHD_RF_HTTP_1_0_COMPATIBLE_STRICT * @note Available since #MHD_VERSION 0x00093701 */ MHD_RF_HTTP_VERSION_1_0_ONLY = 1 << 0, /** * Only respond in HTTP 1.0-mode. * Contrary to the #MHD_RF_HTTP_1_0_COMPATIBLE_STRICT flag, the response's * HTTP version will always be set to 1.0 and keep-alive connections * will be used if explicitly requested by the client. * The "Connection:" header will be added for both "close" and "keep-alive" * connections. * Chunked encoding will not be used for the response. * Due to backward compatibility, responses still can be used with * HTTP/1.1 clients. * This option can be used to emulate HTTP/1.0 server (for response part * only as chunked encoding in requests (if any) is processed by MHD). * @note Available since #MHD_VERSION 0x00097308 */ MHD_RF_HTTP_1_0_SERVER = 1 << 1, /** * The same as #MHD_RF_HTTP_1_0_SERVER * @note Available since #MHD_VERSION 0x00096000 */ MHD_RF_HTTP_VERSION_1_0_RESPONSE = 1 << 1, /** * Disable sanity check preventing clients from manually * setting the HTTP content length option. * Allow to set several "Content-Length" headers. These headers will * be used even with replies without body. * @note Available since #MHD_VERSION 0x00096702 */ MHD_RF_INSANITY_HEADER_CONTENT_LENGTH = 1 << 2, /** * Enable sending of "Connection: keep-alive" header even for * HTTP/1.1 clients when "Keep-Alive" connection is used. * Disabled by default for HTTP/1.1 clients as per RFC. * @note Available since #MHD_VERSION 0x00097310 */ MHD_RF_SEND_KEEP_ALIVE_HEADER = 1 << 3, /** * Enable special processing of the response as body-less (with undefined * body size). No automatic "Content-Length" or "Transfer-Encoding: chunked" * headers are added when the response is used with #MHD_HTTP_NOT_MODIFIED * code or to respond to HEAD request. * The flag also allow to set arbitrary "Content-Length" by * MHD_add_response_header() function. * This flag value can be used only with responses created without body * (zero-size body). * Responses with this flag enabled cannot be used in situations where * reply body must be sent to the client. * This flag is primarily intended to be used when automatic "Content-Length" * header is undesirable in response to HEAD requests. * @note Available since #MHD_VERSION 0x00097701 */ MHD_RF_HEAD_ONLY_RESPONSE = 1 << 4 } _MHD_FIXED_FLAGS_ENUM; /** * MHD options (for future extensions). */ enum MHD_ResponseOptions { /** * End of the list of options. */ MHD_RO_END = 0 } _MHD_FIXED_ENUM; /** * Set special flags and options for a response. * * @param response the response to modify * @param flags to set for the response * @param ... #MHD_RO_END terminated list of options * @return #MHD_YES on success, #MHD_NO on error */ _MHD_EXTERN enum MHD_Result MHD_set_response_options (struct MHD_Response *response, enum MHD_ResponseFlags flags, ...); /** * Create a response object. * The response object can be extended with header information and then be used * any number of times. * * If response object is used to answer HEAD request then the body of the * response is not used, while all headers (including automatic headers) are * used. * * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown * @param block_size preferred block size for querying crc (advisory only, * MHD may still call @a crc using smaller chunks); this * is essentially the buffer size used for IO, clients * should pick a value that is appropriate for IO and * memory performance requirements * @param crc callback to use to obtain response data * @param crc_cls extra argument to @a crc * @param crfc callback to call to free @a crc_cls resources * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_callback (uint64_t size, size_t block_size, MHD_ContentReaderCallback crc, void *crc_cls, MHD_ContentReaderFreeCallback crfc); /** * Create a response object. * The response object can be extended with header information and then be used * any number of times. * * If response object is used to answer HEAD request then the body of the * response is not used, while all headers (including automatic headers) are * used. * * @param size size of the @a data portion of the response * @param data the data itself * @param must_free libmicrohttpd should free data when done * @param must_copy libmicrohttpd must make a copy of @a data * right away, the data may be released anytime after * this call returns * @return NULL on error (i.e. invalid arguments, out of memory) * @deprecated use #MHD_create_response_from_buffer instead * @ingroup response */ _MHD_DEPR_FUNC ( \ "MHD_create_response_from_data() is deprecated, use MHD_create_response_from_buffer()" \ ) \ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_data (size_t size, void *data, int must_free, int must_copy); /** * Specification for how MHD should treat the memory buffer * given for the response. * @ingroup response */ enum MHD_ResponseMemoryMode { /** * Buffer is a persistent (static/global) buffer that won't change * for at least the lifetime of the response, MHD should just use * it, not free it, not copy it, just keep an alias to it. * @ingroup response */ MHD_RESPMEM_PERSISTENT, /** * Buffer is heap-allocated with `malloc()` (or equivalent) and * should be freed by MHD after processing the response has * concluded (response reference counter reaches zero). * The more portable way to automatically free the buffer is function * MHD_create_response_from_buffer_with_free_callback() with '&free' as * crfc parameter as it does not require to use the same runtime library. * @warning It is critical to make sure that the same C-runtime library * is used by both application and MHD (especially * important for W32). * @ingroup response */ MHD_RESPMEM_MUST_FREE, /** * Buffer is in transient memory, but not on the heap (for example, * on the stack or non-`malloc()` allocated) and only valid during the * call to #MHD_create_response_from_buffer. MHD must make its * own private copy of the data for processing. * @ingroup response */ MHD_RESPMEM_MUST_COPY } _MHD_FIXED_ENUM; /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param mode flags for buffer management * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer (size_t size, void *buffer, enum MHD_ResponseMemoryMode mode); /** * Create a response object with the content of provided statically allocated * buffer used as the response body. * * The buffer must be valid for the lifetime of the response. The easiest way * to achieve this is to use a statically allocated buffer. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size the size of the data in @a buffer, can be zero * @param buffer the buffer with the data for the response body, can be NULL * if @a size is zero * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_static (size_t size, const void *buffer); /** * Create a response object with the content of provided temporal buffer * used as the response body. * * An internal copy of the buffer will be made automatically, so buffer have * to be valid only during the call of this function (as a typical example: * buffer is a local (non-static) array). * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size the size of the data in @a buffer, can be zero * @param buffer the buffer with the data for the response body, can be NULL * if @a size is zero * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_copy (size_t size, const void *buffer); /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param crfc function to call to free the @a buffer * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00096000 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_with_free_callback (size_t size, void *buffer, MHD_ContentReaderFreeCallback crfc); /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param crfc function to call to cleanup, if set to NULL then callback * is not called * @param crfc_cls an argument for @a crfc * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097302 * @note 'const' qualifier is used for @a buffer since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_with_free_callback_cls (size_t size, const void *buffer, MHD_ContentReaderFreeCallback crfc, void *crfc_cls); /** * Create a response object with the content of provided file used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd (size_t size, int fd); /** * Create a response object with the response body created by reading * the provided pipe. * * The response object can be extended with header information and * then be used ONLY ONCE. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param fd file descriptor referring to a read-end of a pipe with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097102 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_pipe (int fd); /** * Create a response object with the content of provided file used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response; * sizes larger than 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd64 (uint64_t size, int fd); /** * Create a response object with the content of provided file with * specified offset used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @param offset offset to start reading from in the file; * Be careful! `off_t` may have been compiled to be a * 64-bit variable for MHD, in which case your application * also has to be compiled using the same options! Read * the MHD manual for more details. * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_DEPR_FUNC ( \ "Function MHD_create_response_from_fd_at_offset() is deprecated, use MHD_create_response_from_fd_at_offset64()" \ ) \ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd_at_offset (size_t size, int fd, off_t offset); #if ! defined(_MHD_NO_DEPR_IN_MACRO) || defined(_MHD_NO_DEPR_FUNC) /* Substitute MHD_create_response_from_fd_at_offset64() instead of MHD_create_response_from_fd_at_offset() to minimize potential problems with different off_t sizes */ #define MHD_create_response_from_fd_at_offset(size,fd,offset) \ _MHD_DEPR_IN_MACRO ( \ "Usage of MHD_create_response_from_fd_at_offset() is deprecated, use MHD_create_response_from_fd_at_offset64()") \ MHD_create_response_from_fd_at_offset64 ((size),(fd),(offset)) #endif /* !_MHD_NO_DEPR_IN_MACRO || _MHD_NO_DEPR_FUNC */ /** * Create a response object with the content of provided file with * specified offset used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response; * sizes larger than 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @param offset offset to start reading from in the file; * reading file beyond 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd_at_offset64 (uint64_t size, int fd, uint64_t offset); /** * Create a response object with an array of memory buffers * used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param iov the array for response data buffers, an internal copy of this * will be made * @param iovcnt the number of elements in @a iov * @param free_cb the callback to clean up any data associated with @a iov when * the response is destroyed. * @param cls the argument passed to @a free_cb * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097204 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_iovec (const struct MHD_IoVec *iov, unsigned int iovcnt, MHD_ContentReaderFreeCallback free_cb, void *cls); /** * Create a response object with empty (zero size) body. * * The response object can be extended with header information and then be used * any number of times. * * This function is a faster equivalent of #MHD_create_response_from_buffer call * with zero size combined with call of #MHD_set_response_options. * * @param flags the flags for the new response object * @return NULL on error (i.e. invalid arguments, out of memory), * the pointer to the created response object otherwise * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_empty (enum MHD_ResponseFlags flags); /** * Enumeration for actions MHD should perform on the underlying socket * of the upgrade. This API is not finalized, and in particular * the final set of actions is yet to be decided. This is just an * idea for what we might want. */ enum MHD_UpgradeAction { /** * Close the socket, the application is done with it. * * Takes no extra arguments. */ MHD_UPGRADE_ACTION_CLOSE = 0, /** * Enable CORKing on the underlying socket. */ MHD_UPGRADE_ACTION_CORK_ON = 1, /** * Disable CORKing on the underlying socket. */ MHD_UPGRADE_ACTION_CORK_OFF = 2 } _MHD_FIXED_ENUM; /** * Handle given to the application to manage special * actions relating to MHD responses that "upgrade" * the HTTP protocol (i.e. to WebSockets). */ struct MHD_UpgradeResponseHandle; /** * This connection-specific callback is provided by MHD to * applications (unusual) during the #MHD_UpgradeHandler. * It allows applications to perform 'special' actions on * the underlying socket from the upgrade. * * @param urh the handle identifying the connection to perform * the upgrade @a action on. * @param action which action should be performed * @param ... arguments to the action (depends on the action) * @return #MHD_NO on error, #MHD_YES on success */ _MHD_EXTERN enum MHD_Result MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh, enum MHD_UpgradeAction action, ...); /** * Function called after a protocol "upgrade" response was sent * successfully and the socket should now be controlled by some * protocol other than HTTP. * * Any data already received on the socket will be made available in * @e extra_in. This can happen if the application sent extra data * before MHD send the upgrade response. The application should * treat data from @a extra_in as if it had read it from the socket. * * Note that the application must not close() @a sock directly, * but instead use #MHD_upgrade_action() for special operations * on @a sock. * * Data forwarding to "upgraded" @a sock will be started as soon * as this function return. * * Except when in 'thread-per-connection' mode, implementations * of this function should never block (as it will still be called * from within the main event loop). * * @param cls closure, whatever was given to #MHD_create_response_for_upgrade(). * @param connection original HTTP connection handle, * giving the function a last chance * to inspect the original HTTP request * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback` * @param extra_in if we happened to have read bytes after the * HTTP header already (because the client sent * more than the HTTP header of the request before * we sent the upgrade response), * these are the extra bytes already read from @a sock * by MHD. The application should treat these as if * it had read them from @a sock. * @param extra_in_size number of bytes in @a extra_in * @param sock socket to use for bi-directional communication * with the client. For HTTPS, this may not be a socket * that is directly connected to the client and thus certain * operations (TCP-specific setsockopt(), getsockopt(), etc.) * may not work as expected (as the socket could be from a * socketpair() or a TCP-loopback). The application is expected * to perform read()/recv() and write()/send() calls on the socket. * The application may also call shutdown(), but must not call * close() directly. * @param urh argument for #MHD_upgrade_action()s on this @a connection. * Applications must eventually use this callback to (indirectly) * perform the close() action on the @a sock. */ typedef void (*MHD_UpgradeHandler)(void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh); /** * Create a response object that can be used for 101 UPGRADE * responses, for example to implement WebSockets. After sending the * response, control over the data stream is given to the callback (which * can then, for example, start some bi-directional communication). * If the response is queued for multiple connections, the callback * will be called for each connection. The callback * will ONLY be called after the response header was successfully passed * to the OS; if there are communication errors before, the usual MHD * connection error handling code will be performed. * * Setting the correct HTTP code (i.e. MHD_HTTP_SWITCHING_PROTOCOLS) * and setting correct HTTP headers for the upgrade must be done * manually (this way, it is possible to implement most existing * WebSocket versions using this API; in fact, this API might be useful * for any protocol switch, not just WebSockets). Note that * draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this * way as the header "HTTP/1.1 101 WebSocket Protocol Handshake" * cannot be generated; instead, MHD will always produce "HTTP/1.1 101 * Switching Protocols" (if the response code 101 is used). * * As usual, the response object can be extended with header * information and then be used any number of times (as long as the * header information is not connection-specific). * * @param upgrade_handler function to call with the "upgraded" socket * @param upgrade_handler_cls closure for @a upgrade_handler * @return NULL on error (i.e. invalid arguments, out of memory) */ _MHD_EXTERN struct MHD_Response * MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler, void *upgrade_handler_cls); /** * Destroy a response object and associated resources. Note that * libmicrohttpd may keep some of the resources around if the response * is still in the queue for some clients, so the memory may not * necessarily be freed immediately. * * @param response response to destroy * @ingroup response */ _MHD_EXTERN void MHD_destroy_response (struct MHD_Response *response); /** * Add a header line to the response. * * When reply is generated with queued response, some headers are generated * automatically. Automatically generated headers are only sent to the client, * but not added back to the response object. * * The list of automatic headers: * + "Date" header is added automatically unless already set by * this function * @see #MHD_USE_SUPPRESS_DATE_NO_CLOCK * + "Content-Length" is added automatically when required, attempt to set * it manually by this function is ignored. * @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH * + "Transfer-Encoding" with value "chunked" is added automatically, * when chunked transfer encoding is used automatically. Same header with * the same value can be set manually by this function to enforce chunked * encoding, however for HTTP/1.0 clients chunked encoding will not be used * and manually set "Transfer-Encoding" header is automatically removed * for HTTP/1.0 clients * + "Connection" may be added automatically with value "Keep-Alive" (only * for HTTP/1.0 clients) or "Close". The header "Connection" with value * "Close" could be set by this function to enforce closure of * the connection after sending this response. "Keep-Alive" cannot be * enforced and will be removed automatically. * @see #MHD_RF_SEND_KEEP_ALIVE_HEADER * * Some headers are pre-processed by this function: * * "Connection" headers are combined into single header entry, value is * normilised, "Keep-Alive" tokens are removed. * * "Transfer-Encoding" header: the only one header is allowed, the only * allowed value is "chunked". * * "Date" header: the only one header is allowed, the second added header * replaces the first one. * * "Content-Length" application-defined header is not allowed. * @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH * * Headers are used in order as they were added. * * @param response the response to add a header to * @param header the header name to add, no need to be static, an internal copy * will be created automatically * @param content the header value to add, no need to be static, an internal * copy will be created automatically * @return #MHD_YES on success, * #MHD_NO on error (i.e. invalid header or content format), * or out of memory * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_add_response_header (struct MHD_Response *response, const char *header, const char *content); /** * Add a footer line to the response. * * @param response response to remove a header from * @param footer the footer to delete * @param content value to delete * @return #MHD_NO on error (i.e. invalid footer or content format). * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_add_response_footer (struct MHD_Response *response, const char *footer, const char *content); /** * Delete a header (or footer) line from the response. * * For "Connection" headers this function remove all tokens from existing * value. Successful result means that at least one token has been removed. * If all tokens are removed from "Connection" header, the empty "Connection" * header removed. * * @param response response to remove a header from * @param header the header to delete * @param content value to delete * @return #MHD_NO on error (no such header known) * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_del_response_header (struct MHD_Response *response, const char *header, const char *content); /** * Get all of the headers (and footers) added to a response. * * @param response response to query * @param iterator callback to call on each header; * may be NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over * @ingroup response */ _MHD_EXTERN int MHD_get_response_headers (struct MHD_Response *response, MHD_KeyValueIterator iterator, void *iterator_cls); /** * Get a particular header (or footer) from the response. * * @param response response to query * @param key which header to get * @return NULL if header does not exist * @ingroup response */ _MHD_EXTERN const char * MHD_get_response_header (struct MHD_Response *response, const char *key); /* ********************** PostProcessor functions ********************** */ /** * Create a `struct MHD_PostProcessor`. * * A `struct MHD_PostProcessor` can be used to (incrementally) parse * the data portion of a POST request. Note that some buggy browsers * fail to set the encoding type. If you want to support those, you * may have to call #MHD_set_connection_value with the proper encoding * type before creating a post processor (if no supported encoding * type is set, this function will fail). * * @param connection the connection on which the POST is * happening (used to determine the POST format) * @param buffer_size maximum number of bytes to use for * internal buffering (used only for the parsing, * specifically the parsing of the keys). A * tiny value (256-1024) should be sufficient. * Do NOT use a value smaller than 256. For good * performance, use 32 or 64k (i.e. 65536). * @param iter iterator to be called with the parsed data, * Must NOT be NULL. * @param iter_cls first argument to @a iter * @return NULL on error (out of memory, unsupported encoding), * otherwise a PP handle * @ingroup request */ _MHD_EXTERN struct MHD_PostProcessor * MHD_create_post_processor (struct MHD_Connection *connection, size_t buffer_size, MHD_PostDataIterator iter, void *iter_cls); /** * Parse and process POST data. Call this function when POST data is * available (usually during an #MHD_AccessHandlerCallback) with the * "upload_data" and "upload_data_size". Whenever possible, this will * then cause calls to the #MHD_PostDataIterator. * * @param pp the post processor * @param post_data @a post_data_len bytes of POST data * @param post_data_len length of @a post_data * @return #MHD_YES on success, #MHD_NO on error * (out-of-memory, iterator aborted, parse error) * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_post_process (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len); /** * Release PostProcessor resources. * * @param pp the PostProcessor to destroy * @return #MHD_YES if processing completed nicely, * #MHD_NO if there were spurious characters / formatting * problems; it is common to ignore the return * value of this function * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_destroy_post_processor (struct MHD_PostProcessor *pp); /* ********************* Digest Authentication functions *************** */ /** * Length of the binary output of the MD5 hash function. * @sa #MHD_digest_get_hash_size() * @ingroup authentication */ #define MHD_MD5_DIGEST_SIZE 16 /** * Length of the binary output of the SHA-256 hash function. * @sa #MHD_digest_get_hash_size() * @ingroup authentication */ #define MHD_SHA256_DIGEST_SIZE 32 /** * Length of the binary output of the SHA-512/256 hash function. * @warning While this value is the same as the #MHD_SHA256_DIGEST_SIZE, * the calculated digests for SHA-256 and SHA-512/256 are different. * @sa #MHD_digest_get_hash_size() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ #define MHD_SHA512_256_DIGEST_SIZE 32 /** * Base type of hash calculation. * Used as part of #MHD_DigestAuthAlgo3 values. * * @warning Not used directly by MHD API. * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestBaseAlgo { /** * Invalid hash algorithm value */ MHD_DIGEST_BASE_ALGO_INVALID = 0, /** * MD5 hash algorithm. * As specified by RFC1321 */ MHD_DIGEST_BASE_ALGO_MD5 = (1 << 0), /** * SHA-256 hash algorithm. * As specified by FIPS PUB 180-4 */ MHD_DIGEST_BASE_ALGO_SHA256 = (1 << 1), /** * SHA-512/256 hash algorithm. * As specified by FIPS PUB 180-4 */ MHD_DIGEST_BASE_ALGO_SHA512_256 = (1 << 2) } _MHD_FIXED_FLAGS_ENUM; /** * The flag indicating non-session algorithm types, * like 'MD5', 'SHA-256' or 'SHA-512-256'. * @note Available since #MHD_VERSION 0x00097701 */ #define MHD_DIGEST_AUTH_ALGO3_NON_SESSION (1 << 6) /** * The flag indicating session algorithm types, * like 'MD5-sess', 'SHA-256-sess' or 'SHA-512-256-sess'. * @note Available since #MHD_VERSION 0x00097701 */ #define MHD_DIGEST_AUTH_ALGO3_SESSION (1 << 7) /** * Digest algorithm identification * @warning Do not be confused with #MHD_DigestAuthAlgorithm, * which uses other values! * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthAlgo3 { /** * Unknown or wrong algorithm type. * Used in struct MHD_DigestAuthInfo to indicate client value that * cannot by identified. */ MHD_DIGEST_AUTH_ALGO3_INVALID = 0, /** * The 'MD5' algorithm, non-session version. */ MHD_DIGEST_AUTH_ALGO3_MD5 = MHD_DIGEST_BASE_ALGO_MD5 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION, /** * The 'MD5-sess' algorithm. * Not supported by MHD for authentication. */ MHD_DIGEST_AUTH_ALGO3_MD5_SESSION = MHD_DIGEST_BASE_ALGO_MD5 | MHD_DIGEST_AUTH_ALGO3_SESSION, /** * The 'SHA-256' algorithm, non-session version. */ MHD_DIGEST_AUTH_ALGO3_SHA256 = MHD_DIGEST_BASE_ALGO_SHA256 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION, /** * The 'SHA-256-sess' algorithm. * Not supported by MHD for authentication. */ MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION = MHD_DIGEST_BASE_ALGO_SHA256 | MHD_DIGEST_AUTH_ALGO3_SESSION, /** * The 'SHA-512-256' (SHA-512/256) algorithm. */ MHD_DIGEST_AUTH_ALGO3_SHA512_256 = MHD_DIGEST_BASE_ALGO_SHA512_256 | MHD_DIGEST_AUTH_ALGO3_NON_SESSION, /** * The 'SHA-512-256-sess' (SHA-512/256 session) algorithm. * Not supported by MHD for authentication. */ MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION = MHD_DIGEST_BASE_ALGO_SHA512_256 | MHD_DIGEST_AUTH_ALGO3_SESSION }; /** * Get digest size for specified algorithm. * * The size of the digest specifies the size of the userhash, userdigest * and other parameters which size depends on used hash algorithm. * @param algo3 the algorithm to check * @return the size of the digest (either #MHD_MD5_DIGEST_SIZE or * #MHD_SHA256_DIGEST_SIZE/MHD_SHA512_256_DIGEST_SIZE) * or zero if the input value is not supported or not valid * @sa #MHD_digest_auth_calc_userdigest() * @sa #MHD_digest_auth_calc_userhash(), #MHD_digest_auth_calc_userhash_hex() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN size_t MHD_digest_get_hash_size (enum MHD_DigestAuthAlgo3 algo3); /** * Digest algorithm identification, allow multiple selection. * * #MHD_DigestAuthAlgo3 always can be casted to #MHD_DigestAuthMultiAlgo3, but * not vice versa. * * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthMultiAlgo3 { /** * Unknown or wrong algorithm type. */ MHD_DIGEST_AUTH_MULT_ALGO3_INVALID = MHD_DIGEST_AUTH_ALGO3_INVALID, /** * The 'MD5' algorithm, non-session version. */ MHD_DIGEST_AUTH_MULT_ALGO3_MD5 = MHD_DIGEST_AUTH_ALGO3_MD5, /** * The 'MD5-sess' algorithm. * Not supported by MHD for authentication. * Reserved value. */ MHD_DIGEST_AUTH_MULT_ALGO3_MD5_SESSION = MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, /** * The 'SHA-256' algorithm, non-session version. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA256 = MHD_DIGEST_AUTH_ALGO3_SHA256, /** * The 'SHA-256-sess' algorithm. * Not supported by MHD for authentication. * Reserved value. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA256_SESSION = MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, /** * The 'SHA-512-256' (SHA-512/256) algorithm, non-session version. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256 = MHD_DIGEST_AUTH_ALGO3_SHA512_256, /** * The 'SHA-512-256-sess' (SHA-512/256 session) algorithm. * Not supported by MHD for authentication. * Reserved value. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256_SESSION = MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION, /** * SHA-256 or SHA-512/256 non-session algorithm, MHD will choose * the preferred or the matching one. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA_ANY_NON_SESSION = MHD_DIGEST_AUTH_ALGO3_SHA256 | MHD_DIGEST_AUTH_ALGO3_SHA512_256, /** * Any non-session algorithm, MHD will choose the preferred or * the matching one. */ MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION = (0x3F) | MHD_DIGEST_AUTH_ALGO3_NON_SESSION, /** * The SHA-256 or SHA-512/256 session algorithm. * Not supported by MHD. * Reserved value. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA_ANY_SESSION = MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION | MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION, /** * Any session algorithm. * Not supported by MHD. * Reserved value. */ MHD_DIGEST_AUTH_MULT_ALGO3_ANY_SESSION = (0x3F) | MHD_DIGEST_AUTH_ALGO3_SESSION, /** * The MD5 algorithm, session or non-session. * Currently supported as non-session only. */ MHD_DIGEST_AUTH_MULT_ALGO3_MD5_ANY = MHD_DIGEST_AUTH_MULT_ALGO3_MD5 | MHD_DIGEST_AUTH_MULT_ALGO3_MD5_SESSION, /** * The SHA-256 algorithm, session or non-session. * Currently supported as non-session only. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA256_ANY = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256 | MHD_DIGEST_AUTH_MULT_ALGO3_SHA256_SESSION, /** * The SHA-512/256 algorithm, session or non-session. * Currently supported as non-session only. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256_ANY = MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256 | MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256_SESSION, /** * The SHA-256 or SHA-512/256 algorithm, session or non-session. * Currently supported as non-session only. */ MHD_DIGEST_AUTH_MULT_ALGO3_SHA_ANY_ANY = MHD_DIGEST_AUTH_MULT_ALGO3_SHA_ANY_NON_SESSION | MHD_DIGEST_AUTH_MULT_ALGO3_SHA_ANY_SESSION, /** * Any algorithm, MHD will choose the preferred or the matching one. */ MHD_DIGEST_AUTH_MULT_ALGO3_ANY = (0x3F) | MHD_DIGEST_AUTH_ALGO3_NON_SESSION | MHD_DIGEST_AUTH_ALGO3_SESSION }; /** * Calculate "userhash", return it as binary data. * * The "userhash" is the hash of the string "username:realm". * * The "userhash" could be used to avoid sending username in cleartext in Digest * Authorization client's header. * * Userhash is not designed to hide the username in local database or files, * as username in cleartext is required for #MHD_digest_auth_check3() function * to check the response, but it can be used to hide username in HTTP headers. * * This function could be used when the new username is added to the username * database to save the "userhash" alongside with the username (preferably) or * when loading list of the usernames to generate the userhash for every loaded * username (this will cause delays at the start with the long lists). * * Once "userhash" is generated it could be used to identify users by clients * with "userhash" support. * Avoid repetitive usage of this function for the same username/realm * combination as it will cause excessive CPU load; save and re-use the result * instead. * * @param algo3 the algorithm for userhash calculations * @param username the username * @param realm the realm * @param[out] userhash_bin the output buffer for userhash as binary data; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3) bytes of userhash * upon return * @param bin_buf_size the size of the @a userhash_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3) bytes long * @return MHD_YES on success, * MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH) * @sa #MHD_digest_auth_calc_userhash_hex() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userhash (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, void *userhash_bin, size_t bin_buf_size); /** * Calculate "userhash", return it as hexadecimal string. * * The "userhash" is the hash of the string "username:realm". * * The "userhash" could be used to avoid sending username in cleartext in Digest * Authorization client's header. * * Userhash is not designed to hide the username in local database or files, * as username in cleartext is required for #MHD_digest_auth_check3() function * to check the response, but it can be used to hide username in HTTP headers. * * This function could be used when the new username is added to the username * database to save the "userhash" alongside with the username (preferably) or * when loading list of the usernames to generate the userhash for every loaded * username (this will cause delays at the start with the long lists). * * Once "userhash" is generated it could be used to identify users by clients * with "userhash" support. * Avoid repetitive usage of this function for the same username/realm * combination as it will cause excessive CPU load; save and re-use the result * instead. * * @param algo3 the algorithm for userhash calculations * @param username the username * @param realm the realm * @param[out] userhash_hex the output buffer for userhash as hex string; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3)*2 chars long * userhash zero-terminated string * @param bin_buf_size the size of the @a userhash_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3)*2+1 chars long * @return MHD_YES on success, * MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH). * @sa #MHD_digest_auth_calc_userhash() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userhash_hex (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, char *userhash_hex, size_t hex_buf_size); /** * The type of username used by client in Digest Authorization header * * Values are sorted so simplified checks could be used. * For example: * * (value <= MHD_DIGEST_AUTH_UNAME_TYPE_INVALID) is true if no valid username * is provided by the client * * (value >= MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH) is true if username is * provided in any form * * (value >= MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD) is true if username is * provided in clear text (no userhash matching is needed) * * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthUsernameType { /** * No username parameter in in Digest Authorization header. * This should be treated as an error. */ MHD_DIGEST_AUTH_UNAME_TYPE_MISSING = 0, /** * The 'username' parameter is used to specify the username. */ MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD = (1 << 2), /** * The username is specified by 'username*' parameter with * the extended notation (see RFC 5987 #section-3.2.1). * The only difference between standard and extended types is * the way how username value is encoded in the header. */ MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED = (1 << 3), /** * The username provided in form of 'userhash' as * specified by RFC 7616 #section-3.4.4. * @sa #MHD_digest_auth_calc_userhash_hex(), #MHD_digest_auth_calc_userhash() */ MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH = (1 << 1), /** * The invalid combination of username parameters are used by client. * Either: * * both 'username' and 'username*' are used * * 'username*' is used with 'userhash=true' * * 'username*' used with invalid extended notation * * 'username' is not hexadecimal string, while 'userhash' set to 'true' */ MHD_DIGEST_AUTH_UNAME_TYPE_INVALID = (1 << 0) } _MHD_FIXED_ENUM; /** * The QOP ('quality of protection') types. * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthQOP { /** * Invalid/unknown QOP. * Used in struct MHD_DigestAuthInfo to indicate client value that * cannot by identified. */ MHD_DIGEST_AUTH_QOP_INVALID = 0, /** * No QOP parameter. * As described in old RFC 2069 original specification. * This mode is not allowed by latest RFCs and should be used only to * communicate with clients that do not support more modern modes (with QOP * parameter). * This mode is less secure than other modes and inefficient. */ MHD_DIGEST_AUTH_QOP_NONE = 1 << 0, /** * The 'auth' QOP type. */ MHD_DIGEST_AUTH_QOP_AUTH = 1 << 1, /** * The 'auth-int' QOP type. * Not supported by MHD for authentication. */ MHD_DIGEST_AUTH_QOP_AUTH_INT = 1 << 2 } _MHD_FIXED_FLAGS_ENUM; /** * The QOP ('quality of protection') types, multiple selection. * * #MHD_DigestAuthQOP always can be casted to #MHD_DigestAuthMultiQOP, but * not vice versa. * * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthMultiQOP { /** * Invalid/unknown QOP. */ MHD_DIGEST_AUTH_MULT_QOP_INVALID = MHD_DIGEST_AUTH_QOP_INVALID, /** * No QOP parameter. * As described in old RFC 2069 original specification. * This mode is not allowed by latest RFCs and should be used only to * communicate with clients that do not support more modern modes (with QOP * parameter). * This mode is less secure than other modes and inefficient. */ MHD_DIGEST_AUTH_MULT_QOP_NONE = MHD_DIGEST_AUTH_QOP_NONE, /** * The 'auth' QOP type. */ MHD_DIGEST_AUTH_MULT_QOP_AUTH = MHD_DIGEST_AUTH_QOP_AUTH, /** * The 'auth-int' QOP type. * Not supported by MHD. * Reserved value. */ MHD_DIGEST_AUTH_MULT_QOP_AUTH_INT = MHD_DIGEST_AUTH_QOP_AUTH_INT, /** * The 'auth' QOP type OR the old RFC2069 (no QOP) type. * In other words: any types except 'auth-int'. * RFC2069-compatible mode is allowed, thus this value should be used only * when it is really necessary. */ MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT = MHD_DIGEST_AUTH_QOP_NONE | MHD_DIGEST_AUTH_QOP_AUTH, /** * Any 'auth' QOP type ('auth' or 'auth-int'). * Currently supported as 'auth' QOP type only. */ MHD_DIGEST_AUTH_MULT_QOP_AUTH_ANY = MHD_DIGEST_AUTH_QOP_AUTH | MHD_DIGEST_AUTH_QOP_AUTH_INT } _MHD_FIXED_ENUM; /** * The invalid value of 'nc' parameter in client Digest Authorization header. * @note Available since #MHD_VERSION 0x00097701 */ #define MHD_DIGEST_AUTH_INVALID_NC_VALUE (0) /** * Information from Digest Authorization client's header. * * All buffers pointed by any struct members are freed when #MHD_free() is * called for pointer to this structure. * * Application may modify buffers as needed until #MHD_free() is called for * pointer to this structure * @note Available since #MHD_VERSION 0x00097701 */ struct MHD_DigestAuthInfo { /** * The algorithm as defined by client. * Set automatically to MD5 if not specified by client. * @warning Do not be confused with #MHD_DigestAuthAlgorithm, * which uses other values! */ enum MHD_DigestAuthAlgo3 algo3; /** * The type of username used by client. */ enum MHD_DigestAuthUsernameType uname_type; /** * The username string. * Used only if username type is standard or extended, always NULL otherwise. * If extended notation is used, this string is pct-decoded string * with charset and language tag removed (i.e. it is original username * extracted from the extended notation). * When userhash is used by the client, this member is NULL and * @a userhash_hex and @a userhash_bin are set. * The buffer pointed by the @a username becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *username; /** * The length of the @a username. * When the @a username is NULL, this member is always zero. */ size_t username_len; /** * The userhash string. * Valid only if username type is userhash. * This is unqoted string without decoding of the hexadecimal * digits (as provided by the client). * The buffer pointed by the @a userhash_hex becomes invalid when the pointer * to the structure is freed by #MHD_free(). * @sa #MHD_digest_auth_calc_userhash_hex() */ char *userhash_hex; /** * The length of the @a userhash_hex in characters. * The valid size should be #MHD_digest_get_hash_size(algo3) * 2 characters. * When the @a userhash_hex is NULL, this member is always zero. */ size_t userhash_hex_len; /** * The userhash decoded to binary form. * Used only if username type is userhash, always NULL otherwise. * When not NULL, this points to binary sequence @a userhash_hex_len /2 bytes * long. * The valid size should be #MHD_digest_get_hash_size(algo3) bytes. * The buffer pointed by the @a userhash_bin becomes invalid when the pointer * to the structure is freed by #MHD_free(). * @warning This is a binary data, no zero termination. * @warning To avoid buffer overruns, always check the size of the data before * use, because @a userhash_bin can point even to zero-sized * data. * @sa #MHD_digest_auth_calc_userhash() */ uint8_t *userhash_bin; /** * The 'opaque' parameter value, as specified by client. * NULL if not specified by client. * The buffer pointed by the @a opaque becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *opaque; /** * The length of the @a opaque. * When the @a opaque is NULL, this member is always zero. */ size_t opaque_len; /** * The 'realm' parameter value, as specified by client. * NULL if not specified by client. * The buffer pointed by the @a realm becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *realm; /** * The length of the @a realm. * When the @a realm is NULL, this member is always zero. */ size_t realm_len; /** * The 'qop' parameter value. */ enum MHD_DigestAuthQOP qop; /** * The length of the 'cnonce' parameter value, including possible * backslash-escape characters. * 'cnonce' is used in hash calculation, which is CPU-intensive procedure. * An application may want to reject too large cnonces to limit the CPU load. * A few kilobytes is a reasonable limit, typically cnonce is just 32-160 * characters long. */ size_t cnonce_len; /** * The nc parameter value. * Can be used by application to limit the number of nonce re-uses. If @a nc * is higher than application wants to allow, then "auth required" response * with 'stale=true' could be used to force client to retry with the fresh * 'nonce'. * If not specified by client or does not have hexadecimal digits only, the * value is #MHD_DIGEST_AUTH_INVALID_NC_VALUE. */ uint32_t nc; }; /** * Get information about Digest Authorization client's header. * * @param connection The MHD connection structure * @return NULL if no valid Digest Authorization header is used in the request; * a pointer to the structure with information if the valid request * header found, free using #MHD_free(). * @sa #MHD_digest_auth_get_username3() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_DigestAuthInfo * MHD_digest_auth_get_request_info3 (struct MHD_Connection *connection); /** * Information from Digest Authorization client's header. * * All buffers pointed by any struct members are freed when #MHD_free() is * called for pointer to this structure. * * Application may modify buffers as needed until #MHD_free() is called for * pointer to this structure * @note Available since #MHD_VERSION 0x00097701 */ struct MHD_DigestAuthUsernameInfo { /** * The algorithm as defined by client. * Set automatically to MD5 if not specified by client. * @warning Do not be confused with #MHD_DigestAuthAlgorithm, * which uses other values! */ enum MHD_DigestAuthAlgo3 algo3; /** * The type of username used by client. * The 'invalid' and 'missing' types are not used in this structure, * instead NULL is returned by #MHD_digest_auth_get_username3(). */ enum MHD_DigestAuthUsernameType uname_type; /** * The username string. * Used only if username type is standard or extended, always NULL otherwise. * If extended notation is used, this string is pct-decoded string * with charset and language tag removed (i.e. it is original username * extracted from the extended notation). * When userhash is used by the client, this member is NULL and * @a userhash_hex and @a userhash_bin are set. * The buffer pointed by the @a username becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *username; /** * The length of the @a username. * When the @a username is NULL, this member is always zero. */ size_t username_len; /** * The userhash string. * Valid only if username type is userhash. * This is unqoted string without decoding of the hexadecimal * digits (as provided by the client). * The buffer pointed by the @a userhash_hex becomes invalid when the pointer * to the structure is freed by #MHD_free(). * @sa #MHD_digest_auth_calc_userhash_hex() */ char *userhash_hex; /** * The length of the @a userhash_hex in characters. * The valid size should be #MHD_digest_get_hash_size(algo3) * 2 characters. * When the @a userhash_hex is NULL, this member is always zero. */ size_t userhash_hex_len; /** * The userhash decoded to binary form. * Used only if username type is userhash, always NULL otherwise. * When not NULL, this points to binary sequence @a userhash_hex_len /2 bytes * long. * The valid size should be #MHD_digest_get_hash_size(algo3) bytes. * The buffer pointed by the @a userhash_bin becomes invalid when the pointer * to the structure is freed by #MHD_free(). * @warning This is a binary data, no zero termination. * @warning To avoid buffer overruns, always check the size of the data before * use, because @a userhash_bin can point even to zero-sized * data. * @sa #MHD_digest_auth_calc_userhash() */ uint8_t *userhash_bin; }; /** * Get the username from Digest Authorization client's header. * * @param connection The MHD connection structure * @return NULL if no valid Digest Authorization header is used in the request, * or no username parameter is present in the header, or username is * provided incorrectly by client (see description for * #MHD_DIGEST_AUTH_UNAME_TYPE_INVALID); * a pointer structure with information if the valid request header * found, free using #MHD_free(). * @sa #MHD_digest_auth_get_request_info3() provides more complete information * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_DigestAuthUsernameInfo * MHD_digest_auth_get_username3 (struct MHD_Connection *connection); /** * The result of digest authentication of the client. * * All error values are zero or negative. * * @note Available since #MHD_VERSION 0x00097701 */ enum MHD_DigestAuthResult { /** * Authentication OK. */ MHD_DAUTH_OK = 1, /** * General error, like "out of memory". */ MHD_DAUTH_ERROR = 0, /** * No "Authorization" header or wrong format of the header. * Also may be returned if required parameters in client Authorisation header * are missing or broken (in invalid format). */ MHD_DAUTH_WRONG_HEADER = -1, /** * Wrong 'username'. */ MHD_DAUTH_WRONG_USERNAME = -2, /** * Wrong 'realm'. */ MHD_DAUTH_WRONG_REALM = -3, /** * Wrong 'URI' (or URI parameters). */ MHD_DAUTH_WRONG_URI = -4, /** * Wrong 'qop'. */ MHD_DAUTH_WRONG_QOP = -5, /** * Wrong 'algorithm'. */ MHD_DAUTH_WRONG_ALGO = -6, /** * Too large (>64 KiB) Authorization parameter value. */ MHD_DAUTH_TOO_LARGE = -15, /* The different form of naming is intentionally used for the results below, * as they are more important */ /** * The 'nonce' is too old. Suggest the client to retry with the same * username and password to get the fresh 'nonce'. * The validity of the 'nonce' may be not checked. */ MHD_DAUTH_NONCE_STALE = -17, /** * The 'nonce' was generated by MHD for other conditions. * This value is only returned if #MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE * is set to anything other than #MHD_DAUTH_BIND_NONCE_NONE. * The interpretation of this code could be different. For example, if * #MHD_DAUTH_BIND_NONCE_URI is set and client just used the same 'nonce' for * another URI, the code could be handled as #MHD_DAUTH_NONCE_STALE as * RFCs allow nonces re-using for other URIs in the same "protection * space". However, if only #MHD_DAUTH_BIND_NONCE_CLIENT_IP bit is set and * it is know that clients have fixed IP addresses, this return code could * be handled like #MHD_DAUTH_NONCE_WRONG. */ MHD_DAUTH_NONCE_OTHER_COND = -18, /** * The 'nonce' is wrong. May indicate an attack attempt. */ MHD_DAUTH_NONCE_WRONG = -33, /** * The 'response' is wrong. Typically it means that wrong password used. * May indicate an attack attempt. */ MHD_DAUTH_RESPONSE_WRONG = -34 }; /** * Authenticates the authorization header sent by the client. * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request a new nonce must * be generated and client repeats all requests twice (first time to get a new * nonce and second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param password the password matching the @a username (and the @a realm) * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * if zero is specified then daemon default value is used. * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * if zero is specified then daemon default value is used. * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm used * by the client is not allowed by this parameter * @return #MHD_DAUTH_OK if authenticated, * the error code otherwise * @note Available since #MHD_VERSION 0x00097708 * @ingroup authentication */ _MHD_EXTERN enum MHD_DigestAuthResult MHD_digest_auth_check3 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3); /** * Calculate userdigest, return it as a binary data. * * The "userdigest" is the hash of the "username:realm:password" string. * * The "userdigest" can be used to avoid storing the password in clear text * in database/files * * This function is designed to improve security of stored credentials, * the "userdigest" does not improve security of the authentication process. * * The results can be used to store username & userdigest pairs instead of * username & password pairs. To further improve security, application may * store username & userhash & userdigest triplets. * * @param algo3 the digest algorithm * @param username the username * @param realm the realm * @param password the password * @param[out] userdigest_bin the output buffer for userdigest; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3) bytes of * userdigest upon return * @param bin_buf_size the size of the @a userdigest_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3) bytes long * @return MHD_YES on success, * MHD_NO if @a userdigest_bin is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH). * @sa #MHD_digest_auth_check_digest3() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userdigest (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, const char *password, void *userdigest_bin, size_t bin_buf_size); /** * Authenticates the authorization header sent by the client by using * hash of "username:realm:password". * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request a new nonce must * be generated and client repeats all requests twice (first time to get a new * nonce and second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param userdigest the precalculated binary hash of the string * "username:realm:password", * see #MHD_digest_auth_calc_userdigest() * @param userdigest_size the size of the @a userdigest in bytes, must match the * hashing algorithm (see #MHD_MD5_DIGEST_SIZE, * #MHD_SHA256_DIGEST_SIZE, #MHD_SHA512_256_DIGEST_SIZE, * #MHD_digest_get_hash_size()) * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * if zero is specified then daemon default value is used. * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * if zero is specified then daemon default value is used. * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm used * by the client is not allowed by this parameter; * more than one base algorithms (MD5, SHA-256, SHA-512/256) * cannot be used at the same time for this function * as @a userdigest must match specified algorithm * @return #MHD_DAUTH_OK if authenticated, * the error code otherwise * @sa #MHD_digest_auth_calc_userdigest() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_DigestAuthResult MHD_digest_auth_check_digest3 (struct MHD_Connection *connection, const char *realm, const char *username, const void *userdigest, size_t userdigest_size, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3); /** * Queues a response to request authentication from the client * * This function modifies provided @a response. The @a response must not be * reused and should be destroyed (by #MHD_destroy_response()) after call of * this function. * * If @a mqop allows both RFC 2069 (MHD_DIGEST_AUTH_QOP_NONE) and QOP with * value, then response is formed like if MHD_DIGEST_AUTH_QOP_NONE bit was * not set, because such response should be backward-compatible with RFC 2069. * * If @a mqop allows only MHD_DIGEST_AUTH_MULT_QOP_NONE, then the response is * formed in strict accordance with RFC 2069 (no 'qop', no 'userhash', no * 'charset'). For better compatibility with clients, it is recommended (but * not required) to set @a domain to NULL in this mode. * * @param connection the MHD connection structure * @param realm the realm presented to the client * @param opaque the string for opaque value, can be NULL, but NULL is * not recommended for better compatibility with clients; * the recommended format is hex or Base64 encoded string * @param domain the optional space-separated list of URIs for which the * same authorisation could be used, URIs can be in form * "path-absolute" (the path for the same host with initial slash) * or in form "absolute-URI" (the full path with protocol), in * any case client may assume that URI is in the same "protection * space" if it starts with any of values specified here; * could be NULL (clients typically assume that the same * credentials could be used for any URI on the same host); * this list provides information for the client only and does * not actually restrict anything on the server side * @param response the reply to send; should contain the "access denied" * body; * note: this function sets the "WWW Authenticate" header and * the caller should not set this header; * the NULL is tolerated * @param signal_stale if set to #MHD_YES then indication of stale nonce used in * the client's request is signalled by adding 'stale=true' * to the authentication header, this instructs the client * to retry immediately with the new nonce and the same * credentials, without asking user for the new password * @param mqop the QOP to use * @param malgo3 digest algorithm to use; if several algorithms are allowed * then MD5 is preferred (currently, may be changed in next * versions) * @param userhash_support if set to non-zero value (#MHD_YES) then support of * userhash is indicated, allowing client to provide * hash("username:realm") instead of the username in * clear text; * note that clients are allowed to provide the username * in cleartext even if this parameter set to non-zero; * when userhash is used, application must be ready to * identify users by provided userhash value instead of * username; see #MHD_digest_auth_calc_userhash() and * #MHD_digest_auth_calc_userhash_hex() * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is * added, indicating for the client that UTF-8 encoding for * the username is preferred * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_required_response3 (struct MHD_Connection *connection, const char *realm, const char *opaque, const char *domain, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 algo, int userhash_support, int prefer_utf8); /** * Constant to indicate that the nonce of the provided * authentication code was wrong. * Used as return code by #MHD_digest_auth_check(), #MHD_digest_auth_check2(), * #MHD_digest_auth_check_digest(), #MHD_digest_auth_check_digest2(). * @ingroup authentication */ #define MHD_INVALID_NONCE -1 /** * Get the username from the authorization header sent by the client * * This function supports username in standard and extended notations. * "userhash" is not supported by this function. * * @param connection The MHD connection structure * @return NULL if no username could be found, username provided as * "userhash", extended notation broken or memory allocation error * occurs; * a pointer to the username if found, free using #MHD_free(). * @warning Returned value must be freed by #MHD_free(). * @sa #MHD_digest_auth_get_username3() * @ingroup authentication */ _MHD_EXTERN char * MHD_digest_auth_get_username (struct MHD_Connection *connection); /** * Which digest algorithm should MHD use for HTTP digest authentication? * Used as parameter for #MHD_digest_auth_check2(), * #MHD_digest_auth_check_digest2(), #MHD_queue_auth_fail_response2(). */ enum MHD_DigestAuthAlgorithm { /** * MHD should pick (currently defaults to MD5). */ MHD_DIGEST_ALG_AUTO = 0, /** * Force use of MD5. */ MHD_DIGEST_ALG_MD5, /** * Force use of SHA-256. */ MHD_DIGEST_ALG_SHA256 } _MHD_FIXED_ENUM; /** * Authenticates the authorization header sent by the client. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param password The password used in the authentication * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @param algo digest algorithms allowed for verification * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096200 * @deprecated use MHD_digest_auth_check3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check2 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo); /** * Authenticates the authorization header sent by the client. * Uses #MHD_DIGEST_ALG_MD5 (for now, for backwards-compatibility). * Note that this MAY change to #MHD_DIGEST_ALG_AUTO in the future. * If you want to be sure you get MD5, use #MHD_digest_auth_check2() * and specify MD5 explicitly. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param password The password used in the authentication * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @deprecated use MHD_digest_auth_check3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout); /** * Authenticates the authorization header sent by the client. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param digest An `unsigned char *' pointer to the binary MD5 sum * for the precalculated hash value "username:realm:password" * of @a digest_size bytes * @param digest_size number of bytes in @a digest (size must match @a algo!) * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @param algo digest algorithm allowed for verification; exactly one * algorithm must be named, as @a digest is a hash produced by one * specific algorithm. #MHD_DIGEST_ALG_AUTO cannot be used here * and makes this function return #MHD_NO * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096200 * @deprecated use MHD_digest_auth_check_digest3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check_digest2 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, size_t digest_size, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo); /** * Authenticates the authorization header sent by the client * Uses #MHD_DIGEST_ALG_MD5 (required, as @a digest is of fixed * size). * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param digest An `unsigned char *' pointer to the binary hash * for the precalculated hash value "username:realm:password"; * length must be #MHD_MD5_DIGEST_SIZE bytes * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096000 * @deprecated use #MHD_digest_auth_check_digest3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check_digest (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t digest[MHD_MD5_DIGEST_SIZE], unsigned int nonce_timeout); /** * Queues a response to request authentication from the client * * This function modifies provided @a response. The @a response must not be * reused and should be destroyed after call of this function. * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param opaque string to user for opaque value * @param response reply to send; should contain the "access denied" * body; note that this function will set the "WWW Authenticate" * header and that the caller should not do this; the NULL is tolerated * @param signal_stale #MHD_YES if the nonce is stale to add * 'stale=true' to the authentication header * @param algo digest algorithm to use * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00096200 * @deprecated use MHD_queue_auth_required_response3() * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_fail_response2 (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthAlgorithm algo); /** * Queues a response to request authentication from the client. * For now uses MD5 (for backwards-compatibility). Still, if you * need to be sure, use #MHD_queue_auth_fail_response2(). * * This function modifies provided @a response. The @a response must not be * reused and should be destroyed after call of this function. * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param opaque string to user for opaque value * @param response reply to send; should contain the "access denied" * body; note that this function will set the "WWW Authenticate" * header and that the caller should not do this; the NULL is tolerated * @param signal_stale #MHD_YES if the nonce is stale to add * 'stale=true' to the authentication header * @return #MHD_YES on success, #MHD_NO otherwise * @deprecated use MHD_queue_auth_required_response3() * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_fail_response (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale); /* ********************* Basic Authentication functions *************** */ /** * Information decoded from Basic Authentication client's header. * * The username and the password are technically allowed to have binary zeros, * username_len and password_len could be used to detect such situations. * * The buffers pointed by username and password members are freed * when #MHD_free() is called for pointer to this structure. * * Application may modify buffers as needed until #MHD_free() is called for * pointer to this structure */ struct MHD_BasicAuthInfo { /** * The username, cannot be NULL. * The buffer pointed by the @a username becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *username; /** * The length of the @a username, not including zero-termination */ size_t username_len; /** * The password, may be NULL if password is not encoded by the client. * The buffer pointed by the @a password becomes invalid when the pointer * to the structure is freed by #MHD_free(). */ char *password; /** * The length of the @a password, not including zero-termination; * when the @a password is NULL, the length is always zero. */ size_t password_len; }; /** * Get the username and password from the Basic Authorisation header * sent by the client * * @param connection the MHD connection structure * @return NULL if no valid Basic Authentication header is present in * current request, or * pointer to structure with username and password, which must be * freed by #MHD_free(). * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_BasicAuthInfo * MHD_basic_auth_get_username_password3 (struct MHD_Connection *connection); /** * Queues a response to request basic authentication from the client. * * The given response object is expected to include the payload for * the response; the "WWW-Authenticate" header will be added and the * response queued with the 'UNAUTHORIZED' status code. * * See RFC 7617#section-2 for details. * * The @a response is modified by this function. The modified response object * can be used to respond subsequent requests by #MHD_queue_response() * function with status code #MHD_HTTP_UNAUTHORIZED and must not be used again * with MHD_queue_basic_auth_required_response3() function. The response could * be destroyed right after call of this function. * * @param connection the MHD connection structure * @param realm the realm presented to the client * @param prefer_utf8 if not set to #MHD_NO, parameter'charset="UTF-8"' will * be added, indicating for client that UTF-8 encoding * is preferred * @param response the response object to modify and queue; the NULL * is tolerated * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00097704 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_basic_auth_required_response3 (struct MHD_Connection *connection, const char *realm, int prefer_utf8, struct MHD_Response *response); /** * Get the username and password from the basic authorization header sent by the client * * @param connection The MHD connection structure * @param[out] password a pointer for the password, free using #MHD_free(). * @return NULL if no username could be found, a pointer * to the username if found, free using #MHD_free(). * @deprecated use #MHD_basic_auth_get_username_password3() * @ingroup authentication */ _MHD_EXTERN char * MHD_basic_auth_get_username_password (struct MHD_Connection *connection, char **password); /** * Queues a response to request basic authentication from the client * The given response object is expected to include the payload for * the response; the "WWW-Authenticate" header will be added and the * response queued with the 'UNAUTHORIZED' status code. * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param response response object to modify and queue; the NULL is tolerated * @return #MHD_YES on success, #MHD_NO otherwise * @deprecated use MHD_queue_basic_auth_required_response3() * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_basic_auth_fail_response (struct MHD_Connection *connection, const char *realm, struct MHD_Response *response); /* ********************** generic query functions ********************** */ /** * Obtain information about the given connection. * The returned pointer is invalidated with the next call of this function or * when the connection is closed. * * @param connection what connection to get information about * @param info_type what information is desired? * @param ... depends on @a info_type * @return NULL if this information is not available * (or if the @a info_type is unknown) * @ingroup specialized */ _MHD_EXTERN const union MHD_ConnectionInfo * MHD_get_connection_info (struct MHD_Connection *connection, enum MHD_ConnectionInfoType info_type, ...); /** * MHD connection options. Given to #MHD_set_connection_option to * set custom options for a particular connection. */ enum MHD_CONNECTION_OPTION { /** * Set a custom timeout for the given connection. Specified * as the number of seconds, given as an `unsigned int`. Use * zero for no timeout. * If timeout was set to zero (or unset) before, setup of new value by * MHD_set_connection_option() will reset timeout timer. * Values larger than (UINT64_MAX / 2000 - 1) will * be clipped to this number. */ MHD_CONNECTION_OPTION_TIMEOUT } _MHD_FIXED_ENUM; /** * Set a custom option for the given connection, overriding defaults. * * @param connection connection to modify * @param option option to set * @param ... arguments to the option, depending on the option type * @return #MHD_YES on success, #MHD_NO if setting the option failed * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_set_connection_option (struct MHD_Connection *connection, enum MHD_CONNECTION_OPTION option, ...); /** * Information about an MHD daemon. */ union MHD_DaemonInfo { /** * Size of the key, no longer supported. * @deprecated */ size_t key_size; /** * Size of the mac key, no longer supported. * @deprecated */ size_t mac_key_size; /** * Socket, returned for #MHD_DAEMON_INFO_LISTEN_FD. */ MHD_socket listen_fd; /** * Bind port number, returned for #MHD_DAEMON_INFO_BIND_PORT. */ uint16_t port; /** * epoll FD, returned for #MHD_DAEMON_INFO_EPOLL_FD. */ int epoll_fd; /** * Number of active connections, for #MHD_DAEMON_INFO_CURRENT_CONNECTIONS. */ unsigned int num_connections; /** * Combination of #MHD_FLAG values, for #MHD_DAEMON_INFO_FLAGS. * This value is actually a bitfield. * Note: flags may differ from original 'flags' specified for * daemon, especially if #MHD_USE_AUTO was set. */ enum MHD_FLAG flags; }; /** * Obtain information about the given daemon. * The returned pointer is invalidated with the next call of this function or * when the daemon is stopped. * * @param daemon what daemon to get information about * @param info_type what information is desired? * @param ... depends on @a info_type * @return NULL if this information is not available * (or if the @a info_type is unknown) * @ingroup specialized */ _MHD_EXTERN const union MHD_DaemonInfo * MHD_get_daemon_info (struct MHD_Daemon *daemon, enum MHD_DaemonInfoType info_type, ...); /** * Obtain the version of this library * * @return static version string, e.g. "0.9.9" * @ingroup specialized */ _MHD_EXTERN const char * MHD_get_version (void); /** * Obtain the version of this library as a binary value. * * @return version binary value, e.g. "0x00090900" (#MHD_VERSION of * compiled MHD binary) * @note Available since #MHD_VERSION 0x00097601 * @ingroup specialized */ _MHD_EXTERN uint32_t MHD_get_version_bin (void); /** * Types of information about MHD features, * used by #MHD_is_feature_supported(). */ enum MHD_FEATURE { /** * Get whether messages are supported. If supported then in debug * mode messages can be printed to stderr or to external logger. */ MHD_FEATURE_MESSAGES = 1, /** * Get whether HTTPS is supported. If supported then flag * #MHD_USE_TLS and options #MHD_OPTION_HTTPS_MEM_KEY, * #MHD_OPTION_HTTPS_MEM_CERT, #MHD_OPTION_HTTPS_MEM_TRUST, * #MHD_OPTION_HTTPS_MEM_DHPARAMS, #MHD_OPTION_HTTPS_CRED_TYPE, * #MHD_OPTION_HTTPS_PRIORITIES can be used. */ MHD_FEATURE_TLS = 2, MHD_FEATURE_SSL = 2, /** * Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK is * supported. */ MHD_FEATURE_HTTPS_CERT_CALLBACK = 3, /** * Get whether IPv6 is supported. If supported then flag * #MHD_USE_IPv6 can be used. */ MHD_FEATURE_IPv6 = 4, /** * Get whether IPv6 without IPv4 is supported. If not supported * then IPv4 is always enabled in IPv6 sockets and * flag #MHD_USE_DUAL_STACK is always used when #MHD_USE_IPv6 is * specified. */ MHD_FEATURE_IPv6_ONLY = 5, /** * Get whether `poll()` is supported. If supported then flag * #MHD_USE_POLL can be used. */ MHD_FEATURE_POLL = 6, /** * Get whether `epoll()` is supported. If supported then Flags * #MHD_USE_EPOLL and * #MHD_USE_EPOLL_INTERNAL_THREAD can be used. */ MHD_FEATURE_EPOLL = 7, /** * Get whether shutdown on listen socket to signal other * threads is supported. If not supported flag * #MHD_USE_ITC is automatically forced. */ MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET = 8, /** * Get whether socketpair is used internally instead of pipe to * signal other threads. */ MHD_FEATURE_SOCKETPAIR = 9, /** * Get whether TCP Fast Open is supported. If supported then * flag #MHD_USE_TCP_FASTOPEN and option * #MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE can be used. */ MHD_FEATURE_TCP_FASTOPEN = 10, /** * Get whether HTTP Basic authorization is supported. If supported * then functions #MHD_basic_auth_get_username_password and * #MHD_queue_basic_auth_fail_response can be used. */ MHD_FEATURE_BASIC_AUTH = 11, /** * Get whether HTTP Digest authorization is supported. If * supported then options #MHD_OPTION_DIGEST_AUTH_RANDOM, * #MHD_OPTION_NONCE_NC_SIZE and * #MHD_digest_auth_check() can be used. */ MHD_FEATURE_DIGEST_AUTH = 12, /** * Get whether postprocessor is supported. If supported then * functions #MHD_create_post_processor(), #MHD_post_process() and * #MHD_destroy_post_processor() can * be used. */ MHD_FEATURE_POSTPROCESSOR = 13, /** * Get whether password encrypted private key for HTTPS daemon is * supported. If supported then option * ::MHD_OPTION_HTTPS_KEY_PASSWORD can be used. */ MHD_FEATURE_HTTPS_KEY_PASSWORD = 14, /** * Get whether reading files beyond 2 GiB boundary is supported. * If supported then #MHD_create_response_from_fd(), * #MHD_create_response_from_fd64 #MHD_create_response_from_fd_at_offset() * and #MHD_create_response_from_fd_at_offset64() can be used with sizes and * offsets larger than 2 GiB. If not supported value of size+offset is * limited to 2 GiB. */ MHD_FEATURE_LARGE_FILE = 15, /** * Get whether MHD set names on generated threads. */ MHD_FEATURE_THREAD_NAMES = 16, MHD_THREAD_NAMES = 16, /** * Get whether HTTP "Upgrade" is supported. * If supported then #MHD_ALLOW_UPGRADE, #MHD_upgrade_action() and * #MHD_create_response_for_upgrade() can be used. */ MHD_FEATURE_UPGRADE = 17, /** * Get whether it's safe to use same FD for multiple calls of * #MHD_create_response_from_fd() and whether it's safe to use single * response generated by #MHD_create_response_from_fd() with multiple * connections at same time. * If #MHD_is_feature_supported() return #MHD_NO for this feature then * usage of responses with same file FD in multiple parallel threads may * results in incorrect data sent to remote client. * It's always safe to use same file FD in multiple responses if MHD * is run in any single thread mode. */ MHD_FEATURE_RESPONSES_SHARED_FD = 18, /** * Get whether MHD support automatic detection of bind port number. * @sa #MHD_DAEMON_INFO_BIND_PORT */ MHD_FEATURE_AUTODETECT_BIND_PORT = 19, /** * Get whether MHD supports automatic SIGPIPE suppression. * If SIGPIPE suppression is not supported, application must handle * SIGPIPE signal by itself. */ MHD_FEATURE_AUTOSUPPRESS_SIGPIPE = 20, /** * Get whether MHD use system's sendfile() function to send * file-FD based responses over non-TLS connections. * @note Since v0.9.56 */ MHD_FEATURE_SENDFILE = 21, /** * Get whether MHD supports threads. */ MHD_FEATURE_THREADS = 22, /** * Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK2 is * supported. */ MHD_FEATURE_HTTPS_CERT_CALLBACK2 = 23, /** * Get whether automatic parsing of HTTP Cookie header is supported. * If disabled, no MHD_COOKIE_KIND will be generated by MHD. * MHD versions before 0x00097701 always support cookie parsing. * @note Available since #MHD_VERSION 0x01000200 */ MHD_FEATURE_COOKIE_PARSING = 24, /** * Get whether the early version the Digest Authorization (RFC 2069) is * supported (digest authorisation without QOP parameter). * Since #MHD_VERSION 0x00097701 it is always supported if Digest Auth * module is built. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_RFC2069 = 25, /** * Get whether the MD5-based hashing algorithms are supported for Digest * Authorization. * Currently it is always supported if Digest Auth module is built * unless manually disabled in a custom build. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_MD5 = 26, /** * Get whether the SHA-256-based hashing algorithms are supported for Digest * Authorization. * It is always supported since #MHD_VERSION 0x00096200 if Digest Auth * module is built unless manually disabled in a custom build. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_SHA256 = 27, /** * Get whether the SHA-512/256-based hashing algorithms are supported * for Digest Authorization. * It it always supported since #MHD_VERSION 0x00097701 if Digest Auth * module is built unless manually disabled in a custom build. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_SHA512_256 = 28, /** * Get whether QOP with value 'auth-int' (authentication with integrity * protection) is supported for Digest Authorization. * Currently it is always not supported. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_AUTH_INT = 29, /** * Get whether 'session' algorithms (like 'MD5-sess') are supported for Digest * Authorization. * Currently it is always not supported. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_ALGO_SESSION = 30, /** * Get whether 'userhash' is supported for Digest Authorization. * It is always supported since #MHD_VERSION 0x00097701 if Digest Auth * module is built. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DIGEST_AUTH_USERHASH = 31, /** * Get whether any of hashing algorithms is implemented by external * function (like TLS library) and may fail due to external conditions, * like "out-of-memory". * * If result is #MHD_YES then functions which use hash calculations * like #MHD_digest_auth_calc_userhash(), #MHD_digest_auth_check3() and others * potentially may fail even with valid input because of out-of-memory error * or crypto accelerator device failure, however in practice such fails are * unlikely. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_EXTERN_HASH = 32, /** * Get whether MHD was built with asserts enabled. * For debug builds the error log is always enabled even if #MHD_USE_ERROR_LOG * is not specified for daemon. * @note Available since #MHD_VERSION 0x00097701 */ MHD_FEATURE_DEBUG_BUILD = 33, /** * Get whether MHD was build with support for overridable FD_SETSIZE. * This feature should be always available when the relevant platform ability * is detected. * @sa #MHD_OPTION_APP_FD_SETSIZE * @note Available since #MHD_VERSION 0x00097705 */ MHD_FEATURE_FLEXIBLE_FD_SETSIZE = 34 }; #define MHD_FEATURE_HTTPS_COOKIE_PARSING _MHD_DEPR_IN_MACRO ( \ "Value MHD_FEATURE_HTTPS_COOKIE_PARSING is deprecated, use MHD_FEATURE_COOKIE_PARSING" \ ) MHD_FEATURE_COOKIE_PARSING /** * Get information about supported MHD features. * Indicate that MHD was compiled with or without support for * particular feature. Some features require additional support * by kernel. Kernel support is not checked by this function. * * @param feature type of requested information * @return #MHD_YES if feature is supported by MHD, #MHD_NO if * feature is not supported or feature is unknown. * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_is_feature_supported (enum MHD_FEATURE feature); MHD_C_DECLRATIONS_FINISH_HERE_ #endif libmicrohttpd-1.0.10/src/include/Makefile.in0000664000175000017500000005733015235436270014416 # Makefile.in generated by automake 1.17 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2024 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) am__rm_f = rm -f $(am__rm_f_notfound) am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/include ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(include_HEADERS) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__installdirs = "$(DESTDIR)$(includedir)" HEADERS = $(include_HEADERS) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ am__xargs_n = @am__xargs_n@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain SUBDIRS = . include_HEADERS = microhttpd.h EXTRA_DIST = platform.h autoinit_funcs.h mhd_options.h all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/include/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/include/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-includeHEADERS: $(include_HEADERS) @$(NORMAL_INSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(HEADERS) installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -$(am__rm_f) $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-includeHEADERS install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-includeHEADERS .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool cscopelist-am ctags \ ctags-am distclean distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-includeHEADERS install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am uninstall-includeHEADERS .PRECIOUS: Makefile # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: # Tell GNU make to disable its built-in pattern rules. %:: %,v %:: RCS/%,v %:: RCS/% %:: s.% %:: SCCS/s.% libmicrohttpd-1.0.10/src/include/platform.h0000644000175000017500000000726014760713577014353 /* This file is part of libmicrohttpd Copyright (C) 2008 Christian Grothoff (and other contributing authors) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file platform.h * @brief platform-specific includes for libmicrohttpd * @author Christian Grothoff * * This file is included by the libmicrohttpd code * before "microhttpd.h"; it provides the required * standard headers (which are platform-specific).

* * Note that this file depends on our configure.ac * build process and the generated config.h file. * Hence you cannot include it directly in applications * that use libmicrohttpd. */ #ifndef MHD_PLATFORM_H #define MHD_PLATFORM_H #include "mhd_options.h" #include #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #include #include #ifdef HAVE_UNISTD_H #include #endif #include #include #include #include #ifdef HAVE_STDDEF_H #include #endif /* HAVE_STDDEF_H */ /* different OSes have fd_set in a broad range of header files; we just include most of them (if they are available) */ #if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS) #include #include #ifdef HAVE_SOCKLIB_H #include #endif /* HAVE_SOCKLIB_H */ #ifdef HAVE_INETLIB_H #include #endif /* HAVE_INETLIB_H */ #endif /* __VXWORKS__ */ #ifdef HAVE_MEMORY_H #include #endif #ifdef HAVE_SYS_SELECT_H #include #endif #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_TIME_H #include #endif #ifdef HAVE_SYS_STAT_H #include #endif #ifdef HAVE_SYS_MSG_H #include #endif #ifdef HAVE_SYS_MMAN_H #include #endif #ifdef HAVE_TIME_H #include #endif #ifdef HAVE_SYS_SOCKET_H #include #endif #if defined(_WIN32) && ! defined(__CYGWIN__) #ifndef WIN32_LEAN_AND_MEAN /* Do not include unneeded parts of W32 headers. */ #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #include #endif /* _WIN32 && !__CYGWIN__ */ #if defined(__CYGWIN__) && ! defined(_SYS_TYPES_FD_SET) /* Do not define __USE_W32_SOCKETS under Cygwin! */ #error Cygwin with winsock fd_set is not supported #endif #if defined(_WIN32) && ! defined(__CYGWIN__) #define sleep(seconds) ((SleepEx ((seconds) * 1000, 1)==0) ? 0 : (seconds)) #define usleep(useconds) ((SleepEx ((useconds) / 1000, 1)==0) ? 0 : -1) #endif #if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED) #define _SSIZE_T_DEFINED typedef intptr_t ssize_t; #endif /* !_SSIZE_T_DEFINED */ #if ! defined(_WIN32) || defined(__CYGWIN__) typedef time_t _MHD_TIMEVAL_TV_SEC_TYPE; #else /* _WIN32 && ! __CYGWIN__ */ typedef long _MHD_TIMEVAL_TV_SEC_TYPE; #endif /* _WIN32 && ! __CYGWIN__ */ #if ! defined(IPPROTO_IPV6) && defined(_MSC_FULL_VER) && _WIN32_WINNT >= 0x0501 /* VC use IPPROTO_IPV6 as part of enum */ #define IPPROTO_IPV6 IPPROTO_IPV6 #endif #endif libmicrohttpd-1.0.10/src/include/mhd_options.h0000644000175000017500000002424715035214301015027 /* This file is part of libmicrohttpd Copyright (C) 2016-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file include/mhd_options.h * @brief additional automatic macros for MHD_config.h * @author Karlson2k (Evgeny Grin) * * This file includes MHD_config.h and adds automatic macros based on values * in MHD_config.h, compiler built-in macros and commandline-defined macros * (but not based on values defined in other headers). Works also as a guard * to prevent double inclusion of MHD_config.h */ #ifndef MHD_OPTIONS_H #define MHD_OPTIONS_H 1 #include "MHD_config.h" /** * Macro to make it easy to mark text for translation. Note that * we do not actually call gettext() in MHD, but we do make it * easy to create a ".po" file so that applications that do want * to translate error messages can do so. */ #define _(String) (String) #if defined(_MHD_EXTERN) && ! defined(BUILDING_MHD_LIB) #undef _MHD_EXTERN #endif /* _MHD_EXTERN && ! BUILDING_MHD_LIB */ #ifndef _MHD_EXTERN #if defined(BUILDING_MHD_LIB) && defined(_WIN32) && \ (defined(DLL_EXPORT) || defined(MHD_W32DLL)) #define _MHD_EXTERN __declspec(dllexport) extern #else /* !BUILDING_MHD_LIB || !_WIN32 || (!DLL_EXPORT && !MHD_W32DLL) */ #define _MHD_EXTERN extern #endif /* !BUILDING_MHD_LIB || !_WIN32 || (!DLL_EXPORT && !MHD_W32DLL) */ #endif /* ! _MHD_EXTERN */ /* Some platforms (FreeBSD, Solaris, W32) allow to override default FD_SETSIZE by defining it before including headers. */ #ifdef FD_SETSIZE /* FD_SETSIZE defined in command line or in MHD_config.h */ #elif defined(_WIN32) || defined(__CYGWIN__) /* Platform with WinSock and without overridden FD_SETSIZE */ #define FD_SETSIZE 2048 /* Override default small value (64) */ #else /* !FD_SETSIZE && !W32 */ /* System default value of FD_SETSIZE is used */ #define _MHD_FD_SETSIZE_IS_DEFAULT 1 #endif /* !FD_SETSIZE && !W32 */ #if defined(HAVE_LINUX_SENDFILE) || defined(HAVE_FREEBSD_SENDFILE) || \ defined(HAVE_DARWIN_SENDFILE) || defined(HAVE_SOLARIS_SENDFILE) /* Have any supported sendfile() function. */ #define _MHD_HAVE_SENDFILE #endif /* HAVE_LINUX_SENDFILE || HAVE_FREEBSD_SENDFILE || HAVE_DARWIN_SENDFILE || HAVE_SOLARIS_SENDFILE */ #if defined(HAVE_LINUX_SENDFILE) || defined(HAVE_SOLARIS_SENDFILE) #define MHD_LINUX_SOLARIS_SENDFILE 1 #endif /* HAVE_LINUX_SENDFILE || HAVE_SOLARIS_SENDFILE */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) # ifndef MHD_USE_THREADS # define MHD_USE_THREADS 1 # endif #endif /* MHD_USE_POSIX_THREADS || MHD_USE_W32_THREADS */ #if defined(OS390) #define _OPEN_THREADS #define _OPEN_SYS_SOCK_IPV6 #define _OPEN_MSGQ_EXT #define _LP64 #endif #if defined(_WIN32) && ! defined(__CYGWIN__) /* Declare POSIX-compatible names */ #define _CRT_DECLARE_NONSTDC_NAMES 1 /* Do not warn about POSIX name usage */ #define _CRT_NONSTDC_NO_WARNINGS 1 #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0600 #else /* _WIN32_WINNT */ #if _WIN32_WINNT < 0x0501 #error "Headers for Windows XP or later are required" #endif /* _WIN32_WINNT < 0x0501 */ #endif /* _WIN32_WINNT */ #ifndef WIN32_LEAN_AND_MEAN /* Do not include unneeded parts of W32 headers. */ #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #endif /* _WIN32 && ! __CYGWIN__ */ #if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS) #define RESTRICT __restrict__ #endif /* __VXWORKS__ || __vxworks || OS_VXWORKS */ #if defined(LINUX) && (defined(HAVE_SENDFILE64) || defined(HAVE_LSEEK64)) && \ ! defined(_LARGEFILE64_SOURCE) /* On Linux, special macro is required to enable definitions of some xxx64 functions */ #define _LARGEFILE64_SOURCE 1 #endif #ifdef HAVE_C11_GMTIME_S /* Special macro is required to enable C11 definition of gmtime_s() function */ #define __STDC_WANT_LIB_EXT1__ 1 #endif /* HAVE_C11_GMTIME_S */ #if defined(MHD_FAVOR_FAST_CODE) && defined(MHD_FAVOR_SMALL_CODE) #error \ MHD_FAVOR_FAST_CODE and MHD_FAVOR_SMALL_CODE are both defined. Cannot favor speed and size at the same time. #endif /* MHD_FAVOR_FAST_CODE && MHD_FAVOR_SMALL_CODE */ /* Define MHD_FAVOR_FAST_CODE to force fast code path or define MHD_FAVOR_SMALL_CODE to choose compact code path */ #if ! defined(MHD_FAVOR_FAST_CODE) && ! defined(MHD_FAVOR_SMALL_CODE) /* Try to detect user preferences */ /* Defined by GCC and many compatible compilers */ #if defined(__OPTIMIZE_SIZE__) #define MHD_FAVOR_SMALL_CODE 1 #elif defined(__OPTIMIZE__) #define MHD_FAVOR_FAST_CODE 1 #endif /* __OPTIMIZE__ */ #endif /* !MHD_FAVOR_FAST_CODE && !MHD_FAVOR_SMALL_CODE */ #if ! defined(MHD_FAVOR_FAST_CODE) && ! defined(MHD_FAVOR_SMALL_CODE) /* Use faster code by default */ #define MHD_FAVOR_FAST_CODE 1 #endif /* !MHD_FAVOR_FAST_CODE && !MHD_FAVOR_SMALL_CODE */ #ifndef MHD_ASAN_ACTIVE #if (defined(__GNUC__) || defined(_MSC_VER)) && defined(__SANITIZE_ADDRESS__) #define MHD_ASAN_ACTIVE 1 #elif defined(__has_feature) #if __has_feature (address_sanitizer) #define MHD_ASAN_ACTIVE 1 #endif /* __has_feature(address_sanitizer) */ #endif /* __has_feature */ #endif /* MHD_ASAN_ACTIVE */ #if defined(MHD_ASAN_ACTIVE) && defined(HAVE_SANITIZER_ASAN_INTERFACE_H) && \ (defined(FUNC_PTRCOMPARE_CAST_WORKAROUND_WORKS) || \ (defined(FUNC_ATTR_PTRCOMPARE_WORKS) && \ defined(FUNC_ATTR_PTRSUBTRACT_WORKS)) || \ defined(FUNC_ATTR_NOSANITIZE_WORKS)) #ifndef MHD_ASAN_POISON_ACTIVE /* User ASAN poisoning could be used */ #warning User memory poisoning is not active #endif /* ! MHD_ASAN_POISON_ACTIVE */ #else /* ! (MHD_ASAN_ACTIVE && HAVE_SANITIZER_ASAN_INTERFACE_H && (FUNC_ATTR_PTRCOMPARE_WORKS || FUNC_ATTR_NOSANITIZE_WORKS)) */ #ifdef MHD_ASAN_POISON_ACTIVE #error User memory poisoning is active, but conditions are not suitable #endif /* MHD_ASAN_POISON_ACTIVE */ #endif /* ! (MHD_ASAN_ACTIVE && HAVE_SANITIZER_ASAN_INTERFACE_H && (FUNC_ATTR_PTRCOMPARE_WORKS || FUNC_ATTR_NOSANITIZE_WORKS)) */ #ifndef _MSC_FULL_VER # define MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /* empty */ # define MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ /* empty */ #else /* _MSC_FULL_VER */ # define MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ \ __pragma(runtime_checks("c", off)) # define MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ \ __pragma(runtime_checks("c", restore)) #endif /* _MSC_FULL_VER */ /** * Automatic string with the name of the current function */ #if defined(HAVE___FUNC__) #define MHD_FUNC_ __func__ #define MHD_HAVE_MHD_FUNC_ 1 #elif defined(HAVE___FUNCTION__) #define MHD_FUNC_ __FUNCTION__ #define MHD_HAVE_MHD_FUNC_ 1 #elif defined(HAVE___PRETTY_FUNCTION__) #define MHD_FUNC_ __PRETTY_FUNCTION__ #define MHD_HAVE_MHD_FUNC_ 1 #else #define MHD_FUNC_ "**name unavailable**" #ifdef MHD_HAVE_MHD_FUNC_ #undef MHD_HAVE_MHD_FUNC_ #endif /* MHD_HAVE_MHD_FUNC_ */ #endif /* Un-define some HAVE_DECL_* macro if they equal zero. This should allow safely use #ifdef in the code. Define HAS_DECL_* macros only if matching HAVE_DECL_* macro has non-zero value. Unlike HAVE_DECL_*, macros HAS_DECL_* cannot have zero value. */ #ifdef HAVE_DECL__SC_NPROCESSORS_ONLN # if 0 == HAVE_DECL__SC_NPROCESSORS_ONLN # undef HAVE_DECL__SC_NPROCESSORS_ONLN # else /* 0 != HAVE_DECL__SC_NPROCESSORS_ONLN */ # define HAS_DECL__SC_NPROCESSORS_ONLN 1 # endif /* 0 != HAVE_DECL__SC_NPROCESSORS_ONLN */ #endif /* HAVE_DECL__SC_NPROCESSORS_ONLN */ #ifdef HAVE_DECL__SC_NPROCESSORS_CONF # if 0 == HAVE_DECL__SC_NPROCESSORS_CONF # undef HAVE_DECL__SC_NPROCESSORS_CONF # else /* 0 != HAVE_DECL__SC_NPROCESSORS_CONF */ # define HAS_DECL__SC_NPROCESSORS_CONF 1 # endif /* 0 != HAVE_DECL__SC_NPROCESSORS_CONF */ #endif /* HAVE_DECL__SC_NPROCESSORS_CONF */ #ifdef HAVE_DECL__SC_NPROC_ONLN # if 0 == HAVE_DECL__SC_NPROC_ONLN # undef HAVE_DECL__SC_NPROC_ONLN # else /* 0 != HAVE_DECL__SC_NPROC_ONLN */ # define HAS_DECL__SC_NPROC_ONLN 1 # endif /* 0 != HAVE_DECL__SC_NPROC_ONLN */ #endif /* HAVE_DECL__SC_NPROC_ONLN */ #ifdef HAVE_DECL__SC_CRAY_NCPU # if 0 == HAVE_DECL__SC_CRAY_NCPU # undef HAVE_DECL__SC_CRAY_NCPU # else /* 0 != HAVE_DECL__SC_CRAY_NCPU */ # define HAS_DECL__SC_CRAY_NCPU 1 # endif /* 0 != HAVE_DECL__SC_CRAY_NCPU */ #endif /* HAVE_DECL__SC_CRAY_NCPU */ #ifdef HAVE_DECL_CTL_HW # if 0 == HAVE_DECL_CTL_HW # undef HAVE_DECL_CTL_HW # else /* 0 != HAVE_DECL_CTL_HW */ # define HAS_DECL_CTL_HW 1 # endif /* 0 != HAVE_DECL_CTL_HW */ #endif /* HAVE_DECL_CTL_HW */ #ifdef HAVE_DECL_HW_NCPUONLINE # if 0 == HAVE_DECL_HW_NCPUONLINE # undef HAVE_DECL_HW_NCPUONLINE # else /* 0 != HAVE_DECL_HW_NCPUONLINE */ # define HAS_DECL_HW_NCPUONLINE 1 # endif /* 0 != HAVE_DECL_HW_NCPUONLINE */ #endif /* HAVE_DECL_HW_NCPUONLINE */ #ifdef HAVE_DECL_HW_AVAILCPU # if 0 == HAVE_DECL_HW_AVAILCPU # undef HAVE_DECL_HW_AVAILCPU # else /* 0 != HAVE_DECL_HW_AVAILCPU */ # define HAS_DECL_HW_AVAILCPU 1 # endif /* 0 != HAVE_DECL_HW_AVAILCPU */ #endif /* HAVE_DECL_HW_AVAILCPU */ #ifdef HAVE_DECL_HW_NCPU # if 0 == HAVE_DECL_HW_NCPU # undef HAVE_DECL_HW_NCPU # else /* 0 != HAVE_DECL_HW_NCPU */ # define HAS_DECL_HW_NCPU 1 # endif /* 0 != HAVE_DECL_HW_NCPU */ #endif /* HAVE_DECL_HW_NCPU */ #ifdef HAVE_DECL_CPU_SETSIZE # if 0 == HAVE_DECL_CPU_SETSIZE # undef HAVE_DECL_CPU_SETSIZE # else /* 0 != HAVE_DECL_CPU_SETSIZE */ # define HAS_DECL_CPU_SETSIZE 1 # endif /* 0 != HAVE_DECL_CPU_SETSIZE */ #endif /* HAVE_DECL_CPU_SETSIZE */ #ifndef MHD_DAUTH_DEF_TIMEOUT_ # define MHD_DAUTH_DEF_TIMEOUT_ 90 #endif /* ! MHD_DAUTH_DEF_TIMEOUT_ */ #ifndef MHD_DAUTH_DEF_MAX_NC_ # define MHD_DAUTH_DEF_MAX_NC_ 1000 #endif /* ! MHD_DAUTH_DEF_MAX_NC_ */ #endif /* MHD_OPTIONS_H */ libmicrohttpd-1.0.10/src/include/Makefile.am0000664000175000017500000000021715064541253014373 # This Makefile.am is in the public domain SUBDIRS = . include_HEADERS = microhttpd.h EXTRA_DIST = platform.h autoinit_funcs.h mhd_options.h libmicrohttpd-1.0.10/src/testcurl/0000775000175000017500000000000015235437005012640 5libmicrohttpd-1.0.10/src/testcurl/test_termination.c0000664000175000017500000001036515232103064016311 /* This file is part of libmicrohttpd Copyright (C) 2009 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_termination.c * @brief Testcase for libmicrohttpd tolerating client not closing immediately * @author hollosig * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #include #include #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef __MINGW32__ #include #include #endif #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif static enum MHD_Result connection_handler (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int i; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (*req_cls == NULL) { *req_cls = &i; return MHD_YES; } if (*upload_data_size != 0) { (*upload_data_size) = 0; return MHD_YES; } response = MHD_create_response_from_buffer_static (strlen ("Response"), "Response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static size_t write_data (void *ptr, size_t size, size_t nmemb, void *stream) { (void) ptr; (void) stream; /* Unused. Silent compiler warning. */ return size * nmemb; } int main (void) { struct MHD_Daemon *daemon; uint16_t port; char url[255]; CURL *curl; CURLcode success; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1490; daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, connection_handler, NULL, MHD_OPTION_END); if (daemon == NULL) { fprintf (stderr, "Daemon cannot be started!"); exit (1); } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (daemon); return 32; } port = dinfo->port; } curl = curl_easy_init (); /* curl_easy_setopt(curl, CURLOPT_POST, 1L); */ snprintf (url, sizeof (url), "http://127.0.0.1:%u", (unsigned int) port); curl_easy_setopt (curl, CURLOPT_URL, url); curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, write_data); success = curl_easy_perform (curl); if (success != 0) { fprintf (stderr, "CURL Error"); exit (1); } /* CPU used to go crazy here */ (void) sleep (1); curl_easy_cleanup (curl); MHD_stop_daemon (daemon); return 0; } libmicrohttpd-1.0.10/src/testcurl/test_put_header_fold.c0000664000175000017500000011523615232103064017107 /* This file is part of GNU libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testcurl/test_put_header_fold.c * @brief Testcase for requests with header fold * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #ifndef _WIN32 #include #include #endif #include "internal.h" #include "mhd_has_param.h" #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" /* The next macros are borrowed from memorypool.c Keep them in sync! */ /** * Align to 2x word size (as GNU libc does). */ #define ALIGN_SIZE (2 * sizeof(void*)) /** * Round up 'n' to a multiple of ALIGN_SIZE. */ #define ROUND_TO_ALIGN(n) (((n) + (ALIGN_SIZE - 1)) \ / (ALIGN_SIZE) *(ALIGN_SIZE)) #ifndef MHD_ASAN_POISON_ACTIVE #define _MHD_RED_ZONE_SIZE (0) #else /* MHD_ASAN_POISON_ACTIVE */ #define _MHD_RED_ZONE_SIZE (ALIGN_SIZE) #endif /* MHD_ASAN_POISON_ACTIVE */ #define ROUND_TO_ALIGN_PLUS_RED_ZONE(n) (ROUND_TO_ALIGN(n) + _MHD_RED_ZONE_SIZE) /* The previous macros are borrowed from memorypool.c Keep them in sync! */ #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define TEST_UPLOAD_DATA_SIZE 2048U #define EXPECTED_URI_BASE_PATH "/" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST_PATH URL_SCHEME URL_HOST EXPECTED_URI_BASE_PATH #define RP_HEADER1_NAME "First" #define RP_HEADER1_VALUE "1st" #define RP_HEADER1 RP_HEADER1_NAME ": " RP_HEADER1_VALUE #define RP_HEADER1_CRLF RP_HEADER1 "\r\n" #define RP_HEADER2_NAME "Normal" #define RP_HEADER2_VALUE "it's fine" #define RP_HEADER2 RP_HEADER2_NAME ": " RP_HEADER2_VALUE #define RP_HEADER2_CRLF RP_HEADER2 "\r\n" #define HDR_FOLD "\r\n " #define RQ_HEADER1_NAME RP_HEADER1_NAME #define RQ_HEADER1_VALUE RP_HEADER1_VALUE #define RQ_HEADER1 RQ_HEADER1_NAME ": " RQ_HEADER1_VALUE #define RQ_HEADER2_NAME "Folded" #define RQ_HEADER2_VALUE_S "start" #define RQ_HEADER2_VALUE_E "end" #define RQ_HEADER2_VALUE \ RQ_HEADER2_VALUE_S HDR_FOLD RQ_HEADER2_VALUE_E #define RQ_HEADER2_VALUE_DF \ RQ_HEADER2_VALUE_S HDR_FOLD HDR_FOLD RQ_HEADER2_VALUE_E #define RQ_HEADER2 RQ_HEADER2_NAME ": " RQ_HEADER2_VALUE #define RQ_HEADER2_DF RQ_HEADER2_NAME ": " RQ_HEADER2_VALUE_DF #define RQ_HEADER3_NAME RP_HEADER2_NAME #define RQ_HEADER3_VALUE RP_HEADER2_VALUE #define RQ_HEADER3 RQ_HEADER3_NAME ": " RQ_HEADER3_VALUE /** * The number of request headers: 3 custom headers + 2 automatic headers */ #define RQ_NUM_HEADERS (3 + 2) /** * The extra size in the memory pool for pointers to the headers */ #define HEADERS_POINTERS_SIZE \ RQ_NUM_HEADERS * \ ROUND_TO_ALIGN_PLUS_RED_ZONE(sizeof(struct MHD_HTTP_Req_Header)) #define PAGE \ "libmicrohttpd demo page" \ "Success!" /* Global parameters */ static int verbose; static int oneone; /**< If false use HTTP/1.0 for requests*/ static int use_get; static int use_put; static int use_put_large; static int use_double_fold; static int use_hdr_last; /**< If non-zero, folded header is placed last */ static int use_hdr_large; /**< If non-zero, folded header is large */ /* Static data */ static struct curl_slist *libcurl_headers = NULL; static char *put_data = NULL; /** * Initialise headers for libcurl * * @return non-zero if succeed, * zero if failed */ static void libcurl_headers_init (void) { libcurl_headers = curl_slist_append (NULL, RQ_HEADER1); if (NULL == libcurl_headers) libcurlErrorExitDesc ("curl_slist_append() failed"); if (use_hdr_last) { libcurl_headers = curl_slist_append (libcurl_headers, RQ_HEADER3); if (NULL == libcurl_headers) libcurlErrorExitDesc ("curl_slist_append() failed"); } if (! use_hdr_large) { if (! use_double_fold) libcurl_headers = curl_slist_append (libcurl_headers, RQ_HEADER2); else libcurl_headers = curl_slist_append (libcurl_headers, RQ_HEADER2_DF); if (NULL == libcurl_headers) libcurlErrorExitDesc ("curl_slist_append() failed"); } else { char *buf; size_t pos; buf = malloc (TEST_UPLOAD_DATA_SIZE + 1); if (NULL == buf) externalErrorExitDesc ("malloc() failed"); pos = 0; memcpy (buf, RQ_HEADER2_NAME, MHD_STATICSTR_LEN_ (RQ_HEADER2_NAME)); pos += MHD_STATICSTR_LEN_ (RQ_HEADER2_NAME); buf[pos++] = ':'; buf[pos++] = ' '; memcpy (buf + pos, RQ_HEADER2_VALUE_S, MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_S)); pos += MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_S); memcpy (buf + pos, HDR_FOLD, MHD_STATICSTR_LEN_ (HDR_FOLD)); pos += MHD_STATICSTR_LEN_ (HDR_FOLD); if (use_double_fold) { memcpy (buf + pos, HDR_FOLD, MHD_STATICSTR_LEN_ (HDR_FOLD)); pos += MHD_STATICSTR_LEN_ (HDR_FOLD); } memset (buf + pos, 'a', TEST_UPLOAD_DATA_SIZE - pos - MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E) - 1); pos += TEST_UPLOAD_DATA_SIZE - pos - MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E) - 1; buf[pos++] = ' '; memcpy (buf + pos, RQ_HEADER2_VALUE_E, MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E)); pos += MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E); if (TEST_UPLOAD_DATA_SIZE != pos) externalErrorExitDesc ("Position miscalculation"); buf[pos] = 0; libcurl_headers = curl_slist_append (libcurl_headers, buf); if (NULL == libcurl_headers) libcurlErrorExitDesc ("curl_slist_append() failed"); free (buf); } if (! use_hdr_last) { libcurl_headers = curl_slist_append (libcurl_headers, RQ_HEADER3); if (NULL == libcurl_headers) libcurlErrorExitDesc ("curl_slist_append() failed"); } } static void init_put_data (void) { size_t i; put_data = malloc (TEST_UPLOAD_DATA_SIZE + 1); if (NULL == put_data) externalErrorExit (); for (i = 0; i < (TEST_UPLOAD_DATA_SIZE - 1); ++i) { if (0 == (i % 7)) put_data[i] = ' '; else if (0 == (i % 47)) put_data[i] = '\n'; else if (0 == (i % 11)) put_data[i] = (char) ('A' + i % ('Z' - 'A' + 1)); else put_data[i] = (char) ('a' + i % ('z' - 'a' + 1)); } put_data[TEST_UPLOAD_DATA_SIZE - 1] = '\n'; put_data[TEST_UPLOAD_DATA_SIZE] = 0; } static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); init_put_data (); libcurl_headers_init (); } static void test_global_cleanup (void) { curl_slist_free_all (libcurl_headers); curl_global_cleanup (); if (NULL != put_data) free (put_data); put_data = NULL; } struct headers_check_result { unsigned int expected_size; int header1_found; int header2_found; unsigned int size_found; unsigned int size_broken_found; }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; if ((MHD_STATICSTR_LEN_ (RP_HEADER1_CRLF) == data_size) && (0 == memcmp (RP_HEADER1_CRLF, buffer, data_size))) check_res->header1_found++; else if ((MHD_STATICSTR_LEN_ (RP_HEADER2_CRLF) == data_size) && (0 == memcmp (RP_HEADER2_CRLF, buffer, data_size))) check_res->header2_found++; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ") < data_size) && (0 == memcmp (MHD_HTTP_HEADER_CONTENT_LENGTH ": ", buffer, MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ")))) { char cmpbuf[256]; int res; const unsigned int numbers_pos = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "); res = snprintf (cmpbuf, sizeof(cmpbuf), "%u", check_res->expected_size); if ((res <= 0) || (res > ((int) (sizeof(cmpbuf) - 1)))) externalErrorExit (); if (data_size - numbers_pos <= 2) { fprintf (stderr, "Broken Content-Length.\n"); check_res->size_broken_found++; } else if ((((size_t) res + 2) != data_size - numbers_pos) || (0 != memcmp (buffer + numbers_pos, cmpbuf, (size_t) res))) { fprintf (stderr, "Wrong Content-Length. " "Expected: %u. " "Received: %.*s.\n", check_res->expected_size, (int) (data_size - numbers_pos - 2), buffer + numbers_pos); check_res->size_broken_found++; } else if (0 != memcmp ("\r\n", buffer + data_size - 2, 2)) { fprintf (stderr, "The Content-Length header is not " "terminated by CRLF.\n"); check_res->size_broken_found++; } else check_res->size_found++; } return data_size; } struct CBC { /* Upload members */ size_t up_pos; size_t up_size; /* Download members */ char *dn_buf; size_t dn_pos; size_t dn_buf_size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->dn_pos + size * nmemb > cbc->dn_buf_size) return 0; /* overflow */ memcpy (&cbc->dn_buf[cbc->dn_pos], ptr, size * nmemb); cbc->dn_pos += size * nmemb; return size * nmemb; } static size_t libcurlUploadDataCB (void *stream, size_t item_size, size_t nitems, void *ctx) { size_t to_fill; struct CBC *cbc = ctx; to_fill = cbc->up_size - cbc->up_pos; if (to_fill > item_size * nitems) to_fill = item_size * nitems; /* Avoid libcurl magic numbers */ #ifdef CURL_READFUNC_PAUSE if (CURL_READFUNC_PAUSE == to_fill) to_fill = (CURL_READFUNC_PAUSE - 2); #endif /* CURL_READFUNC_PAUSE */ #ifdef CURL_READFUNC_ABORT if (CURL_READFUNC_ABORT == to_fill) to_fill = (CURL_READFUNC_ABORT - 1); #endif /* CURL_READFUNC_ABORT */ memcpy (stream, put_data + cbc->up_pos, to_fill); cbc->up_pos += to_fill; return to_fill; } static int libcurl_debug_cb (CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { static const char excess_mark[] = "Excess found"; static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark); (void) handle; (void) userptr; #ifdef _DEBUG switch (type) { case CURLINFO_TEXT: fprintf (stderr, "* %.*s", (int) size, data); break; case CURLINFO_HEADER_IN: fprintf (stderr, "< %.*s", (int) size, data); break; case CURLINFO_HEADER_OUT: fprintf (stderr, "> %.*s", (int) size, data); break; case CURLINFO_DATA_IN: #if 0 fprintf (stderr, "<| %.*s\n", (int) size, data); #endif break; case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: case CURLINFO_END: default: break; } #endif /* _DEBUG */ if (CURLINFO_TEXT == type) { if ((size >= excess_mark_len) && (0 == memcmp (data, excess_mark, excess_mark_len))) mhdErrorExitDesc ("Extra data has been detected in MHD reply"); } return 0; } static CURL * setupCURL (void *cbc, uint16_t port, struct headers_check_result *hdr_chk_result) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA, hdr_chk_result)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &libcurl_debug_cb)) || #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, URL_SCHEME_HOST_PATH)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, libcurl_headers)) libcurlErrorExitDesc ("Failed to set request headers"); if (use_put) { if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION, libcurlUploadDataCB)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, cbc))) libcurlErrorExitDesc ("Failed to configure the PUT upload"); } return c; } struct ahc_cls_type { const char *rq_method; const char *rq_url; unsigned int num_req; /* Position in the upload data, not compatible with parallel requests */ size_t up_pos; size_t expected_upload_size; unsigned int req_check_error; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (oneone) { if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); } else { if (0 != strcmp (version, MHD_HTTP_VERSION_1_0)) mhdErrorExitDesc ("Unexpected HTTP version"); } if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (NULL != upload_data) { size_t report_processed_size; if (0 == *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is zero"); report_processed_size = *upload_data_size; /* The next checks are not compatible with parallel requests */ if (*upload_data_size > param->expected_upload_size - param->up_pos) { fprintf (stderr, "Unexpected *upload_data_size value: %lu. " "Already processed data size: %lu. " "Total expected upload size: %lu. " "Expected unprocessed upload size: %lu. " "The upload data cannot be checked.\n", (unsigned long) *upload_data_size, (unsigned long) param->up_pos, (unsigned long) param->expected_upload_size, (unsigned long) (param->expected_upload_size - param->up_pos)); param->req_check_error++; } else { if (0 != memcmp (upload_data, put_data + param->up_pos, *upload_data_size)) { fprintf (stderr, "Wrong upload data.\n" "Expected: '%.*s'\n" "Received: '%.*s'.\n", (int) *upload_data_size, upload_data, (int) *upload_data_size, put_data + param->up_pos); param->req_check_error++; } if (use_put_large && (report_processed_size > param->expected_upload_size / 10)) report_processed_size = param->expected_upload_size / 10; param->up_pos += report_processed_size; } *upload_data_size -= report_processed_size; return MHD_YES; } else { if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); } if (1) { /* Check headers */ const char *value; size_t value_len; unsigned int header_check_error; header_check_error = 0; value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, RQ_HEADER1_NAME); if (NULL == value) { fprintf (stderr, "Request header '" RQ_HEADER1_NAME "' not found.\n"); header_check_error++; } else { if (0 != strcmp (value, RQ_HEADER1_VALUE)) { fprintf (stderr, "Wrong header '" RQ_HEADER1_NAME "'value. " "Expected: '%s'. Received: '%s'.\n", RQ_HEADER1_VALUE, value); header_check_error++; } } if (MHD_YES != MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, RQ_HEADER2_NAME, MHD_STATICSTR_LEN_ (RQ_HEADER2_NAME), &value, &value_len)) { fprintf (stderr, "Request header '" RQ_HEADER2_NAME "' not found.\n"); header_check_error++; } else { if (NULL == value) mhdErrorExitDesc ("The 'value' pointer is NULL"); if (strlen (value) != value_len) mhdErrorExitDesc ("The 'value' length does not match strlen(value)"); if (value_len < MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_S) + MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E)) { fprintf (stderr, "The value_len is too short. The value: '%s'.\n", value); header_check_error++; } if (0 != memcmp (value, RQ_HEADER2_VALUE_S, MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_S))) { fprintf (stderr, "The 'value' does not start with '" RQ_HEADER2_VALUE_S "'. The 'value' is '%s'. ", value); header_check_error++; } if (0 != memcmp (value + value_len - MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E), RQ_HEADER2_VALUE_E, MHD_STATICSTR_LEN_ (RQ_HEADER2_VALUE_E))) { fprintf (stderr, "The 'value' does not end with '" RQ_HEADER2_VALUE_E "'. The 'value' is '%s'. ", value); header_check_error++; } } value = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, RQ_HEADER3_NAME); if (NULL == value) { fprintf (stderr, "Request header '" RQ_HEADER3_NAME "' not found.\n"); header_check_error++; } else { if (0 != strcmp (value, RQ_HEADER3_VALUE)) { fprintf (stderr, "Wrong header '" RQ_HEADER3_NAME "'value. " "Expected: '%s'. Received: '%s'.\n", RQ_HEADER3_VALUE, value); header_check_error++; } } param->req_check_error += header_check_error; } if (&marker != *req_cls) { *req_cls = ▮ if (param->num_req) mhdErrorExitDesc ("Got unexpected second request"); param->num_req++; return MHD_YES; } *req_cls = NULL; if (0 != strcmp (url, EXPECTED_URI_BASE_PATH)) { fprintf (stderr, "Unexpected URI: '%s'. ", url); mhdErrorExitDesc ("Unexpected URI found"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), PAGE); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); if (MHD_YES != MHD_add_response_header (response, RP_HEADER1_NAME, RP_HEADER1_VALUE)) mhdErrorExitDesc ("Cannot add header1"); if (MHD_YES != MHD_add_response_header (response, RP_HEADER2_NAME, RP_HEADER2_VALUE)) mhdErrorExitDesc ("Cannot add header2"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; int libcurl_finished; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ if (NULL != *multi_reuse) multi = *multi_reuse; else { multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); *multi_reuse = multi; } if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); libcurl_finished = 0; start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (! libcurl_finished) { int running; curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); libcurl_finished = ! 0; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (libcurl_finished) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; if (0 == MHD_get_timeout64s (d)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((unsigned long) tv.tv_usec / 1000); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, long expected_code, struct CBC *pcbc, struct headers_check_result *hdr_res, struct ahc_cls_type *ahc_cls) { long code; unsigned int ret; fflush (stderr); fflush (stdout); if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); return 0; } if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (expected_code != code) { fprintf (stderr, "The response has wrong HTTP code: %ld\tExpected: %ld.\n", code, expected_code); return 0; } else if (verbose) printf ("The response has expected HTTP code: %ld\n", expected_code); ret = 1; if (ahc_cls->req_check_error) { fprintf (stderr, "One or more errors have been detected by access " "handler callback.\n"); ret = 0; } if (ahc_cls->expected_upload_size != ahc_cls->up_pos) { fprintf (stderr, "Upload size does not match expected. " "Expected: %lu. " "Received: %lu.\n", (unsigned long) ahc_cls->expected_upload_size, (unsigned long) ahc_cls->up_pos); ret = 0; } if (1 != hdr_res->header1_found) { if (0 == hdr_res->header1_found) fprintf (stderr, "Response header1 was not found.\n"); else fprintf (stderr, "Response header1 was found %d times " "instead of one time only.\n", hdr_res->header1_found); ret = 0; } else if (verbose) printf ("Header1 is present in the response.\n"); if (1 != hdr_res->header2_found) { if (0 == hdr_res->header2_found) fprintf (stderr, "Response header2 was not found.\n"); else fprintf (stderr, "Response header2 was found %d times " "instead of one time only.\n", hdr_res->header2_found); ret = 0; } else if (verbose) printf ("Header2 is present in the response.\n"); if (1 != hdr_res->size_found) { if (0 == hdr_res->size_found) fprintf (stderr, "Correct response 'Content-Length' header " "was not found.\n"); else fprintf (stderr, "Correct response 'Content-Length' header " "was found %u times instead of one time only.\n", hdr_res->size_found); ret = 0; } else if (verbose) printf ("'Content-Length' header with correct value " "is present in the response.\n"); if (0 != hdr_res->size_broken_found) { fprintf (stderr, "Wrong response 'Content-Length' header was found " "%u times.\n", hdr_res->size_broken_found); ret = 0; } if (pcbc->dn_pos != MHD_STATICSTR_LEN_ (PAGE)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) pcbc->dn_pos, (int) pcbc->dn_pos, pcbc->dn_buf, (unsigned) MHD_STATICSTR_LEN_ (PAGE)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != memcmp (PAGE, pcbc->dn_buf, pcbc->dn_pos)) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) pcbc->dn_pos, pcbc->dn_buf); mhdErrorExitDesc ("Wrong returned data"); } fflush (stderr); fflush (stdout); return ret; } static unsigned int performCheck (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; struct ahc_cls_type ahc_param; struct headers_check_result rp_headers_check; char buf[2048]; CURL *c; CURLM *multi_reuse; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = UINT16_C (4220); if (! oneone) port += UINT16_C (1); if (use_put) port += UINT16_C (2); if (use_put_large) port += UINT16_C (4); if (use_hdr_last) port += UINT16_C (8); if (use_hdr_large) port += UINT16_C (16); } if (1) { size_t mem_limit; if (use_put_large) mem_limit = (size_t) (TEST_UPLOAD_DATA_SIZE / 2 + HEADERS_POINTERS_SIZE); else mem_limit = (size_t) ((TEST_UPLOAD_DATA_SIZE * 4) / 3 + 2 + HEADERS_POINTERS_SIZE); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahcCheck, &ahc_param, MHD_OPTION_CONNECTION_MEMORY_LIMIT, mem_limit, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); } if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } /* First request */ ahc_param.rq_method = use_put ? MHD_HTTP_METHOD_PUT : MHD_HTTP_METHOD_GET; ahc_param.rq_url = EXPECTED_URI_BASE_PATH; ahc_param.expected_upload_size = use_put ? TEST_UPLOAD_DATA_SIZE : 0; ahc_param.req_check_error = 0; ahc_param.num_req = 0; ahc_param.up_pos = 0; rp_headers_check.expected_size = MHD_STATICSTR_LEN_ (PAGE); rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; rp_headers_check.size_broken_found = 0; cbc.dn_buf = buf; cbc.dn_buf_size = sizeof (buf); cbc.dn_pos = 0; memset (cbc.dn_buf, 0, cbc.dn_buf_size); cbc.up_size = TEST_UPLOAD_DATA_SIZE; cbc.up_pos = 0; c = setupCURL (&cbc, port, &rp_headers_check); multi_reuse = NULL; /* First request */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_OK, &cbc, &rp_headers_check, &ahc_param)) { fflush (stderr); if (verbose) printf ("Got first expected response.\n"); fflush (stdout); } else { fprintf (stderr, "First request FAILED.\n"); fflush (stderr); failed = 1; } /* Second request */ ahc_param.req_check_error = 0; ahc_param.num_req = 0; ahc_param.up_pos = 0; rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; rp_headers_check.size_broken_found = 0; /* Reset buffer position */ cbc.dn_pos = 0; memset (cbc.dn_buf, 0, cbc.dn_buf_size); cbc.up_pos = 0; if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_OK, &cbc, &rp_headers_check, &ahc_param)) { fflush (stderr); if (verbose) printf ("Got second expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Second request FAILED.\n"); fflush (stderr); failed = 1; } /* Third request */ ahc_param.req_check_error = 0; ahc_param.num_req = 0; ahc_param.up_pos = 0; rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; rp_headers_check.size_broken_found = 0; /* Reset buffer position */ cbc.dn_pos = 0; memset (cbc.dn_buf, 0, cbc.dn_buf_size); cbc.up_pos = 0; if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); multi_reuse = NULL; /* Force new connection */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_OK, &cbc, &rp_headers_check, &ahc_param)) { fflush (stderr); if (verbose) printf ("Got third expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Third request FAILED.\n"); fflush (stderr); failed = 1; } curl_easy_cleanup (c); if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; /* Test type and test parameters */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); oneone = ! has_in_name (argv[0], "10"); use_get = has_in_name (argv[0], "_get"); use_put = has_in_name (argv[0], "_put"); use_double_fold = has_in_name (argv[0], "_double_fold"); use_put_large = has_in_name (argv[0], "_put_large"); use_hdr_last = has_in_name (argv[0], "_last"); use_hdr_large = has_in_name (argv[0], "_fold_large"); if (1 != ((use_get ? 1 : 0) + (use_put ? 1 : 0))) { fprintf (stderr, "Wrong test name '%s': no or multiple indications " "for the test type.\n", argv[0] ? argv[0] : "(NULL)"); return 99; } test_global_init (); errorCount += performCheck (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_process_headers.c0000664000175000017500000004005515232103064017130 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_process_headers.c * @brief Testcase for HTTP header access * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result kv_cb (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { if ((0 == strcmp (key, MHD_HTTP_HEADER_HOST)) && (0 == strncmp (value, "127.0.0.1", strlen ("127.0.0.1"))) && (kind == MHD_HEADER_KIND)) { *((int *) cls) = 1; return MHD_NO; } return MHD_YES; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; const char *hdr; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; ret = 0; MHD_get_connection_values (connection, MHD_HEADER_KIND, &kv_cb, &ret); if (ret != 1) abort (); hdr = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, "NotFound"); if (hdr != NULL) abort (); hdr = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT); if ((hdr == NULL) || (0 != strcmp (hdr, "*/*"))) abort (); hdr = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_HOST); if ((hdr == NULL) || (0 != strncmp (hdr, "127.0.0.1", strlen ("127.0.0.1")))) abort (); MHD_set_connection_value (connection, MHD_HEADER_KIND, "FakeHeader", "NowPresent"); hdr = MHD_lookup_connection_value (connection, MHD_HEADER_KIND, "FakeHeader"); if ((hdr == NULL) || (0 != strcmp (hdr, "NowPresent"))) abort (); response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); if (NULL == response) abort (); MHD_add_response_header (response, "MyHeader", "MyValue"); hdr = MHD_get_response_header (response, "MyHeader"); if (0 != strcmp ("MyValue", hdr)) abort (); MHD_add_response_header (response, "MyHeader", "MyValueToo"); if (MHD_YES != MHD_del_response_header (response, "MyHeader", "MyValue")) abort (); hdr = MHD_get_response_header (response, "MyHeader"); if (0 != strcmp ("MyValueToo", hdr)) abort (); if (1 != MHD_get_response_headers (response, NULL, NULL)) abort (); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1420; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1421; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1422; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1423; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (); errorCount += testMultithreadedGet (); errorCount += testMultithreadedPoolGet (); } errorCount += testExternalGet (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_process_arguments.c0000664000175000017500000002131315232103064017516 /* This file is part of libmicrohttpd Copyright (C) 2007, 2013 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_process_arguments.c * @brief Testcase for HTTP URI arguments * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; const char *hdr; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; hdr = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "k"); if ((hdr == NULL) || (0 != strcmp (hdr, "v x"))) abort (); hdr = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "hash"); if ((hdr == NULL) || (0 != strcmp (hdr, "#foo"))) abort (); hdr = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "space"); if ((hdr == NULL) || (0 != strcmp (hdr, "\240bar"))) abort (); if (3 != MHD_get_connection_values (connection, MHD_GET_ARGUMENT_KIND, NULL, NULL)) abort (); response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1410; if (oneone) port += 5; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello+world?k=v+x&hash=%23foo&space=%A0bar"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello+world")) return 8192; if (0 != strncmp ("/hello+world", cbc.buf, strlen ("/hello+world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testExternalGet (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/perf_get.c0000664000175000017500000004605015232103064014514 /* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file perf_get.c * @brief benchmark simple GET operations (sequential access). * Note that we run libcurl in the same process at the * same time, so the execution time given is the combined * time for both MHD and libcurl; it is quite possible * that more time is spend with libcurl than with MHD, * so the performance scores calculated with this code * should NOT be used to compare with other HTTP servers * (since MHD is actually better); only the relative * scores between MHD versions are meaningful. * Furthermore, this code ONLY tests MHD processing * a single request at a time. This is again * not universally meaningful (i.e. when comparing * multithreaded vs. single-threaded or select/poll). * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif /** * How many rounds of operations do we do for each * test? */ #if MHD_CPU_COUNT > 8 #ifndef _WIN32 #define ROUNDS (1 + (30000 / 12) / MHD_CPU_COUNT) #else /* _WIN32 */ #define ROUNDS (1 + (3000 / 12) / MHD_CPU_COUNT) #endif /* _WIN32 */ #else #define ROUNDS 500 #endif /** * Do we use HTTP 1.1? */ static int oneone; /** * Response to return (re-used). */ static struct MHD_Response *response; /** * Time this round was started. */ static unsigned long long start_time; /** * Get the current timestamp * * @return current time in ms */ static unsigned long long now (void) { struct timeval tv; gettimeofday (&tv, NULL); return (((unsigned long long) tv.tv_sec * 1000LL) + ((unsigned long long) tv.tv_usec / 1000LL)); } /** * Start the timer. */ static void start_timer (void) { start_time = now (); } /** * Stop the timer and report performance * * @param desc description of the threading mode we used */ static void stop (const char *desc) { double rps = ((double) (ROUNDS * 1000)) / ((double) (now () - start_time)); fprintf (stderr, "Sequential GETs using %s: %f %s\n", desc, rps, "requests/s"); } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; unsigned int i; char url[64]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); start_timer (); for (i = 0; i < ROUNDS; i++) { cbc.pos = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); } stop (poll_flag == MHD_USE_AUTO ? "internal thread with 'auto'" : poll_flag == MHD_USE_POLL ? "internal thread with poll()" : poll_flag == MHD_USE_EPOLL ? "internal thread with epoll" : "internal thread with select()"); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; unsigned int i; char url[64]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); start_timer (); for (i = 0; i < ROUNDS; i++) { cbc.pos = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); } stop ((poll_flag & MHD_USE_AUTO) ? "internal thread with 'auto' and thread per connection" : (poll_flag & MHD_USE_POLL) ? "internal thread with poll() and thread per connection" : (poll_flag & MHD_USE_EPOLL) ? "internal thread with epoll and thread per connection" : "internal thread with select() and thread per connection"); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; unsigned int i; char url[64]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); start_timer (); for (i = 0; i < ROUNDS; i++) { cbc.pos = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); } stop (0 != (poll_flag & MHD_USE_AUTO) ? "internal thread pool with 'auto'" : 0 != (poll_flag & MHD_USE_POLL) ? "internal thread pool with poll()" : 0 != (poll_flag & MHD_USE_EPOLL) ? "internal thread pool with epoll" : "internal thread pool with select()"); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalGet (uint16_t port) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; unsigned int i; char url[64]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; multi = NULL; cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (NULL == d) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); start_timer (); multi = curl_multi_init (); if (multi == NULL) { MHD_stop_daemon (d); return 512; } for (i = 0; i < ROUNDS; i++) { cbc.pos = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (c != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); c = NULL; break; } /* two possibilities here; as select sets are tiny, this makes virtually no difference in actual runtime right now, even though the number of select calls is virtually cut in half (and 'select' is the most expensive of our system calls according to 'strace') */ if (0) MHD_run (d); else MHD_run_from_select (d, &rs, &ws, &es); } if (NULL != c) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); fprintf (stderr, "Timeout!?\n"); } } stop ("external select"); if (multi != NULL) { curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; uint16_t port = 1130; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (oneone) port += 15; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; response = MHD_create_response_from_buffer_copy (strlen ("/hello_world"), "/hello_world"); errorCount += testExternalGet (port++); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (port++, MHD_USE_AUTO); errorCount += testMultithreadedGet (port++, MHD_USE_AUTO); errorCount += testMultithreadedPoolGet (port++, MHD_USE_AUTO); errorCount += testInternalGet (port++, 0); errorCount += testMultithreadedGet (port++, 0); errorCount += testMultithreadedPoolGet (port++, 0); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { errorCount += testInternalGet (port++, MHD_USE_POLL); errorCount += testMultithreadedGet (port++, MHD_USE_POLL); errorCount += testMultithreadedPoolGet (port++, MHD_USE_POLL); } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { errorCount += testInternalGet (port++, MHD_USE_EPOLL); errorCount += testMultithreadedPoolGet (port++, MHD_USE_EPOLL); } } MHD_destroy_response (response); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return errorCount != 0; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_head.c0000664000175000017500000006267415232103064014673 /* This file is part of GNU libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testcurl/test_head.c * @brief Testcase for HEAD requests * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #ifndef _WIN32 #include #include #else #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define EXPECTED_URI_BASE_PATH "/" #define EXISTING_URI EXPECTED_URI_BASE_PATH #define EXPECTED_URI_BASE_PATH_MISSING "/wrong_uri" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST URL_SCHEME URL_HOST #define HEADER1_NAME "First" #define HEADER1_VALUE "1st" #define HEADER1 HEADER1_NAME ": " HEADER1_VALUE #define HEADER1_CRLF HEADER1 "\r\n" #define HEADER2_NAME "Normal" #define HEADER2_VALUE "it's fine" #define HEADER2 HEADER2_NAME ": " HEADER2_VALUE #define HEADER2_CRLF HEADER2 "\r\n" #define PAGE \ "libmicrohttpd demo page" \ "Success!" #define PAGE_404 \ "404 error" \ "Error 404: The requested URI does not exist" /* Global parameters */ static int verbose; static int oneone; /**< If false use HTTP/1.0 for requests*/ static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); } static void test_global_cleanup (void) { curl_global_cleanup (); } struct headers_check_result { unsigned int expected_size; int header1_found; int header2_found; int size_found; }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; if ((MHD_STATICSTR_LEN_ (HEADER1_CRLF) == data_size) && (0 == memcmp (HEADER1_CRLF, buffer, data_size))) check_res->header1_found++; else if ((MHD_STATICSTR_LEN_ (HEADER2_CRLF) == data_size) && (0 == memcmp (HEADER2_CRLF, buffer, data_size))) check_res->header2_found++; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ") < data_size) && (0 == memcmp (MHD_HTTP_HEADER_CONTENT_LENGTH ": ", buffer, MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ")))) { char cmpbuf[256]; int res; const unsigned int numbers_pos = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "); res = snprintf (cmpbuf, sizeof(cmpbuf), "%u", check_res->expected_size); if ((res <= 0) || (res > ((int) (sizeof(cmpbuf) - 1)))) externalErrorExit (); if (data_size - numbers_pos <= 2) mhdErrorExitDesc ("Broken Content-Length"); else if ((((size_t) res + 2) != data_size - numbers_pos) || (0 != memcmp (buffer + numbers_pos, cmpbuf, (size_t) res))) { fprintf (stderr, "Wrong Content-Length.\n" "Expected:\n%u\n" "Received:\n%s", check_res->expected_size, buffer + numbers_pos); mhdErrorExitDesc ("Wrong Content-Length"); } else if (0 != memcmp ("\r\n", buffer + data_size - 2, 2)) { mhdErrorExitDesc ("The Content-Length header is not " \ "terminated by CRLF"); } check_res->size_found++; } return data_size; } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; /* Unused, mute compiler warning */ (void) ctx; /* Unused, mute compiler warning */ if ((0 != size) && (0 != nmemb)) libcurlErrorExitDesc ("Received unexpected body data"); return size * nmemb; } struct ahc_cls_type { const char *rq_method; const char *rq_url; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; unsigned int http_code; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (oneone) { if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); } else { if (0 != strcmp (version, MHD_HTTP_VERSION_1_0)) mhdErrorExitDesc ("Unexpected HTTP version"); } if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (NULL != upload_data) mhdErrorExitDesc ("'upload_data' is not NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } *req_cls = NULL; if (0 == strcmp (url, EXISTING_URI)) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), PAGE); http_code = MHD_HTTP_OK; } else { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE_404), PAGE_404); http_code = MHD_HTTP_NOT_FOUND; } if (NULL == response) mhdErrorExitDesc ("Failed to create response"); if (MHD_YES != MHD_add_response_header (response, HEADER1_NAME, HEADER1_VALUE)) mhdErrorExitDesc ("Cannot add header1"); if (MHD_YES != MHD_add_response_header (response, HEADER2_NAME, HEADER2_VALUE)) mhdErrorExitDesc ("Cannot add header2"); ret = MHD_queue_response (connection, http_code, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } /** * Set required URI for the request * @param c the CURL handle to use * @param uri_exist if non-zero use request for "existing" URI */ static void setCURL_rq_path (CURL *c, int uri_exist) { if (uri_exist) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, URL_SCHEME_HOST EXPECTED_URI_BASE_PATH)) libcurlErrorExitDesc ("Cannot set request URL"); } else { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, URL_SCHEME_HOST EXPECTED_URI_BASE_PATH_MISSING)) libcurlErrorExitDesc ("Cannot set request URL"); } } static int libcurl_debug_cb (CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { static const char excess_mark[] = "Excess found"; static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark); (void) handle; (void) userptr; #ifdef _DEBUG switch (type) { case CURLINFO_TEXT: fprintf (stderr, "* %.*s", (int) size, data); break; case CURLINFO_HEADER_IN: fprintf (stderr, "< %.*s", (int) size, data); break; case CURLINFO_HEADER_OUT: fprintf (stderr, "> %.*s", (int) size, data); break; case CURLINFO_DATA_IN: #if 0 fprintf (stderr, "<| %.*s\n", (int) size, data); #endif break; case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: case CURLINFO_END: default: break; } #endif /* _DEBUG */ if (CURLINFO_TEXT == type) { if ((size >= excess_mark_len) && (0 == memcmp (data, excess_mark, excess_mark_len))) mhdErrorExitDesc ("Extra data has been detected in MHD reply"); } return 0; } static CURL * setupCURL (void *cbc, uint16_t port, struct headers_check_result *hdr_chk_result) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA, hdr_chk_result)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &libcurl_debug_cb)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); /* When 'CURLOPT_NOBODY' is set, libcurl should use HEAD request. */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_NOBODY, (long) 1)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ if (NULL != *multi_reuse) multi = *multi_reuse; else { multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); *multi_reuse = multi; } if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; if (0 == MHD_get_timeout64s (d)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((unsigned long) tv.tv_usec / 1000); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, long expected_code, struct headers_check_result *hdr_res) { long code; unsigned int ret; if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (expected_code != code) { fprintf (stderr, "The response has wrong HTTP code: %ld\tExpected: %ld.\n", code, expected_code); return 0; } else if (verbose) printf ("The response has expected HTTP code: %ld\n", expected_code); ret = 1; if (1 != hdr_res->header1_found) { if (0 == hdr_res->header1_found) fprintf (stderr, "Response header1 was not found.\n"); else fprintf (stderr, "Response header1 was found %d times " "instead of one time only.\n", hdr_res->header1_found); ret = 0; } else if (verbose) printf ("Header1 is present in the response.\n"); if (1 != hdr_res->header2_found) { if (0 == hdr_res->header2_found) fprintf (stderr, "Response header2 was not found.\n"); else fprintf (stderr, "Response header2 was found %d times " "instead of one time only.\n", hdr_res->header2_found); ret = 0; } else if (verbose) printf ("Header2 is present in the response.\n"); if (1 != hdr_res->size_found) { if (0 == hdr_res->size_found) fprintf (stderr, "Response 'Content-Length' header was not found.\n"); else fprintf (stderr, "Response 'Content-Length' header was found %d times " "instead of one time only.\n", hdr_res->size_found); ret = 0; } else if (verbose) printf ("'Content-Length' header with correct value " "is present in the response.\n"); return ret; } static unsigned int testHead (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; struct ahc_cls_type ahc_param; struct headers_check_result rp_headers_check; char buf[2048]; CURL *c; CURLM *multi_reuse; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4220 + oneone ? 0 : 1; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahcCheck, &ahc_param, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } /* First request */ ahc_param.rq_method = MHD_HTTP_METHOD_HEAD; ahc_param.rq_url = EXPECTED_URI_BASE_PATH; rp_headers_check.expected_size = MHD_STATICSTR_LEN_ (PAGE); rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port, &rp_headers_check); setCURL_rq_path (c, 1); multi_reuse = NULL; /* First request */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_OK, &rp_headers_check)) { fflush (stderr); if (verbose) printf ("Got first expected response.\n"); fflush (stdout); } else { fprintf (stderr, "First request FAILED.\n"); fflush (stderr); failed = 1; } /* Second request */ rp_headers_check.expected_size = MHD_STATICSTR_LEN_ (PAGE_404); rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; cbc.pos = 0; /* Reset buffer position */ ahc_param.rq_url = EXPECTED_URI_BASE_PATH_MISSING; setCURL_rq_path (c, 0); if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_NOT_FOUND, &rp_headers_check)) { fflush (stderr); if (verbose) printf ("Got second expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Second request FAILED.\n"); fflush (stderr); failed = 1; } /* Third request */ rp_headers_check.header1_found = 0; rp_headers_check.header2_found = 0; rp_headers_check.size_found = 0; cbc.pos = 0; /* Reset buffer position */ if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); multi_reuse = NULL; /* Force new connection */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_NOT_FOUND, &rp_headers_check)) { fflush (stderr); if (verbose) printf ("Got third expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Third request FAILED.\n"); fflush (stderr); failed = 1; } curl_easy_cleanup (c); if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; /* Test type and test parameters */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); oneone = ! has_in_name (argv[0], "10"); test_global_init (); errorCount += testHead (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_patch.c0000664000175000017500000003247715232103064015067 /* This file is part of libmicrohttpd Copyright (C) 2020 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_patch.c * @brief Testcase for libmicrohttpd PATCH operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = ptr; size_t wrt; wrt = size * nmemb; if (wrt > 8 - (*pos)) wrt = 8 - (*pos); memcpy (stream, &("Hello123"[*pos]), wrt); (*pos) += wrt; return wrt; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { int *done = cls; struct MHD_Response *response; enum MHD_Result ret; (void) version; (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp ("PATCH", method)) return MHD_NO; /* unexpected method */ if ((*done) == 0) { if (*upload_data_size != 8) return MHD_YES; /* not yet ready */ if (0 == memcmp (upload_data, "Hello123", 8)) { *upload_data_size = 0; } else { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } *done = 1; return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static CURL * setup_curl (long port, struct CBC *cbc, size_t *pos) { CURL *c; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); return c; } static unsigned int testInternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1450; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = setup_curl (port, &cbc, &pos); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1451; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = setup_curl (port, &cbc, &pos); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1452; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = setup_curl (port, &cbc, &pos); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; int maxposixs; /* Max socket number unused on W32 */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; size_t pos = 0; int done_flag = 0; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1453; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = setup_curl (port, &cbc, &pos); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } #ifdef MHD_POSIX_SOCKETS if (maxsock > maxposixs) maxposixs = maxsock; #endif /* MHD_POSIX_SOCKETS */ tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalPut (); errorCount += testMultithreadedPut (); errorCount += testMultithreadedPoolPut (); } errorCount += testExternalPut (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_timeout.c0000664000175000017500000002646015232103064015451 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_timeout.c * @brief Testcase for libmicrohttpd PUT operations * @author Matthias Wachs * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_TIME_H #include #endif /* HAVE_TIME_H */ #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" /** * Pause execution for specified number of milliseconds. * @param ms the number of milliseconds to sleep */ static void _MHD_sleep (uint32_t ms) { #if defined(_WIN32) Sleep (ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp = {ms / 1000, (ms % 1000) * 1000000}; struct timespec rmn; int num_retries = 0; while (0 != nanosleep (&slp, &rmn)) { if (num_retries++ > 8) break; slp = rmn; } #elif defined(HAVE_USLEEP) uint64_t us = ms * 1000; do { uint64_t this_sleep; if (999999 < us) this_sleep = 999999; else this_sleep = us; /* Ignore return value as it could be void */ usleep (this_sleep); us -= this_sleep; } while (us > 0); #else fprintf (stderr, "No sleep function available on this system.\n"); #endif } static int oneone; static int withTimeout = 0; static int withoutTimeout = 0; struct CBC { char *buf; size_t pos; size_t size; }; static void termination_cb (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { int *test = cls; (void) connection; (void) req_cls; /* Unused. Silent compiler warning. */ switch (toe) { case MHD_REQUEST_TERMINATED_COMPLETED_OK: if (test == &withoutTimeout) { withoutTimeout = 1; } else { fprintf (stderr, "Connection completed without errors while " "timeout is expected.\n"); } break; case MHD_REQUEST_TERMINATED_WITH_ERROR: fprintf (stderr, "Connection terminated with error.\n"); exit (4); break; case MHD_REQUEST_TERMINATED_READ_ERROR: fprintf (stderr, "Connection terminated with read error.\n"); exit (4); break; case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED: if (test == &withTimeout) { withTimeout = 1; } else { fprintf (stderr, "Connection terminated with timeout while expected " "to be successfully completed.\n"); } break; case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN: fprintf (stderr, "Connection terminated by daemon shutdown.\n"); exit (4); break; case MHD_REQUEST_TERMINATED_CLIENT_ABORT: fprintf (stderr, "Connection terminated by client.\n"); exit (4); break; } } static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = ptr; size_t wrt; wrt = size * nmemb; if (wrt > 8 - (*pos)) wrt = 8 - (*pos); memcpy (stream, &("Hello123"[*pos]), wrt); (*pos) += wrt; return wrt; } static size_t putBuffer_fail (void *stream, size_t size, size_t nmemb, void *ptr) { (void) stream; (void) size; (void) nmemb; (void) ptr; /* Unused. Silent compiler warning. */ _MHD_sleep (100); /* Avoid busy-waiting */ return 0; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { int *done = cls; struct MHD_Response *response; enum MHD_Result ret; (void) version; (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_PUT, method)) return MHD_NO; /* unexpected method */ if ((*done) == 0) { if (*upload_data_size != 8) return MHD_YES; /* not yet ready */ if (0 == memcmp (upload_data, "Hello123", 8)) { *upload_data_size = 0; } else { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } *done = 1; return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testWithoutTimeout (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1500; if (oneone) port += 5; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_CONNECTION_TIMEOUT, 2, MHD_OPTION_NOTIFY_COMPLETED, &termination_cb, &withoutTimeout, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); withoutTimeout = 0; if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: '%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (0 == withoutTimeout) { fprintf (stderr, "Request wasn't processed successfully.\n"); return 2; } if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testWithTimeout (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1501; if (oneone) port += 5; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_CONNECTION_TIMEOUT, 2, MHD_OPTION_NOTIFY_COMPLETED, &termination_cb, &withTimeout, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer_fail); curl_easy_setopt (c, CURLOPT_READDATA, &testWithTimeout); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); withTimeout = 0; if (CURLE_OK != (errornum = curl_easy_perform (c))) { curl_easy_cleanup (c); MHD_stop_daemon (d); if ((errornum == CURLE_GOT_NOTHING) || (CURLE_READ_ERROR == errornum)) { if (0 != withTimeout) { /* mhd had the timeout */ return 0; } else { fprintf (stderr, "Timeout wasn't detected.\n"); return 8; } } else { fprintf (stderr, "libcurl reported error: %s (%u)\n", curl_easy_strerror (errornum), errornum); return 32; } } curl_easy_cleanup (c); MHD_stop_daemon (d); return 64; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 16; errorCount += testWithoutTimeout (); errorCount += testWithTimeout (); if (errorCount != 0) fprintf (stderr, "Error during test execution (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_suspend_resume_thread.c0000664000175000017500000002276715235436227020376 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_suspend_resume_thread.c * @brief Testcase for suspend/resume with a thread per connection * * The content reader suspends the connection and returns zero, which is * the pattern microhttpd.h prescribes for "no body data yet". The * resume comes from a separate thread, as it would from an application * that is waiting on some other I/O. Several clients run at once and * every response stalls repeatedly, so a single lost resume anywhere * hangs the connection it belongs to and the body arrives short. * * @author Christian Grothoff */ #include "mhd_options.h" #include #include #include #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif /** * Number of clients to run against the daemon at the same time. */ #define NUM_CLIENTS 4 /** * Total size of the response body. */ #define BODY_SIZE 64 /** * Number of bytes the content reader hands out at a time. */ #define CHUNK_SIZE 8 /** * Number of times the content reader stalls before each chunk. */ #define NUM_STALLS 3 /** * The byte the response body is made of. */ #define BODY_FILL 'x' struct ReaderData { /** * Connection to suspend and resume. */ struct MHD_Connection *connection; /** * Number of stalls left before the next chunk is handed out. */ unsigned int stalls_left; }; static uint16_t port; static volatile unsigned int panicked; _MHD_NORETURN static void test_panic_cb (void *cls, const char *file, unsigned int line, const char *reason) { (void) cls; fprintf (stderr, "PANIC: %s at %s:%u\n", (NULL != reason) ? reason : "", file, line); panicked = 1; exit (99); } static void * resume_thread (void *cls) { /* Give the connection's thread a chance to actually park itself, so that the resume has to travel between threads. */ (void) usleep (1000); MHD_resume_connection (cls); return NULL; } static ssize_t content_reader (void *cls, uint64_t pos, char *buf, size_t max) { struct ReaderData *data = cls; pthread_t tid; if (pos >= BODY_SIZE) return MHD_CONTENT_READER_END_OF_STREAM; if (0 != data->stalls_left) { /* No data yet. Park the connection and report that, as documented for #MHD_ContentReaderCallback. */ data->stalls_left--; MHD_suspend_connection (data->connection); if (0 != pthread_create (&tid, NULL, &resume_thread, data->connection)) return MHD_CONTENT_READER_END_WITH_ERROR; (void) pthread_detach (tid); return 0; } data->stalls_left = NUM_STALLS; if (max > CHUNK_SIZE) max = CHUNK_SIZE; if (max > (size_t) (BODY_SIZE - pos)) max = (size_t) (BODY_SIZE - pos); memset (buf, BODY_FILL, max); return (ssize_t) max; } static void free_reader_data (void *cls) { free (cls); } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; struct ReaderData *data; enum MHD_Result ret; (void) cls; (void) url; (void) method; (void) version; (void) upload_data; (void) upload_data_size; if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } data = malloc (sizeof (struct ReaderData)); if (NULL == data) return MHD_NO; data->connection = connection; data->stalls_left = NUM_STALLS; response = MHD_create_response_from_callback (BODY_SIZE, 4096, &content_reader, data, &free_reader_data); if (NULL == response) { free (data); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } struct Buffer { size_t used; char data[2 * BODY_SIZE]; }; static size_t copy_buffer (void *ptr, size_t size, size_t nmemb, void *cls) { struct Buffer *buf = cls; if (0 == size * nmemb) return 0; if (buf->used + size * nmemb > sizeof (buf->data)) return 0; /* overflow */ memcpy (&buf->data[buf->used], ptr, size * nmemb); buf->used += size * nmemb; return size * nmemb; } /** * Fetch the response once. * * @param cls unused * @return NULL on success, non-NULL on failure */ static void * client_thread (void *cls) { static int failure = 1; char url[128]; struct Buffer buf; CURL *c; CURLcode errornum; (void) cls; memset (&buf, 0, sizeof (buf)); c = curl_easy_init (); if (NULL == c) return &failure; snprintf (url, sizeof (url), "http://127.0.0.1:%u/", (unsigned int) port); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©_buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &buf); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 30L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 30L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); errornum = curl_easy_perform (c); curl_easy_cleanup (c); if (CURLE_OK != errornum) { fprintf (stderr, "curl_easy_perform() failed: `%s'\n", curl_easy_strerror (errornum)); return &failure; } if (BODY_SIZE != buf.used) { fprintf (stderr, "Got %u bytes of body, expected %u.\n", (unsigned int) buf.used, (unsigned int) BODY_SIZE); return &failure; } if (BODY_SIZE != strspn (buf.data, "x")) { fprintf (stderr, "Body has unexpected content.\n"); return &failure; } return NULL; } /** * Run all clients against a daemon started with the given flags. * * @param flags the flags to start the daemon with * @return 0 on success */ static unsigned int test_daemon (unsigned int flags) { pthread_t clients[NUM_CLIENTS]; struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; void *res; unsigned int i; unsigned int started; unsigned int failures; d = MHD_start_daemon (flags | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_ALLOW_SUSPEND_RESUME | MHD_USE_ERROR_LOG, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start daemon with flags %x.\n", flags); return 1; } dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); fprintf (stderr, "Failed to get the port number.\n"); return 1; } port = dinfo->port; failures = 0; for (started = 0; started < NUM_CLIENTS; started++) { if (0 != pthread_create (&clients[started], NULL, &client_thread, NULL)) { fprintf (stderr, "Failed to create a client thread.\n"); failures++; break; } } for (i = 0; i < started; i++) { res = NULL; if (0 != pthread_join (clients[i], &res)) { fprintf (stderr, "Failed to join a client thread.\n"); failures++; } else if (NULL != res) failures++; } MHD_stop_daemon (d); return failures; } int main (int argc, char *const *argv) { unsigned int failures = 0; (void) argc; (void) argv; MHD_set_panic_func (&test_panic_cb, NULL); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; /* Without an ITC, and with one; both use select() internally. */ failures += test_daemon (0); failures += test_daemon (MHD_USE_ITC); if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_POLL)) failures += test_daemon (MHD_USE_POLL | MHD_USE_ITC); curl_global_cleanup (); if (0 != panicked) return 99; return (0 == failures) ? 0 : 1; } libmicrohttpd-1.0.10/src/testcurl/test_add_conn.c0000664000175000017500000011143515232103064015525 /* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) - large rework, multithreading. libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_add_conn.c * @brief Testcase for libmicrohttpd GET operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #include "mhd_has_param.h" #include "mhd_sockets.h" /* only macros used */ /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifdef HAVE_PTHREAD_H #include #endif /* HAVE_PTHREAD_H */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 /* Number of requests per daemon in cleanup test, * the number must be more than one as the first connection * will be processed and the rest will stay in the list of unprocessed */ #define CLEANUP_NUM_REQS_PER_DAEMON 6 /* Cleanup test: max number of concurrent daemons depending on maximum number * of open FDs. */ #define CLEANUP_MAX_DAEMONS(max_fds) (unsigned int) \ ( ((max_fds) < 10) ? \ 0 : ( (((max_fds) - 10) / (CLEANUP_NUM_REQS_PER_DAEMON * 5 + 3)) ) ) #define EXPECTED_URI_BASE_PATH "/hello_world" #define EXPECTED_URI_QUERY "a=%26&b=c" #define EXPECTED_URI_FULL_PATH EXPECTED_URI_BASE_PATH "?" EXPECTED_URI_QUERY /* Global parameters */ static int oneone; /**< Use HTTP/1.1 instead of HTTP/1.0 */ static int no_listen; /**< Start MHD daemons without listen socket */ static uint16_t global_port; /**< MHD daemons listen port number */ static int cleanup_test; /**< Test for final cleanup */ static int slow_reply = 0; /**< Slowdown MHD replies */ static int ignore_response_errors = 0; /**< Do not fail test if CURL returns error */ static int response_timeout_val = TIMEOUTS_VAL; static int sys_max_fds; /**< Current system limit for number of open files. */ struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static void * log_cb (void *cls, const char *uri, struct MHD_Connection *con) { (void) cls; (void) con; if (0 != strcmp (uri, EXPECTED_URI_FULL_PATH)) { fprintf (stderr, "Wrong URI: `%s'\n", uri); _exit (22); } return NULL; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; const char *v; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silence compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; v = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "a"); if ( (NULL == v) || (0 != strcmp ("&", v)) ) { fprintf (stderr, "Found while looking for 'a=&': 'a=%s'\n", NULL == v ? "NULL" : v); _exit (17); } v = NULL; if (MHD_YES != MHD_lookup_connection_value_n (connection, MHD_GET_ARGUMENT_KIND, "b", 1, &v, NULL)) { fprintf (stderr, "Not found 'b' GET argument.\n"); _exit (18); } if ( (NULL == v) || (0 != strcmp ("c", v)) ) { fprintf (stderr, "Found while looking for 'b=c': 'b=%s'\n", NULL == v ? "NULL" : v); _exit (19); } if (slow_reply) usleep (200000); response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) { fprintf (stderr, "Failed to queue response.\n"); _exit (19); } return ret; } _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); _exit (99); } #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #endif /* Static const value, indicates that result value was not set yet */ static const unsigned int eMarker = 0xCE; static MHD_socket createListeningSocket (uint16_t *pport) { MHD_socket skt; struct sockaddr_in sin; socklen_t sin_len; #ifdef MHD_POSIX_SOCKETS static int on = 1; #endif /* MHD_POSIX_SOCKETS */ skt = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == skt) externalErrorExitDesc ("socket() failed"); #ifdef MHD_POSIX_SOCKETS setsockopt (skt, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof (on)); /* Ignore possible error */ #endif /* MHD_POSIX_SOCKETS */ memset (&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons (*pport); sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != bind (skt, (struct sockaddr *) &sin, sizeof(sin))) externalErrorExitDesc ("bind() failed"); if (0 != listen (skt, SOMAXCONN)) externalErrorExitDesc ("listen() failed"); if (0 == *pport) { memset (&sin, 0, sizeof(sin)); sin_len = (socklen_t) sizeof(sin); if (0 != getsockname (skt, (struct sockaddr *) &sin, &sin_len)) externalErrorExitDesc ("getsockname() failed"); if (sizeof(sin) < (size_t) sin_len) externalErrorExitDesc ("getsockname() failed"); if (AF_INET != sin.sin_family) externalErrorExitDesc ("getsockname() returned wrong socket family"); *pport = ntohs (sin.sin_port); } return skt; } static MHD_socket acceptTimeLimited (MHD_socket lstn_sk, struct sockaddr *paddr, socklen_t *paddr_len) { fd_set rs; struct timeval timeoutval; MHD_socket accepted; FD_ZERO (&rs); FD_SET (lstn_sk, &rs); timeoutval.tv_sec = TIMEOUTS_VAL; timeoutval.tv_usec = 0; if (1 != select (((int) lstn_sk) + 1, &rs, NULL, NULL, &timeoutval)) externalErrorExitDesc ("select() failed"); accepted = accept (lstn_sk, paddr, paddr_len); if (MHD_INVALID_SOCKET == accepted) externalErrorExitDesc ("accept() failed"); return accepted; } struct addConnParam { struct MHD_Daemon *d; MHD_socket lstn_sk; MHD_socket clent_sk; /* Non-zero indicate error */ volatile unsigned int result; #ifdef HAVE_PTHREAD_H pthread_t addConnThread; #endif /* HAVE_PTHREAD_H */ }; static unsigned int doAcceptAndAddConnInThread (struct addConnParam *p) { struct sockaddr addr; socklen_t addr_len = sizeof(addr); p->clent_sk = acceptTimeLimited (p->lstn_sk, &addr, &addr_len); p->result = (MHD_YES == MHD_add_connection (p->d, p->clent_sk, &addr, addr_len)) ? 0 : 1; if (p->result) fprintf (stderr, "MHD_add_connection() failed, errno=%d.\n", errno); return p->result; } #ifdef HAVE_PTHREAD_H static void * doAcceptAndAddConn (void *param) { struct addConnParam *p = param; (void) doAcceptAndAddConnInThread (p); return (void *) p; } static void startThreadAddConn (struct addConnParam *param) { /* thread must reset this value to zero if succeed */ param->result = eMarker; if (0 != pthread_create (¶m->addConnThread, NULL, &doAcceptAndAddConn, (void *) param)) externalErrorExitDesc ("pthread_create() failed"); } static unsigned int finishThreadAddConn (struct addConnParam *param) { struct addConnParam *result; if (0 != pthread_join (param->addConnThread, (void **) &result)) externalErrorExitDesc ("pthread_join() failed"); if (param != result) abort (); /* Test used in a wrong way */ if (eMarker == param->result) abort (); /* Test used in a wrong way */ return result->result; } #endif /* HAVE_PTHREAD_H */ struct curlQueryParams { /* Destination path for CURL query */ const char *queryPath; /* Destination port for CURL query */ uint16_t queryPort; /* CURL query result error flag */ volatile unsigned int queryError; #ifdef HAVE_PTHREAD_H pthread_t queryThread; #endif /* HAVE_PTHREAD_H */ }; static CURL * curlEasyInitForTest (const char *queryPath, uint16_t port, struct CBC *pcbc) { CURL *c; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); _exit (99); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, queryPath)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); _exit (99); } return c; } static unsigned int doCurlQueryInThread (struct curlQueryParams *p) { CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; if (NULL == p->queryPath) abort (); if (0 == p->queryPort) abort (); cbc.buf = buf; cbc.size = sizeof(buf); cbc.pos = 0; c = curlEasyInitForTest (p->queryPath, p->queryPort, &cbc); errornum = curl_easy_perform (c); if (ignore_response_errors) { p->queryError = 0; curl_easy_cleanup (c); return p->queryError; } if (CURLE_OK != errornum) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); p->queryError = 2; } else { if (cbc.pos != strlen (EXPECTED_URI_BASE_PATH)) { fprintf (stderr, "curl reports wrong size of MHD reply body data.\n"); p->queryError = 4; } else if (0 != strncmp (EXPECTED_URI_BASE_PATH, cbc.buf, strlen (EXPECTED_URI_BASE_PATH))) { fprintf (stderr, "curl reports wrong MHD reply body data.\n"); p->queryError = 4; } else p->queryError = 0; } curl_easy_cleanup (c); return p->queryError; } #ifdef HAVE_PTHREAD_H static void * doCurlQuery (void *param) { struct curlQueryParams *p = (struct curlQueryParams *) param; (void) doCurlQueryInThread (p); return param; } static void startThreadCurlQuery (struct curlQueryParams *param) { /* thread must reset this value to zero if succeed */ param->queryError = eMarker; if (0 != pthread_create (¶m->queryThread, NULL, &doCurlQuery, (void *) param)) externalErrorExitDesc ("pthread_create() failed"); } static unsigned int finishThreadCurlQuery (struct curlQueryParams *param) { struct curlQueryParams *result; if (0 != pthread_join (param->queryThread, (void **) &result)) externalErrorExitDesc ("pthread_join() failed"); if (param != result) abort (); /* Test used in wrong way */ if (eMarker == param->queryError) abort (); /* Test used in wrong way */ return result->queryError; } /* Perform test queries and shut down MHD daemon */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port) { struct curlQueryParams qParam; struct addConnParam aParam; uint16_t a_port; /* Additional listening socket port */ unsigned int ret = 0; /* Return value */ qParam.queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH; a_port = 0; /* auto-assign */ aParam.d = d; aParam.lstn_sk = createListeningSocket (&a_port); /* Sets a_port */ /* Test of adding connection in the same thread */ qParam.queryError = eMarker; /* to be zeroed in new thread */ qParam.queryPort = a_port; /* Connect to additional socket */ startThreadCurlQuery (&qParam); ret |= doAcceptAndAddConnInThread (&aParam); ret |= finishThreadCurlQuery (&qParam); if (! no_listen) { /* Test of the daemon itself can accept and process new connection. */ ret <<= 3; /* Remember errors for each step */ qParam.queryPort = d_port; /* Connect to the daemon */ ret |= doCurlQueryInThread (&qParam); } /* Test of adding connection in an external thread */ ret <<= 3; /* Remember errors for each step */ aParam.result = eMarker; /* to be zeroed in new thread */ qParam.queryPort = a_port; /* Connect to the daemon */ startThreadAddConn (&aParam); ret |= doCurlQueryInThread (&qParam); ret |= finishThreadAddConn (&aParam); (void) MHD_socket_close_ (aParam.lstn_sk); MHD_stop_daemon (d); return ret; } /* Perform test for cleanup and shutdown MHD daemon */ static unsigned int performTestCleanup (struct MHD_Daemon *d, unsigned int num_queries) { struct curlQueryParams *qParamList; struct addConnParam aParam; MHD_socket lstn_sk; /* Additional listening socket */ MHD_socket *clntSkList; uint16_t a_port; /* Additional listening socket port */ unsigned int i; unsigned int ret = 0; /* Return value */ a_port = 0; /* auto-assign */ if (0 >= num_queries) abort (); /* Test's API violation */ lstn_sk = createListeningSocket (&a_port); /* Sets a_port */ qParamList = malloc (sizeof(struct curlQueryParams) * num_queries); clntSkList = malloc (sizeof(MHD_socket) * num_queries); if ((NULL == qParamList) || (NULL == clntSkList)) externalErrorExitDesc ("malloc failed"); /* Start CURL queries */ for (i = 0; i < num_queries; i++) { qParamList[i].queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH; qParamList[i].queryError = 0; qParamList[i].queryPort = a_port; startThreadCurlQuery (qParamList + i); } /* Accept and add required number of client sockets */ aParam.d = d; aParam.lstn_sk = lstn_sk; for (i = 0; i < num_queries; i++) { aParam.clent_sk = MHD_INVALID_SOCKET; ret |= doAcceptAndAddConnInThread (&aParam); clntSkList[i] = aParam.clent_sk; } /* Stop daemon while some of new connection are not yet * processed because of slow response to the first queries. */ MHD_stop_daemon (d); (void) MHD_socket_close_ (aParam.lstn_sk); /* Check whether all client sockets were closed by MHD. * Closure of socket by MHD indicate valid cleanup performed. */ for (i = 0; i < num_queries; i++) { if (MHD_INVALID_SOCKET != clntSkList[i]) { /* Check whether socket could be closed one more time. */ if (MHD_socket_close_ (clntSkList[i])) { ret |= 2; fprintf (stderr, "Client socket was not closed by MHD during" \ "cleanup process.\n"); } } } /* Wait for CURL threads to complete. */ /* Ignore soft CURL errors as many connection shouldn't get any response. * Hard failures are detected in processing function. */ for (i = 0; i < num_queries; i++) (void) finishThreadCurlQuery (qParamList + i); free (clntSkList); free (qParamList); return ret; } #endif /* HAVE_PTHREAD_H */ enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; if (! cleanup_test) return numThreads; /* No practical limit for non-cleanup test */ if (CLEANUP_MAX_DAEMONS (sys_max_fds) < numThreads) numThreads = CLEANUP_MAX_DAEMONS (sys_max_fds); if ((testMhdPollBySelect == pollType) && (CLEANUP_MAX_DAEMONS (FD_SETSIZE) < numThreads)) numThreads = CLEANUP_MAX_DAEMONS (FD_SETSIZE); if (2 > numThreads) abort (); return (unsigned int) numThreads; } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 1550; if (oneone) *pport += 1; if (no_listen) *pport += 2; if (cleanup_test) *pport += 4; } switch (thrType) { case testMhdThreadExternal: d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | MHD_USE_NO_THREAD_SAFETY | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0) | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); break; case testMhdThreadInternalPool: d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | MHD_USE_ITC | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0) | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); break; case testMhdThreadInternal: case testMhdThreadInternalPerConnection: d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | MHD_USE_ITC | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0) | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); break; default: abort (); break; } if (NULL == d) { fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno); abort (); } if ((! no_listen) && (0 == *pport)) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } *pport = dinfo->port; } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; CURL *c_d; char buf_d[2048]; struct CBC cbc_d; CURL *c_a; char buf_a[2048]; struct CBC cbc_a; CURLM *multi; time_t start; struct timeval tv; uint16_t d_port = global_port; /* Daemon's port */ uint16_t a_port = 0; /* Additional listening socket port */ struct addConnParam aParam; unsigned int ret = 0; /* Return value of the test */ const int c_no_listen = no_listen; /* Local const value to mute analyzer */ d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port); aParam.d = d; aParam.lstn_sk = createListeningSocket (&a_port); multi = NULL; cbc_d.buf = buf_d; cbc_d.size = sizeof(buf_d); cbc_d.pos = 0; cbc_a.buf = buf_a; cbc_a.size = sizeof(buf_a); cbc_a.pos = 0; if (cleanup_test) abort (); /* Not possible with "external poll" as connections are directly added to the daemon processing in the mode. */ if (! c_no_listen) c_d = curlEasyInitForTest ("http://127.0.0.1" EXPECTED_URI_FULL_PATH, d_port, &cbc_d); else c_d = NULL; /* To mute compiler warning only */ c_a = curlEasyInitForTest ("http://127.0.0.1" EXPECTED_URI_FULL_PATH, a_port, &cbc_a); multi = curl_multi_init (); if (multi == NULL) { fprintf (stderr, "curl_multi_init() failed.\n"); _exit (99); } if (! c_no_listen) { if (CURLM_OK != curl_multi_add_handle (multi, c_d)) { fprintf (stderr, "curl_multi_add_handle() failed.\n"); _exit (99); } } if (CURLM_OK != curl_multi_add_handle (multi, c_a)) { fprintf (stderr, "curl_multi_add_handle() failed.\n"); _exit (99); } start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) { fprintf (stderr, "curl_multi_info_read failed, NULL returned.\n"); _exit (99); } totalMsgs++; if (CURLMSG_DONE == msg->msg) { if (CURLE_OK != msg->data.result) { fprintf (stderr, "curl_multi_info_read failed, error: '%s'\n", curl_easy_strerror (msg->data.result)); ret |= 2; } } } while (msgLeft > 0); if ((no_listen ? 1 : 2) != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); _exit (99); } break; /* All transfers have finished. */ } if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) { fprintf (stderr, "curl_multi_fdset() failed.\n"); _exit (99); } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) { ret |= 8; break; } FD_SET (aParam.lstn_sk, &rs); if (maxMhdSk < aParam.lstn_sk) maxMhdSk = aParam.lstn_sk; tv.tv_sec = 0; tv.tv_usec = 1000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } if (FD_ISSET (aParam.lstn_sk, &rs)) ret |= doAcceptAndAddConnInThread (&aParam); if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) { fprintf (stderr, "MHD_run_from_select() failed.\n"); ret |= 1; break; } } MHD_stop_daemon (d); (void) MHD_socket_close_ (aParam.lstn_sk); if (! c_no_listen) { curl_multi_remove_handle (multi, c_d); curl_easy_cleanup (c_d); if (cbc_d.pos != strlen ("/hello_world")) { fprintf (stderr, "curl reports wrong size of MHD reply body data at line %d.\n", __LINE__); ret |= 4; } if (0 != strncmp ("/hello_world", cbc_d.buf, strlen ("/hello_world"))) { fprintf (stderr, "curl reports wrong MHD reply body data at line %d.\n", __LINE__); ret |= 4; } } curl_multi_remove_handle (multi, c_a); curl_easy_cleanup (c_a); curl_multi_cleanup (multi); if (cbc_a.pos != strlen ("/hello_world")) { fprintf (stderr, "curl reports wrong size of MHD reply body data at line %d.\n", __LINE__); ret |= 4; } if (0 != strncmp ("/hello_world", cbc_a.buf, strlen ("/hello_world"))) { fprintf (stderr, "curl reports wrong MHD reply body data at line %d.\n", __LINE__); ret |= 4; } return ret; } #ifdef HAVE_PTHREAD_H static unsigned int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port); if (cleanup_test) return performTestCleanup (d, CLEANUP_NUM_REQS_PER_DAEMON); return performTestQueries (d, d_port); } static unsigned int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port); if (cleanup_test) abort (); /* Cannot be tested as main daemon thread cannot be slowed down by slow responses, so it processes all new connections before daemon could be stopped. */ return performTestQueries (d, d_port); } static unsigned int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port); if (cleanup_test) return performTestCleanup (d, CLEANUP_NUM_REQS_PER_DAEMON * testNumThreadsForPool (pollType)); return performTestQueries (d, d_port); } static unsigned int testStopRace (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ uint16_t a_port = 0; /* Additional listening socket port */ struct sockaddr_in sin; MHD_socket fd1; MHD_socket fd2; struct addConnParam aParam; unsigned int ret = 0; /* Return value of the test */ d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port); if (! no_listen) { fd1 = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == fd1) externalErrorExitDesc ("socket() failed"); memset (&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons (d_port); sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (connect (fd1, (struct sockaddr *) (&sin), sizeof(sin)) < 0) externalErrorExitDesc ("socket() failed"); } else fd1 = MHD_INVALID_SOCKET; aParam.d = d; aParam.lstn_sk = createListeningSocket (&a_port); /* Sets a_port */ startThreadAddConn (&aParam); fd2 = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == fd2) externalErrorExitDesc ("socket() failed"); memset (&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons (a_port); sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (connect (fd2, (struct sockaddr *) (&sin), sizeof(sin)) < 0) externalErrorExitDesc ("socket() failed"); ret |= finishThreadAddConn (&aParam); /* Let the thread get going. */ usleep (500000); MHD_stop_daemon (d); if (MHD_INVALID_SOCKET != fd1) (void) MHD_socket_close_ (fd1); (void) MHD_socket_close_ (aParam.lstn_sk); (void) MHD_socket_close_ (fd2); return ret; } #endif /* HAVE_PTHREAD_H */ int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; int verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); /* Whether to test MHD daemons without listening socket. */ no_listen = has_in_name (argv[0], "_nolisten"); /* Whether to test for correct final cleanup instead of * of test of normal processing. */ cleanup_test = has_in_name (argv[0], "_cleanup"); /* There are almost nothing that could be tested externally * for final cleanup. Cleanup test actually just tests that * all added client connections were closed by MHD and * nothing fails or crashes when final cleanup is performed. * Mostly useful when configured with '--enable-asserts. */ slow_reply = cleanup_test; ignore_response_errors = cleanup_test; #ifndef HAVE_PTHREAD_H if (cleanup_test) return 77; /* Cannot run without threads */ #endif /* HAVE_PTHREAD_H */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); if (cleanup_test) { #ifndef _WIN32 /* Find system limit for number of open FDs. */ #if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX) sys_max_fds = sysconf (_SC_OPEN_MAX) > 500000 ? 500000 : (int) sysconf (_SC_OPEN_MAX); #else /* ! HAVE_SYSCONF || ! _SC_OPEN_MAX */ sys_max_fds = -1; #endif /* ! HAVE_SYSCONF || ! _SC_OPEN_MAX */ if (0 > sys_max_fds) { #if defined(OPEN_MAX) && (0 < ((OPEN_MAX) +1)) sys_max_fds = OPEN_MAX > 500000 ? 500000 : (int) OPEN_MAX; #else /* ! OPEN_MAX */ sys_max_fds = 256; /* Use reasonable value */ #endif /* ! OPEN_MAX */ if (2 > CLEANUP_MAX_DAEMONS (sys_max_fds)) return 77; /* Multithreaded test cannot be run */ } #else /* _WIN32 */ sys_max_fds = 120; /* W32 has problems with ports exhaust */ #endif /* _WIN32 */ } if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 99; /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; if (! cleanup_test) { test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; } #ifdef HAVE_PTHREAD_H if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; if (! cleanup_test) { test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testStopRace (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testStopRace (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testStopRace (testMhdPollBySelect).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollByPoll).\n"); errorCount += test_result; if (! cleanup_test) { test_result = testMultithreadedGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollByPoll).\n"); errorCount += test_result; test_result = testStopRace (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testStopRace (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testStopRace (testMhdPollByPoll).\n"); errorCount += test_result; } } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollByEpoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollByEpoll).\n"); errorCount += test_result; } } #endif /* HAVE_PTHREAD_H */ if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); curl_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_iplimit.c0000664000175000017500000002245615232103064015433 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_iplimit.c * @brief Testcase for libmicrohttpd limits per IP * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; char buf[2048]; int k; unsigned int success; unsigned int failure; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1260; if (oneone) port += 5; } /* Test only valid for HTTP/1.1 (uses persistent connections) */ if (! oneone) return 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 2, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } for (k = 0; k < 3; ++k) { struct CBC cbc[3]; CURL *cenv[3]; int i; success = 0; failure = 0; for (i = 0; i < 3; ++i) { CURL *c; CURLcode errornum; cenv[i] = c = curl_easy_init (); cbc[i].buf = buf; cbc[i].size = 2048; cbc[i].pos = 0; curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc[i]); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_FORBID_REUSE, 0L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); errornum = curl_easy_perform (c); if (CURLE_OK == errornum) success++; else failure++; } /* Cleanup the environments */ for (i = 0; i < 3; ++i) curl_easy_cleanup (cenv[i]); if ( (2 != success) || (1 != failure) ) { fprintf (stderr, "Unexpected number of success (%u) or failure (%u)\n", success, failure); MHD_stop_daemon (d); return 32; } (void) sleep (2); for (i = 0; i < 2; ++i) { if (cbc[i].pos != strlen ("/hello_world")) { MHD_stop_daemon (d); return 64; } if (0 != strncmp ("/hello_world", cbc[i].buf, strlen ("/hello_world"))) { MHD_stop_daemon (d); return 128; } } } MHD_stop_daemon (d); return 0; } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; char buf[2048]; int k; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1261; if (oneone) port += 5; } /* Test only valid for HTTP/1.1 (uses persistent connections) */ if (! oneone) return 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 2, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } for (k = 0; k < 3; ++k) { struct CBC cbc[3]; CURL *cenv[3]; int i; for (i = 0; i < 3; ++i) { CURL *c; CURLcode errornum; cenv[i] = c = curl_easy_init (); cbc[i].buf = buf; cbc[i].size = 2048; cbc[i].pos = 0; curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc[i]); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_FORBID_REUSE, 0L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); errornum = curl_easy_perform (c); if ( ( (CURLE_OK != errornum) && (i < 2) ) || ( (CURLE_OK == errornum) && (i == 2) ) ) { int j; /* First 2 should succeed */ if (i < 2) fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); /* Last request should have failed */ else fprintf (stderr, "No error on IP address over limit\n"); for (j = 0; j < i; ++j) curl_easy_cleanup (cenv[j]); MHD_stop_daemon (d); return 32; } } /* Cleanup the environments */ for (i = 0; i < 3; ++i) curl_easy_cleanup (cenv[i]); (void) sleep (2); for (i = 0; i < 2; ++i) { if (cbc[i].pos != strlen ("/hello_world")) { MHD_stop_daemon (d); return 64; } if (0 != strncmp ("/hello_world", cbc[i].buf, strlen ("/hello_world"))) { MHD_stop_daemon (d); return 128; } } } MHD_stop_daemon (d); return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount |= testMultithreadedGet (); errorCount |= testMultithreadedPoolGet (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_post_loop.c0000664000175000017500000004545015232103064016001 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_post_loop.c * @brief Testcase for libmicrohttpd POST operations using URL-encoding * @author Christian Grothoff (inspired by bug report #1296) * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define POST_DATA \ "\n\n1\n\n" #ifndef __APPLE__ #define LOOPCOUNT 1000 #else /* __APPLE__ */ /* FIXME: macOS may fail in this test with "unable to connect". Investigate deeper? */ #define LOOPCOUNT 200 #endif /* __APPLE__ */ static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp ("POST", method)) { printf ("METHOD: %s\n", method); return MHD_NO; /* unexpected method */ } if ((*req_cls != NULL) && (0 == *upload_data_size)) { if (*req_cls != &marker) abort (); response = MHD_create_response_from_buffer_static (2, "OK"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); *req_cls = NULL; return ret; } if (strlen (POST_DATA) != *upload_data_size) return MHD_YES; *upload_data_size = 0; *req_cls = ▮ return MHD_YES; } static unsigned int testInternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int i; char url[1024]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1350; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } for (i = 0; i < LOOPCOUNT; i++) { if (99 == i % 100) fprintf (stderr, "."); c = curl_easy_init (); cbc.pos = 0; buf[0] = '\0'; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hw%d", (unsigned int) port, i); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); if ((buf[0] != 'O') || (buf[1] != 'K')) { MHD_stop_daemon (d); return 4; } } MHD_stop_daemon (d); if (LOOPCOUNT >= 99) fprintf (stderr, "\n"); return 0; } static unsigned int testMultithreadedPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int i; char url[1024]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1351; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } for (i = 0; i < LOOPCOUNT; i++) { if (99 == i % 100) fprintf (stderr, "."); c = curl_easy_init (); cbc.pos = 0; buf[0] = '\0'; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hw%d", (unsigned int) port, i); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); if ((buf[0] != 'O') || (buf[1] != 'K')) { MHD_stop_daemon (d); return 64; } } MHD_stop_daemon (d); if (LOOPCOUNT >= 99) fprintf (stderr, "\n"); return 0; } static unsigned int testMultithreadedPoolPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int i; char url[1024]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1352; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } for (i = 0; i < LOOPCOUNT; i++) { if (99 == i % 100) fprintf (stderr, "."); c = curl_easy_init (); cbc.pos = 0; buf[0] = '\0'; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hw%d", (unsigned int) port, i); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); if ((buf[0] != 'O') || (buf[1] != 'K')) { MHD_stop_daemon (d); return 64; } } MHD_stop_daemon (d); if (LOOPCOUNT >= 99) fprintf (stderr, "\n"); return 0; } static unsigned int testExternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; int i; uint64_t timeout64; long ctimeout; char url[1024]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1353; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } multi = curl_multi_init (); if (multi == NULL) { MHD_stop_daemon (d); return 512; } for (i = 0; i < LOOPCOUNT; i++) { if (99 == i % 100) fprintf (stderr, "."); c = curl_easy_init (); cbc.pos = 0; buf[0] = '\0'; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hw%d", (unsigned int) port, i); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform (multi, &running)) ; mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } if (MHD_NO == MHD_get_timeout64 (d, &timeout64)) timeout64 = 100; /* 100ms == INFTY -- CURL bug... */ if ((CURLM_OK == curl_multi_timeout (multi, &ctimeout)) && (ctimeout >= 0) && ((uint64_t) ctimeout < timeout64)) timeout64 = (uint64_t) ctimeout; if (0 == running) timeout64 = 0; /* terminate quickly... */ #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (timeout64 / 1000); #else /* Native W32 */ tv.tv_sec = (long) (timeout64 / 1000); #endif /* Native W32 */ tv.tv_usec = (long) (1000 * (timeout64 % 1000)); if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform (multi, &running)) ; if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } break; } MHD_run (d); } if (NULL != c) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); } if ((buf[0] != 'O') || (buf[1] != 'K')) { curl_multi_cleanup (multi); MHD_stop_daemon (d); return 8192; } } curl_multi_cleanup (multi); MHD_stop_daemon (d); if (LOOPCOUNT >= 99) fprintf (stderr, "\n"); return 0; } /** * Time this round was started. */ static unsigned long long start_time; /** * Get the current timestamp * * @return current time in ms */ static unsigned long long now (void) { struct timeval tv; gettimeofday (&tv, NULL); return (((unsigned long long) tv.tv_sec * 1000LL) + ((unsigned long long) tv.tv_usec / 1000LL)); } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { start_time = now (); errorCount += testInternalPost (); fprintf (stderr, oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n", "internal select", (double) 1000 * LOOPCOUNT / ((double) (now () - start_time) + 1.0)); start_time = now (); errorCount += testMultithreadedPost (); fprintf (stderr, oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n", "multithreaded post", (double) 1000 * LOOPCOUNT / ((double) (now () - start_time) + 1.0)); start_time = now (); errorCount += testMultithreadedPoolPost (); fprintf (stderr, oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n", "thread with pool", (double) 1000 * LOOPCOUNT / ((double) (now () - start_time) + 1.0)); } start_time = now (); errorCount += testExternalPost (); fprintf (stderr, oneone ? "%s: Sequential POSTs (http/1.1) %f/s\n" : "%s: Sequential POSTs (http/1.0) %f/s\n", "external select", (double) 1000 * LOOPCOUNT / ((double) (now () - start_time) + 1.0)); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_put.c0000664000175000017500000003746015232103064014575 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_put.c * @brief Testcase for libmicrohttpd PUT operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = ptr; size_t wrt; wrt = size * nmemb; if (wrt > 8 - (*pos)) wrt = 8 - (*pos); memcpy (stream, &("Hello123"[*pos]), wrt); (*pos) += wrt; return wrt; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { int *done = cls; struct MHD_Response *response; enum MHD_Result ret; (void) version; (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp ("PUT", method)) return MHD_NO; /* unexpected method */ if ((*done) == 0) { if (*upload_data_size != 8) return MHD_YES; /* not yet ready */ if (0 == memcmp (upload_data, "Hello123", 8)) { *upload_data_size = 0; } else { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } *done = 1; return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testInternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1450; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1451; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1452; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; int maxposixs; /* Max socket number unused on W32 */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; size_t pos = 0; int done_flag = 0; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1453; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } #ifdef MHD_POSIX_SOCKETS if (maxsock > maxposixs) maxposixs = maxsock; #endif /* MHD_POSIX_SOCKETS */ tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalPut (); errorCount += testMultithreadedPut (); errorCount += testMultithreadedPoolPut (); } errorCount += testExternalPut (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_urlparse.c0000664000175000017500000001410415232103064015610 /* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_urlparse.c * @brief Testcase for libmicrohttpd url parsing * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif static int oneone; static int matches; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result test_values (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { (void) cls; (void) kind; /* Unused. Silent compiler warning. */ if ( (0 == strcmp (key, "a")) && (0 == strcmp (value, "b")) ) matches += 1; if ( (0 == strcmp (key, "c")) && (0 == strcmp (value, "")) ) matches += 2; if ( (0 == strcmp (key, "d")) && (NULL == value) ) matches += 4; return MHD_YES; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } MHD_get_connection_values (connection, MHD_GET_ARGUMENT_KIND, &test_values, NULL); *req_cls = NULL; response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1510; if (oneone) port += 5; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world?a=b&c=&d"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; if (matches != 7) return 16; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testInternalGet (0); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_get_chunked.c0000664000175000017500000005332215232103064016240 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get_chunked.c * @brief Testcase for libmicrohttpd GET operations with chunked content encoding * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #endif #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define HDR_CHUNKED_ENCODING MHD_HTTP_HEADER_TRANSFER_ENCODING ": chunked" #define RESP_FOOTER_NAME "Footer" #define RESP_FOOTER_VALUE "working" #define RESP_FOOTER RESP_FOOTER_NAME ": " RESP_FOOTER_VALUE #define RESP_BLOCK_SIZE 128 #define RESP_BLOCK_QUANTIY 10 #define RESP_SIZE (RESP_BLOCK_SIZE * RESP_BLOCK_QUANTIY) /** * Use "Connection: close" header? */ static int conn_close; /** * Use static string response instead of callback-generated? */ static int resp_string; /** * Use response with known size? */ static int resp_sized; /** * Use empty (zero-sized) response? */ static int resp_empty; /** * Force chunked response by response header? */ static int chunked_forced; /** * MHD port used for testing */ static uint16_t port_global; struct headers_check_result { int found_chunked; int found_footer; }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; if ((data_size == strlen (HDR_CHUNKED_ENCODING) + 2) && (0 == memcmp (buffer, HDR_CHUNKED_ENCODING "\r\n", data_size))) check_res->found_chunked = 1; if ((data_size == strlen (RESP_FOOTER) + 2) && (0 == memcmp (buffer, RESP_FOOTER "\r\n", data_size))) check_res->found_footer = 1; return data_size; } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } /** * MHD content reader callback that returns data in chunks. */ static ssize_t crc (void *cls, uint64_t pos, char *buf, size_t max) { struct MHD_Response **responseptr = cls; if (resp_empty || (pos == RESP_SIZE - RESP_BLOCK_SIZE)) { /* Add footer with the last block */ if (MHD_YES != MHD_add_response_footer (*responseptr, RESP_FOOTER_NAME, RESP_FOOTER_VALUE)) abort (); } if (resp_empty || (pos == RESP_SIZE)) return MHD_CONTENT_READER_END_OF_STREAM; if (max < RESP_BLOCK_SIZE) abort (); /* should not happen in this testcase... */ memset (buf, 'A' + (char) (unsigned char) (pos / RESP_BLOCK_SIZE), RESP_BLOCK_SIZE); return RESP_BLOCK_SIZE; } /** * Dummy function that frees the "responseptr". */ static void crcf (void *ptr) { free (ptr); } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } if (! resp_string) { struct MHD_Response **responseptr; responseptr = malloc (sizeof (struct MHD_Response *)); if (NULL == responseptr) _exit (99); response = MHD_create_response_from_callback (resp_sized ? RESP_SIZE : MHD_SIZE_UNKNOWN, 1024, &crc, responseptr, &crcf); *responseptr = response; } else { if (! resp_empty) { size_t pos; static const size_t resp_size = RESP_SIZE; char *buf = malloc (resp_size); if (NULL == buf) _exit (99); for (pos = 0; pos < resp_size; pos += RESP_BLOCK_SIZE) memset (buf + pos, 'A' + (char) (unsigned char) (pos / RESP_BLOCK_SIZE), RESP_BLOCK_SIZE); response = MHD_create_response_from_buffer_copy (resp_size, buf); free (buf); } else response = MHD_create_response_empty (MHD_RF_NONE); } if (NULL == response) abort (); if (chunked_forced) { if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked")) abort (); } if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_TRAILER, RESP_FOOTER_NAME)) abort (); if (resp_string || (resp_sized && resp_empty)) { /* There is no chance to add footer later */ if (MHD_YES != MHD_add_response_footer (response, RESP_FOOTER_NAME, RESP_FOOTER_VALUE)) abort (); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int validate (struct CBC cbc, unsigned int ebase) { int i; char buf[RESP_BLOCK_SIZE]; if (resp_empty) { if (0 != cbc.pos) { fprintf (stderr, "Got %u bytes instead of zero!\n", (unsigned int) cbc.pos); return 1; } return 0; } if (cbc.pos != RESP_SIZE) { fprintf (stderr, "Got %u bytes instead of 1280!\n", (unsigned int) cbc.pos); return ebase; } for (i = 0; i < RESP_BLOCK_QUANTIY; i++) { memset (buf, 'A' + i, RESP_BLOCK_SIZE); if (0 != memcmp (buf, &cbc.buf[i * RESP_BLOCK_SIZE], RESP_BLOCK_SIZE)) { fprintf (stderr, "Got `%.*s'\nWant `%.*s'\n", RESP_BLOCK_SIZE, &cbc.buf[i * RESP_BLOCK_SIZE], RESP_BLOCK_SIZE, buf); return ebase * 2; } } return 0; } static unsigned int testInternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; struct curl_slist *h_list = NULL; struct headers_check_result hdr_check; port = port_global; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; if (0 == port_global) port_global = port; /* Re-use the same port for all checks */ } hdr_check.found_chunked = 0; hdr_check.found_footer = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback); curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (conn_close) { h_list = curl_slist_append (h_list, "Connection: close"); if (NULL == h_list) abort (); curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); if (1 != hdr_check.found_chunked) { fprintf (stderr, "Chunked encoding header was not found in the response\n"); return 8; } if (1 != hdr_check.found_footer) { fprintf (stderr, "The specified footer was not found in the response\n"); return 16; } return validate (cbc, 4); } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; struct curl_slist *h_list = NULL; struct headers_check_result hdr_check; port = port_global; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; if (0 == port_global) port_global = port; /* Re-use the same port for all checks */ } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); hdr_check.found_chunked = 0; hdr_check.found_footer = 0; curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback); curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check); if (conn_close) { h_list = curl_slist_append (h_list, "Connection: close"); if (NULL == h_list) abort (); curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); if (1 != hdr_check.found_chunked) { fprintf (stderr, "Chunked encoding header was not found in the response\n"); return 8; } if (1 != hdr_check.found_footer) { fprintf (stderr, "The specified footer was not found in the response\n"); return 16; } return validate (cbc, 64); } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; struct curl_slist *h_list = NULL; struct headers_check_result hdr_check; port = port_global; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; if (0 == port_global) port_global = port; /* Re-use the same port for all checks */ } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); hdr_check.found_chunked = 0; hdr_check.found_footer = 0; curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback); curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check); if (conn_close) { h_list = curl_slist_append (h_list, "Connection: close"); if (NULL == h_list) abort (); curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); if (1 != hdr_check.found_chunked) { fprintf (stderr, "Chunked encoding header was not found in the response\n"); return 8; } if (1 != hdr_check.found_footer) { fprintf (stderr, "The specified footer was not found in the response\n"); return 16; } return validate (cbc, 64); } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; struct curl_slist *h_list = NULL; struct headers_check_result hdr_check; port = port_global; multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; if (0 == port_global) port_global = port; /* Re-use the same port for all checks */ } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 5L); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); hdr_check.found_chunked = 0; hdr_check.found_footer = 0; curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback); curl_easy_setopt (c, CURLOPT_HEADERDATA, &hdr_check); if (conn_close) { h_list = curl_slist_append (h_list, "Connection: close"); if (NULL == h_list) abort (); curl_easy_setopt (c, CURLOPT_HTTPHEADER, h_list); } multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); curl_slist_free_all (h_list); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); curl_slist_free_all (h_list); h_list = NULL; c = NULL; multi = NULL; } MHD_run (d); } MHD_stop_daemon (d); if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } curl_slist_free_all (h_list); if (1 != hdr_check.found_chunked) { fprintf (stderr, "Chunked encoding header was not found in the response\n"); return 8; } if (1 != hdr_check.found_footer) { fprintf (stderr, "The specified footer was not found in the response\n"); return 16; } return validate (cbc, 8192); } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; conn_close = has_in_name (argv[0], "_close"); resp_string = has_in_name (argv[0], "_string"); resp_sized = has_in_name (argv[0], "_sized"); resp_empty = has_in_name (argv[0], "_empty"); chunked_forced = has_in_name (argv[0], "_forced"); if (resp_string) resp_sized = ! 0; if (resp_sized) chunked_forced = ! 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port_global = 0; else { port_global = 4100; if (conn_close) port_global += 1 << 0; if (resp_string) port_global += 1 << 1; if (resp_sized) port_global += 1 << 2; if (resp_empty) port_global += 1 << 3; if (chunked_forced) port_global += 1 << 4; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (); errorCount += testMultithreadedGet (); errorCount += testMultithreadedPoolGet (); } errorCount += testExternalGet (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/mhd_has_in_name.h0000644000175000017500000000410714760713577016037 /* This file is part of libmicrohttpd Copyright (C) 2016-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file testcurl/mhd_has_in_name.h * @brief Static functions and macros helpers for testsuite. * @author Karlson2k (Evgeny Grin) */ #include /** * Check whether program name contains specific @a marker string. * Only last component in pathname is checked for marker presence, * all leading directories names (if any) are ignored. Directories * separators are handled correctly on both non-W32 and W32 * platforms. * @param prog_name program name, may include path * @param marker marker to look for. * @return zero if any parameter is NULL or empty string or * @a prog_name ends with slash or @a marker is not found in * program name, non-zero if @a maker is found in program * name. */ static int has_in_name (const char *prog_name, const char *marker) { size_t name_pos; size_t pos; if (! prog_name || ! marker || ! prog_name[0] || ! marker[0]) return 0; pos = 0; name_pos = 0; while (prog_name[pos]) { if ('/' == prog_name[pos]) name_pos = pos + 1; #if defined(_WIN32) || defined(__CYGWIN__) else if ('\\' == prog_name[pos]) name_pos = pos + 1; #endif /* _WIN32 || __CYGWIN__ */ pos++; } if (name_pos == pos) return 0; return strstr (prog_name + name_pos, marker) != (char *) 0; } libmicrohttpd-1.0.10/src/testcurl/test_tricky.c0000664000175000017500000011074115232103064015264 /* This file is part of libmicrohttpd Copyright (C) 2014-2025 Evgeny Grin (Karlson2k) Copyright (C) 2007, 2009, 2011 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_toolarge.c * @brief Testcase for handling of untypical data. * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #include "mhd_has_param.h" #include "mhd_sockets.h" /* only macros used */ /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define EXPECTED_URI_BASE_PATH "/a" #define EXPECTED_URI_BASE_PATH_TRICKY "/one\rtwo" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST URL_SCHEME URL_HOST #define HEADER1_NAME "First" #define HEADER1_VALUE "1st" #define HEADER1 HEADER1_NAME ": " HEADER1_VALUE #define HEADER2_NAME "Second" #define HEADER2CR_VALUE "2\rnd" #define HEADER2CR HEADER2_NAME ": " HEADER2CR_VALUE /* Use headers when it would be properly supported by MHD #define HEADER3CR_NAME "Thi\rrd" #define HEADER3CR_VALUE "3r\rd" #define HEADER3CR HEADER3CR_NAME ": " HEADER3CR_VALUE */ #define HEADER4_NAME "Normal" #define HEADER4_VALUE "it's fine" #define HEADER4 HEADER4_NAME ": " HEADER4_VALUE /* Global parameters */ static int verbose; /**< Be verbose */ static int oneone; /**< If false use HTTP/1.0 for requests*/ static uint16_t global_port; /**< MHD daemons listen port number */ static int response_timeout_val = TIMEOUTS_VAL; static int tricky_url; /**< Tricky request URL */ static int tricky_header2; /**< Tricky request header2 */ /* Current test parameters */ /* * Moved to local variables * */ /* Static helper variables */ /* * None for this test * */ static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); } static void test_global_cleanup (void) { curl_global_cleanup (); } struct headers_check_result { int dummy; /* no checks in this test */ }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; /* no checks in this test */ (void) check_res; (void) buffer; return data_size; } struct lcurl_data_cb_param { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct lcurl_data_cb_param *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) externalErrorExit (); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } struct check_uri_cls { const char *volatile uri; }; static void * check_uri_cb (void *cls, const char *uri, struct MHD_Connection *con) { struct check_uri_cls *param = (struct check_uri_cls *) cls; (void) con; if (0 != strcmp (param->uri, uri)) { fprintf (stderr, "Wrong URI: '%s', line: %d\n", uri, __LINE__); exit (22); } return NULL; } struct mhd_header_checker_param { int found_header1; int found_header2; int found_header4; }; static enum MHD_Result headerCheckerInterator (void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct mhd_header_checker_param *const param = (struct mhd_header_checker_param *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (MHD_HEADER_KIND != kind) return MHD_YES; /* Continue iteration */ if (0 == key_size) mhdErrorExitDesc ("Zero key length"); if ((strlen (HEADER1_NAME) == key_size) && (0 == memcmp (key, HEADER1_NAME, key_size))) { if ((strlen (HEADER1_VALUE) == value_size) && (0 == memcmp (value, HEADER1_VALUE, value_size))) param->found_header1 = 1; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, HEADER1_VALUE); } else if ((strlen (HEADER2_NAME) == key_size) && (0 == memcmp (key, HEADER2_NAME, key_size))) { if ((strlen (HEADER2CR_VALUE) == value_size) && (0 == memcmp (value, HEADER2CR_VALUE, value_size))) param->found_header2 = 1; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, HEADER2CR_VALUE); } else if ((strlen (HEADER4_NAME) == key_size) && (0 == memcmp (key, HEADER4_NAME, key_size))) { if ((strlen (HEADER4_VALUE) == value_size) && (0 == memcmp (value, HEADER4_VALUE, value_size))) param->found_header4 = 1; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, HEADER4_VALUE); } return MHD_YES; } struct ahc_cls_type { const char *volatile rp_data; volatile size_t rp_data_size; struct mhd_header_checker_param header_check_param; const char *volatile rq_method; const char *volatile rq_url; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (NULL != upload_data) mhdErrorExitDesc ("'upload_data' is not NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; if (1 > MHD_get_connection_values_n (connection, MHD_HEADER_KIND, &headerCheckerInterator, ¶m->header_check_param)) mhdErrorExitDesc ("Wrong number of headers in the request"); response = MHD_create_response_from_buffer_copy (param->rp_data_size, (const void *) param->rp_data); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } struct curlQueryParams { /* Destination path for CURL query */ const char *queryPath; #if CURL_AT_LEAST_VERSION (7, 62, 0) CURLU *url; #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ #if CURL_AT_LEAST_VERSION (7, 55, 0) /* A string used as the request target directly, without modifications */ const char *queryTarget; #endif /* CURL_AT_LEAST_VERSION(7, 55, 0) */ /* Custom query method, NULL for default */ const char *method; /* Destination port for CURL query */ uint16_t queryPort; /* List of additional request headers */ struct curl_slist *headers; /* CURL query result error flag */ volatile unsigned int queryError; /* Response HTTP code, zero if no response */ volatile int responseCode; }; static CURL * curlEasyInitForTest (struct curlQueryParams *p, struct lcurl_data_cb_param *dcbp, struct headers_check_result *hdr_chk_result) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); #if CURL_AT_LEAST_VERSION (7, 62, 0) if (NULL != p->url) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CURLU, p->url)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); } else /* combined with the next 'if()' */ #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, p->queryPath)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) p->queryPort)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, dcbp)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA, hdr_chk_result)) || #if CURL_AT_LEAST_VERSION (7, 42, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PATH_AS_IS, (long) 1)) || #endif /* CURL_AT_LEAST_VERSION(7, 42, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, p->method)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, p->headers)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); #if CURL_AT_LEAST_VERSION (7, 55, 0) if (NULL != p->queryTarget) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_REQUEST_TARGET, p->queryTarget)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); } #endif /* CURL_AT_LEAST_VERSION(7, 55, 0) */ return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ multi = NULL; multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 1000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep (1); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /* Returns zero for successful response and non-zero for failed response */ static unsigned int doCurlQueryInThread (struct MHD_Daemon *d, struct curlQueryParams *p, struct headers_check_result *hdr_res, const char *expected_data, size_t expected_data_size) { const union MHD_DaemonInfo *dinfo; CURL *c; struct lcurl_data_cb_param dcbp; CURLcode errornum; int use_external_poll; long resp_code; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); use_external_poll = (0 == (dinfo->flags & MHD_USE_INTERNAL_POLLING_THREAD)); if (NULL == p->queryPath #if CURL_AT_LEAST_VERSION (7, 62, 0) && NULL == p->url #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ ) abort (); if (0 == p->queryPort) abort (); /* Test must not fail due to test's internal buffer shortage */ dcbp.size = expected_data_size * 2 + 1; dcbp.buf = malloc (dcbp.size); if (NULL == dcbp.buf) externalErrorExit (); dcbp.pos = 0; memset (hdr_res, 0, sizeof(*hdr_res)); c = curlEasyInitForTest (p, &dcbp, hdr_res); if (! use_external_poll) errornum = curl_easy_perform (c); else errornum = performQueryExternal (d, c); if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &resp_code)) libcurlErrorExitDesc ("curl_easy_getinfo() failed"); p->responseCode = (int) resp_code; if ((CURLE_OK == errornum) && (200 != resp_code)) { fprintf (stderr, "Got reply with unexpected status code: %d\n", p->responseCode); mhdErrorExit (); } if (CURLE_OK != errornum) { if ((CURLE_GOT_NOTHING != errornum) && (CURLE_RECV_ERROR != errornum) && (CURLE_HTTP_RETURNED_ERROR != errornum)) { if (CURLE_OPERATION_TIMEDOUT == errornum) mhdErrorExitDesc ("Request was aborted due to timeout"); fprintf (stderr, "libcurl returned unexpected error: %s\n", curl_easy_strerror (errornum)); mhdErrorExitDesc ("Request failed due to unexpected error"); } p->queryError = 1; if ((0 != resp_code) && ((499 < resp_code) || (400 > resp_code))) /* TODO: add all expected error codes */ { fprintf (stderr, "Got reply with unexpected status code: %ld\n", resp_code); mhdErrorExit (); } } else { if (dcbp.pos != expected_data_size) mhdErrorExit ("libcurl reports wrong size of MHD reply body data"); else if (0 != memcmp (expected_data, dcbp.buf, expected_data_size)) mhdErrorExit ("libcurl reports wrong MHD reply body data"); else p->queryError = 0; } curl_easy_cleanup (c); free (dcbp.buf); return p->queryError; } /* Perform test queries, shut down MHD daemon, and free parameters */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port, struct ahc_cls_type *ahc_param, struct check_uri_cls *uri_cb_param) { struct curlQueryParams qParam; unsigned int ret = 0; /* Return value */ struct headers_check_result rp_headers_check; struct curl_slist *curl_headers; curl_headers = NULL; /* Common parameters, to be individually overridden by specific test cases */ qParam.queryPort = d_port; qParam.method = NULL; /* Use libcurl default: GET */ qParam.queryPath = URL_SCHEME_HOST EXPECTED_URI_BASE_PATH; #if CURL_AT_LEAST_VERSION (7, 55, 0) qParam.queryTarget = NULL; #endif /* CURL_AT_LEAST_VERSION(7, 55, 0) */ #if CURL_AT_LEAST_VERSION (7, 62, 0) qParam.url = NULL; #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ qParam.headers = NULL; /* No additional headers */ uri_cb_param->uri = EXPECTED_URI_BASE_PATH; ahc_param->rq_url = EXPECTED_URI_BASE_PATH; ahc_param->rq_method = "GET"; /* Default expected method */ ahc_param->rp_data = "~"; ahc_param->rp_data_size = 1; curl_headers = curl_slist_append (curl_headers, HEADER1); if (NULL == curl_headers) externalErrorExit (); curl_headers = curl_slist_append (curl_headers, HEADER4); if (NULL == curl_headers) externalErrorExit (); qParam.headers = curl_headers; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (tricky_url) { #if CURL_AT_LEAST_VERSION (7, 55, 0) #if CURL_AT_LEAST_VERSION (7, 62, 0) unsigned int urlu_flags = CURLU_PATH_AS_IS; CURLU *url; url = curl_url (); if (NULL == url) externalErrorExit (); qParam.url = url; #ifdef CURLU_ALLOW_SPACE urlu_flags |= CURLU_ALLOW_SPACE; #endif /* CURLU_ALLOW_SPACE */ if ((CURLUE_OK != curl_url_set (qParam.url, CURLUPART_SCHEME, "http", 0)) || (CURLUE_OK != curl_url_set (qParam.url, CURLUPART_HOST, URL_HOST, urlu_flags)) || (CURLUE_OK != curl_url_set (qParam.url, CURLUPART_PATH, EXPECTED_URI_BASE_PATH_TRICKY, urlu_flags))) libcurlErrorExit (); #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ qParam.queryTarget = EXPECTED_URI_BASE_PATH_TRICKY; uri_cb_param->uri = EXPECTED_URI_BASE_PATH_TRICKY; ahc_param->rq_url = EXPECTED_URI_BASE_PATH_TRICKY; if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { /* TODO: Allow fail only if relevant MHD mode set */ if (0 == qParam.responseCode) { fprintf (stderr, "Request failed without any valid response.\n"); ret = 1; } else { if (verbose) printf ("Request failed with %d response code.\n", qParam.responseCode); (void) qParam.responseCode; /* TODO: check for the right response code */ ret = 0; } } else { if (200 != qParam.responseCode) { fprintf (stderr, "Request succeed with wrong response code: %d.\n", qParam.responseCode); ret = 1; } else { ret = 0; if (verbose) printf ("Request succeed.\n"); } if (! ahc_param->header_check_param.found_header1) mhdErrorExitDesc ("Required header1 was not detected in request"); if (! ahc_param->header_check_param.found_header4) mhdErrorExitDesc ("Required header4 was not detected in request"); } #if CURL_AT_LEAST_VERSION (7, 62, 0) curl_url_cleanup (url); #endif /* CURL_AT_LEAST_VERSION(7, 62, 0) */ #else fprintf (stderr, "This test requires libcurl version 7.55.0 or newer.\n"); abort (); #endif /* CURL_AT_LEAST_VERSION(7, 55, 0) */ } else if (tricky_header2) { /* Reset libcurl headers */ qParam.headers = NULL; curl_slist_free_all (curl_headers); curl_headers = NULL; /* Set special libcurl headers */ curl_headers = curl_slist_append (curl_headers, HEADER1); if (NULL == curl_headers) externalErrorExit (); curl_headers = curl_slist_append (curl_headers, HEADER2CR); if (NULL == curl_headers) externalErrorExit (); curl_headers = curl_slist_append (curl_headers, HEADER4); if (NULL == curl_headers) externalErrorExit (); qParam.headers = curl_headers; if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { /* TODO: Allow fail only if relevant MHD mode set */ if (0 == qParam.responseCode) { fprintf (stderr, "Request failed without any valid response.\n"); ret = 1; } else { if (verbose) printf ("Request failed with %d response code.\n", qParam.responseCode); (void) qParam.responseCode; /* TODO: check for the right response code */ ret = 0; } } else { if (200 != qParam.responseCode) { fprintf (stderr, "Request succeed with wrong response code: %d.\n", qParam.responseCode); ret = 1; } else { ret = 0; if (verbose) printf ("Request succeed.\n"); } if (! ahc_param->header_check_param.found_header1) mhdErrorExitDesc ("Required header1 was not detected in request"); if (! ahc_param->header_check_param.found_header2) mhdErrorExitDesc ("Required header2 was not detected in request"); if (! ahc_param->header_check_param.found_header4) mhdErrorExitDesc ("Required header4 was not detected in request"); } } else externalErrorExitDesc ("No valid test test was selected"); MHD_stop_daemon (d); curl_slist_free_all (curl_headers); free (uri_cb_param); free (ahc_param); return ret; } enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; (void) pollType; /* Don't care about pollType for this test */ return numThreads; /* No practical limit for non-cleanup test */ } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport, struct ahc_cls_type **ahc_param, struct check_uri_cls **uri_cb_param) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; if ((NULL == ahc_param) || (NULL == uri_cb_param)) abort (); *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type)); if (NULL == *ahc_param) externalErrorExit (); *uri_cb_param = (struct check_uri_cls *) malloc (sizeof(struct check_uri_cls)); if (NULL == *uri_cb_param) externalErrorExit (); if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 4150; if (tricky_url) *pport += 1; if (tricky_header2) *pport += 2; if (! oneone) *pport += 16; } if (testMhdThreadExternal == thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0) | MHD_USE_NO_THREAD_SAFETY, *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); else if (testMhdThreadInternalPool != thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_END); else d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno); abort (); } if (0 == *pport) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } *pport = dinfo->port; if (0 == global_port) global_port = *pport; /* Reuse the same port for all tests */ } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static void check_test_can_be_used (void) { #if ! CURL_AT_LEAST_VERSION (7, 55, 0) if (tricky_url) { fprintf (stderr, "This test requires libcurl version 7.55.0 or newer.\n"); exit (77); } #endif /* ! CURL_AT_LEAST_VERSION(7, 55, 0) */ return; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = ! has_in_name (argv[0], "10"); tricky_url = has_in_name (argv[0], "_url") ? 1 : 0; tricky_header2 = has_in_name (argv[0], "_header2") ? 1 : 0; if (1 != tricky_url + tricky_header2) return 99; verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); check_test_can_be_used (); test_global_init (); /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollAuto); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; #ifdef _MHD_HEAVY_TESTS /* Actually tests are not heavy, but took too long to complete while * not really provide any additional results. */ test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; } #else /* Mute compiler warnings */ (void) testMultithreadedGet; (void) testMultithreadedPoolGet; #endif /* _MHD_HEAVY_TESTS */ } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); test_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/https/0000775000175000017500000000000015235437005014002 5libmicrohttpd-1.0.10/src/testcurl/https/test_https_get_select.c0000664000175000017500000002011115232103064020450 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_get_select.c * @brief Testcase for libmicrohttpd HTTPS GET operations using external select * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static int oneone; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testExternalGet (unsigned int flags) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3030; multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_TLS | flags, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); /* TLS options */ curl_easy_setopt (c, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT); curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 != maxposixs) { if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) abort (); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws. fd_count) || (0 != es.fd_count) ) abort (); Sleep (1000); #endif } } else (void) sleep (1); curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ oneone = 1; if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } #ifdef EPOLL_SUPPORT errorCount += testExternalGet (MHD_USE_EPOLL); #endif if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) errorCount += testExternalGet (MHD_NO_FLAG); errorCount += testExternalGet (MHD_USE_NO_THREAD_SAFETY); curl_global_cleanup (); if (errorCount != 0) fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/https/test_https_time_out.c0000664000175000017500000001603715232103064020173 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_time_out.c * @brief: daemon TLS timeout test * * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include "tls_test_common.h" #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_TIME_H #include #endif /* HAVE_TIME_H */ #include "mhd_sockets.h" /* only macros used */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static const unsigned int timeout_val = 2; static volatile unsigned int num_connects = 0; static volatile unsigned int num_disconnects = 0; /** * Pause execution for specified number of milliseconds. * @param ms the number of milliseconds to sleep */ static void _MHD_sleep (uint32_t ms) { #if defined(_WIN32) Sleep (ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp = {ms / 1000, (ms % 1000) * 1000000}; struct timespec rmn; int num_retries = 0; while (0 != nanosleep (&slp, &rmn)) { if (num_retries++ > 8) break; slp = rmn; } #elif defined(HAVE_USLEEP) uint64_t us = ms * 1000; do { uint64_t this_sleep; if (999999 < us) this_sleep = 999999; else this_sleep = us; /* Ignore return value as it could be void */ usleep (this_sleep); us -= this_sleep; } while (us > 0); #else sleep ((ms + 999) / 1000); #endif } static void socket_cb (void *cls, struct MHD_Connection *c, void **socket_context, enum MHD_ConnectionNotificationCode toe) { if (NULL == socket_context) abort (); if (NULL == c) abort (); if (NULL != cls) abort (); if (MHD_CONNECTION_NOTIFY_STARTED == toe) { num_connects++; #ifdef _DEBUG fprintf (stderr, "MHD: Connection has started.\n"); #endif /* _DEBUG */ } else if (MHD_CONNECTION_NOTIFY_CLOSED == toe) { num_disconnects++; #ifdef _DEBUG fprintf (stderr, "MHD: Connection has closed.\n"); #endif /* _DEBUG */ } else abort (); } static unsigned int test_tls_session_time_out (gnutls_session_t session, uint16_t port) { int ret; MHD_socket sd; struct sockaddr_in sa; sd = socket (AF_INET, SOCK_STREAM, 0); if (sd == MHD_INVALID_SOCKET) { fprintf (stderr, "Failed to create socket: %s\n", strerror (errno)); return 2; } memset (&sa, '\0', sizeof (struct sockaddr_in)); sa.sin_family = AF_INET; sa.sin_port = htons (port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); ret = connect (sd, (struct sockaddr *) &sa, sizeof (struct sockaddr_in)); if (ret < 0) { fprintf (stderr, "Error: %s\n", MHD_E_FAILED_TO_CONNECT); MHD_socket_close_chk_ (sd); return 2; } #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64) gnutls_transport_set_int (session, (int) (sd)); #else /* GnuTLS before 3.1.9 or Win64 */ gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) (intptr_t) (sd)); #endif /* GnuTLS before 3.1.9 or Win64 */ ret = gnutls_handshake (session); if (ret < 0) { fprintf (stderr, "Handshake failed\n"); MHD_socket_close_chk_ (sd); return 2; } _MHD_sleep (timeout_val * 1000 + 1700); if (0 == num_connects) { fprintf (stderr, "MHD has not detected any connection attempt.\n"); MHD_socket_close_chk_ (sd); return 4; } /* check that server has closed the connection */ if (0 == num_disconnects) { fprintf (stderr, "MHD has not detected any disconnections.\n"); MHD_socket_close_chk_ (sd); return 1; } MHD_socket_close_chk_ (sd); return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; struct MHD_Daemon *d; gnutls_session_t session; gnutls_certificate_credentials_t xcred; uint16_t port; (void) argc; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3070; #ifdef MHD_SEND_SPIPE_SUPPRESS_NEEDED #if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) { fprintf (stderr, "Error suppressing SIGPIPE signal.\n"); exit (99); } #else /* ! HAVE_SIGNAL_H || ! SIGPIPE */ fprintf (stderr, "Cannot suppress SIGPIPE signal.\n"); /* exit (77); */ #endif #endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (GNUTLS_E_SUCCESS != gnutls_global_init ()) { fprintf (stderr, "Cannot initialize GnuTLS.\n"); exit (99); } gnutls_global_set_log_level (11); d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port, NULL, NULL, &http_dummy_ahc, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) timeout_val, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, MHD_E_SERVER_INIT); return -1; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 99; } port = dinfo->port; } if (0 != setup_session (&session, &xcred)) { fprintf (stderr, "failed to setup session\n"); return 1; } errorCount += test_tls_session_time_out (session, port); teardown_session (session, xcred); print_test_result (errorCount, argv[0]); MHD_stop_daemon (d); gnutls_global_deinit (); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/https/mhdhost2.crt0000644000175000017500000000346614674632555016210 -----BEGIN CERTIFICATE----- MIIFJjCCAw6gAwIBAgIBBjANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0 LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQ1MDVaGA8yMTIyMDMyNjE4 NDUwNVowXzELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxETAPBgNVBAMMCG1o ZGhvc3QyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy2v1c39RQPgG EqhYisiQX5QDTJFCr93B/KC96AqxXfUqxYHQZHHByeh2yHX5XeY+cwiza9Pb8kB5 Wyu5IV7pHYbLXetUQ7Ha8oCXcXZBihzMGjdTQApBvKES2rotkgxIArzFRk/KnO3D 2r87E2/fHqlHjg0Y8d58i846m7GSFpH2uAYogm2Zhi2ojE4O/qfaO6cSTdjUhDbM iDkQlf/fkq9o3ZeGzKXdzLC5PeIJ/7HbEcBJ0e6lyAFbYZtpTAtQ6/tuqAZTs3tM G5Yq3cAZY7x4vGECZaAWZAlgstBpCYd8b/dlXa8qvx4JuMF4q+7vVbgwHVoXsAzm ZAxSNy+dmQIDAQABo4HHMIHEMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8EAjAAMBYG A1UdJQEB/wQMMAoGCCsGAQUFBwMBMBMGA1UdEQQMMAqCCG1oZGhvc3QyMB0GA1Ud DgQWBBSB0kA6mqq1/wMzKke35+L6aZym9zAnBglghkgBhvhCAQ0EGhYYVGVzdCBs aWJtaWNyb2h0dHBkIGhvc3QyMBEGCWCGSAGG+EIBAQQEAwIGQDAfBgNVHSMEGDAW gBRYdUPApWoxw4U13Rqsjf9AHdbpLDANBgkqhkiG9w0BAQsFAAOCAgEAhEeSsKYb KWVhC3bVxXX4EynaHVWwrQaqNMtogt2akKBfZRzM6CHVvts8IrvcMdS4ZvXB2kL8 wDsYpVsNVgLLuSKXH2xJPZmYrGsUu++UcR4umvuV1kwFcA/Dc5XkW1EMcMvSPDs2 /gJFRCpx3UAs2/KCL2KASHGiOcNSf8aRLxI6KqWqQLxsZdK02HUNodqiG2UXIaHg shD7rAMSDN4CdG4cdSX3l45aL+BoYcEKi5XUoJMRjNrAGKMWUku089hr1gI617Jx gHKZxvSizGxCHhMkAPTT+9UyNFzd+3dS6cHx8oTFpnamNgMin3C88GCmu5YN6gCi af3imb8OaHFJ0k9M9acM++5sRfvRgZ/tQWnPdyg5TlLwwF14yLbz6e/DbxlmP7PG 3W3FbVST/creb2KTtwWFu187uKl4v1Xe5DC0I2gcOzq2g0GHbu8WjuD45Os/lc4v cqGctYRMUfqshmsK9PQCZmPcC5nqXf6iO8L1P9Gi0VDwT/WeHUvi87UVYsUgVuVt 0RxCE5Nqad8S7ziQj9Aa3xspPf7CKw6Obbp/UNui/YwaDufJho7qsBpp1lMnG5f4 qA8+yKUVADTnV5tJqgcDiRyBxOzb2CaGezTqNshUkVIpkHZsCpSdu9QrEOIzcaaA WXmQOPOpxW5QVf22mPJh/GZaqZ3/ZMmFabI= -----END CERTIFICATE----- libmicrohttpd-1.0.10/src/testcurl/https/mhdhost1.crt0000644000175000017500000000346614674632555016207 -----BEGIN CERTIFICATE----- MIIFJjCCAw6gAwIBAgIBBTANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0 LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQ1MDVaGA8yMTIyMDMyNjE4 NDUwNVowXzELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxETAPBgNVBAMMCG1o ZGhvc3QxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxb5LkwTfvNtW eFSYAPoEzqwVARWxDDR2PfQmmBtrHhMNEQyUCTg+Na00hEQbcZbz7fgS0FOY1hjy MFJamNGP031HvMS7zHNQJ4HbEz0d1EuePgjEvWaFMFncTKGn07Cn9e3Rcv2ihJ/I I8wf3ph/k/UTOv62YhIs2fMQM5LD6oX9ulKJhAaOvFT6hyrB1xe3nVhPT0PsrUXl ky253k7XXEAIWO6dLZnK377UiRDJInFS9FN/hojFb+8gcByo/n39LHMBtp5WGM5+ xGwEHyYkwtnaM8IEKofbUNERQT3cgPv4zN7ny3LwljR2A1c5gHXmKO7G245tbfqb VtOh3+1bJQIDAQABo4HHMIHEMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8EAjAAMBYG A1UdJQEB/wQMMAoGCCsGAQUFBwMBMBMGA1UdEQQMMAqCCG1oZGhvc3QxMB0GA1Ud DgQWBBTTxzQ/fcuT83JlCzPx8qJzuHCG4jAnBglghkgBhvhCAQ0EGhYYVGVzdCBs aWJtaWNyb2h0dHBkIGhvc3QxMBEGCWCGSAGG+EIBAQQEAwIGQDAfBgNVHSMEGDAW gBRYdUPApWoxw4U13Rqsjf9AHdbpLDANBgkqhkiG9w0BAQsFAAOCAgEAMdHjWHxt 51LH3V8Um3djUh+QYVnYhxFVX4CIXMq2DAg7iYw6tg2S1SOm3R+qEB/rAHxRw/cd nekjx0zm2rAnn4SsIQg5rXzniM4dJ2UQJrn7m88fb/czjXCrvf6hGIXCSAw/YyU0 IkxXlOYv1mYNZBuVvFREUbqqK2Fn+ooIi816Q2UCQFMd+QI8+mn8eqK8XeJElKkt SR0WCLW7UkwYxOk73FCdrr1TlX9hAF76gTAK71OJN3F35hzg+pTAEe3nwFMZbG/k xHmVob51L+Op4Y15j1HoJxW0Ox+PuxVcp9EpC7Qb8UmtExAsYOuN2PP8hU+pmtE4 iYpCDckx6kT66ssjndaKziRmoxX/czvKCAwVDder6Ofl4SwGUEpE+0oO2ux6iNrl iKxRCvyBqErFlzlEj7oO3agqe83jtTH8bXzOCtx36lNVjCuADYI4o7r5NVHaGIx6 1q5BiZ5pj22EYgBZbRAgE1ZPxVBIZJKoHewmQqpcR5WsSeBIf8XDuytnadhv8NDN tpLMDry8KkUh7rtjrQIGb66BqCt0n1tz1/6nLlL9OF5kUt4902wCtN3SbotssfV3 NCX9X4udquRdcFwNLCSfZ505FqhYbeSLraDHJ46/96V//Vx4oAnULdcCm4QgGQmP EGEJDJkaCKKTGMHAvZAtgRchc/RTf59jhoc= -----END CERTIFICATE----- libmicrohttpd-1.0.10/src/testcurl/https/test_https_get_parallel.c0000664000175000017500000001442115232103064020774 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_get_parallel.c * @brief Testcase for libmicrohttpd HTTPS GET operations with single-threaded * MHD daemon and several clients working in parallel * @author Sagie Amir * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 4 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 4 #endif /** * used when spawning multiple threads executing curl server requests * */ static void * https_transfer_thread_adapter (void *args) { static int nonnull; struct https_test_data *cargs = args; unsigned int ret; ret = test_https_transfer (NULL, cargs->port, cargs->cipher_suite, cargs->proto_version); if (ret == 0) return NULL; return &nonnull; } /** * Test non-parallel requests. * * @return: 0 upon all client requests returning '0', 1 otherwise. * * TODO : make client_count a parameter - number of curl client threads to spawn */ static unsigned int test_single_client (void *cls, uint16_t port, const char *cipher_suite, int curl_proto_version) { void *client_thread_ret; struct https_test_data client_args = { NULL, port, cipher_suite, curl_proto_version }; (void) cls; /* Unused. Silent compiler warning. */ client_thread_ret = https_transfer_thread_adapter (&client_args); if (client_thread_ret != NULL) return 1; return 0; } /** * Test parallel request handling. * * @return: 0 upon all client requests returning '0', 1 otherwise. * * TODO : make client_count a parameter - number of curl client threads to spawn */ static unsigned int test_parallel_clients (void *cls, uint16_t port, const char *cipher_suite, int curl_proto_version) { int i; int client_count = (MHD_CPU_COUNT - 1); void *client_thread_ret; pthread_t client_arr[client_count]; struct https_test_data client_args = { NULL, port, cipher_suite, curl_proto_version }; (void) cls; /* Unused. Silent compiler warning. */ for (i = 0; i < client_count; ++i) { if (pthread_create (&client_arr[i], NULL, &https_transfer_thread_adapter, &client_args) != 0) { fprintf (stderr, "Error: failed to spawn test client threads.\n"); return 1; } } /* check all client requests fulfilled correctly */ for (i = 0; i < client_count; ++i) { if ((pthread_join (client_arr[i], &client_thread_ret) != 0) || (client_thread_ret != NULL)) return 1; } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; uint16_t port; unsigned int iseed; (void) argc; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3020; /* initialize random seed used by curl clients */ iseed = (unsigned int) time (NULL); srand (iseed); if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); return 77; } #ifdef EPOLL_SUPPORT errorCount += test_wrap ("single threaded daemon, single client, epoll", &test_single_client, NULL, port, MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG | MHD_USE_EPOLL, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); #endif errorCount += test_wrap ("single threaded daemon, single client", &test_single_client, NULL, port, MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); #ifdef EPOLL_SUPPORT errorCount += test_wrap ("single threaded daemon, parallel clients, epoll", &test_parallel_clients, NULL, port, MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG | MHD_USE_EPOLL, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); #endif errorCount += test_wrap ("single threaded daemon, parallel clients", &test_parallel_clients, NULL, port, MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); curl_global_cleanup (); if (errorCount != 0) fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/https/test_https_get_iovec.c0000664000175000017500000002652415232103064020314 /* This file is part of libmicrohttpd Copyright (C) 2007-2021 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_get_iovec.c * @brief Testcase for libmicrohttpd HTTPS GET operations using an iovec * @author Sagie Amir * @author Karlson2k (Evgeny Grin) * @author Lawrence Sebald */ /* * This testcase is derived from the test_https_get.c testcase. This version * adds the usage of a scatter/gather array for storing the response data. */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static uint16_t global_port; /* Use large enough pieces (>16KB) to test partially consumed * data as TLS doesn't take more than 16KB by a single call. */ #define TESTSTR_IOVLEN 20480 #define TESTSTR_IOVCNT 30 #define TESTSTR_SIZE (TESTSTR_IOVCNT * TESTSTR_IOVLEN) static void iov_free_callback (void *cls) { free (cls); } static int check_read_data (const void *ptr, size_t len) { const int *buf; size_t i; if (len % sizeof(int)) return -1; buf = (const int *) ptr; for (i = 0; i < len / sizeof(int); ++i) { if (buf[i] != (int) i) return -1; } return 0; } static enum MHD_Result iovec_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; int *data; struct MHD_IoVec iov[TESTSTR_IOVCNT]; int i; int j; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ /* Create some test data. */ if (NULL == (data = malloc (TESTSTR_SIZE))) return MHD_NO; for (j = 0; j < TESTSTR_IOVCNT; ++j) { int *chunk; /* Assign chunks of memory area in the reverse order * to make non-continuous set of data therefore * possible buffer overruns could be detected */ chunk = data + (((TESTSTR_IOVCNT - 1) - (unsigned int) j) * (TESTSTR_SIZE / TESTSTR_IOVCNT / sizeof(int))); iov[j].iov_base = chunk; iov[j].iov_len = TESTSTR_SIZE / TESTSTR_IOVCNT; for (i = 0; i < (int) (TESTSTR_IOVLEN / sizeof(int)); ++i) chunk[i] = i + (j * (int) (TESTSTR_IOVLEN / sizeof(int))); } response = MHD_create_response_from_iovec (iov, TESTSTR_IOVCNT, &iov_free_callback, data); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int test_iovec_transfer (void *cls, uint16_t port, const char *cipher_suite, int proto_version) { size_t len; unsigned int ret = 0; struct CBC cbc; char url[255]; (void) cls; /* Unused. Silent compiler warning. */ len = TESTSTR_SIZE; if (NULL == (cbc.buf = malloc (sizeof (char) * len))) { fprintf (stderr, MHD_E_MEM); return 1; } cbc.size = len; cbc.pos = 0; if (gen_test_uri (url, sizeof (url), port)) { ret = 1; goto cleanup; } if (CURLE_OK != send_curl_req (url, &cbc, cipher_suite, proto_version)) { ret = 1; goto cleanup; } if ((cbc.pos != TESTSTR_SIZE) || (0 != check_read_data (cbc.buf, cbc.pos))) { fprintf (stderr, "Error: local file & received file differ.\n"); ret = 1; } cleanup: free (cbc.buf); return ret; } /* perform a HTTP GET request via SSL/TLS */ static unsigned int test_secure_get (FILE *test_fd, const char *cipher_suite, int proto_version) { unsigned int ret; struct MHD_Daemon *d; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3045; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port, NULL, NULL, &iovec_ahc, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return 1; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 1; } port = dinfo->port; } ret = test_iovec_transfer (test_fd, port, cipher_suite, proto_version); MHD_stop_daemon (d); return ret; } static enum MHD_Result ahc_empty (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; struct MHD_IoVec iov; (void) cls; (void) url; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; iov.iov_base = NULL; iov.iov_len = 0; response = MHD_create_response_from_iovec (&iov, 1, NULL, NULL); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) { fprintf (stderr, "Failed to queue response.\n"); _exit (20); } return ret; } static int curlExcessFound (CURL *c, curl_infotype type, char *data, size_t size, void *cls) { static const char *excess_found = "Excess found"; const size_t str_size = strlen (excess_found); (void) c; /* Unused. Silence compiler warning. */ #ifdef _DEBUG if ((CURLINFO_TEXT == type) || (CURLINFO_HEADER_IN == type) || (CURLINFO_HEADER_OUT == type)) fprintf (stderr, "%.*s", (int) size, data); #endif /* _DEBUG */ if ((CURLINFO_TEXT == type) && (size >= str_size) && (0 == strncmp (excess_found, data, str_size))) *(int *) cls = 1; return 0; } static unsigned int testEmptyGet (unsigned int poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int excess_found = 0; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1225; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | poll_flag | MHD_USE_TLS, global_port, NULL, NULL, &ahc_empty, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 4194304; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &curlExcessFound); curl_easy_setopt (c, CURLOPT_DEBUGDATA, &excess_found); curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 8388608; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != 0) return 16777216; if (excess_found) return 33554432; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount += test_secure_get (NULL, NULL, CURL_SSLVERSION_DEFAULT); errorCount += testEmptyGet (0); curl_global_cleanup (); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/https/test_empty_response.c0000664000175000017500000001623015232103064020173 /* This file is part of libmicrohttpd Copyright (C) 2013 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_empty_response.c * @brief Testcase for libmicrohttpd HTTPS GET operations with empty reply * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static int oneone; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) method; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testInternalSelectGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; int maxposixs; /* Max socket number unused on W32 */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3000; multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_TLS | MHD_USE_INTERNAL_POLLING_THREAD, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); /* TLS options */ curl_easy_setopt (c, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT); curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 != maxposixs) { if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) abort (); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws. fd_count) || (0 != es.fd_count) ) abort (); Sleep (1000); #endif } } else (void) sleep (1); curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != 0) return 8192; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ oneone = 1; if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } if (0 != (errorCount = testInternalSelectGet ())) fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount); curl_global_cleanup (); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/https/tls_test_common.c0000644000175000017500000004765614760713574017331 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2017-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file tls_test_common.c * @brief Common tls test functions * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include #include "tls_test_common.h" #include "tls_test_keys.h" /** * Map @a know_gnutls_tls_ids values to printable names. */ const char *tls_names[KNOW_TLS_IDS_COUNT] = { "Bad value", "SSL version 3", "TLS version 1.0", "TLS version 1.1", "TLS version 1.2", "TLS version 1.3" }; /** * Map @a know_gnutls_tls_ids values to GnuTLS priorities strings. */ const char *priorities_map[KNOW_TLS_IDS_COUNT] = { "NONE", "NORMAL:!VERS-ALL:+VERS-SSL3.0", "NORMAL:!VERS-ALL:+VERS-TLS1.0", "NORMAL:!VERS-ALL:+VERS-TLS1.1", "NORMAL:!VERS-ALL:+VERS-TLS1.2", "NORMAL:!VERS-ALL:+VERS-TLS1.3" }; /** * Map @a know_gnutls_tls_ids values to GnuTLS priorities append strings. */ const char *priorities_append_map[KNOW_TLS_IDS_COUNT] = { "NONE", "!VERS-ALL:+VERS-SSL3.0", "!VERS-ALL:+VERS-TLS1.0", "!VERS-ALL:+VERS-TLS1.1", "!VERS-ALL:+VERS-TLS1.2", "!VERS-ALL:+VERS-TLS1.3" }; /** * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value. */ const long libcurl_tls_vers_map[KNOW_TLS_IDS_COUNT] = { CURL_SSLVERSION_LAST, /* bad value */ CURL_SSLVERSION_SSLv3, #if CURL_AT_LEAST_VERSION (7,34,0) CURL_SSLVERSION_TLSv1_0, #else /* CURL VER < 7.34.0 */ CURL_SSLVERSION_TLSv1, /* TLS 1.0 or later */ #endif /* CURL VER < 7.34.0 */ #if CURL_AT_LEAST_VERSION (7,34,0) CURL_SSLVERSION_TLSv1_1, #else /* CURL VER < 7.34.0 */ CURL_SSLVERSION_LAST, /* bad value, not supported by this libcurl version */ #endif /* CURL VER < 7.34.0 */ #if CURL_AT_LEAST_VERSION (7,34,0) CURL_SSLVERSION_TLSv1_2, #else /* CURL VER < 7.34.0 */ CURL_SSLVERSION_LAST, /* bad value, not supported by this libcurl version */ #endif /* CURL VER < 7.34.0 */ #if CURL_AT_LEAST_VERSION (7,52,0) CURL_SSLVERSION_TLSv1_3 #else /* CURL VER < 7.34.0 */ CURL_SSLVERSION_LAST /* bad value, not supported by this libcurl version */ #endif /* CURL VER < 7.34.0 */ }; #if CURL_AT_LEAST_VERSION (7,54,0) /** * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value * for maximum supported TLS version. */ const long libcurl_tls_max_vers_map[KNOW_TLS_IDS_COUNT] = { CURL_SSLVERSION_MAX_DEFAULT, /* bad value */ CURL_SSLVERSION_MAX_DEFAULT, /* SSLv3 */ CURL_SSLVERSION_MAX_TLSv1_0, CURL_SSLVERSION_MAX_TLSv1_1, CURL_SSLVERSION_MAX_TLSv1_2, CURL_SSLVERSION_MAX_TLSv1_3 }; #endif /* CURL_AT_LEAST_VERSION(7,54,0) */ /* * test HTTPS transfer */ enum test_get_result test_daemon_get (void *cls, const char *cipher_suite, int proto_version, uint16_t port, int ver_peer) { CURL *c; struct CBC cbc; CURLcode errornum; CURLcode e; char url[255]; size_t len; (void) cls; /* Unused. Silence compiler warning. */ len = strlen (test_data); if (NULL == (cbc.buf = malloc (sizeof (char) * len))) { fprintf (stderr, MHD_E_MEM); return TEST_GET_HARD_ERROR; } cbc.size = len; cbc.pos = 0; /* construct url - this might use doc_path */ gen_test_uri (url, sizeof (url), port); c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_URL, url))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)))) { fprintf (stderr, "curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); free (cbc.buf); return TEST_GET_CURL_GEN_ERROR; } /* TLS options */ if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSLVERSION, proto_version))) || ((NULL != cipher_suite) && (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST, cipher_suite)))) || /* perform peer authentication */ /* TODO merge into send_curl_req */ (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, ver_peer))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L)))) { fprintf (stderr, "HTTPS curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); free (cbc.buf); return TEST_GET_CURL_GEN_ERROR; } if (ver_peer && (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_CAINFO, ca_cert_file_name)))) { fprintf (stderr, "HTTPS curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); free (cbc.buf); return TEST_GET_CURL_CA_ERROR; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); free (cbc.buf); if ((CURLE_SSL_CACERT_BADFILE == errornum) #if CURL_AT_LEAST_VERSION (7,21,5) || (CURLE_NOT_BUILT_IN == errornum) #endif /* CURL_AT_LEAST_VERSION (7,21,5) */ ) return TEST_GET_CURL_CA_ERROR; if (CURLE_OUT_OF_MEMORY == errornum) return TEST_GET_HARD_ERROR; return TEST_GET_ERROR; } curl_easy_cleanup (c); if (memcmp (cbc.buf, test_data, len) != 0) { fprintf (stderr, "Error: local data & received data differ.\n"); free (cbc.buf); return TEST_GET_TRANSFER_ERROR; } free (cbc.buf); return TEST_GET_OK; } void print_test_result (unsigned int test_outcome, const char *test_name) { if (test_outcome != 0) fprintf (stderr, "running test: %s [fail: %u]\n", test_name, test_outcome); #if 0 else fprintf (stdout, "running test: %s [pass]\n", test_name); #endif } size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) { fprintf (stderr, "Server data does not fit buffer.\n"); return 0; /* overflow */ } memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } /** * HTTP access handler call back */ enum MHD_Result http_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_buffer_static (strlen (test_data), test_data); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /* HTTP access handler call back */ enum MHD_Result http_dummy_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; (void) connection; (void) url; (void) method; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ return 0; } /** * send a test http request to the daemon * @param url * @param cbc - may be null * @param cipher_suite * @param proto_version * @return */ /* TODO have test wrap consider a NULL cbc */ CURLcode send_curl_req (char *url, struct CBC *cbc, const char *cipher_suite, int proto_version) { CURL *c; CURLcode errornum; CURLcode e; c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_URL, url))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_TIMEOUT, 60L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 60L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)))) { fprintf (stderr, "curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); return e; } if (cbc != NULL) { if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)))) { fprintf (stderr, "curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); return e; } } /* TLS options */ if ((CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSLVERSION, proto_version))) || ((NULL != cipher_suite) && (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_CIPHER_LIST, cipher_suite)))) || /* currently skip any peer authentication */ (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L))) || (CURLE_OK != (e = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L)))) { fprintf (stderr, "HTTPS curl_easy_setopt failed: `%s'\n", curl_easy_strerror (e)); curl_easy_cleanup (c); return e; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); return errornum; } curl_easy_cleanup (c); return CURLE_OK; } /** * compile test URI * * @param[out] uri - char buffer into which the url is compiled * @param uri_len number of bytes available in @a url * @param port port to use for the test * @return 1 on error */ unsigned int gen_test_uri (char *uri, size_t uri_len, uint16_t port) { int res; res = snprintf (uri, uri_len, "https://127.0.0.1:%u/urlpath", (unsigned int) port); if (res <= 0) return 1; if ((size_t) res >= uri_len) return 1; return 0; } /** * test HTTPS data transfer */ unsigned int test_https_transfer (void *cls, uint16_t port, const char *cipher_suite, int proto_version) { size_t len; unsigned int ret = 0; struct CBC cbc; char url[255]; (void) cls; /* Unused. Silent compiler warning. */ len = strlen (test_data); if (NULL == (cbc.buf = malloc (sizeof (char) * len))) { fprintf (stderr, MHD_E_MEM); return 1; } cbc.size = len; cbc.pos = 0; if (gen_test_uri (url, sizeof (url), port)) { ret = 1; goto cleanup; } if (CURLE_OK != send_curl_req (url, &cbc, cipher_suite, proto_version)) { ret = 1; goto cleanup; } /* compare test data & daemon response */ if ( (len != strlen (test_data)) || (memcmp (cbc.buf, test_data, len) != 0) ) { fprintf (stderr, "Error: original data & received data differ.\n"); ret = 1; } cleanup: free (cbc.buf); return ret; } /** * setup test case * * @param d * @param daemon_flags * @param arg_list * @return port number on success or zero on failure */ static uint16_t setup_testcase (struct MHD_Daemon **d, uint16_t port, unsigned int daemon_flags, va_list arg_list) { *d = MHD_start_daemon_va (daemon_flags, port, NULL, NULL, &http_ahc, NULL, arg_list); if (*d == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return 0; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (*d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (*d); return 0; } port = dinfo->port; } return port; } static void teardown_testcase (struct MHD_Daemon *d) { MHD_stop_daemon (d); } unsigned int setup_session (gnutls_session_t *session, gnutls_certificate_credentials_t *xcred) { if (GNUTLS_E_SUCCESS == gnutls_init (session, GNUTLS_CLIENT)) { if (GNUTLS_E_SUCCESS == gnutls_set_default_priority (*session)) { if (GNUTLS_E_SUCCESS == gnutls_certificate_allocate_credentials (xcred)) { if (GNUTLS_E_SUCCESS == gnutls_credentials_set (*session, GNUTLS_CRD_CERTIFICATE, *xcred)) { return 0; } gnutls_certificate_free_credentials (*xcred); } } gnutls_deinit (*session); } return 1; } unsigned int teardown_session (gnutls_session_t session, gnutls_certificate_credentials_t xcred) { gnutls_deinit (session); gnutls_certificate_free_credentials (xcred); return 0; } /* TODO test_wrap: change sig to (setup_func, test, va_list test_arg) */ unsigned int test_wrap (const char *test_name, unsigned int (*test_function)(void *cls, uint16_t port, const char *cipher_suite, int proto_version), void *cls, uint16_t port, unsigned int daemon_flags, const char *cipher_suite, int proto_version, ...) { unsigned int ret; va_list arg_list; struct MHD_Daemon *d; (void) cls; /* Unused. Silent compiler warning. */ va_start (arg_list, proto_version); port = setup_testcase (&d, port, daemon_flags, arg_list); if (0 == port) { va_end (arg_list); fprintf (stderr, "Failed to setup testcase %s\n", test_name); return 1; } #if 0 fprintf (stdout, "running test: %s ", test_name); #endif ret = test_function (NULL, port, cipher_suite, proto_version); #if 0 if (ret == 0) { fprintf (stdout, "[pass]\n"); } else { fprintf (stdout, "[fail]\n"); } #endif teardown_testcase (d); va_end (arg_list); return ret; } static int inited_tls_is_gnutls = 0; static int inited_tls_is_openssl = 0; int curl_tls_is_gnutls (void) { const char *tlslib; if (inited_tls_is_gnutls) return 1; if (inited_tls_is_openssl) return 0; tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tlslib) return 0; if (0 == strncmp (tlslib, "GnuTLS/", 7)) return 1; /* Multi-backends handled during initialization by setting variable */ return 0; } int curl_tls_is_openssl (void) { const char *tlslib; if (inited_tls_is_gnutls) return 0; if (inited_tls_is_openssl) return 1; tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tlslib) return 0; if (0 == strncmp (tlslib, "OpenSSL/", 8)) return 1; /* Multi-backends handled during initialization by setting variable */ return 0; } int curl_tls_is_nss (void) { const char *tlslib; if (inited_tls_is_gnutls) return 0; if (inited_tls_is_openssl) return 0; tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tlslib) return 0; if (0 == strncmp (tlslib, "NSS/", 4)) return 1; /* Handle multi-backends with selected backend */ if (NULL != strstr (tlslib," NSS/")) return 1; return 0; } int curl_tls_is_schannel (void) { const char *tlslib; if (inited_tls_is_gnutls) return 0; if (inited_tls_is_openssl) return 0; tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tlslib) return 0; if ((0 == strncmp (tlslib, "Schannel", 8)) || (0 == strncmp (tlslib, "WinSSL", 6))) return 1; /* Handle multi-backends with selected backend */ if ((NULL != strstr (tlslib," Schannel")) || (NULL != strstr (tlslib, " WinSSL"))) return 1; return 0; } int curl_tls_is_sectransport (void) { const char *tlslib; if (inited_tls_is_gnutls) return 0; if (inited_tls_is_openssl) return 0; tlslib = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tlslib) return 0; if (0 == strncmp (tlslib, "SecureTransport", 15)) return 1; /* Handle multi-backends with selected backend */ if (NULL != strstr (tlslib," SecureTransport")) return 1; return 0; } int testsuite_curl_global_init (void) { CURLcode res; #if LIBCURL_VERSION_NUM >= 0x073800 if (CURLSSLSET_OK != curl_global_sslset (CURLSSLBACKEND_GNUTLS, NULL, NULL)) { CURLsslset e; e = curl_global_sslset (CURLSSLBACKEND_OPENSSL, NULL, NULL); if (CURLSSLSET_TOO_LATE == e) fprintf (stderr, "WARNING: libcurl was already initialised.\n"); else if (CURLSSLSET_OK == e) inited_tls_is_openssl = 1; } else inited_tls_is_gnutls = 1; #endif /* LIBCURL_VERSION_NUM >= 0x07380 */ res = curl_global_init (CURL_GLOBAL_ALL); if (CURLE_OK != res) { fprintf (stderr, "libcurl initialisation error: %s\n", curl_easy_strerror (res)); return 0; } return 1; } /** * Check whether program name contains specific @a marker string. * Only last component in pathname is checked for marker presence, * all leading directories names (if any) are ignored. Directories * separators are handled correctly on both non-W32 and W32 * platforms. * @param prog_name program name, may include path * @param marker marker to look for. * @return zero if any parameter is NULL or empty string or * @a prog_name ends with slash or @a marker is not found in * program name, non-zero if @a maker is found in program * name. */ int has_in_name (const char *prog_name, const char *marker) { size_t name_pos; size_t pos; if (! prog_name || ! marker || ! prog_name[0] || ! marker[0]) return 0; pos = 0; name_pos = 0; while (prog_name[pos]) { if ('/' == prog_name[pos]) name_pos = pos + 1; #if defined(_WIN32) || defined(__CYGWIN__) else if ('\\' == prog_name[pos]) name_pos = pos + 1; #endif /* _WIN32 || __CYGWIN__ */ pos++; } if (name_pos == pos) return 0; return strstr (prog_name + name_pos, marker) != (char *) 0; } libmicrohttpd-1.0.10/src/testcurl/https/test_https_multi_daemon.c0000664000175000017500000001275015232103064021021 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_multi_daemon.c * @brief Testcase for libmicrohttpd multiple HTTPS daemon scenario * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" /* * assert initiating two separate daemons and having one shut down * doesn't affect the other */ static unsigned int test_concurent_daemon_pair (void *cls, const char *cipher_suite, int proto_version) { unsigned int ret; enum test_get_result res; struct MHD_Daemon *d1; struct MHD_Daemon *d2; uint16_t port1, port2; (void) cls; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port1 = port2 = 0; else { port1 = 3050; port2 = 3051; } d1 = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port1, NULL, NULL, &http_ahc, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (d1 == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return 1; } if (0 == port1) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d1, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "Cannot detect daemon bind port.\n"); MHD_stop_daemon (d1); return 1; } port1 = dinfo->port; } d2 = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port2, NULL, NULL, &http_ahc, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (d2 == NULL) { MHD_stop_daemon (d1); fprintf (stderr, MHD_E_SERVER_INIT); return 1; } if (0 == port2) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d2, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "Cannot detect daemon bind port.\n"); MHD_stop_daemon (d1); MHD_stop_daemon (d2); return 1; } port2 = dinfo->port; } res = test_daemon_get (NULL, cipher_suite, proto_version, port1, 0); ret = (unsigned int) res; if ((TEST_GET_HARD_ERROR == res) || (TEST_GET_CURL_GEN_ERROR == res)) { fprintf (stderr, "libcurl error.\nTest aborted.\n"); MHD_stop_daemon (d2); MHD_stop_daemon (d1); return 99; } res = test_daemon_get (NULL, cipher_suite, proto_version, port2, 0); ret += (unsigned int) res; if ((TEST_GET_HARD_ERROR == res) || (TEST_GET_CURL_GEN_ERROR == res)) { fprintf (stderr, "libcurl error.\nTest aborted.\n"); MHD_stop_daemon (d2); MHD_stop_daemon (d1); return 99; } MHD_stop_daemon (d2); res = test_daemon_get (NULL, cipher_suite, proto_version, port1, 0); ret += (unsigned int) res; if ((TEST_GET_HARD_ERROR == res) || (TEST_GET_CURL_GEN_ERROR == res)) { fprintf (stderr, "libcurl error.\nTest aborted.\n"); MHD_stop_daemon (d1); return 99; } MHD_stop_daemon (d1); return ret; } int main (int argc, char *const *argv) { unsigned int errorCount; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount = test_concurent_daemon_pair (NULL, NULL, CURL_SSLVERSION_DEFAULT); print_test_result (errorCount, "concurent_daemon_pair"); curl_global_cleanup (); if (99 == errorCount) return 99; return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/https/test_https_get.c0000664000175000017500000001701315232103064017120 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_get.c * @brief Testcase for libmicrohttpd HTTPS GET operations * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static uint16_t global_port; /* perform a HTTP GET request via SSL/TLS */ static unsigned int test_secure_get (const char *cipher_suite, int proto_version) { unsigned int ret; struct MHD_Daemon *d; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3041; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port, NULL, NULL, &http_ahc, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return 1; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 1; } port = dinfo->port; } ret = test_https_transfer (NULL, port, cipher_suite, proto_version); MHD_stop_daemon (d); return ret; } static enum MHD_Result ahc_empty (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) { fprintf (stderr, "Failed to queue response.\n"); _exit (20); } return ret; } static int curlExcessFound (CURL *c, curl_infotype type, char *data, size_t size, void *cls) { static const char *excess_found = "Excess found"; const size_t str_size = strlen (excess_found); (void) c; /* Unused. Silence compiler warning. */ #ifdef _DEBUG if ((CURLINFO_TEXT == type) || (CURLINFO_HEADER_IN == type) || (CURLINFO_HEADER_OUT == type)) fprintf (stderr, "%.*s", (int) size, data); #endif /* _DEBUG */ if ((CURLINFO_TEXT == type) && (size >= str_size) && (0 == strncmp (excess_found, data, str_size))) *(int *) cls = 1; return 0; } static unsigned int testEmptyGet (unsigned int poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int excess_found = 0; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1225; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | poll_flag | MHD_USE_TLS, global_port, NULL, NULL, &ahc_empty, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 4194304; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt (c, CURLOPT_URL, "https://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &curlExcessFound); curl_easy_setopt (c, CURLOPT_DEBUGDATA, &excess_found); curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 8388608; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != 0) return 16777216; if (excess_found) return 33554432; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount += test_secure_get (NULL, CURL_SSLVERSION_DEFAULT); errorCount += testEmptyGet (0); curl_global_cleanup (); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/https/test_tls_options.c0000664000175000017500000003430315232103064017475 /* This file is part of libmicrohttpd Copyright (C) 2007, 2016 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_tls_options.c * @brief Testcase for libmicrohttpd HTTPS TLS version match/mismatch * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" /* * HTTP access handler call back * used to query negotiated security parameters */ static enum MHD_Result simple_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) method; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (NULL == *req_cls) { *req_cls = (void *) &simple_ahc; return MHD_YES; } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (EMPTY_PAGE), EMPTY_PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } enum check_result { CHECK_RES_OK = 0, CHECK_RES_ERR = 1, CHECK_RES_MHD_START_FAILED = 17, CHECK_RES_CURL_TLS_INIT_FAIL = 18, CHECK_RES_CURL_TLS_CONN_FAIL = 19, CHECK_RES_HARD_ERROR = 99 }; static enum check_result check_tls_match_inner (enum know_gnutls_tls_id tls_ver_mhd, enum know_gnutls_tls_id tls_ver_libcurl, uint16_t *pport, struct MHD_Daemon **d_ptr, struct CBC *pcbc, CURL **c_ptr) { CURLcode errornum; char url[256]; int libcurl_tls_set; CURL *c; struct MHD_Daemon *d; /* setup test */ d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &simple_ahc, NULL, MHD_OPTION_HTTPS_PRIORITIES, priorities_map[tls_ver_mhd], MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); fflush (stderr); fflush (stdout); *d_ptr = d; if (d == NULL) { fprintf (stderr, "MHD_start_daemon() with %s failed.\n", tls_names[tls_ver_mhd]); return CHECK_RES_MHD_START_FAILED; } if (0 == *pport) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); return CHECK_RES_ERR; } *pport = dinfo->port; /* Use the same port for rest of the checks */ } if (0 != gen_test_uri (url, sizeof (url), *pport)) { fprintf (stderr, "failed to generate URI.\n"); return CHECK_RES_CURL_TLS_INIT_FAIL; } c = curl_easy_init (); fflush (stderr); fflush (stdout); *c_ptr = c; if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); return CHECK_RES_HARD_ERROR; } #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif if ((CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_URL, url))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc))) || /* TLS options */ /* currently skip any peer authentication */ (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)))) { fflush (stderr); fflush (stdout); fprintf (stderr, "Error setting libcurl option: %s.\n", curl_easy_strerror (errornum)); return CHECK_RES_HARD_ERROR; } libcurl_tls_set = 0; #if CURL_AT_LEAST_VERSION (7,54,0) if (CURL_SSLVERSION_MAX_DEFAULT != libcurl_tls_max_vers_map[tls_ver_libcurl]) { errornum = curl_easy_setopt (c, CURLOPT_SSLVERSION, libcurl_tls_vers_map[tls_ver_libcurl] | libcurl_tls_max_vers_map[tls_ver_libcurl]); if (CURLE_OK == errornum) libcurl_tls_set = 1; else { fprintf (stderr, "Error setting libcurl TLS version range: " "%s.\nRetrying with minimum TLS version only.\n", curl_easy_strerror (errornum)); } } #endif /* CURL_AT_LEAST_VERSION(7,54,0) */ if (! libcurl_tls_set && (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_SSLVERSION, libcurl_tls_vers_map[tls_ver_libcurl])))) { fprintf (stderr, "Error setting libcurl minimum TLS version: %s.\n", curl_easy_strerror (errornum)); return CHECK_RES_CURL_TLS_INIT_FAIL; } errornum = curl_easy_perform (c); fflush (stderr); fflush (stdout); if (CURLE_OK != errornum) { if ((CURLE_SSL_CONNECT_ERROR == errornum) || (CURLE_SSL_CIPHER == errornum)) { fprintf (stderr, "libcurl request failed due to TLS error: '%s'\n", curl_easy_strerror (errornum)); return CHECK_RES_CURL_TLS_CONN_FAIL; } else { fprintf (stderr, "curl_easy_perform failed: '%s'\n", curl_easy_strerror (errornum)); return CHECK_RES_ERR; } } return CHECK_RES_OK; } /** * negotiate a secure connection with server with specific TLS versions * set for MHD and for libcurl */ static enum check_result check_tls_match (enum know_gnutls_tls_id tls_ver_mhd, enum know_gnutls_tls_id tls_ver_libcurl, uint16_t *pport) { CURL *c; struct CBC cbc; enum check_result ret; struct MHD_Daemon *d; if (NULL == (cbc.buf = malloc (sizeof (char) * 255))) return CHECK_RES_HARD_ERROR; cbc.size = 255; cbc.pos = 0; d = NULL; c = NULL; ret = check_tls_match_inner (tls_ver_mhd, tls_ver_libcurl, pport, &d, &cbc, &c); fflush (stderr); fflush (stdout); if (NULL != d) MHD_stop_daemon (d); if (NULL != c) curl_easy_cleanup (c); free (cbc.buf); return ret; } static unsigned int test_first_supported_versions (void) { enum know_gnutls_tls_id ver_for_check; /**< TLS version used for test */ const gnutls_protocol_t *vers_list; /**< The list of GnuTLS supported TLS versions */ uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; /* Use system automatic assignment */ else port = 3080; /* Use predefined port, may break parallel testing of another MHD build */ vers_list = gnutls_protocol_list (); if (NULL == vers_list) { fprintf (stderr, "Error getting GnuTLS supported TLS versions"); return 99; } for (ver_for_check = KNOWN_TLS_MIN; KNOWN_TLS_MAX >= ver_for_check; ++ver_for_check) { const gnutls_protocol_t *ver_ptr; /**< The pointer to the position on the @a vers_list */ enum check_result res; for (ver_ptr = vers_list; 0 != *ver_ptr; ++ver_ptr) { if (ver_for_check == (enum know_gnutls_tls_id) *ver_ptr) break; } if (0 == *ver_ptr) { printf ("%s is not supported by GnuTLS, skipping.\n\n", tls_names[ver_for_check]); fflush (stdout); continue; } if (CURL_SSLVERSION_LAST == libcurl_tls_vers_map[ver_for_check]) { printf ("%s is not supported by libcurl, skipping.\n\n", tls_names[ver_for_check]); fflush (stdout); continue; } /* Found some TLS version that supported by GnuTLS and should be supported by libcurl (but in practice support depends on used TLS library) */ if (KNOWN_TLS_MIN != ver_for_check) printf ("\n"); printf ("Starting check with MHD set to '%s' and " "libcurl set to '%s' (successful connection is expected)...\n", tls_names[ver_for_check], tls_names[ver_for_check]); fflush (stdout); /* Check with MHD and libcurl set to the same TLS version */ res = check_tls_match (ver_for_check, ver_for_check, &port); if (CHECK_RES_HARD_ERROR == res) { fprintf (stderr, "Hard error. Test stopped.\n"); fflush (stderr); return 99; } else if (CHECK_RES_ERR == res) { printf ("Test failed.\n"); fflush (stdout); return 2; } else if (CHECK_RES_MHD_START_FAILED == res) { printf ("Skipping '%s' as MHD cannot be started with this setting.\n", tls_names[ver_for_check]); fflush (stdout); continue; } else if (CHECK_RES_CURL_TLS_INIT_FAIL == res) { printf ("Skipping '%s' as libcurl rejected this setting.\n", tls_names[ver_for_check]); fflush (stdout); continue; } else if (CHECK_RES_CURL_TLS_CONN_FAIL == res) { printf ("Skipping '%s' as it is not supported by current libcurl " "and GnuTLS combination.\n", tls_names[ver_for_check]); fflush (stdout); continue; } printf ("Connection succeeded for MHD set to '%s' and " "libcurl set to '%s'.\n\n", tls_names[ver_for_check], tls_names[ver_for_check]); /* Check with libcurl set to the next TLS version relative to MHD setting */ if (KNOWN_TLS_MAX == ver_for_check) { printf ("Test is incomplete as the latest known TLS version ('%s') " "was found as minimum working version.\nThere is no space to " "advance to the next version.\nAssuming that test is fine.\n", tls_names[ver_for_check]); fflush (stdout); return 0; } if (CURL_SSLVERSION_LAST == libcurl_tls_vers_map[ver_for_check + 1]) { printf ("Test is incomplete as '%s' is the latest version supported " "by libcurl.\nThere is no space to " "advance to the next version.\nAssuming that test is fine.\n", tls_names[ver_for_check]); fflush (stdout); return 0; } printf ("Starting check with MHD set to '%s' and " "minimum libcurl TLS version set to '%s' " "(failed connection is expected)...\n", tls_names[ver_for_check], tls_names[ver_for_check + 1]); fflush (stdout); res = check_tls_match (ver_for_check, ver_for_check + 1, &port); if (CHECK_RES_HARD_ERROR == res) { fprintf (stderr, "Hard error. Test stopped.\n"); fflush (stderr); return 99; } else if (CHECK_RES_ERR == res) { printf ("Test failed.\n"); fflush (stdout); return 2; } else if (CHECK_RES_MHD_START_FAILED == res) { printf ("MHD cannot be started for the second time with " "the same setting.\n"); fflush (stdout); return 4; } else if (CHECK_RES_CURL_TLS_INIT_FAIL == res) { printf ("'%s' has been rejected by libcurl.\n" "Assuming that test is fine.\n", tls_names[ver_for_check + 1]); fflush (stdout); return 0; } else if (CHECK_RES_CURL_TLS_CONN_FAIL == res) { printf ("As expected, libcurl cannot connect to MHD when libcurl " "minimum TLS version is set to '%s' while MHD TLS version set " "to '%s'.\n" "Test succeeded.\n", tls_names[ver_for_check + 1], tls_names[ver_for_check]); fflush (stdout); return 0; } } fprintf (stderr, "The test skipped: No know TLS versions are supported by " "both MHD and libcurl.\n"); fflush (stderr); return 77; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; const char *ssl_version; (void) argc; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; ssl_version = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount = test_first_supported_versions (); fflush (stderr); fflush (stdout); curl_global_cleanup (); if (77 == errorCount) return 77; else if (99 == errorCount) return 99; print_test_result (errorCount, argv[0]); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/https/test_https_sni.c0000664000175000017500000002240015232103064017126 /* This file is part of libmicrohttpd Copyright (C) 2013, 2016 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_sni.c * @brief Testcase for libmicrohttpd HTTPS with SNI operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" /* This test only works with GnuTLS >= 3.0 */ #if GNUTLS_VERSION_MAJOR >= 3 #include /** * A hostname, server key and certificate. */ struct Hosts { struct Hosts *next; const char *hostname; gnutls_pcert_st pcrt; gnutls_privkey_t key; }; /** * Linked list of supported TLDs and respective certificates. */ static struct Hosts *hosts; /* Load the certificate and the private key. * (This code is largely taken from GnuTLS). */ static void load_keys (const char *hostname, const char *CERT_FILE, const char *KEY_FILE) { int ret; gnutls_datum_t data; struct Hosts *host; host = malloc (sizeof (struct Hosts)); if (NULL == host) abort (); host->hostname = hostname; host->next = hosts; hosts = host; ret = gnutls_load_file (CERT_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading certificate file %s.\n", CERT_FILE); exit (1); } ret = gnutls_pcert_import_x509_raw (&host->pcrt, &data, GNUTLS_X509_FMT_PEM, 0); if (ret < 0) { fprintf (stderr, "*** Error loading certificate file: %s\n", gnutls_strerror (ret)); exit (1); } gnutls_free (data.data); ret = gnutls_load_file (KEY_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading key file %s.\n", KEY_FILE); exit (1); } gnutls_privkey_init (&host->key); ret = gnutls_privkey_import_x509_raw (host->key, &data, GNUTLS_X509_FMT_PEM, NULL, 0); if (ret < 0) { fprintf (stderr, "*** Error loading key file: %s\n", gnutls_strerror (ret)); exit (1); } gnutls_free (data.data); } /** * @param session the session we are giving a cert for * @param req_ca_dn NULL on server side * @param nreqs length of req_ca_dn, and thus 0 on server side * @param pk_algos NULL on server side * @param pk_algos_length 0 on server side * @param pcert list of certificates (to be set) * @param pcert_length length of pcert (to be set) * @param pkey the private key (to be set) */ static int sni_callback (gnutls_session_t session, const gnutls_datum_t *req_ca_dn, int nreqs, const gnutls_pk_algorithm_t *pk_algos, int pk_algos_length, gnutls_pcert_st **pcert, unsigned int *pcert_length, gnutls_privkey_t *pkey) { char name[256]; size_t name_len; struct Hosts *host; unsigned int type; (void) req_ca_dn; (void) nreqs; (void) pk_algos; (void) pk_algos_length; /* Unused. Silent compiler warning. */ name_len = sizeof (name); if (GNUTLS_E_SUCCESS != gnutls_server_name_get (session, name, &name_len, &type, 0 /* index */)) return -1; for (host = hosts; NULL != host; host = host->next) if (0 == strncmp (name, host->hostname, name_len)) break; if (NULL == host) { fprintf (stderr, "Need certificate for %.*s\n", (int) name_len, name); return -1; } #if 0 fprintf (stderr, "Returning certificate for %.*s\n", (int) name_len, name); #endif *pkey = host->key; *pcert_length = 1; *pcert = &host->pcrt; return 0; } /* perform a HTTP GET request via SSL/TLS */ static int do_get (const char *url, uint16_t port) { CURL *c; struct CBC cbc; CURLcode errornum; size_t len; struct curl_slist *dns_info; char buf[256]; len = strlen (test_data); if (NULL == (cbc.buf = malloc (sizeof (char) * len))) { fprintf (stderr, MHD_E_MEM); return -1; } cbc.size = len; cbc.pos = 0; c = curl_easy_init (); #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_CAINFO, SRCDIR "/test-ca.crt"); /* perform peer authentication */ /* TODO merge into send_curl_req */ curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 2L); sprintf (buf, "mhdhost1:%u:127.0.0.1", (unsigned int) port); dns_info = curl_slist_append (NULL, buf); sprintf (buf, "mhdhost2:%u:127.0.0.1", (unsigned int) port); dns_info = curl_slist_append (dns_info, buf); curl_easy_setopt (c, CURLOPT_RESOLVE, dns_info); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); free (cbc.buf); curl_slist_free_all (dns_info); return -1; } curl_easy_cleanup (c); curl_slist_free_all (dns_info); if (memcmp (cbc.buf, test_data, len) != 0) { fprintf (stderr, "Error: local file & received file differ.\n"); free (cbc.buf); return -1; } free (cbc.buf); return 0; } int main (int argc, char *const *argv) { unsigned int error_count = 0; struct MHD_Daemon *d; uint16_t port; const char *tls_backend; (void) argc; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3065; #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; tls_backend = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == tls_backend) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } if (! curl_tls_is_gnutls () && ! curl_tls_is_openssl ()) { fprintf (stderr, "This test is reliable only with libcurl with GnuTLS or " "OpenSSL backends.\nSkipping the test as libcurl has '%s' " "backend.\n", tls_backend); curl_global_cleanup (); return 77; } load_keys ("mhdhost1", SRCDIR "/mhdhost1.crt", SRCDIR "/mhdhost1.key"); load_keys ("mhdhost2", SRCDIR "/mhdhost2.crt", SRCDIR "/mhdhost2.key"); d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port, NULL, NULL, &http_ahc, NULL, MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return -1; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return -1; } port = dinfo->port; } if (0 != do_get ("https://mhdhost1/", port)) error_count++; if (0 != do_get ("https://mhdhost2/", port)) error_count++; MHD_stop_daemon (d); curl_global_cleanup (); if (error_count != 0) fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], error_count); return (0 != error_count) ? 1 : 0; } #else int main (void) { fprintf (stderr, "SNI not supported by GnuTLS < 3.0\n"); return 77; } #endif libmicrohttpd-1.0.10/src/testcurl/https/test-ca.crt0000644000175000017500000000421314674632555016007 -----BEGIN CERTIFICATE----- MIIGITCCBAmgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0 LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMTA0MDcxNzM2MThaGA8yMTIxMDMxNDE3 MzYxOFowgYExCzAJBgNVBAYTAlJVMQ8wDQYDVQQIDAZNb3Njb3cxDzANBgNVBAcM Bk1vc2NvdzEbMBkGA1UECgwSdGVzdC1saWJtaWNyb2h0dHBkMSEwHwYJKoZIhvcN AQkBFhJub2JvZHlAZXhhbXBsZS5vcmcxEDAOBgNVBAMMB3Rlc3QtQ0EwggIiMA0G CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDdaWupA4qZjCBNkJoJOm5xnCaizl36 ZLUwp4xBL/YfXPWE3LkmAREiVI/YnAb8l6G7CJnz8dTsOJWkNXG6T1KVP5/2RvBI IaaaufRIAl7hEnj1j9E2hQlV2fxF2ZNhz+nqi0LqKV4LJSpclkXADf2FA9HsVRP/ B7zYh+DP0fSU8V6bsu8XCeRGshroAPrc8rH8lFEEXpNLNIqQr8yKx6SmdB6hfja6 6SQ0++qBhl0aJtn4LHWZohgjBmkIaGFPYIJLgxQ/xyp2Grz2q7lGKJ+zBkBF8iOP t3x+F1hSCBnr/DGYWmjEm5tYm+7pyuriPddXdCc8+qa2LxMZo3EXxLo5YISpPCyw Z7V3YAOZTr3m1C24LiYvPehCq1CTIkhhmqtlVJXU7ISD48cx9y+5Pi34wtbTI/gN x4voyTLAfyavKMmIpxxIRsWldiF2n06HdvCRVdihDQUad10ygTmWf1J/s2ZETAtH QaSd7MD389t6nQFtTIXigsNKnnDPlrtxt7rOLvLQeR0K04Gzrf/scheOanRAfOXH KNBFU7YkDFG8rqizlC65rx9qeXFYXQcHZTuqxK7tgZnSgJat3E70VbTSCsEEG7eR bNX/fChUKAIIpWaiW6HDlKLl6m2y+BzM91umBsKOqTvntMVFBSF9pVYlXK854aIR q8A2Xujd012seQIDAQABo4GfMIGcMAsGA1UdDwQEAwICpDASBgNVHRMBAf8ECDAG AQH/AgEBMB0GA1UdDgQWBBRYdUPApWoxw4U13Rqsjf9AHdbpLDATBgNVHSUEDDAK BggrBgEFBQcDATAkBglghkgBhvhCAQ0EFxYVVGVzdCBsaWJtaWNyb2h0dHBkIENB MB8GA1UdIwQYMBaAFFh1Q8ClajHDhTXdGqyN/0Ad1uksMA0GCSqGSIb3DQEBCwUA A4ICAQBvrrcTKVeI1EYnXo4BQD4oCvf9z1fYQmL21EbHwgjg1nmaPkvStgWAc5p1 kKwySrpEMKXfu68X76RccXZyWWIamEjz2OCWYZgjX6d6FpjhLphL8WxXDy5C9eay ixN7+URz2XQoi22wqR+tCPDhrIzcMPyMkx/6gRgcYeDnaFrkdSeSsKsID4plfcIj ISWJDvv+IAgrtsG1NVHnGwpAv0od3A8/4/fR6PPyewaU3aydvjZ7Au8O9DGDjlU9 9HdlOkkY6GVJ1pfGZib7cV7lhy0D2kj1g9xZh97YjpoUfppPl9r+6A8gDm0hXlAD TlzNYlwTb681ZEoSd9PiLEY8HETssHlays2dYXdcNwAEp69iIHz8q1Q98Be9LScl WEzgaOT9U7lpIw/MWbELoMsC+Ecs1cVWBIuiIq8aSG2kRr1x3S8yVXbAohAXif2s E6puieM/VJ25iaNhkbLmDkk58QVVmn9NZNv6ETxuSQMp9e0EwbVlj68vzClQ91Y/ nmAiGcLFUEwB9G0szv9+vR+oDW4IkvdFZSUbcICd2cnynnwAD395onqS4hEZO1xM Gy5ZldbTMTjgn7fChNopz15ChPBnwFIjhm+S0CyiLRQAowfknRVq2IBkj7/5kOWg 4mcxcq76HoQWK/8X/8RFL1eFVAvY7TNHYJ0RS51DMuwCNQictA== -----END CERTIFICATE----- libmicrohttpd-1.0.10/src/testcurl/https/test_https_get_parallel_threads.c0000664000175000017500000001331615232103064022510 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_get_parallel_threads.c * @brief Testcase for libmicrohttpd HTTPS GET operations with multi-threaded * MHD daemon and several clients working in parallel * @author Sagie Amir * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) * * TODO: add test for external select! */ #include "platform.h" #include "microhttpd.h" #include #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 4 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 4 #endif /** * used when spawning multiple threads executing curl server requests * */ static void * https_transfer_thread_adapter (void *args) { static int nonnull; struct https_test_data *cargs = args; unsigned int ret; ret = test_https_transfer (cargs->cls, cargs->port, cargs->cipher_suite, cargs->proto_version); if (ret == 0) return NULL; return &nonnull; } /** * Test non-parallel requests. * * @return: 0 upon all client requests returning '0', 1 otherwise. * * TODO : make client_count a parameter - number of curl client threads to spawn */ static unsigned int test_single_client (void *cls, uint16_t port, const char *cipher_suite, int curl_proto_version) { void *client_thread_ret; struct https_test_data client_args = { NULL, port, cipher_suite, curl_proto_version }; (void) cls; /* Unused. Silent compiler warning. */ client_thread_ret = https_transfer_thread_adapter (&client_args); if (client_thread_ret != NULL) return 1; return 0; } /** * Test parallel request handling. * * @return: 0 upon all client requests returning '0', 1 otherwise. * * TODO : make client_count a parameter - number of curl client threads to spawn */ static unsigned int test_parallel_clients (void *cls, uint16_t port, const char *cipher_suite, int curl_proto_version) { int i; int client_count = (MHD_CPU_COUNT - 1); void *client_thread_ret; pthread_t client_arr[client_count]; struct https_test_data client_args = { NULL, port, cipher_suite, curl_proto_version }; (void) cls; /* Unused. Silent compiler warning. */ for (i = 0; i < client_count; ++i) { if (pthread_create (&client_arr[i], NULL, &https_transfer_thread_adapter, &client_args) != 0) { fprintf (stderr, "Error: failed to spawn test client threads.\n"); return 1; } } /* check all client requests fulfilled correctly */ for (i = 0; i < client_count; ++i) { if ((pthread_join (client_arr[i], &client_thread_ret) != 0) || (client_thread_ret != NULL)) return 1; } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; const char *ssl_version; uint16_t port; unsigned int iseed; (void) argc; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3010; /* initialize random seed used by curl clients */ iseed = (unsigned int) time (NULL); #ifdef MHD_HTTPS_REQUIRE_GCRYPT #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ srand (iseed); if (! testsuite_curl_global_init ()) return 99; ssl_version = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount += test_wrap ("multi threaded daemon, single client", &test_single_client, NULL, port, MHD_USE_TLS | MHD_USE_ERROR_LOG | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); errorCount += test_wrap ("multi threaded daemon, parallel client", &test_parallel_clients, NULL, port, MHD_USE_TLS | MHD_USE_ERROR_LOG | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, NULL, CURL_SSLVERSION_DEFAULT, MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (errorCount != 0) fprintf (stderr, "Failed test: %s, error: %u.\n", argv[0], errorCount); curl_global_cleanup (); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/https/Makefile.in0000664000175000017500000021520315235436271015776 # Makefile.in generated by automake 1.17 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2024 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) am__rm_f = rm -f $(am__rm_f_notfound) am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = --coverage check_PROGRAMS = test_https_get_select$(EXEEXT) $(am__EXEEXT_5) @USE_THREADS_TRUE@am__append_2 = \ @USE_THREADS_TRUE@ $(THREAD_ONLY_TESTS) subdir = src/testcurl/https ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@am__EXEEXT_1 = test_https_time_out$(EXEEXT) \ @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@ test_https_get_parallel$(EXEEXT) \ @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@ test_https_get_parallel_threads$(EXEEXT) @HAVE_GNUTLS_SNI_TRUE@am__EXEEXT_2 = test_https_sni$(EXEEXT) am__EXEEXT_3 = am__EXEEXT_4 = test_tls_options$(EXEEXT) \ test_tls_authentication$(EXEEXT) $(am__EXEEXT_1) \ $(am__EXEEXT_2) test_https_session_info$(EXEEXT) \ test_https_session_info_append$(EXEEXT) \ test_https_multi_daemon$(EXEEXT) test_https_get$(EXEEXT) \ test_empty_response$(EXEEXT) test_https_get_iovec$(EXEEXT) \ $(am__EXEEXT_3) @USE_THREADS_TRUE@am__EXEEXT_5 = $(am__EXEEXT_4) am_test_empty_response_OBJECTS = test_empty_response.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_empty_response_OBJECTS = $(am_test_empty_response_OBJECTS) test_empty_response_LDADD = $(LDADD) am__DEPENDENCIES_1 = test_empty_response_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am_test_https_get_OBJECTS = test_https_get.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_https_get_OBJECTS = $(am_test_https_get_OBJECTS) test_https_get_LDADD = $(LDADD) test_https_get_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_get_iovec_OBJECTS = test_https_get_iovec.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_https_get_iovec_OBJECTS = $(am_test_https_get_iovec_OBJECTS) test_https_get_iovec_LDADD = $(LDADD) test_https_get_iovec_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_get_parallel_OBJECTS = \ test_https_get_parallel-test_https_get_parallel.$(OBJEXT) \ test_https_get_parallel-tls_test_common.$(OBJEXT) test_https_get_parallel_OBJECTS = \ $(am_test_https_get_parallel_OBJECTS) am__DEPENDENCIES_2 = $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) test_https_get_parallel_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_https_get_parallel_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_https_get_parallel_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_https_get_parallel_threads_OBJECTS = test_https_get_parallel_threads-test_https_get_parallel_threads.$(OBJEXT) \ test_https_get_parallel_threads-tls_test_common.$(OBJEXT) test_https_get_parallel_threads_OBJECTS = \ $(am_test_https_get_parallel_threads_OBJECTS) test_https_get_parallel_threads_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_https_get_parallel_threads_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_test_https_get_select_OBJECTS = test_https_get_select.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_https_get_select_OBJECTS = $(am_test_https_get_select_OBJECTS) test_https_get_select_LDADD = $(LDADD) test_https_get_select_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_multi_daemon_OBJECTS = \ test_https_multi_daemon.$(OBJEXT) tls_test_common.$(OBJEXT) test_https_multi_daemon_OBJECTS = \ $(am_test_https_multi_daemon_OBJECTS) test_https_multi_daemon_LDADD = $(LDADD) test_https_multi_daemon_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_session_info_OBJECTS = \ test_https_session_info.$(OBJEXT) tls_test_common.$(OBJEXT) test_https_session_info_OBJECTS = \ $(am_test_https_session_info_OBJECTS) test_https_session_info_LDADD = $(LDADD) test_https_session_info_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am__objects_1 = test_https_session_info.$(OBJEXT) \ tls_test_common.$(OBJEXT) am_test_https_session_info_append_OBJECTS = $(am__objects_1) test_https_session_info_append_OBJECTS = \ $(am_test_https_session_info_append_OBJECTS) test_https_session_info_append_LDADD = $(LDADD) test_https_session_info_append_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_sni_OBJECTS = test_https_sni.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_https_sni_OBJECTS = $(am_test_https_sni_OBJECTS) test_https_sni_LDADD = $(LDADD) test_https_sni_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_https_time_out_OBJECTS = test_https_time_out.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_https_time_out_OBJECTS = $(am_test_https_time_out_OBJECTS) test_https_time_out_LDADD = $(LDADD) test_https_time_out_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_tls_authentication_OBJECTS = \ test_tls_authentication.$(OBJEXT) tls_test_common.$(OBJEXT) test_tls_authentication_OBJECTS = \ $(am_test_tls_authentication_OBJECTS) test_tls_authentication_LDADD = $(LDADD) test_tls_authentication_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) am_test_tls_options_OBJECTS = test_tls_options.$(OBJEXT) \ tls_test_common.$(OBJEXT) test_tls_options_OBJECTS = $(am_test_tls_options_OBJECTS) test_tls_options_LDADD = $(LDADD) test_tls_options_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/test_empty_response.Po \ ./$(DEPDIR)/test_https_get.Po \ ./$(DEPDIR)/test_https_get_iovec.Po \ ./$(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po \ ./$(DEPDIR)/test_https_get_parallel-tls_test_common.Po \ ./$(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po \ ./$(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po \ ./$(DEPDIR)/test_https_get_select.Po \ ./$(DEPDIR)/test_https_multi_daemon.Po \ ./$(DEPDIR)/test_https_session_info.Po \ ./$(DEPDIR)/test_https_sni.Po \ ./$(DEPDIR)/test_https_time_out.Po \ ./$(DEPDIR)/test_tls_authentication.Po \ ./$(DEPDIR)/test_tls_options.Po ./$(DEPDIR)/tls_test_common.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(test_empty_response_SOURCES) $(test_https_get_SOURCES) \ $(test_https_get_iovec_SOURCES) \ $(test_https_get_parallel_SOURCES) \ $(test_https_get_parallel_threads_SOURCES) \ $(test_https_get_select_SOURCES) \ $(test_https_multi_daemon_SOURCES) \ $(test_https_session_info_SOURCES) \ $(test_https_session_info_append_SOURCES) \ $(test_https_sni_SOURCES) $(test_https_time_out_SOURCES) \ $(test_tls_authentication_SOURCES) $(test_tls_options_SOURCES) DIST_SOURCES = $(test_empty_response_SOURCES) \ $(test_https_get_SOURCES) $(test_https_get_iovec_SOURCES) \ $(test_https_get_parallel_SOURCES) \ $(test_https_get_parallel_threads_SOURCES) \ $(test_https_get_select_SOURCES) \ $(test_https_multi_daemon_SOURCES) \ $(test_https_session_info_SOURCES) \ $(test_https_session_info_append_SOURCES) \ $(test_https_sni_SOURCES) $(test_https_time_out_SOURCES) \ $(test_tls_authentication_SOURCES) $(test_tls_options_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ check recheck distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ $$am__collect_skipped_logs \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(IGNORE_SKIPPED_LOGS)'; then \ am__collect_skipped_logs='--collect-skipped-logs no'; \ else \ am__collect_skipped_logs=''; \ fi; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ am__xargs_n = @am__xargs_n@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain EMPTY_ITEM = SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ -DSRCDIR=\"$(srcdir)\" \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ $(am__append_1) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(MHD_TLS_LIB_LDFLAGS) $(MHD_TLS_LIBDEPS) @LIBGCRYPT_LIBS@ @LIBCURL@ @HAVE_GNUTLS_SNI_TRUE@TEST_HTTPS_SNI = test_https_sni @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@HTTPS_PARALLEL_TESTS = \ @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@ test_https_time_out \ @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@ test_https_get_parallel \ @HAVE_GNUTLS_MTHREAD_BROKEN_FALSE@ test_https_get_parallel_threads THREAD_ONLY_TESTS = \ test_tls_options \ test_tls_authentication \ $(HTTPS_PARALLEL_TESTS) \ $(TEST_HTTPS_SNI) \ test_https_session_info \ test_https_session_info_append \ test_https_multi_daemon \ test_https_get \ test_empty_response \ test_https_get_iovec \ $(EMPTY_ITEM) EXTRA_DIST = \ test-ca.crt test-ca.key \ mhdhost1.crt mhdhost1.key \ mhdhost2.crt mhdhost2.key TESTS = \ $(check_PROGRAMS) test_https_time_out_SOURCES = \ test_https_time_out.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_tls_options_SOURCES = \ test_tls_options.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_SOURCES = \ test_https_get_parallel.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_https_get_parallel_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_empty_response_SOURCES = \ test_empty_response.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_threads_SOURCES = \ test_https_get_parallel_threads.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_threads_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_https_get_parallel_threads_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_tls_authentication_SOURCES = \ test_tls_authentication.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_session_info_SOURCES = \ test_https_session_info.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_session_info_append_SOURCES = $(test_https_session_info_SOURCES) test_https_multi_daemon_SOURCES = \ test_https_multi_daemon.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_SOURCES = \ test_https_get.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_iovec_SOURCES = \ test_https_get_iovec.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_sni_SOURCES = \ test_https_sni.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_select_SOURCES = \ test_https_get_select.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/testcurl/https/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/testcurl/https/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: $(am__rm_f) $(check_PROGRAMS) test -z "$(EXEEXT)" || $(am__rm_f) $(check_PROGRAMS:$(EXEEXT)=) test_empty_response$(EXEEXT): $(test_empty_response_OBJECTS) $(test_empty_response_DEPENDENCIES) $(EXTRA_test_empty_response_DEPENDENCIES) @rm -f test_empty_response$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_empty_response_OBJECTS) $(test_empty_response_LDADD) $(LIBS) test_https_get$(EXEEXT): $(test_https_get_OBJECTS) $(test_https_get_DEPENDENCIES) $(EXTRA_test_https_get_DEPENDENCIES) @rm -f test_https_get$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_get_OBJECTS) $(test_https_get_LDADD) $(LIBS) test_https_get_iovec$(EXEEXT): $(test_https_get_iovec_OBJECTS) $(test_https_get_iovec_DEPENDENCIES) $(EXTRA_test_https_get_iovec_DEPENDENCIES) @rm -f test_https_get_iovec$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_get_iovec_OBJECTS) $(test_https_get_iovec_LDADD) $(LIBS) test_https_get_parallel$(EXEEXT): $(test_https_get_parallel_OBJECTS) $(test_https_get_parallel_DEPENDENCIES) $(EXTRA_test_https_get_parallel_DEPENDENCIES) @rm -f test_https_get_parallel$(EXEEXT) $(AM_V_CCLD)$(test_https_get_parallel_LINK) $(test_https_get_parallel_OBJECTS) $(test_https_get_parallel_LDADD) $(LIBS) test_https_get_parallel_threads$(EXEEXT): $(test_https_get_parallel_threads_OBJECTS) $(test_https_get_parallel_threads_DEPENDENCIES) $(EXTRA_test_https_get_parallel_threads_DEPENDENCIES) @rm -f test_https_get_parallel_threads$(EXEEXT) $(AM_V_CCLD)$(test_https_get_parallel_threads_LINK) $(test_https_get_parallel_threads_OBJECTS) $(test_https_get_parallel_threads_LDADD) $(LIBS) test_https_get_select$(EXEEXT): $(test_https_get_select_OBJECTS) $(test_https_get_select_DEPENDENCIES) $(EXTRA_test_https_get_select_DEPENDENCIES) @rm -f test_https_get_select$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_get_select_OBJECTS) $(test_https_get_select_LDADD) $(LIBS) test_https_multi_daemon$(EXEEXT): $(test_https_multi_daemon_OBJECTS) $(test_https_multi_daemon_DEPENDENCIES) $(EXTRA_test_https_multi_daemon_DEPENDENCIES) @rm -f test_https_multi_daemon$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_multi_daemon_OBJECTS) $(test_https_multi_daemon_LDADD) $(LIBS) test_https_session_info$(EXEEXT): $(test_https_session_info_OBJECTS) $(test_https_session_info_DEPENDENCIES) $(EXTRA_test_https_session_info_DEPENDENCIES) @rm -f test_https_session_info$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_session_info_OBJECTS) $(test_https_session_info_LDADD) $(LIBS) test_https_session_info_append$(EXEEXT): $(test_https_session_info_append_OBJECTS) $(test_https_session_info_append_DEPENDENCIES) $(EXTRA_test_https_session_info_append_DEPENDENCIES) @rm -f test_https_session_info_append$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_session_info_append_OBJECTS) $(test_https_session_info_append_LDADD) $(LIBS) test_https_sni$(EXEEXT): $(test_https_sni_OBJECTS) $(test_https_sni_DEPENDENCIES) $(EXTRA_test_https_sni_DEPENDENCIES) @rm -f test_https_sni$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_sni_OBJECTS) $(test_https_sni_LDADD) $(LIBS) test_https_time_out$(EXEEXT): $(test_https_time_out_OBJECTS) $(test_https_time_out_DEPENDENCIES) $(EXTRA_test_https_time_out_DEPENDENCIES) @rm -f test_https_time_out$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_https_time_out_OBJECTS) $(test_https_time_out_LDADD) $(LIBS) test_tls_authentication$(EXEEXT): $(test_tls_authentication_OBJECTS) $(test_tls_authentication_DEPENDENCIES) $(EXTRA_test_tls_authentication_DEPENDENCIES) @rm -f test_tls_authentication$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_tls_authentication_OBJECTS) $(test_tls_authentication_LDADD) $(LIBS) test_tls_options$(EXEEXT): $(test_tls_options_OBJECTS) $(test_tls_options_DEPENDENCIES) $(EXTRA_test_tls_options_DEPENDENCIES) @rm -f test_tls_options$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_tls_options_OBJECTS) $(test_tls_options_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_empty_response.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_iovec.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel-tls_test_common.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_get_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_multi_daemon.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_session_info.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_sni.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_https_time_out.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_tls_authentication.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_tls_options.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tls_test_common.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @: >>$@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< test_https_get_parallel-test_https_get_parallel.o: test_https_get_parallel.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-test_https_get_parallel.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo -c -o test_https_get_parallel-test_https_get_parallel.o `test -f 'test_https_get_parallel.c' || echo '$(srcdir)/'`test_https_get_parallel.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_https_get_parallel.c' object='test_https_get_parallel-test_https_get_parallel.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-test_https_get_parallel.o `test -f 'test_https_get_parallel.c' || echo '$(srcdir)/'`test_https_get_parallel.c test_https_get_parallel-test_https_get_parallel.obj: test_https_get_parallel.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-test_https_get_parallel.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo -c -o test_https_get_parallel-test_https_get_parallel.obj `if test -f 'test_https_get_parallel.c'; then $(CYGPATH_W) 'test_https_get_parallel.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Tpo $(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_https_get_parallel.c' object='test_https_get_parallel-test_https_get_parallel.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-test_https_get_parallel.obj `if test -f 'test_https_get_parallel.c'; then $(CYGPATH_W) 'test_https_get_parallel.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel.c'; fi` test_https_get_parallel-tls_test_common.o: tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-tls_test_common.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo -c -o test_https_get_parallel-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel-tls_test_common.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel-tls_test_common.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c test_https_get_parallel-tls_test_common.obj: tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -MT test_https_get_parallel-tls_test_common.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo -c -o test_https_get_parallel-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel-tls_test_common.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel-tls_test_common.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi` test_https_get_parallel_threads-test_https_get_parallel_threads.o: test_https_get_parallel_threads.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-test_https_get_parallel_threads.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.o `test -f 'test_https_get_parallel_threads.c' || echo '$(srcdir)/'`test_https_get_parallel_threads.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_https_get_parallel_threads.c' object='test_https_get_parallel_threads-test_https_get_parallel_threads.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.o `test -f 'test_https_get_parallel_threads.c' || echo '$(srcdir)/'`test_https_get_parallel_threads.c test_https_get_parallel_threads-test_https_get_parallel_threads.obj: test_https_get_parallel_threads.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-test_https_get_parallel_threads.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.obj `if test -f 'test_https_get_parallel_threads.c'; then $(CYGPATH_W) 'test_https_get_parallel_threads.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel_threads.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Tpo $(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_https_get_parallel_threads.c' object='test_https_get_parallel_threads-test_https_get_parallel_threads.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-test_https_get_parallel_threads.obj `if test -f 'test_https_get_parallel_threads.c'; then $(CYGPATH_W) 'test_https_get_parallel_threads.c'; else $(CYGPATH_W) '$(srcdir)/test_https_get_parallel_threads.c'; fi` test_https_get_parallel_threads-tls_test_common.o: tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-tls_test_common.o -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo -c -o test_https_get_parallel_threads-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel_threads-tls_test_common.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-tls_test_common.o `test -f 'tls_test_common.c' || echo '$(srcdir)/'`tls_test_common.c test_https_get_parallel_threads-tls_test_common.obj: tls_test_common.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -MT test_https_get_parallel_threads-tls_test_common.obj -MD -MP -MF $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo -c -o test_https_get_parallel_threads-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Tpo $(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tls_test_common.c' object='test_https_get_parallel_threads-tls_test_common.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_https_get_parallel_threads_CFLAGS) $(CFLAGS) -c -o test_https_get_parallel_threads-tls_test_common.obj `if test -f 'tls_test_common.c'; then $(CYGPATH_W) 'tls_test_common.c'; else $(CYGPATH_W) '$(srcdir)/tls_test_common.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ output_system_information () \ { \ echo; \ { uname -a | $(AWK) '{ \ printf "System information (uname -a):"; \ for (i = 1; i < NF; ++i) \ { \ if (i != 2) \ printf " %s", $$i; \ } \ printf "\n"; \ }'; } 2>&1; \ if test -r /etc/os-release; then \ echo "Distribution information (/etc/os-release):"; \ sed 8q /etc/os-release; \ elif test -r /etc/issue; then \ echo "Distribution information (/etc/issue):"; \ cat /etc/issue; \ fi; \ }; \ please_report () \ { \ echo "Some test(s) failed. Please report this to $(PACKAGE_BUGREPORT),"; \ echo "together with the test-suite.log file (gzipped) and your system"; \ echo "information. Thanks."; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ output_system_information; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG) for debugging.$${std}";\ if test -n "$(PACKAGE_BUGREPORT)"; then \ please_report | sed -e "s/^/$${col}/" -e s/'$$'/"$${std}"/; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) @$(am__rm_f) $(RECHECK_LOGS) @$(am__rm_f) $(RECHECK_LOGS:.log=.trs) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_https_get_select.log: test_https_get_select$(EXEEXT) @p='test_https_get_select$(EXEEXT)'; \ b='test_https_get_select'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_tls_options.log: test_tls_options$(EXEEXT) @p='test_tls_options$(EXEEXT)'; \ b='test_tls_options'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_tls_authentication.log: test_tls_authentication$(EXEEXT) @p='test_tls_authentication$(EXEEXT)'; \ b='test_tls_authentication'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_time_out.log: test_https_time_out$(EXEEXT) @p='test_https_time_out$(EXEEXT)'; \ b='test_https_time_out'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_get_parallel.log: test_https_get_parallel$(EXEEXT) @p='test_https_get_parallel$(EXEEXT)'; \ b='test_https_get_parallel'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_get_parallel_threads.log: test_https_get_parallel_threads$(EXEEXT) @p='test_https_get_parallel_threads$(EXEEXT)'; \ b='test_https_get_parallel_threads'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_sni.log: test_https_sni$(EXEEXT) @p='test_https_sni$(EXEEXT)'; \ b='test_https_sni'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_session_info.log: test_https_session_info$(EXEEXT) @p='test_https_session_info$(EXEEXT)'; \ b='test_https_session_info'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_session_info_append.log: test_https_session_info_append$(EXEEXT) @p='test_https_session_info_append$(EXEEXT)'; \ b='test_https_session_info_append'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_multi_daemon.log: test_https_multi_daemon$(EXEEXT) @p='test_https_multi_daemon$(EXEEXT)'; \ b='test_https_multi_daemon'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_get.log: test_https_get$(EXEEXT) @p='test_https_get$(EXEEXT)'; \ b='test_https_get'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_empty_response.log: test_empty_response$(EXEEXT) @p='test_empty_response$(EXEEXT)'; \ b='test_empty_response'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_https_get_iovec.log: test_https_get_iovec$(EXEEXT) @p='test_https_get_iovec$(EXEEXT)'; \ b='test_https_get_iovec'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -$(am__rm_f) $(TEST_LOGS) -$(am__rm_f) $(TEST_LOGS:.log=.trs) -$(am__rm_f) $(TEST_SUITE_LOG) clean-generic: distclean-generic: -$(am__rm_f) $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/test_empty_response.Po -rm -f ./$(DEPDIR)/test_https_get.Po -rm -f ./$(DEPDIR)/test_https_get_iovec.Po -rm -f ./$(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po -rm -f ./$(DEPDIR)/test_https_get_parallel-tls_test_common.Po -rm -f ./$(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po -rm -f ./$(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po -rm -f ./$(DEPDIR)/test_https_get_select.Po -rm -f ./$(DEPDIR)/test_https_multi_daemon.Po -rm -f ./$(DEPDIR)/test_https_session_info.Po -rm -f ./$(DEPDIR)/test_https_sni.Po -rm -f ./$(DEPDIR)/test_https_time_out.Po -rm -f ./$(DEPDIR)/test_tls_authentication.Po -rm -f ./$(DEPDIR)/test_tls_options.Po -rm -f ./$(DEPDIR)/tls_test_common.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/test_empty_response.Po -rm -f ./$(DEPDIR)/test_https_get.Po -rm -f ./$(DEPDIR)/test_https_get_iovec.Po -rm -f ./$(DEPDIR)/test_https_get_parallel-test_https_get_parallel.Po -rm -f ./$(DEPDIR)/test_https_get_parallel-tls_test_common.Po -rm -f ./$(DEPDIR)/test_https_get_parallel_threads-test_https_get_parallel_threads.Po -rm -f ./$(DEPDIR)/test_https_get_parallel_threads-tls_test_common.Po -rm -f ./$(DEPDIR)/test_https_get_select.Po -rm -f ./$(DEPDIR)/test_https_multi_daemon.Po -rm -f ./$(DEPDIR)/test_https_session_info.Po -rm -f ./$(DEPDIR)/test_https_sni.Po -rm -f ./$(DEPDIR)/test_https_time_out.Po -rm -f ./$(DEPDIR)/test_tls_authentication.Po -rm -f ./$(DEPDIR)/test_tls_options.Po -rm -f ./$(DEPDIR)/tls_test_common.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) check-am install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am .PRECIOUS: Makefile @HEAVY_TESTS_NOTPARALLEL@ $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: # Tell GNU make to disable its built-in pattern rules. %:: %,v %:: RCS/%,v %:: RCS/% %:: s.% %:: SCCS/s.% libmicrohttpd-1.0.10/src/testcurl/https/mhdhost1.key0000644000175000017500000000325014674632555016176 -----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDFvkuTBN+821Z4 VJgA+gTOrBUBFbEMNHY99CaYG2seEw0RDJQJOD41rTSERBtxlvPt+BLQU5jWGPIw UlqY0Y/TfUe8xLvMc1AngdsTPR3US54+CMS9ZoUwWdxMoafTsKf17dFy/aKEn8gj zB/emH+T9RM6/rZiEizZ8xAzksPqhf26UomEBo68VPqHKsHXF7edWE9PQ+ytReWT LbneTtdcQAhY7p0tmcrfvtSJEMkicVL0U3+GiMVv7yBwHKj+ff0scwG2nlYYzn7E bAQfJiTC2dozwgQqh9tQ0RFBPdyA+/jM3ufLcvCWNHYDVzmAdeYo7sbbjm1t+ptW 06Hf7VslAgMBAAECggEALshrttezW0oFNijFYY3FL2Q0//Gy1nFe/B9UNi5edFoL gFoad+fvh+F3iEdYutH82fMT+GeexCBYxCfnuTnzLhT4sOdWivNJJl+phe6yrPRK 9uA6M5kar6rC3Ppt6z5jLmLaZ7ssBPaMcjOr4ozvugCEUTPL0H3+UH4Z+imh4kzw MgLsF8QkWPCF/fxsVhCwC3y3Dctl3oLh6qQFudYKtymRjk2I7zFAuQGsGoYonPbF 1LZ6xHOjegXtqhC0pK8Kpn4N7LgYVVNPT1TAckQ9GDDi0IgMYwIsSQb/ncaV5Cwb 9tPqBv1Oi2ayINeXrG5J/G8S1cEbIzdSL8ZqG+CcjQKBgQD1c89Rh/Hbc0zxxgdR eGx6oOtNjAZ3zgnNyVnXiZ7mXtbCcjMHJhcW41RL8lg+mhKfj9MgXamDP/R4X2In H358dEekfN4wjogeXs9lmh48cGC7zez4/RS752OmrwmhOqkKDa7dy+SLR5QJ3L2n 4k/2eQwTlXpuPIMrBT1hUvsA3wKBgQDOPaTy03oXX1bwwX6sHUTrQTKAC52v4hQl bya+6t+VGpj+cdWzxRFoR5mN85b9Kkj1nAFx+6zioOPLUOZhnnqihlQBwm06gH1p v3qkxuXOhnMPJsNg4lltUq/18UlSQwFZuKr7G2vDhckHwZdlu06P/rlA9K5Kxjzi gX3I+XoQewKBgQDrn/YYXXmW4jOuMR0bX5A7lDjuY4pd/iO5Mh6V453vpoFhfoFv zmgB588nbQi7Z+qS1F2nx2IQBhgoaeBukDQ7QuD3jYs6b8lJ5lgQQAfgmzyxbPic +U6rJ3CpNYT4Crj1VrdUYgQOlHMPmKFUBdQfVop6TleOdXaxmMEYqbEdXwKBgQCz xZwQZjJYSSyZc7CdCm5Wul/wqS9sbp6s+rRFWqpFaAfQUx26M582zKKWz6vfRYqP PMsttfk/Gos1YHFQyjmPjZOQbQ+VHQc0tEmNdCpA2YVVwa4wt1zIJHlo4kfNQsbc lFHFzGMk7WsMLb1wWdLjRV/ptN5wI1hTABjKpFu4HQKBgExQNTHMxzpAAh9XFiJ3 oGvf+9+JtjmrgKsR0T7q60xjOYH0E2rznvvBVNeZlAc+tjawmedxiuiitmjQUteG hW4ncX0UcqFPm7Ahqo9+NDemJlV7DYHRcvL/xVNUbr8yV7OpHILd4Hk/s8J4QGl/ bC1zEehy8q0jMywvSR8vsS1v -----END PRIVATE KEY----- libmicrohttpd-1.0.10/src/testcurl/https/test_tls_authentication.c0000664000175000017500000001026215232103064021017 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_tls_authentication.c * @brief Testcase for libmicrohttpd HTTPS GET operations with CA-signed TLS server certificate * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" /* perform a HTTP GET request via SSL/TLS */ static unsigned int test_secure_get (void *cls, const char *cipher_suite, int proto_version) { enum test_get_result ret; struct MHD_Daemon *d; uint16_t port; (void) cls; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 3075; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, port, NULL, NULL, &http_ahc, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, MHD_E_SERVER_INIT); return 1; } if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 1; } port = dinfo->port; } ret = test_daemon_get (NULL, cipher_suite, proto_version, port, 1); MHD_stop_daemon (d); if (TEST_GET_HARD_ERROR == ret) return 99; if (TEST_GET_CURL_GEN_ERROR == ret) { fprintf (stderr, "libcurl error.\nTest aborted.\n"); return 99; } if ((TEST_GET_CURL_CA_ERROR == ret) || (TEST_GET_CURL_NOT_IMPLT == ret)) { fprintf (stderr, "libcurl TLS backend does not support custom CA.\n" "Test skipped.\n"); return 77; } return TEST_GET_OK == ret ? 0 : 1; } int main (int argc, char *const *argv) { unsigned int errorCount; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (! testsuite_curl_global_init ()) return 99; if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } #if ! CURL_AT_LEAST_VERSION (7,60,0) if (curl_tls_is_schannel ()) { fprintf (stderr, "libcurl before version 7.60.0 does not support " "custom CA with Schannel backend.\nTest skipped.\n"); curl_global_cleanup (); return 77; } #endif /* ! CURL_AT_LEAST_VERSION(7,60,0) */ errorCount = test_secure_get (NULL, NULL, CURL_SSLVERSION_DEFAULT); print_test_result (errorCount, argv[0]); curl_global_cleanup (); if (77 == errorCount) return 77; if (99 == errorCount) return 77; return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/https/tls_test_keys.h0000644000175000017500000002460714760713577017013 /* This file is part of libmicrohttpd Copyright (C) 2006, 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2021-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MHD_TLS_TEST_KEYS_H #define MHD_TLS_TEST_KEYS_H /* Test Certificates */ /* Certificate Authority cert */ static const char ca_cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIGITCCBAmgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMTA0MDcxNzM2MThaGA8yMTIxMDMxNDE3\n\ MzYxOFowgYExCzAJBgNVBAYTAlJVMQ8wDQYDVQQIDAZNb3Njb3cxDzANBgNVBAcM\n\ Bk1vc2NvdzEbMBkGA1UECgwSdGVzdC1saWJtaWNyb2h0dHBkMSEwHwYJKoZIhvcN\n\ AQkBFhJub2JvZHlAZXhhbXBsZS5vcmcxEDAOBgNVBAMMB3Rlc3QtQ0EwggIiMA0G\n\ CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDdaWupA4qZjCBNkJoJOm5xnCaizl36\n\ ZLUwp4xBL/YfXPWE3LkmAREiVI/YnAb8l6G7CJnz8dTsOJWkNXG6T1KVP5/2RvBI\n\ IaaaufRIAl7hEnj1j9E2hQlV2fxF2ZNhz+nqi0LqKV4LJSpclkXADf2FA9HsVRP/\n\ B7zYh+DP0fSU8V6bsu8XCeRGshroAPrc8rH8lFEEXpNLNIqQr8yKx6SmdB6hfja6\n\ 6SQ0++qBhl0aJtn4LHWZohgjBmkIaGFPYIJLgxQ/xyp2Grz2q7lGKJ+zBkBF8iOP\n\ t3x+F1hSCBnr/DGYWmjEm5tYm+7pyuriPddXdCc8+qa2LxMZo3EXxLo5YISpPCyw\n\ Z7V3YAOZTr3m1C24LiYvPehCq1CTIkhhmqtlVJXU7ISD48cx9y+5Pi34wtbTI/gN\n\ x4voyTLAfyavKMmIpxxIRsWldiF2n06HdvCRVdihDQUad10ygTmWf1J/s2ZETAtH\n\ QaSd7MD389t6nQFtTIXigsNKnnDPlrtxt7rOLvLQeR0K04Gzrf/scheOanRAfOXH\n\ KNBFU7YkDFG8rqizlC65rx9qeXFYXQcHZTuqxK7tgZnSgJat3E70VbTSCsEEG7eR\n\ bNX/fChUKAIIpWaiW6HDlKLl6m2y+BzM91umBsKOqTvntMVFBSF9pVYlXK854aIR\n\ q8A2Xujd012seQIDAQABo4GfMIGcMAsGA1UdDwQEAwICpDASBgNVHRMBAf8ECDAG\n\ AQH/AgEBMB0GA1UdDgQWBBRYdUPApWoxw4U13Rqsjf9AHdbpLDATBgNVHSUEDDAK\n\ BggrBgEFBQcDATAkBglghkgBhvhCAQ0EFxYVVGVzdCBsaWJtaWNyb2h0dHBkIENB\n\ MB8GA1UdIwQYMBaAFFh1Q8ClajHDhTXdGqyN/0Ad1uksMA0GCSqGSIb3DQEBCwUA\n\ A4ICAQBvrrcTKVeI1EYnXo4BQD4oCvf9z1fYQmL21EbHwgjg1nmaPkvStgWAc5p1\n\ kKwySrpEMKXfu68X76RccXZyWWIamEjz2OCWYZgjX6d6FpjhLphL8WxXDy5C9eay\n\ ixN7+URz2XQoi22wqR+tCPDhrIzcMPyMkx/6gRgcYeDnaFrkdSeSsKsID4plfcIj\n\ ISWJDvv+IAgrtsG1NVHnGwpAv0od3A8/4/fR6PPyewaU3aydvjZ7Au8O9DGDjlU9\n\ 9HdlOkkY6GVJ1pfGZib7cV7lhy0D2kj1g9xZh97YjpoUfppPl9r+6A8gDm0hXlAD\n\ TlzNYlwTb681ZEoSd9PiLEY8HETssHlays2dYXdcNwAEp69iIHz8q1Q98Be9LScl\n\ WEzgaOT9U7lpIw/MWbELoMsC+Ecs1cVWBIuiIq8aSG2kRr1x3S8yVXbAohAXif2s\n\ E6puieM/VJ25iaNhkbLmDkk58QVVmn9NZNv6ETxuSQMp9e0EwbVlj68vzClQ91Y/\n\ nmAiGcLFUEwB9G0szv9+vR+oDW4IkvdFZSUbcICd2cnynnwAD395onqS4hEZO1xM\n\ Gy5ZldbTMTjgn7fChNopz15ChPBnwFIjhm+S0CyiLRQAowfknRVq2IBkj7/5kOWg\n\ 4mcxcq76HoQWK/8X/8RFL1eFVAvY7TNHYJ0RS51DMuwCNQictA==\n\ -----END CERTIFICATE-----"; /* test server key */ static const char srv_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n\ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\ rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\ UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\ +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\ HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\ CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\ dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\ +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\ XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\ znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\ pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\ D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\ pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\ zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\ pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\ KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\ OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\ XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\ wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\ ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\ 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\ ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\ QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\ qdJNJ1DkyUc9dN2cliX4R+rG\n\ -----END PRIVATE KEY-----"; /* test server CA signed certificates */ static const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\ NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\ TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\ c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\ psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\ atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\ 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\ n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\ qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\ kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\ AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\ c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\ 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\ IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\ Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\ X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\ aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\ HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\ hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\ 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\ UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\ B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\ SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\ WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\ OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\ /w0gW9EVWzFhsFeGEssi\n\ -----END CERTIFICATE-----"; /* test server self signed certificates */ static const char srv_self_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n" "MIIDJzCCAg+gAwIBAgIUOKf6e6Heee2XA+yF5St3t+fVM40wDQYJKoZIhvcNAQEF\n" "BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTIyMTAxMDA4MzQ0N1oYDzIxMjIw\n" "OTE2MDgzNDQ3WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB\n" "AQUAA4IBDwAwggEKAoIBAQClivgF8Xq0ekQli++0l7Q5JFwJCuLf04Cb1UKIS80U\n" "CfphFd1ILJepNw4bWR3OV1sRI1vFiw6LnCz53vOwVNyiZ+sMGi4bDX4AV9Xd+F83\n" "xhG8AjOmKTayW0TxSIvt47Qd5S/4fgraxMtvqrRRBen30iKOwX7uNF/4dYb9vdin\n" "OldV/e8uzbqSurMGkNDznOeSaNBmdO/7x0VMFZM2hwmHyiiw75/j4BhUlLCcMEvK\n" "oN+YHNCNcTt3Qm1vVuiGXmh9QreOV09Gc1SzAltxF2gmI0jzw8r/duz18QXMNsMw\n" "El/Ah4+02gR70L7qlgttN1NPU3RJpK/L34J7yg649wHTAgMBAAGjbzBtMB0GA1Ud\n" "DgQWBBROVferD+YYcV1YEnFgC0jYm5X9BjAfBgNVHSMEGDAWgBROVferD+YYcV1Y\n" "EnFgC0jYm5X9BjAPBgNVHRMBAf8EBTADAQH/MBoGA1UdEQQTMBGCCWxvY2FsaG9z\n" "dIcEfwAAATANBgkqhkiG9w0BAQUFAAOCAQEAoRbozsm5xXdNX3VO++s2LMzw5KM9\n" "RpIInHNkMJbnyLJFKJ8DF7nTxSGCA38YMkX3tphPNKZXbg+V64Dqr/XpzOVyiinU\n" "7hIwyUdSSKKyErZxIWR97lY6Q3SOyPAg8ZElbtvSsSzmd772VE23VTXGDi7AW0PQ\n" "hag9N2EEnHURMvID15O+UXyFpDdyUyQIbx3HuswsGDH9xBTm4irLyrZwO0KwKg5a\n" "JBeUiPs0SYRRfn9/MoE6VwAnmOCg3LLR6ZPU3hQtTPLHj2Op1g5fey3X3X6lC+JC\n" "K6dNZc1zBFPz8KANGUsFYbmoP2bvAAA+6KwCnZZEflUgE7/HFEmQhVOezw==\n" "-----END CERTIFICATE-----\n"; /* test server key */ static const char srv_self_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n" "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQClivgF8Xq0ekQl\n" "i++0l7Q5JFwJCuLf04Cb1UKIS80UCfphFd1ILJepNw4bWR3OV1sRI1vFiw6LnCz5\n" "3vOwVNyiZ+sMGi4bDX4AV9Xd+F83xhG8AjOmKTayW0TxSIvt47Qd5S/4fgraxMtv\n" "qrRRBen30iKOwX7uNF/4dYb9vdinOldV/e8uzbqSurMGkNDznOeSaNBmdO/7x0VM\n" "FZM2hwmHyiiw75/j4BhUlLCcMEvKoN+YHNCNcTt3Qm1vVuiGXmh9QreOV09Gc1Sz\n" "AltxF2gmI0jzw8r/duz18QXMNsMwEl/Ah4+02gR70L7qlgttN1NPU3RJpK/L34J7\n" "yg649wHTAgMBAAECggEAERbbCtYGakoy7cNX8Ac3Kiz4OVC/4gZWAQBPeX2FwrtS\n" "9yHIMbK0x1mxIZ6eBpabBpZlW2vDCSOKuxLKiloAWt2qdJnhR5apesSWhe8leT7/\n" "xq5dgZpAlMH6SIRKObknd2yY+qicW0A0licDrVeUcypkueL8xP9wJtiPInOuQXkI\n" "QROhB13eStRuRKYwOn5gtwAHJ+J1DFKKiqpBOkrSYf4625StGegJO9+bjK0ei+0W\n" "tp6unpiwA/lXTgz6Xim1Z3fzWs4XjFgVKzK5s/6yBJjr8spHX6lv7QsahP4w6HZ/\n" "VcRxP6cJNd/otiTEtJXpbxiiyccwXm/AOcOn22P1cQKBgQDAnY/0G/ap/G98pneE\n" "suzNXhWOQ8JoL8d66Io8vwTvfiJggfgUcwblI7pPCrSlaZMR7/q6JImE53lZtPk8\n" "eI3c9lN0ocr8E7+huDpYdk7cMYj9SuxySsXoMLiMqzHFi+NcIhKMF56kk6a5CFCt\n" "yP1Ofy76LVweGE3XvTwpwE7wUQKBgQDcBLyH1cC71s0I0Gz28AyELV9hPhasjAKO\n" "12CVbeBVTPd+28uk/3o80wSrTksc6H5ehAA2aTvrb4OhwssWNL+D0fS8YK2cJ3V0\n" "FJxGAM266+vC4d/8jRTHJnc+6PP3ix5t6vAt+K2Y0fePtefLqf4ebgXx/ODAj3J2\n" "aZKBldjK4wKBgGIRFpTLk/eR/dUyEBHw4x3gdAsdtqJDCUYrlQ4+ly20Q55tLbiD\n" "pBQP77CEm9rH+MgeLcKODbIsBB3HRUojet7wTydHpMhY6a1V1ebqPVZgpgWIGwBJ\n" "z59bBusf0lRo15Y2Bslq0SurvSvh7um8NjO8D1fytj7gUumvgC0lq0sxAoGBAI1+\n" "kkx9IBTtIDER8XGhkTsT/uoHxwcyh5abVmbjIclZ1TUFX2L+Vft17ePJVy8BKfvY\n" "wlY7uShBMBNAteDTDXNV/CGFv0DUc4myk4nFjIkwng9XufeuN3WX/Eo+AF/rXSdt\n" "VwcJjYLhTWdjoe1tppqlQTeN3HCaEA+s92ZVGvXnAoGAMCXGS6WZl1e5wsHRq0Yy\n" "8Ef2Wrk620bBjKHolkTfvgfhlvxeZM1sv1ioZGsOeQ0z7O7wdJhvL0M/WAG+3yQj\n" "HSXp81T1vOICPwNYZf8xcvbLKmvj7rHFt6ZAZF2o4EK8ReZTRyA3DUpBCDY+s3FN\n" "GmBv0D7N3QP0CT3SzfQrPkc=\n" "-----END PRIVATE KEY-----\n"; #endif libmicrohttpd-1.0.10/src/testcurl/https/mhdhost2.key0000644000175000017500000000325014674632555016177 -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDLa/Vzf1FA+AYS qFiKyJBflANMkUKv3cH8oL3oCrFd9SrFgdBkccHJ6HbIdfld5j5zCLNr09vyQHlb K7khXukdhstd61RDsdrygJdxdkGKHMwaN1NACkG8oRLaui2SDEgCvMVGT8qc7cPa vzsTb98eqUeODRjx3nyLzjqbsZIWkfa4BiiCbZmGLaiMTg7+p9o7pxJN2NSENsyI ORCV/9+Sr2jdl4bMpd3MsLk94gn/sdsRwEnR7qXIAVthm2lMC1Dr+26oBlOze0wb lirdwBljvHi8YQJloBZkCWCy0GkJh3xv92Vdryq/Hgm4wXir7u9VuDAdWhewDOZk DFI3L52ZAgMBAAECggEBAIS8cXFoBpEqRmwuRXhp3ys+3dg8gRNY1JgQG1sqfwoc TEiMqHqicB1b/wZXVNycvOs7JjiaCc9NmuKO6UKJN/v4VQN354g0qfXLSwbSb3m7 yMLijwQerT50rGTlT48ZTHPc0a1Lq54y17YJSncobKMJOpPKoBhTYVmovD2T5Qus EDFg8wLBA79YZnrImbt9hcRsi/bM341V3aSoPFdHz6NTi+5WA08oTiGCv6gThV8T PUCiy1uDJZ1gk3xne+APZfdTutVtwCYVw7mhgTHiL5tL1KCjDjzK3XgnfAWaN+wG ex9EYbn/uAxN57UrvdyvGtuBo01vs/XtsVlpRpmlBnECgYEA+L8D8UY36IubeMAl xFCoFSXSmT+2YtA6ISg4/8a14wpwAskJPW/Nf8CzzwbGA7QaDVeK4rTGDOwNQJV8 /fiTaG6vDI7GS3UkvSKStfJzoMRBTzCYp/TbkG/jW2i8tR1AATlQlGllx0BQVXhC iYpR/WzbxGi5iyB4K6WPbSKboh8CgYEA0VqUR7w+2PEEFXyFRL2drpzkWKk5RiIa cIzQk3VlrHztJp0g6w8MiWCIpzL+7BuBy72byxJwpFmOz4HYsEqc6mOF4xXezfYh oN0P1+/aH4NrpWmjb65TGrtwrmi2sJrmATmr9WKFxEIpgrbotOTDF7pIx9pY2ScA aohOxqb7eUcCgYAHtHL80D3/GAPy05DX6d+q+Abz9ENEAEssp8BMO+16YOJjU7LT klj9MgzfxsfvaW69Jw8IQq03zUAD1h2PCFoYjAUkEHAX+kLvENkWhbILMskLGOhB m5YJfU2/kRj3SzamUw4p6rHaYCWc4CK/e+daQDr2dH/6zUCrqW8t5DqJ5QKBgF8E voIkhV3PXiwmXRJLAXNMEDPRcoZLWja1IsGaqe/0r2o0LMmjBeygHMXOVndxMKL5 RumPUAK4ByJVa7Tv2HJlg1IDDiHq0W6ChvtaCGT/L+9el+hLdbqPUmBGdIyJcVUj CNIRyma+JLsIK2xW29k8GmZiyqqckgrIHQD6ru5nAoGAAcdAHQojvGs5dQ2Agqcn EOgF1dic7VgCjAEG4CNCydzskE92jEOgv2DI+oBPoLrtktHbewFrsxBBNbS+PcHY DyV5/WXf8wwwdkG1VLyw+dPeWNGWanvjllplckDXSGz1ia0s7ENNAt8o2MXdlZrQ MMHn0wo/1rTa1YroHF8cKVA= -----END PRIVATE KEY----- libmicrohttpd-1.0.10/src/testcurl/https/tls_test_common.h0000644000175000017500000001561614760713577017330 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2017-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef TLS_TEST_COMMON_H_ #define TLS_TEST_COMMON_H_ #include "platform.h" #include "microhttpd.h" #include #include #include #include #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #define test_data "Hello World\n" #define ca_cert_file_name SRCDIR "/test-ca.crt" #define EMPTY_PAGE \ "Empty pageEmpty page" #define PAGE_NOT_FOUND \ "File not foundFile not found" #define MHD_E_MEM "Error: memory error\n" #define MHD_E_SERVER_INIT "Error: failed to start server\n" #define MHD_E_TEST_FILE_CREAT "Error: failed to setup test file\n" #define MHD_E_CERT_FILE_CREAT "Error: failed to setup test certificate\n" #define MHD_E_KEY_FILE_CREAT "Error: failed to setup test certificate\n" #define MHD_E_FAILED_TO_CONNECT \ "Error: server connection could not be established\n" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /* The local copy if GnuTLS IDs to avoid long #ifdefs list with various * GnuTLS versions */ /** * The list of know (at the moment of writing) GnuTLS IDs of TLS versions. * Can be safely casted to/from @a gnutls_protocol_t. */ enum know_gnutls_tls_id { KNOWN_BAD = 0, /**< No TLS */ KNOWN_TLS_SSLv3 = 1, /**< GNUTLS_SSL3 */ KNOWN_TLS_V1_0 = 2, /**< GNUTLS_TLS1_0 */ KNOWN_TLS_V1_1 = 3, /**< GNUTLS_TLS1_1 */ KNOWN_TLS_V1_2 = 4, /**< GNUTLS_TLS1_2 */ KNOWN_TLS_V1_3 = 5, /**< GNUTLS_TLS1_3 */ KNOWN_TLS_MIN = KNOWN_TLS_SSLv3, /**< Minimum valid value */ KNOWN_TLS_MAX = KNOWN_TLS_V1_3 /**< Maximum valid value */ }; #define KNOW_TLS_IDS_COUNT 6 /* KNOWN_TLS_MAX + 1 */ /** * Map @a know_gnutls_tls_ids values to printable names. */ extern const char *tls_names[KNOW_TLS_IDS_COUNT]; /** * Map @a know_gnutls_tls_ids values to GnuTLS priorities strings. */ extern const char *priorities_map[KNOW_TLS_IDS_COUNT]; /** * Map @a know_gnutls_tls_ids values to GnuTLS priorities append strings. */ extern const char *priorities_append_map[KNOW_TLS_IDS_COUNT]; /** * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value. */ extern const long libcurl_tls_vers_map[KNOW_TLS_IDS_COUNT]; #if CURL_AT_LEAST_VERSION (7,54,0) /** * Map @a know_gnutls_tls_ids values to libcurl @a CURLOPT_SSLVERSION value * for maximum supported TLS version. */ extern const long libcurl_tls_max_vers_map[KNOW_TLS_IDS_COUNT]; #endif /* CURL_AT_LEAST_VERSION(7,54,0) */ struct https_test_data { void *cls; uint16_t port; const char *cipher_suite; int proto_version; }; struct CBC { char *buf; size_t pos; size_t size; }; int curl_tls_is_gnutls (void); int curl_tls_is_openssl (void); int curl_tls_is_nss (void); int curl_tls_is_schannel (void); int curl_tls_is_sectransport (void); enum test_get_result { TEST_GET_OK = 0, TEST_GET_ERROR = 1, TEST_GET_MHD_ERROR = 16, TEST_GET_TRANSFER_ERROR = 17, TEST_GET_CURL_GEN_ERROR = 32, TEST_GET_CURL_CA_ERROR = 33, TEST_GET_CURL_NOT_IMPLT = 34, TEST_GET_HARD_ERROR = 999 }; /** * perform cURL request for file */ enum test_get_result test_daemon_get (void *cls, const char *cipher_suite, int proto_version, uint16_t port, int ver_peer); void print_test_result (unsigned int test_outcome, const char *test_name); size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx); enum MHD_Result http_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *upload_data, const char *version, size_t *upload_data_size, void **req_cls); enum MHD_Result http_dummy_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *upload_data, const char *version, size_t *upload_data_size, void **req_cls); /** * compile test URI * * @param[out] uri - char buffer into which the url is compiled * @param uri_len number of bytes available in @a url * @param port port to use for the test * @return 1 on error */ unsigned int gen_test_uri (char *uri, size_t uri_len, uint16_t port); CURLcode send_curl_req (char *url, struct CBC *cbc, const char *cipher_suite, int proto_version); unsigned int test_https_transfer (void *cls, uint16_t port, const char *cipher_suite, int proto_version); unsigned int setup_session (gnutls_session_t *session, gnutls_certificate_credentials_t *xcred); unsigned int teardown_session (gnutls_session_t session, gnutls_certificate_credentials_t xcred); unsigned int test_wrap (const char *test_name, unsigned int (*test_function)(void *cls, uint16_t port, const char *cipher_suite, int proto_version), void *cls, uint16_t port, unsigned int daemon_flags, const char *cipher_suite, int proto_version, ...); int testsuite_curl_global_init (void); /** * Check whether program name contains specific @a marker string. * Only last component in pathname is checked for marker presence, * all leading directories names (if any) are ignored. Directories * separators are handled correctly on both non-W32 and W32 * platforms. * @param prog_name program name, may include path * @param marker marker to look for. * @return zero if any parameter is NULL or empty string or * @a prog_name ends with slash or @a marker is not found in * program name, non-zero if @a maker is found in program * name. */ int has_in_name (const char *prog_name, const char *marker); #endif /* TLS_TEST_COMMON_H_ */ libmicrohttpd-1.0.10/src/testcurl/https/test-ca.key0000644000175000017500000000625714674632555016021 -----BEGIN RSA PRIVATE KEY----- MIIJKgIBAAKCAgEA3WlrqQOKmYwgTZCaCTpucZwmos5d+mS1MKeMQS/2H1z1hNy5 JgERIlSP2JwG/JehuwiZ8/HU7DiVpDVxuk9SlT+f9kbwSCGmmrn0SAJe4RJ49Y/R NoUJVdn8RdmTYc/p6otC6ileCyUqXJZFwA39hQPR7FUT/we82Ifgz9H0lPFem7Lv FwnkRrIa6AD63PKx/JRRBF6TSzSKkK/MisekpnQeoX42uukkNPvqgYZdGibZ+Cx1 maIYIwZpCGhhT2CCS4MUP8cqdhq89qu5RiifswZARfIjj7d8fhdYUggZ6/wxmFpo xJubWJvu6crq4j3XV3QnPPqmti8TGaNxF8S6OWCEqTwssGe1d2ADmU695tQtuC4m Lz3oQqtQkyJIYZqrZVSV1OyEg+PHMfcvuT4t+MLW0yP4DceL6MkywH8mryjJiKcc SEbFpXYhdp9Oh3bwkVXYoQ0FGnddMoE5ln9Sf7NmREwLR0GknezA9/Pbep0BbUyF 4oLDSp5wz5a7cbe6zi7y0HkdCtOBs63/7HIXjmp0QHzlxyjQRVO2JAxRvK6os5Qu ua8fanlxWF0HB2U7qsSu7YGZ0oCWrdxO9FW00grBBBu3kWzV/3woVCgCCKVmoluh w5Si5eptsvgczPdbpgbCjqk757TFRQUhfaVWJVyvOeGiEavANl7o3dNdrHkCAwEA AQKCAgEA2nPJ4j75P9gOgxj5scMx9uve/uDnvkYgszmMW0DL8FPSdd0k3AdPdXTD XC9NgWjGDHhHFXXz44FMu3BzniPnUhQtalrBdhmlfKGeEHIuVJjaOUZFYCpQdKEX k39BN89gdqYiRlC8Vfi8XA90EDJ9gQCs3SVwDj7/JxChUcpQK6gd9TbNSQjcbpgJ jgBxgw/9Zjyb1tjNMPVNBcY95Gtn20dUdXfG3hFrRM+Mp3D/aO8OPhr3iLZyZBRO CxqZcCzDQWe50dda4J4u9J2ntj4cmxC+14Q5a/HYZbv4yy7tDHWOJUiGd/0jf4CS b59isgfb8JBMqpCPbc7yZGhrC81xAZdsw0jvDYgGUf86785983clipdCVJIKMqZm yjoo2DuSaivCGnaWUV1f+W2CgigpSXcDQ1/gDMt7xVoZNpfmdTgZzthUxXK3dFYO Jwem/ls6KD5THKpkHuA9BpnoksnpZqREK5FdMw8hCUpJEe1kXy4ZlQB91Ya74HQ0 tgygL9BwEXDJ2vU14Onq8CH+Ul4kOzXnqMae35eKj1+/QI2PP1Wuk/vypSmrurfm 3YLsnwm7OYSuWrAfFRmGTMhfny3v1xlw1ynmVBvxgQ2v2czxKGw8JG+9LoqbSB5O GP05Gpcys1CwR9Z2EjfExFNcWFIJQjwcZemlgHHwvHCBy1fz0AUCggEBAPSnznDv Wuj3gTkUDfNFTplsa8z3GIyrfBYDUyGJ51YiN5C2myGRcu60r5iMl4hxXC6mL4Cd 5ew8LsXojPmC0sWZ2Cp+uhSH5FZaMNRumg4R8EA0Phwi0iBgDXM5318reMZF3BUr FSTn9a3nBkFpYMw1hxBlLj0o6S0TfZBmviTJUO7eiq6mAdO43l320Pw7E6xSWble QQaXzk2yGr2bV02heZcWfw+Fnui6xLruWZbVdvh+Q5KEJv90y9HcXm14LXiPRMBg zYvbW6tVZSQeXTs4wGC1RAZWZC7MG0XOoVj18WGx8hSZQND6awxFwHbItSlv05TX QkJ9ybZ7bcOQT78CggEBAOetsug2BQejAwRbbAsC078Vlr6PUspHmeT1Efp8ArFq rsmx2n2EoIcZSLkedZK1cXN7HMxVz1U0yx7k/OLIKlsfGNQdAQhCW875mbn0ET0c jUNpeJRXL6U5pwdPrsENyyAPsDyCsBT4ArGuEIFIxPlWtZTBzOAhJN9AwB5KW8g/ zg1mwv1TCNNlQu3Ex46egI3cCUk+6b1BNwPuSKhuP+P22Vg+JBhIY+/iSJvgSRfP 3LCNU0ds2D5xiwJNVwzVtrn3wIaYHj6S7lhfVGWdvQb8RsF9kyR06yJNTUyyybZ0 pTHeRwNtbUoTeBUlwoBac6izNyGGguA42pDYmoAcEccCggEAfXgZrV1zWAqmoOki BmLC3nf2CRWn52yCpJ9r4MVieI/vwy2C/YIkWTsc2rUveW/5gIsFzYYsxixPKHwM 4GExStmNPK3lLGZMueRjKm7WXuTgO20PdUp+TNA11aQWZC5dMAHfzpNbsqOrIVZb pOwwEkpZTBU303HJs65NNOMcHK2J7hb/NHY6daRXlgTgRJrfif5puWEXJBRyXvI6 OIcUDOIFA3EsFH/IcT5nah6Wn342F1ZZvSg8/8GcTbIgUy/Q0gVXkvmSMGl8569R wWY5FggS0QXlLwLbOgy+59wCbycidaHWrq2xyfrDL3YOMFzaW7fX4HtMpeDws781 GZhG7QKCAQEAhCfJTjzCUcDjD7E2yHEsaGvgOYN4Lnr5hmllgAUNZDb+zX7uq3rk NyxtF2wQlUd7F+y6WLT6OBiNZWop9xNHVgM/HoAM/rEbvc0Tq8dVrg6DZljbt4Kk YxOn+7uwa996ZyeL2HiUCOIQZ1prf9QKyFB19A042QEPD2rYLG8uO+RpnatovyiG eE/jBc6iJvCzVDiX83g3zQVOZKegOrPpLhi5kmSgIlno6AWkdYZTK4oe0XdMcgnc sIIEUaPcbC3ctehlomFTn04hN7fpZK2+DiYKFoWTUdB/8Gk4FvBFsBaJxRCOYZ4i IYdJkIahlKYEI89XO4CHV3AW/VkRiNJ6MQKCAQEAhosdYqtpJtdRJ3FWM4i6Miua OBEg7FU4JTH/0cekj0UMYFww3KK9c4KEdgVwRtsvLTZ++CXZ3XF9Er+6nPmC6nAo 46b3Ow7rPzpm18jUNWMW0s+CZwKWkGe1sbek81L8SBCDRJKKhl6XgiPHGB/i8g65 ZQv3B47BPflrjxJCQVADHpdW5vo0xY7xRr9zKYoAl4LQBTwLVMTP229iIcBFvRPp rs4KUecFQfEyXrJLwgQTl0uBItO86BWopCdh7T/0A7BjBk9jdklJNgml8Ctq+Yt9 nqduIeW3c1aNqbNhn+IA27WW+tv+yzA4gNPS/OWr8J67HDGm4WSUAFGMLwmcSw== -----END RSA PRIVATE KEY----- libmicrohttpd-1.0.10/src/testcurl/https/Makefile.am0000644000175000017500000000661215035214301015747 # This Makefile.am is in the public domain EMPTY_ITEM = SUBDIRS = . @HEAVY_TESTS_NOTPARALLEL@ AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ -DSRCDIR=\"$(srcdir)\" \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) if USE_COVERAGE AM_CFLAGS += --coverage endif $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(MHD_TLS_LIB_LDFLAGS) $(MHD_TLS_LIBDEPS) @LIBGCRYPT_LIBS@ @LIBCURL@ if HAVE_GNUTLS_SNI TEST_HTTPS_SNI = test_https_sni endif if !HAVE_GNUTLS_MTHREAD_BROKEN HTTPS_PARALLEL_TESTS = \ test_https_time_out \ test_https_get_parallel \ test_https_get_parallel_threads endif THREAD_ONLY_TESTS = \ test_tls_options \ test_tls_authentication \ $(HTTPS_PARALLEL_TESTS) \ $(TEST_HTTPS_SNI) \ test_https_session_info \ test_https_session_info_append \ test_https_multi_daemon \ test_https_get \ test_empty_response \ test_https_get_iovec \ $(EMPTY_ITEM) check_PROGRAMS = \ test_https_get_select if USE_THREADS check_PROGRAMS += \ $(THREAD_ONLY_TESTS) endif EXTRA_DIST = \ test-ca.crt test-ca.key \ mhdhost1.crt mhdhost1.key \ mhdhost2.crt mhdhost2.key TESTS = \ $(check_PROGRAMS) test_https_time_out_SOURCES = \ test_https_time_out.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_tls_options_SOURCES = \ test_tls_options.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_SOURCES = \ test_https_get_parallel.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_https_get_parallel_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_empty_response_SOURCES = \ test_empty_response.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_threads_SOURCES = \ test_https_get_parallel_threads.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_parallel_threads_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_https_get_parallel_threads_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_tls_authentication_SOURCES = \ test_tls_authentication.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_session_info_SOURCES = \ test_https_session_info.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_session_info_append_SOURCES = $(test_https_session_info_SOURCES) test_https_multi_daemon_SOURCES = \ test_https_multi_daemon.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_SOURCES = \ test_https_get.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_iovec_SOURCES = \ test_https_get_iovec.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_sni_SOURCES = \ test_https_sni.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c test_https_get_select_SOURCES = \ test_https_get_select.c \ tls_test_keys.h \ tls_test_common.h \ tls_test_common.c libmicrohttpd-1.0.10/src/testcurl/https/test_https_session_info.c0000664000175000017500000002576615232103064021055 /* This file is part of libmicrohttpd Copyright (C) 2007, 2016 Christian Grothoff Copyright (C) 2016-2021 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_https_session_info.c * @brief Testcase for libmicrohttpd HTTPS connection querying operations * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include "tls_test_common.h" #include "tls_test_keys.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static int test_append_prio; /* * HTTP access handler call back * used to query negotiated security parameters */ static enum MHD_Result query_info_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; const union MHD_ConnectionInfo *conn_info; enum know_gnutls_tls_id *used_tls_ver; (void) url; (void) method; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ used_tls_ver = (enum know_gnutls_tls_id *) cls; if (NULL == *req_cls) { *req_cls = (void *) &query_info_ahc; return MHD_YES; } conn_info = MHD_get_connection_info (connection, MHD_CONNECTION_INFO_PROTOCOL); if (NULL == conn_info) { fflush (stderr); fflush (stdout); fprintf (stderr, "MHD_get_connection_info() failed.\n"); fflush (stderr); return MHD_NO; } if (0 == (unsigned int) conn_info->protocol) { fflush (stderr); fflush (stdout); fprintf (stderr, "MHD_get_connection_info()->protocol has " "wrong zero value.\n"); fflush (stderr); return MHD_NO; } *used_tls_ver = (enum know_gnutls_tls_id) conn_info->protocol; response = MHD_create_response_from_buffer_static (strlen (EMPTY_PAGE), EMPTY_PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * negotiate a secure connection with server & query negotiated security parameters */ static unsigned int test_query_session (enum know_gnutls_tls_id tls_ver, uint16_t *pport) { CURL *c; struct CBC cbc; CURLcode errornum; char url[256]; enum know_gnutls_tls_id found_tls_ver; struct MHD_Daemon *d; if (NULL == (cbc.buf = malloc (sizeof (char) * 255))) return 99; cbc.size = 255; cbc.pos = 0; /* setup test */ found_tls_ver = KNOWN_BAD; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &query_info_ahc, &found_tls_ver, test_append_prio ? MHD_OPTION_HTTPS_PRIORITIES_APPEND : MHD_OPTION_HTTPS_PRIORITIES, test_append_prio ? priorities_append_map[tls_ver] : priorities_map[tls_ver], MHD_OPTION_HTTPS_MEM_KEY, srv_self_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem, MHD_OPTION_END); if (d == NULL) { free (cbc.buf); fprintf (stderr, "MHD_start_daemon() with %s failed.\n", tls_names[tls_ver]); fflush (stderr); return 77; } if (0 == *pport) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); free (cbc.buf); fprintf (stderr, "MHD_get_daemon_info() failed.\n"); fflush (stderr); return 10; } *pport = dinfo->port; /* Use the same port for rest of the checks */ } gen_test_uri (url, sizeof (url), *pport); c = curl_easy_init (); fflush (stderr); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); fflush (stderr); MHD_stop_daemon (d); free (cbc.buf); return 99; } #ifdef _DEBUG curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); #endif if ((CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_URL, url))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_TIMEOUT, 10L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 10L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc))) || /* TLS options */ /* currently skip any peer authentication */ (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYPEER, 0L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_SSL_VERIFYHOST, 0L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L))) || (CURLE_OK != (errornum = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)))) { curl_easy_cleanup (c); free (cbc.buf); MHD_stop_daemon (d); fflush (stderr); fflush (stdout); fprintf (stderr, "Error setting libcurl option: %s.\n", curl_easy_strerror (errornum)); fflush (stderr); return 99; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { unsigned int ret; curl_easy_cleanup (c); free (cbc.buf); MHD_stop_daemon (d); fflush (stderr); fflush (stdout); if ((CURLE_SSL_CONNECT_ERROR == errornum) || (CURLE_SSL_CIPHER == errornum)) { ret = 77; fprintf (stderr, "libcurl request failed due to TLS error: '%s'\n", curl_easy_strerror (errornum)); } else { ret = 1; fprintf (stderr, "curl_easy_perform failed: '%s'\n", curl_easy_strerror (errornum)); } fflush (stderr); return ret; } curl_easy_cleanup (c); free (cbc.buf); MHD_stop_daemon (d); if (tls_ver != found_tls_ver) { fflush (stderr); fflush (stdout); fprintf (stderr, "MHD_get_connection_info (conn, " "MHD_CONNECTION_INFO_PROTOCOL) returned unexpected " "protocol version.\n" "\tReturned: %s (%u)\tExpected: %s (%u)\n", ((unsigned int) found_tls_ver) > KNOWN_TLS_MAX ? "[wrong value]" : tls_names[found_tls_ver], (unsigned int) found_tls_ver, tls_names[tls_ver], (unsigned int) tls_ver); fflush (stderr); return 2; } return 0; } static unsigned int test_all_supported_versions (void) { enum know_gnutls_tls_id ver_for_test; /**< TLS version used for test */ const gnutls_protocol_t *vers_list; /**< The list of GnuTLS supported TLS versions */ uint16_t port; unsigned int num_success; /**< Number of tests succeeded */ unsigned int num_failed; /**< Number of tests failed */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; /* Use system automatic assignment */ else port = 3060; /* Use predefined port, may break parallel testing of another MHD build */ vers_list = gnutls_protocol_list (); if (NULL == vers_list) { fprintf (stderr, "Error getting GnuTLS supported TLS versions"); return 99; } num_success = 0; num_failed = 0; for (ver_for_test = KNOWN_TLS_MIN; KNOWN_TLS_MAX >= ver_for_test; ++ver_for_test) { const gnutls_protocol_t *ver_ptr; /**< The pointer to the position on the @a vers_list */ unsigned int res; for (ver_ptr = vers_list; 0 != *ver_ptr; ++ver_ptr) { if (ver_for_test == (enum know_gnutls_tls_id) *ver_ptr) break; } if (0 == *ver_ptr) { printf ("%s is not supported by GnuTLS, skipping.\n\n", tls_names[ver_for_test]); fflush (stdout); continue; } printf ("Starting check for %s...\n", tls_names[ver_for_test]); fflush (stdout); res = test_query_session (ver_for_test, &port); fflush (stderr); fflush (stdout); if (99 == res) { fprintf (stderr, "Hard error. Test stopped.\n"); fflush (stderr); return 99; } else if (77 == res) { printf ("%s does not work with libcurl client and GnuTLS " "server combination, skipping.\n", tls_names[ver_for_test]); fflush (stdout); } else if (0 != res) { fprintf (stderr, "Check failed for %s.\n", tls_names[ver_for_test]); fflush (stderr); num_failed++; } else { printf ("Check succeeded for %s.\n", tls_names[ver_for_test]); fflush (stdout); num_success++; } printf ("\n"); fflush (stdout); } if (0 == num_failed) { if (0 == num_success) { fprintf (stderr, "No supported TLS version was found.\n"); fflush (stderr); return 77; } return 0; } return num_failed; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; const char *ssl_version; (void) argc; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ test_append_prio = has_in_name (argv[0], "_append"); if (! testsuite_curl_global_init ()) return 99; ssl_version = curl_version_info (CURLVERSION_NOW)->ssl_version; if (NULL == ssl_version) { fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); curl_global_cleanup (); return 77; } errorCount = test_all_supported_versions (); fflush (stderr); fflush (stdout); curl_global_cleanup (); if (77 == errorCount) return 77; else if (99 == errorCount) return 99; print_test_result (errorCount, argv[0]); return errorCount != 0 ? 1 : 0; } libmicrohttpd-1.0.10/src/testcurl/test_get_wait.c0000664000175000017500000001517615232103064015570 /* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get_wait.c * @brief Test 'MHD_run_wait()' function. * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif /** * How many rounds of operations do we do for each * test. * Check all three types of requests for HTTP/1.1: * * first request, new connection; * * "middle" request, existing connection with stay-alive; * * final request, no data processed after. */ #define ROUNDS 3 /** * Do we use HTTP 1.1? */ static int oneone; /** * Response to return (re-used). */ static struct MHD_Response *response; /** * Set to 1 if the worker threads are done. */ static volatile int signal_done; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; (void) ctx; /* Unused. Silent compiler warning. */ return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (ret == MHD_NO) abort (); return ret; } static void * thread_gets (void *param) { CURL *c; CURLcode errornum; unsigned int i; char url[64]; uint16_t port = (uint16_t) (intptr_t) param; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); c = curl_easy_init (); if (NULL == c) _exit (99); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 15L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 15L); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); for (i = 0; i < ROUNDS; i++) { if (CURLE_OK != (errornum = curl_easy_perform (c))) { signal_done = 1; fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); abort (); } } curl_easy_cleanup (c); signal_done = 1; return NULL; } static unsigned int testRunWaitGet (uint16_t port, uint32_t poll_flag) { pthread_t get_tid; struct MHD_Daemon *d; const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ? "MHD_USE_AUTO" : (poll_flag & MHD_USE_POLL) ? "MHD_USE_POLL" : (poll_flag & MHD_USE_EPOLL) ? "MHD_USE_EPOLL" : "select()"); if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; printf ("Starting MHD_run_wait() test with MHD in %s polling mode.\n", test_desc); signal_done = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) abort (); if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) abort (); port = dinfo->port; } if (0 != pthread_create (&get_tid, NULL, &thread_gets, (void *) (intptr_t) port)) _exit (99); /* As another thread sets "done" flag after ending of network * activity, it's required to set positive timeout value for MHD_run_wait(). * Alternatively, to use timeout value "-1" here, another thread should start * additional connection to wake MHD after setting "done" flag. */ do { if (MHD_NO == MHD_run_wait (d, 50)) abort (); } while (0 == signal_done); if (0 != pthread_join (get_tid, NULL)) _exit (99); MHD_stop_daemon (d); printf ("Test succeeded.\n"); return 0; } int main (int argc, char *const *argv) { uint16_t port = 1675; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (oneone) port += 5; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; response = MHD_create_response_from_buffer_static (strlen ("/hello_world"), "/hello_world"); testRunWaitGet (port++, 0); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) testRunWaitGet (port++, MHD_USE_EPOLL); testRunWaitGet (port++, MHD_USE_AUTO); MHD_destroy_response (response); curl_global_cleanup (); return 0; /* Errors produce abort() or _exit() */ } libmicrohttpd-1.0.10/src/testcurl/test_digestauth_with_arguments.c0000664000175000017500000002277115232103064021245 /* This file is part of libmicrohttpd Copyright (C) 2010, 2012 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_digestauth_with_arguments.c * @brief Testcase for libmicrohttpd Digest Auth with arguments * @author Amr Ali * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ #ifndef WINDOWS #include #include #else #include #endif #define PAGE \ "libmicrohttpd demoAccess granted" #define DENIED \ "libmicrohttpd demoAccess denied" #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; char *username; const char *password = "testpass"; const char *realm = "test@example.com"; enum MHD_Result ret; int ret_i; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } username = MHD_digest_auth_get_username (connection); if ( (username == NULL) || (0 != strcmp (username, "testuser")) ) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, MHD_NO, MHD_DIGEST_ALG_MD5); MHD_destroy_response (response); return ret; } ret_i = MHD_digest_auth_check2 (connection, realm, username, password, 300, MHD_DIGEST_ALG_MD5); MHD_free (username); if (ret_i != MHD_YES) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) fprintf (stderr, "MHD_create_response_from_buffer() failed.\n"); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, (MHD_INVALID_NONCE == ret_i) ? MHD_YES : MHD_NO, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) fprintf (stderr, "MHD_queue_auth_fail_response2() failed.\n"); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testDigestAuth (void) { CURL *c; CURLcode errornum; struct MHD_Daemon *d; struct CBC cbc; char buf[2048]; char rnd[8]; uint16_t port; char url[128]; #ifndef WINDOWS int fd; size_t len; size_t off = 0; #endif /* ! WINDOWS */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1160; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; #ifndef WINDOWS fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) { fprintf (stderr, "Failed to open `%s': %s\n", "/dev/urandom", strerror (errno)); return 1; } while (off < 8) { len = (size_t) read (fd, rnd + off, 8 - off); if (len == (size_t) -1) { fprintf (stderr, "Failed to read `%s': %s\n", "/dev/urandom", strerror (errno)); (void) close (fd); return 1; } off += len; } (void) close (fd); #else { HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (b == 0) { fprintf (stderr, "Failed to acquire crypto provider context: %lu\n", GetLastError ()); return 1; } b = CryptGenRandom (cc, 8, (BYTE *) rnd); if (b == 0) { fprintf (stderr, "Failed to generate 8 random bytes: %lu\n", GetLastError ()); } CryptReleaseContext (cc, 0); if (b == 0) return 1; } #endif d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC, (uint32_t) 999, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/bar%%20foo?" "key=value&more=even%%20more&empty&=no_key&&same=one&&same=two", (unsigned int) port); c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass"); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (PAGE)) return 4; if (0 != strncmp (PAGE, cbc.buf, strlen (PAGE))) return 8; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #if (LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR == 62) if (1) { fprintf (stderr, "libcurl version 7.62.x has bug in processing" "URI with GET arguments for Digest Auth.\n"); fprintf (stderr, "This test cannot be performed.\n"); exit (77); } #endif /* libcurl version 7.62.x */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT #ifdef HAVE_GCRYPT_H gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testDigestAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_quiesce_stream.c0000664000175000017500000001540115232103064016765 /* This file is part of libmicrohttpd Copyright (C) 2016 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_quiesce_stream.c * @brief Testcase for libmicrohttpd quiescing * @author Markus Doppelbauer * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifdef HAVE_UNISTD_H #include #elif defined(_WIN32) #include #define sleep(s) (Sleep ((s) * 1000), 0) #endif /* _WIN32 */ static volatile unsigned int request_counter; _MHD_NORETURN static void http_PanicCallback (void *cls, const char *file, unsigned int line, const char *reason) { (void) cls; /* Unused. Silent compiler warning. */ fprintf (stderr, "PANIC: exit process: %s at %s:%u\n", reason, file, line); exit (EXIT_FAILURE); } static void * resume_connection (void *arg) { struct MHD_Connection *connection = arg; /* fprintf (stderr, "Calling resume\n"); */ MHD_resume_connection (connection); return NULL; } static void suspend_connection (struct MHD_Connection *connection) { pthread_t thread_id; int status; /* fprintf (stderr, "Calling suspend\n"); */ MHD_suspend_connection (connection); status = pthread_create (&thread_id, NULL, &resume_connection, connection); if (0 != status) { fprintf (stderr, "Could not create thead\n"); exit (EXIT_FAILURE); } pthread_detach (thread_id); } struct ContentReaderUserdata { size_t bytes_written; struct MHD_Connection *connection; }; static ssize_t http_ContentReaderCallback (void *cls, uint64_t pos, char *buf, size_t max) { static const char alphabet[] = "\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; struct ContentReaderUserdata *userdata = cls; (void) pos; (void) max; /* Unused. Silent compiler warning. */ if (userdata->bytes_written >= 1024) { fprintf (stderr, "finish: %u\n", request_counter); return MHD_CONTENT_READER_END_OF_STREAM; } userdata->bytes_written++; buf[0] = alphabet[userdata->bytes_written % (sizeof(alphabet) - 1)]; suspend_connection (userdata->connection); return 1; } static void free_crc_data (void *crc_data) { struct ContentReaderUserdata *userdata = crc_data; free (userdata); } static enum MHD_Result http_AccessHandlerCallback (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { enum MHD_Result ret; struct MHD_Response *response; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ /* Never respond on first call */ if (NULL == *req_cls) { struct ContentReaderUserdata *userdata; fprintf (stderr, "start: %u\n", ++request_counter); userdata = malloc (sizeof(struct ContentReaderUserdata)); if (NULL == userdata) return MHD_NO; userdata->bytes_written = 0; userdata->connection = connection; *req_cls = userdata; return MHD_YES; } /* Second call: create response */ response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 32 * 1024, &http_ContentReaderCallback, *req_cls, &free_crc_data); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); suspend_connection (connection); return ret; } int main (void) { uint16_t port; char command_line[1024]; /* Flags */ unsigned int daemon_flags = MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_AUTO | MHD_ALLOW_SUSPEND_RESUME | MHD_USE_ITC; struct MHD_Daemon *daemon; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1470; /* Panic callback */ MHD_set_panic_func (&http_PanicCallback, NULL); /* Create daemon */ daemon = MHD_start_daemon (daemon_flags, port, NULL, NULL, &http_AccessHandlerCallback, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (daemon); return 32; } port = dinfo->port; } snprintf (command_line, sizeof (command_line), "curl -s http://127.0.0.1:%u", (unsigned int) port); if (0 != system (command_line)) { MHD_stop_daemon (daemon); return 1; } /* wait for a request */ while (0 == request_counter) (void) sleep (1); fprintf (stderr, "quiesce\n"); MHD_quiesce_daemon (daemon); /* wait a second */ (void) sleep (1); fprintf (stderr, "stopping daemon\n"); MHD_stop_daemon (daemon); return 0; } libmicrohttpd-1.0.10/src/testcurl/test_post.c0000664000175000017500000005630215232103064014746 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_post.c * @brief Testcase for libmicrohttpd POST operations using URL-encoding * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #endif #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define POST_DATA "name=daniel&project=curl" static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static void completed_cb (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct MHD_PostProcessor *pp = *req_cls; (void) cls; (void) connection; (void) toe; /* Unused. Silent compiler warning. */ if (NULL != pp) MHD_destroy_post_processor (pp); *req_cls = NULL; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } /** * Note that this post_iterator is not perfect * in that it fails to support incremental processing. * (to be fixed in the future) */ static enum MHD_Result post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *value, uint64_t off, size_t size) { int *eok = cls; (void) kind; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; (void) off; /* Unused. Silent compiler warning. */ if ((0 == strcmp (key, "name")) && (size == strlen ("daniel")) && (0 == strncmp (value, "daniel", size))) (*eok) |= 1; if ((0 == strcmp (key, "project")) && (size == strlen ("curl")) && (0 == strncmp (value, "curl", size))) (*eok) |= 2; return MHD_YES; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int eok; struct MHD_Response *response; struct MHD_PostProcessor *pp; enum MHD_Result ret; (void) cls; (void) version; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_POST, method)) { fprintf (stderr, "METHOD: %s\n", method); return MHD_NO; /* unexpected method */ } pp = *req_cls; if (pp == NULL) { eok = 0; pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok); *req_cls = pp; } MHD_post_process (pp, upload_data, *upload_data_size); if ((eok == 3) && (0 == *upload_data_size)) { response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); MHD_destroy_post_processor (pp); *req_cls = NULL; return ret; } *upload_data_size = 0; return MHD_YES; } static unsigned int testInternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1370; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1371; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1372; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1373; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_DATA); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, strlen (POST_DATA)); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } static enum MHD_Result ahc_cancel (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp ("POST", method)) { fprintf (stderr, "Unexpected method `%s'\n", method); return MHD_NO; } if (*req_cls == NULL) { static int marker = 1; *req_cls = ▮ /* We don't want the body. Send a 500. */ response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, 500, response); if (ret != MHD_YES) fprintf (stderr, "Failed to queue response\n"); MHD_destroy_response (response); return ret; } else { fprintf (stderr, "In ahc_cancel again. This should not happen.\n"); return MHD_NO; } } struct CRBC { const char *buffer; size_t size; size_t pos; }; static size_t readBuffer (void *p, size_t size, size_t nmemb, void *opaque) { struct CRBC *data = opaque; size_t required = size * nmemb; size_t left = data->size - data->pos; if (required > left) required = left; memcpy (p, data->buffer + data->pos, required); data->pos += required; return required / size; } static size_t slowReadBuffer (void *p, size_t size, size_t nmemb, void *opaque) { (void) sleep (1); return readBuffer (p, size, nmemb, opaque); } #define FLAG_EXPECT_CONTINUE 1 #define FLAG_CHUNKED 2 #define FLAG_FORM_DATA 4 #define FLAG_SLOW_READ 8 #define FLAG_COUNT 16 static unsigned int testMultithreadedPostCancelPart (int flags) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; struct curl_slist *headers = NULL; long response_code; CURLcode cc; unsigned int result = 0; struct CRBC crbc; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1374; if (oneone) port += 10; } /* Don't test features that aren't available with HTTP/1.0 in * HTTP/1.0 mode. */ if (! oneone && (flags & (FLAG_EXPECT_CONTINUE | FLAG_CHUNKED))) return 0; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_cancel, NULL, MHD_OPTION_END); if (d == NULL) return 32768; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } crbc.buffer = "Test content"; crbc.size = strlen (crbc.buffer); crbc.pos = 0; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, (flags & FLAG_SLOW_READ) ? &slowReadBuffer : &readBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &crbc); curl_easy_setopt (c, CURLOPT_POSTFIELDS, NULL); curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, crbc.size); curl_easy_setopt (c, CURLOPT_POST, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (flags & FLAG_CHUNKED) headers = curl_slist_append (headers, "Transfer-Encoding: chunked"); if (! (flags & FLAG_FORM_DATA)) headers = curl_slist_append (headers, "Content-Type: application/octet-stream"); if (flags & FLAG_EXPECT_CONTINUE) headers = curl_slist_append (headers, "Expect: 100-Continue"); curl_easy_setopt (c, CURLOPT_HTTPHEADER, headers); if (CURLE_HTTP_RETURNED_ERROR != (errornum = curl_easy_perform (c))) { #ifdef _WIN32 curl_version_info_data *curlverd = curl_version_info (CURLVERSION_NOW); if ((0 != (flags & FLAG_SLOW_READ)) && (CURLE_RECV_ERROR == errornum) && ((curlverd == NULL) || (curlverd->ares_num < 0x073100) ) ) { /* libcurl up to version 7.49.0 didn't have workaround for WinSock bug */ fprintf (stderr, "Ignored curl_easy_perform expected failure on W32 with \"slow read\".\n"); result = 0; } else #else /* ! _WIN32 */ if (1) #endif /* ! _WIN32 */ { fprintf (stderr, "flibbet curl_easy_perform didn't fail as expected: `%s' %u\n", curl_easy_strerror (errornum), (unsigned int) errornum); result = 65536; } curl_easy_cleanup (c); MHD_stop_daemon (d); curl_slist_free_all (headers); return result; } if (CURLE_OK != (cc = curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &response_code))) { fprintf (stderr, "curl_easy_getinfo failed: '%s'\n", curl_easy_strerror (cc)); result = 65536; } if (! result && (response_code != 500)) { fprintf (stderr, "Unexpected response code: %ld\n", response_code); result = 131072; } if (! result && (cbc.pos != 0)) result = 262144; curl_easy_cleanup (c); MHD_stop_daemon (d); curl_slist_free_all (headers); return result; } static unsigned int testMultithreadedPostCancel (void) { unsigned int result = 0; int flags; for (flags = 0; flags < FLAG_COUNT; ++flags) result |= testMultithreadedPostCancelPart (flags); return result; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testMultithreadedPostCancel (); errorCount += testInternalPost (); errorCount += testMultithreadedPost (); errorCount += testMultithreadedPoolPost (); } errorCount += testExternalPost (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_put_broken_len.c0000664000175000017500000005125415232103064016770 /* This file is part of GNU libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testcurl/test_head.c * @brief Testcase for PUT requests with broken Content-Length header * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #ifndef _WIN32 #include #include #else #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 500000 #define EXPECTED_URI_BASE_PATH "/" #define EXISTING_URI EXPECTED_URI_BASE_PATH #define EXPECTED_URI_BASE_PATH_MISSING "/wrong_uri" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST URL_SCHEME URL_HOST #define PAGE \ "libmicrohttpd demo page" \ "Success!" #define PAGE_404 \ "404 error" \ "Error 404: The requested URI does not exist" /* Global parameters */ static int verbose; static int oneone; /**< If false use HTTP/1.0 for requests*/ static struct curl_slist *hdr_broken_cnt_len = NULL; static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); hdr_broken_cnt_len = curl_slist_append (hdr_broken_cnt_len, MHD_HTTP_HEADER_CONTENT_LENGTH ": 123bad"); } static void test_global_cleanup (void) { curl_slist_free_all (hdr_broken_cnt_len); curl_global_cleanup (); } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; /* Unused, mute compiler warning */ (void) ctx; /* Unused, mute compiler warning */ /* Discard data */ return size * nmemb; } struct ahc_cls_type { const char *rq_method; const char *rq_url; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; unsigned int http_code; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (oneone) { if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); } else { if (0 != strcmp (version, MHD_HTTP_VERSION_1_0)) mhdErrorExitDesc ("Unexpected HTTP version"); } if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (NULL != upload_data) mhdErrorExitDesc ("'upload_data' is not NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } *req_cls = NULL; if (0 == strcmp (url, EXISTING_URI)) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), PAGE); http_code = MHD_HTTP_OK; } else { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE_404), PAGE_404); http_code = MHD_HTTP_NOT_FOUND; } if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, http_code, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } static int libcurl_debug_cb (CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { static const char excess_mark[] = "Excess found"; static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark); (void) handle; (void) userptr; #ifdef _DEBUG switch (type) { case CURLINFO_TEXT: fprintf (stderr, "* %.*s", (int) size, data); break; case CURLINFO_HEADER_IN: fprintf (stderr, "< %.*s", (int) size, data); break; case CURLINFO_HEADER_OUT: fprintf (stderr, "> %.*s", (int) size, data); break; case CURLINFO_DATA_IN: #if 0 fprintf (stderr, "<| %.*s\n", (int) size, data); #endif break; case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: case CURLINFO_END: default: break; } #endif /* _DEBUG */ if (CURLINFO_TEXT == type) { if ((size >= excess_mark_len) && (0 == memcmp (data, excess_mark, excess_mark_len))) mhdErrorExitDesc ("Extra data has been detected in MHD reply"); } return 0; } static CURL * setupCURL (void *cbc, uint16_t port) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &libcurl_debug_cb)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, URL_SCHEME_HOST EXPECTED_URI_BASE_PATH)) libcurlErrorExitDesc ("Cannot set request URI"); /* Set as a "custom" request, because no actual upload data is provided. */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, MHD_HTTP_METHOD_PUT)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, hdr_broken_cnt_len)) libcurlErrorExitDesc ("Cannot set '" MHD_HTTP_HEADER_CONTENT_LENGTH "'.\n"); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ if (NULL != *multi_reuse) multi = *multi_reuse; else { multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); *multi_reuse = multi; } if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; if (0 == MHD_get_timeout64s (d)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((unsigned long) tv.tv_usec / 1000); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, long expected_code) { long code; if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (expected_code != code) { fprintf (stderr, "The response has wrong HTTP code: %ld\tExpected: %ld.\n", code, expected_code); return 0; } else if (verbose) printf ("The response has expected HTTP code: %ld\n", expected_code); return ! 0; } static unsigned int performTest (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; struct ahc_cls_type ahc_param; char buf[2048]; CURL *c; CURLM *multi_reuse; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4220 + oneone ? 0 : 1; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahcCheck, &ahc_param, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } /* First request */ ahc_param.rq_method = MHD_HTTP_METHOD_PUT; ahc_param.rq_url = EXPECTED_URI_BASE_PATH; cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port); multi_reuse = NULL; /* First request */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_BAD_REQUEST)) { fflush (stderr); if (verbose) printf ("Got first expected response.\n"); fflush (stdout); } else { fprintf (stderr, "First request FAILED.\n"); fflush (stderr); failed = 1; } /* Second request */ cbc.pos = 0; /* Reset buffer position */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_BAD_REQUEST)) { fflush (stderr); if (verbose) printf ("Got second expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Second request FAILED.\n"); fflush (stderr); failed = 1; } /* Third request */ cbc.pos = 0; /* Reset buffer position */ if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); multi_reuse = NULL; /* Force new connection */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_BAD_REQUEST)) { fflush (stderr); if (verbose) printf ("Got third expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Third request FAILED.\n"); fflush (stderr); failed = 1; } curl_easy_cleanup (c); if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; /* Test type and test parameters */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); oneone = ! has_in_name (argv[0], "10"); test_global_init (); errorCount += performTest (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_digestauth.c0000664000175000017500000004146615232103064016127 /* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_digestauth.c * @brief Testcase for libmicrohttpd Digest Auth * @author Amr Ali * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ #ifndef WINDOWS #include #include #else #include #endif #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define MHD_URI_BASE_PATH "/bar%20foo%20without%20args" #define PAGE \ "libmicrohttpd demoAccess granted" #define DENIED \ "libmicrohttpd demoAccess denied" #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) mhdErrorExitDesc ("Wrong too large data"); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; char *username; const char *password = "testpass"; const char *realm = "test@example.com"; enum MHD_Result ret; int ret_i; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } username = MHD_digest_auth_get_username (connection); if ( (username == NULL) || (0 != strcmp (username, "testuser")) ) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer failed"); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, MHD_NO, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2 failed"); MHD_destroy_response (response); return ret; } ret_i = MHD_digest_auth_check2 (connection, realm, username, password, 300, MHD_DIGEST_ALG_MD5); MHD_free (username); if (ret_i != MHD_YES) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer() failed"); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, (MHD_INVALID_NONCE == ret_i) ? MHD_YES : MHD_NO, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed"); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer() failed"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed"); MHD_destroy_response (response); return ret; } static CURL * setupCURL (void *cbc, uint16_t port) { CURL *c; char url[512]; if (1) { int res; /* A workaround for some old libcurl versions, which ignore the specified * port by CURLOPT_PORT when digest authorisation is used. */ res = snprintf (url, (sizeof(url) / sizeof(url[0])), "http://127.0.0.1:%u%s", (unsigned int) port, MHD_URI_BASE_PATH); if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res)) externalErrorExitDesc ("Cannot form request URL"); } c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass"))) libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed"); return c; } static unsigned int testDigestAuth (void) { CURL *c; struct MHD_Daemon *d; struct CBC cbc; char buf[2048]; char rnd[8]; uint16_t port; #ifndef WINDOWS int fd; size_t len; size_t off = 0; #endif /* ! WINDOWS */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1165; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; #ifndef WINDOWS fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) externalErrorExitDesc ("Failed to open '/dev/urandom'"); while (off < 8) { len = (size_t) read (fd, rnd + off, 8 - off); if (len == (size_t) -1) externalErrorExitDesc ("Failed to read '/dev/urandom'"); off += len; } (void) close (fd); #else { HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (b == 0) externalErrorExitDesc ("CryptAcquireContext() failed"); b = CryptGenRandom (cc, 8, (BYTE *) rnd); if (b == 0) externalErrorExitDesc ("CryptGenRandom() failed"); CryptReleaseContext (cc, 0); } #endif d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC, (uint32_t) 999, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } c = setupCURL (&cbc, port); checkCURLE_OK (curl_easy_perform (c)); curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (PAGE)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (PAGE, cbc.buf, strlen (PAGE))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testDigestAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/mhd_has_param.h0000644000175000017500000000327714760713577015540 /* This file is part of libmicrohttpd Copyright (C) 2016-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file testcurl/mhd_has_param.h * @brief Static functions and macros helpers for testsuite. * @author Karlson2k (Evgeny Grin) */ #include /** * Check whether one of strings in array is equal to @a param. * String @a argv[0] is ignored. * @param argc number of strings in @a argv, as passed to main function * @param argv array of strings, as passed to main function * @param param parameter to look for. * @return zero if @a argv is NULL, @a param is NULL or empty string, * @a argc is less then 2 or @a param is not found in @a argv, * non-zero if one of strings in @a argv is equal to @a param. */ static int has_param (int argc, char *const argv[], const char *param) { int i; if (! argv || ! param || ! param[0]) return 0; for (i = 1; i < argc; i++) { if (argv[i] && (strcmp (argv[i], param) == 0) ) return ! 0; } return 0; } libmicrohttpd-1.0.10/src/testcurl/test_concurrent_stop.c0000664000175000017500000002351715232103064017212 /* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011, 2015, 2016 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_concurrent_stop.c * @brief test stopping server while concurrent GETs are ongoing * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif /** * How many requests do we do in parallel? */ #if SIZEOF_SIZE_T >= 8 || MHD_CPU_COUNT < 8 # define PAR (MHD_CPU_COUNT * 4) #elif MHD_CPU_COUNT < 16 /* Limit load */ # define PAR (MHD_CPU_COUNT * 2) #else /* Limit load */ # define PAR (MHD_CPU_COUNT * 1) #endif /** * Do we use HTTP 1.1? */ static int oneone; /** * Response to return (re-used). */ static struct MHD_Response *response; /** * Continue generating new requests? */ static volatile int continue_requesting; /** * Continue waiting in watchdog thread? */ static volatile int watchdog_continue; static const char *watchdog_obj; /** * Indicate that client detected error */ static volatile CURLcode client_error; static void * thread_watchdog (void *param) { int seconds_passed; const int timeout_val = (int) (intptr_t) param; seconds_passed = 0; while (watchdog_continue) /* Poor threads sync, but works for testing. */ { if (0 == sleep (1)) /* Poor accuracy, but enough for testing. */ seconds_passed++; if (timeout_val < seconds_passed) { fprintf (stderr, "%s timeout expired.\n", watchdog_obj ? watchdog_obj : "Watchdog"); fflush (stderr); _exit (16); } } return NULL; } static pthread_t watchdog_tid; static void start_watchdog (int timeout, const char *obj_name) { watchdog_continue = 1; watchdog_obj = obj_name; if (0 != pthread_create (&watchdog_tid, NULL, &thread_watchdog, (void *) (intptr_t) timeout)) { fprintf (stderr, "Failed to start watchdog.\n"); _exit (99); } } static void stop_watchdog (void) { watchdog_continue = 0; if (0 != pthread_join (watchdog_tid, NULL)) { fprintf (stderr, "Failed to stop watchdog.\n"); _exit (99); } } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; (void) ctx; /* Unused. Silent compiler warning. */ return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } *req_cls = NULL; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (ret == MHD_NO) abort (); return ret; } static void * thread_gets (void *param) { CURL *c; CURLcode errornum; char *const url = (char *) param; c = NULL; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init failed.\n"); _exit (99); } curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 2L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 2L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); while (continue_requesting) { errornum = curl_easy_perform (c); if (CURLE_OK != errornum) { curl_easy_cleanup (c); client_error = errornum; return NULL; } } curl_easy_cleanup (c); return NULL; } static void * do_gets (void *param) { int j; pthread_t par[PAR]; char url[64]; uint16_t port = (uint16_t) (intptr_t) param; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); for (j = 0; j < PAR; j++) { if (0 != pthread_create (&par[j], NULL, &thread_gets, (void *) url)) { fprintf (stderr, "pthread_create failed.\n"); continue_requesting = 0; for (j--; j >= 0; j--) { pthread_join (par[j], NULL); } _exit (99); } } (void) sleep (1); for (j = 0; j < PAR; j++) { pthread_join (par[j], NULL); } return NULL; } static pthread_t start_gets (uint16_t port) { pthread_t tid; continue_requesting = 1; if (0 != pthread_create (&tid, NULL, &do_gets, (void *) (intptr_t) port)) { fprintf (stderr, "pthread_create failed.\n"); _exit (99); } return tid; } static unsigned int testMultithreadedGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; pthread_t p; unsigned int result; result = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } client_error = CURLE_OK; /* clear client error state */ p = start_gets (port); (void) sleep (1); start_watchdog (10, "daemon_stop() in testMultithreadedGet"); if (CURLE_OK != client_error) /* poor sync, but enough for test */ { result = 64; fprintf (stderr, "libcurl reported at least one error: \"%s\"\n", curl_easy_strerror (client_error)); } MHD_stop_daemon (d); stop_watchdog (); continue_requesting = 0; pthread_join (p, NULL); return result; } static unsigned int testMultithreadedPoolGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; pthread_t p; unsigned int result; result = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } client_error = CURLE_OK; /* clear client error state */ p = start_gets (port); (void) sleep (1); start_watchdog (10, "daemon_stop() in testMultithreadedPoolGet"); if (CURLE_OK != client_error) /* poor sync, but enough for test */ { result = 64; fprintf (stderr, "libcurl reported at least one error: \"%s\"\n", curl_easy_strerror (client_error)); } MHD_stop_daemon (d); stop_watchdog (); continue_requesting = 0; pthread_join (p, NULL); return result; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; uint16_t port; (void) argc; /* Unused. Silent compiler warning. */ (void) argv; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1142; /* Do reuse connection, otherwise all available local ports may exhausted. */ oneone = 1; if ((0 != port) && oneone) port += 5; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; response = MHD_create_response_from_buffer_copy (strlen ("/hello_world"), "/hello_world"); errorCount += testMultithreadedGet (port, 0); if (0 != port) port++; errorCount += testMultithreadedPoolGet (port, 0); MHD_destroy_response (response); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/Makefile.in0000664000175000017500000070541715235436270014646 # Makefile.in generated by automake 1.17 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2024 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) am__rm_f = rm -f $(am__rm_f_notfound) am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = -fprofile-arcs -ftest-coverage @ENABLE_HTTPS_TRUE@am__append_2 = https @HEAVY_TESTS_TRUE@am__append_3 = \ @HEAVY_TESTS_TRUE@ test_add_conn_cleanup \ @HEAVY_TESTS_TRUE@ test_add_conn_cleanup_nolisten \ @HEAVY_TESTS_TRUE@ test_timeout \ @HEAVY_TESTS_TRUE@ $(EMPTY_ITEM) @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__append_4 = \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ perf_get_concurrent11 \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ $(EMPTY_ITEM) @HAVE_POSIX_THREADS_TRUE@am__append_5 = \ @HAVE_POSIX_THREADS_TRUE@ test_get_wait \ @HAVE_POSIX_THREADS_TRUE@ test_get_wait11 \ @HAVE_POSIX_THREADS_TRUE@ test_suspend_resume_thread \ @HAVE_POSIX_THREADS_TRUE@ $(EMPTY_ITEM) @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__append_6 = \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ test_concurrent_stop \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ test_quiesce \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ $(EMPTY_ITEM) @HAVE_CURL_BINARY_TRUE@@HAVE_POSIX_THREADS_TRUE@am__append_7 = \ @HAVE_CURL_BINARY_TRUE@@HAVE_POSIX_THREADS_TRUE@ test_quiesce_stream @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__append_8 = \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ perf_get_concurrent @RUN_LIBCURL_TESTS_TRUE@check_PROGRAMS = test_get$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_head$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_head10$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_iovec$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_sendfile$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_close$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_close10$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_keep_alive$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_keep_alive10$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_delete$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_patch$(EXEEXT) test_put$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_add_conn$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_add_conn_nolisten$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_process_headers$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_process_arguments$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_method$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_url$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_request_header_name$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_request_header_value$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_request_headers$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_reply_header_name$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_reply_header_value$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_toolarge_reply_headers$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_tricky_url$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_tricky_header2$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_large_put$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_iovec11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_sendfile11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_patch11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_large_put11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_large_put_inc11$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_broken_len10$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_broken_len$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_string$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_string$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_empty$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_empty$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_string_empty$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_string_empty$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_sized$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_sized$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_empty_sized$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_empty_sized$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_forced$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_forced$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_empty_forced$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_chunked_close_empty_forced$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_chunked$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_callback$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_header_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_large_header_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_fold_last$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_fold_large$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_get_header_double_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_double_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_large_header_double_fold$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_double_fold_last$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ test_put_header_double_fold_large$(EXEEXT) \ @RUN_LIBCURL_TESTS_TRUE@ $(am__EXEEXT_1) $(am__EXEEXT_2) \ @RUN_LIBCURL_TESTS_TRUE@ $(am__EXEEXT_3) $(am__EXEEXT_4) \ @RUN_LIBCURL_TESTS_TRUE@ $(am__EXEEXT_5) $(am__EXEEXT_6) \ @RUN_LIBCURL_TESTS_TRUE@ $(am__EXEEXT_7) $(am__EXEEXT_8) \ @RUN_LIBCURL_TESTS_TRUE@ $(am__EXEEXT_18) $(am__EXEEXT_19) @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_9 = \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_p2 \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_p1 \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_zero \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_n2 \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_n3 @HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_10 = \ @HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@ perf_get @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_11 = \ @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_basicauth test_basicauth_preauth \ @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_basicauth_oldapi test_basicauth_preauth_oldapi @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_12 = \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_postform \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post_loop \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post11 \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_postform11 \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post_loop11 @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_13 = \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_with_arguments \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_concurrent @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_14 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_sha256 @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_15 = \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_emu_ext \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_emu_ext_oldapi \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2 \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_rfc2069 \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_rfc2069_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1 \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2 \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userhash \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userhash_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_bind_all \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_bind_uri \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_bind_all \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_bind_uri @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_16 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256 \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userhash \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_sha256 \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_sha256_userdigest \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userhash_userdigest @HAVE_CURL_BINARY_TRUE@@HAVE_FORK_WAITPID_TRUE@@HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__append_17 = test_get_response_cleanup @RUN_LIBCURL_TESTS_TRUE@@USE_POSIX_THREADS_TRUE@am__append_18 = \ @RUN_LIBCURL_TESTS_TRUE@@USE_POSIX_THREADS_TRUE@ $(THREAD_ONLY_TESTS) @RUN_LIBCURL_TESTS_TRUE@@USE_W32_THREADS_TRUE@am__append_19 = \ @RUN_LIBCURL_TESTS_TRUE@@USE_W32_THREADS_TRUE@ $(THREAD_ONLY_TESTS) subdir = src/testcurl ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__EXEEXT_1 = @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_2 = test_parse_cookies_discp_p2$(EXEEXT) \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_p1$(EXEEXT) \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_zero$(EXEEXT) \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_n2$(EXEEXT) \ @ENABLE_COOKIE_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_parse_cookies_discp_n3$(EXEEXT) @HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_3 = \ @HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@ perf_get$(EXEEXT) @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_4 = test_basicauth$(EXEEXT) \ @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_basicauth_preauth$(EXEEXT) \ @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_basicauth_oldapi$(EXEEXT) \ @ENABLE_BAUTH_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_basicauth_preauth_oldapi$(EXEEXT) @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_5 = test_post$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_postform$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post_loop$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post11$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_postform11$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_post_loop11$(EXEEXT) @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_6 = test_digestauth_emu_ext$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_emu_ext_oldapi$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_rfc2069$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_rfc2069_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userhash$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_userhash_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_bind_all$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_bind_uri$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_bind_all$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi1_bind_uri$(EXEEXT) @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_7 = test_digestauth2_sha256$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userhash$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_sha256$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_oldapi2_sha256_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth2_sha256_userhash_userdigest$(EXEEXT) @HAVE_CURL_BINARY_TRUE@@HAVE_FORK_WAITPID_TRUE@@HEAVY_TESTS_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_8 = test_get_response_cleanup$(EXEEXT) @HEAVY_TESTS_TRUE@am__EXEEXT_9 = test_add_conn_cleanup$(EXEEXT) \ @HEAVY_TESTS_TRUE@ test_add_conn_cleanup_nolisten$(EXEEXT) \ @HEAVY_TESTS_TRUE@ test_timeout$(EXEEXT) $(am__EXEEXT_1) @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__EXEEXT_10 = perf_get_concurrent11$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ $(am__EXEEXT_1) @HAVE_POSIX_THREADS_TRUE@am__EXEEXT_11 = test_get_wait$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@ test_get_wait11$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@ test_suspend_resume_thread$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@ $(am__EXEEXT_1) @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__EXEEXT_12 = test_concurrent_stop$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ test_quiesce$(EXEEXT) \ @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@ $(am__EXEEXT_1) @HAVE_CURL_BINARY_TRUE@@HAVE_POSIX_THREADS_TRUE@am__EXEEXT_13 = test_quiesce_stream$(EXEEXT) @HAVE_POSIX_THREADS_TRUE@@HEAVY_TESTS_TRUE@am__EXEEXT_14 = perf_get_concurrent$(EXEEXT) @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_15 = test_digestauth$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_with_arguments$(EXEEXT) \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@@RUN_LIBCURL_TESTS_TRUE@ test_digestauth_concurrent$(EXEEXT) @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@@RUN_LIBCURL_TESTS_TRUE@am__EXEEXT_16 = test_digestauth_sha256$(EXEEXT) am__EXEEXT_17 = test_urlparse$(EXEEXT) test_long_header$(EXEEXT) \ test_long_header11$(EXEEXT) test_iplimit11$(EXEEXT) \ test_termination$(EXEEXT) $(am__EXEEXT_1) $(am__EXEEXT_9) \ $(am__EXEEXT_10) $(am__EXEEXT_11) $(am__EXEEXT_12) \ $(am__EXEEXT_13) $(am__EXEEXT_14) $(am__EXEEXT_15) \ $(am__EXEEXT_16) @RUN_LIBCURL_TESTS_TRUE@@USE_POSIX_THREADS_TRUE@am__EXEEXT_18 = $(am__EXEEXT_17) @RUN_LIBCURL_TESTS_TRUE@@USE_W32_THREADS_TRUE@am__EXEEXT_19 = $(am__EXEEXT_17) am_perf_get_OBJECTS = perf_get.$(OBJEXT) perf_get_OBJECTS = $(am_perf_get_OBJECTS) perf_get_LDADD = $(LDADD) perf_get_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am_perf_get_concurrent_OBJECTS = \ perf_get_concurrent-perf_get_concurrent.$(OBJEXT) perf_get_concurrent_OBJECTS = $(am_perf_get_concurrent_OBJECTS) am__DEPENDENCIES_1 = am__DEPENDENCIES_2 = $(top_builddir)/src/microhttpd/libmicrohttpd.la perf_get_concurrent_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) perf_get_concurrent_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(perf_get_concurrent_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_perf_get_concurrent11_OBJECTS = \ perf_get_concurrent11-perf_get_concurrent.$(OBJEXT) perf_get_concurrent11_OBJECTS = $(am_perf_get_concurrent11_OBJECTS) perf_get_concurrent11_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) perf_get_concurrent11_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(perf_get_concurrent11_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_add_conn_OBJECTS = test_add_conn-test_add_conn.$(OBJEXT) test_add_conn_OBJECTS = $(am_test_add_conn_OBJECTS) test_add_conn_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_add_conn_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_add_conn_CFLAGS) \ $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_test_add_conn_cleanup_OBJECTS = \ test_add_conn_cleanup-test_add_conn.$(OBJEXT) test_add_conn_cleanup_OBJECTS = $(am_test_add_conn_cleanup_OBJECTS) test_add_conn_cleanup_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_add_conn_cleanup_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_add_conn_cleanup_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_add_conn_cleanup_nolisten_OBJECTS = \ test_add_conn_cleanup_nolisten-test_add_conn.$(OBJEXT) test_add_conn_cleanup_nolisten_OBJECTS = \ $(am_test_add_conn_cleanup_nolisten_OBJECTS) test_add_conn_cleanup_nolisten_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_add_conn_cleanup_nolisten_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_add_conn_cleanup_nolisten_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_test_add_conn_nolisten_OBJECTS = \ test_add_conn_nolisten-test_add_conn.$(OBJEXT) test_add_conn_nolisten_OBJECTS = $(am_test_add_conn_nolisten_OBJECTS) test_add_conn_nolisten_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_add_conn_nolisten_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_add_conn_nolisten_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_basicauth_OBJECTS = test_basicauth.$(OBJEXT) test_basicauth_OBJECTS = $(am_test_basicauth_OBJECTS) test_basicauth_LDADD = $(LDADD) test_basicauth_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_basicauth_oldapi_OBJECTS = test_basicauth.$(OBJEXT) test_basicauth_oldapi_OBJECTS = $(am_test_basicauth_oldapi_OBJECTS) test_basicauth_oldapi_LDADD = $(LDADD) test_basicauth_oldapi_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_basicauth_preauth_OBJECTS = test_basicauth.$(OBJEXT) test_basicauth_preauth_OBJECTS = $(am_test_basicauth_preauth_OBJECTS) test_basicauth_preauth_LDADD = $(LDADD) test_basicauth_preauth_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_basicauth_preauth_oldapi_OBJECTS = test_basicauth.$(OBJEXT) test_basicauth_preauth_oldapi_OBJECTS = \ $(am_test_basicauth_preauth_oldapi_OBJECTS) test_basicauth_preauth_oldapi_LDADD = $(LDADD) test_basicauth_preauth_oldapi_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_callback_OBJECTS = test_callback.$(OBJEXT) test_callback_OBJECTS = $(am_test_callback_OBJECTS) test_callback_LDADD = $(LDADD) test_callback_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_concurrent_stop_OBJECTS = \ test_concurrent_stop-test_concurrent_stop.$(OBJEXT) test_concurrent_stop_OBJECTS = $(am_test_concurrent_stop_OBJECTS) test_concurrent_stop_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_concurrent_stop_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_concurrent_stop_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_delete_OBJECTS = test_delete.$(OBJEXT) test_delete_OBJECTS = $(am_test_delete_OBJECTS) test_delete_LDADD = $(LDADD) test_delete_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth_OBJECTS = test_digestauth.$(OBJEXT) test_digestauth_OBJECTS = $(am_test_digestauth_OBJECTS) test_digestauth_DEPENDENCIES = $(am__DEPENDENCIES_2) am_test_digestauth2_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_OBJECTS = $(am_test_digestauth2_OBJECTS) test_digestauth2_LDADD = $(LDADD) test_digestauth2_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_bind_all_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_bind_all_OBJECTS = \ $(am_test_digestauth2_bind_all_OBJECTS) test_digestauth2_bind_all_LDADD = $(LDADD) test_digestauth2_bind_all_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_bind_uri_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_bind_uri_OBJECTS = \ $(am_test_digestauth2_bind_uri_OBJECTS) test_digestauth2_bind_uri_LDADD = $(LDADD) test_digestauth2_bind_uri_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi1_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_oldapi1_OBJECTS = \ $(am_test_digestauth2_oldapi1_OBJECTS) test_digestauth2_oldapi1_LDADD = $(LDADD) test_digestauth2_oldapi1_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi1_bind_all_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi1_bind_all_OBJECTS = \ $(am_test_digestauth2_oldapi1_bind_all_OBJECTS) test_digestauth2_oldapi1_bind_all_LDADD = $(LDADD) test_digestauth2_oldapi1_bind_all_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi1_bind_uri_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi1_bind_uri_OBJECTS = \ $(am_test_digestauth2_oldapi1_bind_uri_OBJECTS) test_digestauth2_oldapi1_bind_uri_LDADD = $(LDADD) test_digestauth2_oldapi1_bind_uri_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi1_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi1_userdigest_OBJECTS = \ $(am_test_digestauth2_oldapi1_userdigest_OBJECTS) test_digestauth2_oldapi1_userdigest_LDADD = $(LDADD) test_digestauth2_oldapi1_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi2_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_oldapi2_OBJECTS = \ $(am_test_digestauth2_oldapi2_OBJECTS) test_digestauth2_oldapi2_LDADD = $(LDADD) test_digestauth2_oldapi2_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi2_sha256_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi2_sha256_OBJECTS = \ $(am_test_digestauth2_oldapi2_sha256_OBJECTS) test_digestauth2_oldapi2_sha256_LDADD = $(LDADD) test_digestauth2_oldapi2_sha256_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi2_sha256_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi2_sha256_userdigest_OBJECTS = \ $(am_test_digestauth2_oldapi2_sha256_userdigest_OBJECTS) test_digestauth2_oldapi2_sha256_userdigest_LDADD = $(LDADD) test_digestauth2_oldapi2_sha256_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_oldapi2_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_oldapi2_userdigest_OBJECTS = \ $(am_test_digestauth2_oldapi2_userdigest_OBJECTS) test_digestauth2_oldapi2_userdigest_LDADD = $(LDADD) test_digestauth2_oldapi2_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_rfc2069_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_rfc2069_OBJECTS = \ $(am_test_digestauth2_rfc2069_OBJECTS) test_digestauth2_rfc2069_LDADD = $(LDADD) test_digestauth2_rfc2069_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_rfc2069_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_rfc2069_userdigest_OBJECTS = \ $(am_test_digestauth2_rfc2069_userdigest_OBJECTS) test_digestauth2_rfc2069_userdigest_LDADD = $(LDADD) test_digestauth2_rfc2069_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_sha256_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_sha256_OBJECTS = \ $(am_test_digestauth2_sha256_OBJECTS) test_digestauth2_sha256_LDADD = $(LDADD) test_digestauth2_sha256_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_sha256_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_sha256_userdigest_OBJECTS = \ $(am_test_digestauth2_sha256_userdigest_OBJECTS) test_digestauth2_sha256_userdigest_LDADD = $(LDADD) test_digestauth2_sha256_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_sha256_userhash_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_sha256_userhash_OBJECTS = \ $(am_test_digestauth2_sha256_userhash_OBJECTS) test_digestauth2_sha256_userhash_LDADD = $(LDADD) test_digestauth2_sha256_userhash_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_sha256_userhash_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_sha256_userhash_userdigest_OBJECTS = \ $(am_test_digestauth2_sha256_userhash_userdigest_OBJECTS) test_digestauth2_sha256_userhash_userdigest_LDADD = $(LDADD) test_digestauth2_sha256_userhash_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_userdigest_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_userdigest_OBJECTS = \ $(am_test_digestauth2_userdigest_OBJECTS) test_digestauth2_userdigest_LDADD = $(LDADD) test_digestauth2_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_userhash_OBJECTS = test_digestauth2.$(OBJEXT) test_digestauth2_userhash_OBJECTS = \ $(am_test_digestauth2_userhash_OBJECTS) test_digestauth2_userhash_LDADD = $(LDADD) test_digestauth2_userhash_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth2_userhash_userdigest_OBJECTS = \ test_digestauth2.$(OBJEXT) test_digestauth2_userhash_userdigest_OBJECTS = \ $(am_test_digestauth2_userhash_userdigest_OBJECTS) test_digestauth2_userhash_userdigest_LDADD = $(LDADD) test_digestauth2_userhash_userdigest_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth_concurrent_OBJECTS = test_digestauth_concurrent-test_digestauth_concurrent.$(OBJEXT) test_digestauth_concurrent_OBJECTS = \ $(am_test_digestauth_concurrent_OBJECTS) test_digestauth_concurrent_DEPENDENCIES = $(am__DEPENDENCIES_2) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_2) test_digestauth_concurrent_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_digestauth_concurrent_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_digestauth_emu_ext_OBJECTS = \ test_digestauth_emu_ext.$(OBJEXT) test_digestauth_emu_ext_OBJECTS = \ $(am_test_digestauth_emu_ext_OBJECTS) test_digestauth_emu_ext_LDADD = $(LDADD) test_digestauth_emu_ext_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth_emu_ext_oldapi_OBJECTS = \ test_digestauth_emu_ext.$(OBJEXT) test_digestauth_emu_ext_oldapi_OBJECTS = \ $(am_test_digestauth_emu_ext_oldapi_OBJECTS) test_digestauth_emu_ext_oldapi_LDADD = $(LDADD) test_digestauth_emu_ext_oldapi_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digestauth_sha256_OBJECTS = test_digestauth_sha256.$(OBJEXT) test_digestauth_sha256_OBJECTS = $(am_test_digestauth_sha256_OBJECTS) test_digestauth_sha256_DEPENDENCIES = $(am__DEPENDENCIES_2) am_test_digestauth_with_arguments_OBJECTS = \ test_digestauth_with_arguments.$(OBJEXT) test_digestauth_with_arguments_OBJECTS = \ $(am_test_digestauth_with_arguments_OBJECTS) test_digestauth_with_arguments_DEPENDENCIES = $(am__DEPENDENCIES_2) am_test_get_OBJECTS = test_get.$(OBJEXT) test_get_OBJECTS = $(am_test_get_OBJECTS) test_get_LDADD = $(LDADD) test_get_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get11_OBJECTS = test_get.$(OBJEXT) test_get11_OBJECTS = $(am_test_get11_OBJECTS) test_get11_LDADD = $(LDADD) test_get11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_OBJECTS = $(am_test_get_chunked_OBJECTS) test_get_chunked_LDADD = $(LDADD) test_get_chunked_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_close_OBJECTS = $(am_test_get_chunked_close_OBJECTS) test_get_chunked_close_LDADD = $(LDADD) test_get_chunked_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_empty_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_close_empty_OBJECTS = \ $(am_test_get_chunked_close_empty_OBJECTS) test_get_chunked_close_empty_LDADD = $(LDADD) test_get_chunked_close_empty_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_empty_forced_OBJECTS = \ test_get_chunked.$(OBJEXT) test_get_chunked_close_empty_forced_OBJECTS = \ $(am_test_get_chunked_close_empty_forced_OBJECTS) test_get_chunked_close_empty_forced_LDADD = $(LDADD) test_get_chunked_close_empty_forced_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_empty_sized_OBJECTS = \ test_get_chunked.$(OBJEXT) test_get_chunked_close_empty_sized_OBJECTS = \ $(am_test_get_chunked_close_empty_sized_OBJECTS) test_get_chunked_close_empty_sized_LDADD = $(LDADD) test_get_chunked_close_empty_sized_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_forced_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_close_forced_OBJECTS = \ $(am_test_get_chunked_close_forced_OBJECTS) test_get_chunked_close_forced_LDADD = $(LDADD) test_get_chunked_close_forced_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_sized_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_close_sized_OBJECTS = \ $(am_test_get_chunked_close_sized_OBJECTS) test_get_chunked_close_sized_LDADD = $(LDADD) test_get_chunked_close_sized_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_string_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_close_string_OBJECTS = \ $(am_test_get_chunked_close_string_OBJECTS) test_get_chunked_close_string_LDADD = $(LDADD) test_get_chunked_close_string_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_string_empty_OBJECTS = \ test_get_chunked.$(OBJEXT) test_get_chunked_close_string_empty_OBJECTS = \ $(am_test_get_chunked_close_string_empty_OBJECTS) test_get_chunked_close_string_empty_LDADD = $(LDADD) test_get_chunked_close_string_empty_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_empty_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_empty_OBJECTS = $(am_test_get_chunked_empty_OBJECTS) test_get_chunked_empty_LDADD = $(LDADD) test_get_chunked_empty_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_empty_forced_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_empty_forced_OBJECTS = \ $(am_test_get_chunked_empty_forced_OBJECTS) test_get_chunked_empty_forced_LDADD = $(LDADD) test_get_chunked_empty_forced_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_empty_sized_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_empty_sized_OBJECTS = \ $(am_test_get_chunked_empty_sized_OBJECTS) test_get_chunked_empty_sized_LDADD = $(LDADD) test_get_chunked_empty_sized_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_forced_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_forced_OBJECTS = \ $(am_test_get_chunked_forced_OBJECTS) test_get_chunked_forced_LDADD = $(LDADD) test_get_chunked_forced_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_sized_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_sized_OBJECTS = $(am_test_get_chunked_sized_OBJECTS) test_get_chunked_sized_LDADD = $(LDADD) test_get_chunked_sized_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_string_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_string_OBJECTS = \ $(am_test_get_chunked_string_OBJECTS) test_get_chunked_string_LDADD = $(LDADD) test_get_chunked_string_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_string_empty_OBJECTS = test_get_chunked.$(OBJEXT) test_get_chunked_string_empty_OBJECTS = \ $(am_test_get_chunked_string_empty_OBJECTS) test_get_chunked_string_empty_LDADD = $(LDADD) test_get_chunked_string_empty_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_close_OBJECTS = test_get_close_keep_alive.$(OBJEXT) test_get_close_OBJECTS = $(am_test_get_close_OBJECTS) test_get_close_LDADD = $(LDADD) test_get_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_close10_OBJECTS = test_get_close_keep_alive.$(OBJEXT) test_get_close10_OBJECTS = $(am_test_get_close10_OBJECTS) test_get_close10_LDADD = $(LDADD) test_get_close10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_1 = test_put_header_fold.$(OBJEXT) am_test_get_header_double_fold_OBJECTS = $(am__objects_1) test_get_header_double_fold_OBJECTS = \ $(am_test_get_header_double_fold_OBJECTS) test_get_header_double_fold_LDADD = $(LDADD) test_get_header_double_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_header_fold_OBJECTS = $(am__objects_1) test_get_header_fold_OBJECTS = $(am_test_get_header_fold_OBJECTS) test_get_header_fold_LDADD = $(LDADD) test_get_header_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_iovec_OBJECTS = test_get_iovec.$(OBJEXT) test_get_iovec_OBJECTS = $(am_test_get_iovec_OBJECTS) test_get_iovec_LDADD = $(LDADD) test_get_iovec_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_iovec11_OBJECTS = test_get_iovec.$(OBJEXT) test_get_iovec11_OBJECTS = $(am_test_get_iovec11_OBJECTS) test_get_iovec11_LDADD = $(LDADD) test_get_iovec11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_keep_alive_OBJECTS = test_get_close_keep_alive.$(OBJEXT) test_get_keep_alive_OBJECTS = $(am_test_get_keep_alive_OBJECTS) test_get_keep_alive_LDADD = $(LDADD) test_get_keep_alive_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_keep_alive10_OBJECTS = \ test_get_close_keep_alive.$(OBJEXT) test_get_keep_alive10_OBJECTS = $(am_test_get_keep_alive10_OBJECTS) test_get_keep_alive10_LDADD = $(LDADD) test_get_keep_alive10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_response_cleanup_OBJECTS = \ test_get_response_cleanup.$(OBJEXT) test_get_response_cleanup_OBJECTS = \ $(am_test_get_response_cleanup_OBJECTS) test_get_response_cleanup_LDADD = $(LDADD) test_get_response_cleanup_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_sendfile_OBJECTS = test_get_sendfile.$(OBJEXT) test_get_sendfile_OBJECTS = $(am_test_get_sendfile_OBJECTS) test_get_sendfile_LDADD = $(LDADD) test_get_sendfile_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_sendfile11_OBJECTS = test_get_sendfile.$(OBJEXT) test_get_sendfile11_OBJECTS = $(am_test_get_sendfile11_OBJECTS) test_get_sendfile11_LDADD = $(LDADD) test_get_sendfile11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_wait_OBJECTS = test_get_wait-test_get_wait.$(OBJEXT) test_get_wait_OBJECTS = $(am_test_get_wait_OBJECTS) test_get_wait_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_get_wait_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_get_wait_CFLAGS) \ $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_test_get_wait11_OBJECTS = test_get_wait11-test_get_wait.$(OBJEXT) test_get_wait11_OBJECTS = $(am_test_get_wait11_OBJECTS) test_get_wait11_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_get_wait11_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_get_wait11_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ am_test_head_OBJECTS = test_head.$(OBJEXT) test_head_OBJECTS = $(am_test_head_OBJECTS) test_head_LDADD = $(LDADD) test_head_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_head10_OBJECTS = test_head.$(OBJEXT) test_head10_OBJECTS = $(am_test_head10_OBJECTS) test_head10_LDADD = $(LDADD) test_head10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_iplimit11_OBJECTS = test_iplimit.$(OBJEXT) test_iplimit11_OBJECTS = $(am_test_iplimit11_OBJECTS) test_iplimit11_LDADD = $(LDADD) test_iplimit11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_large_put_OBJECTS = test_large_put.$(OBJEXT) test_large_put_OBJECTS = $(am_test_large_put_OBJECTS) test_large_put_LDADD = $(LDADD) test_large_put_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_large_put11_OBJECTS = test_large_put.$(OBJEXT) test_large_put11_OBJECTS = $(am_test_large_put11_OBJECTS) test_large_put11_LDADD = $(LDADD) test_large_put11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_large_put_inc11_OBJECTS = test_large_put.$(OBJEXT) test_large_put_inc11_OBJECTS = $(am_test_large_put_inc11_OBJECTS) test_large_put_inc11_LDADD = $(LDADD) test_large_put_inc11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_long_header_OBJECTS = test_long_header.$(OBJEXT) test_long_header_OBJECTS = $(am_test_long_header_OBJECTS) test_long_header_LDADD = $(LDADD) test_long_header_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_long_header11_OBJECTS = test_long_header.$(OBJEXT) test_long_header11_OBJECTS = $(am_test_long_header11_OBJECTS) test_long_header11_LDADD = $(LDADD) test_long_header11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_2 = test_parse_cookies.$(OBJEXT) am_test_parse_cookies_discp_n2_OBJECTS = $(am__objects_2) test_parse_cookies_discp_n2_OBJECTS = \ $(am_test_parse_cookies_discp_n2_OBJECTS) test_parse_cookies_discp_n2_LDADD = $(LDADD) test_parse_cookies_discp_n2_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_parse_cookies_discp_n3_OBJECTS = $(am__objects_2) test_parse_cookies_discp_n3_OBJECTS = \ $(am_test_parse_cookies_discp_n3_OBJECTS) test_parse_cookies_discp_n3_LDADD = $(LDADD) test_parse_cookies_discp_n3_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_parse_cookies_discp_p1_OBJECTS = $(am__objects_2) test_parse_cookies_discp_p1_OBJECTS = \ $(am_test_parse_cookies_discp_p1_OBJECTS) test_parse_cookies_discp_p1_LDADD = $(LDADD) test_parse_cookies_discp_p1_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_parse_cookies_discp_p2_OBJECTS = $(am__objects_2) test_parse_cookies_discp_p2_OBJECTS = \ $(am_test_parse_cookies_discp_p2_OBJECTS) test_parse_cookies_discp_p2_LDADD = $(LDADD) test_parse_cookies_discp_p2_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_parse_cookies_discp_zero_OBJECTS = \ test_parse_cookies.$(OBJEXT) test_parse_cookies_discp_zero_OBJECTS = \ $(am_test_parse_cookies_discp_zero_OBJECTS) test_parse_cookies_discp_zero_LDADD = $(LDADD) test_parse_cookies_discp_zero_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_patch_OBJECTS = test_patch.$(OBJEXT) test_patch_OBJECTS = $(am_test_patch_OBJECTS) test_patch_LDADD = $(LDADD) test_patch_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_patch11_OBJECTS = test_patch.$(OBJEXT) test_patch11_OBJECTS = $(am_test_patch11_OBJECTS) test_patch11_LDADD = $(LDADD) test_patch11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_OBJECTS = test_post.$(OBJEXT) test_post_OBJECTS = $(am_test_post_OBJECTS) test_post_LDADD = $(LDADD) test_post_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post11_OBJECTS = test_post.$(OBJEXT) test_post11_OBJECTS = $(am_test_post11_OBJECTS) test_post11_LDADD = $(LDADD) test_post11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_loop_OBJECTS = test_post_loop.$(OBJEXT) test_post_loop_OBJECTS = $(am_test_post_loop_OBJECTS) test_post_loop_LDADD = $(LDADD) test_post_loop_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_loop11_OBJECTS = test_post_loop.$(OBJEXT) test_post_loop11_OBJECTS = $(am_test_post_loop11_OBJECTS) test_post_loop11_LDADD = $(LDADD) test_post_loop11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_postform_OBJECTS = test_postform.$(OBJEXT) test_postform_OBJECTS = $(am_test_postform_OBJECTS) test_postform_DEPENDENCIES = $(am__DEPENDENCIES_2) am_test_postform11_OBJECTS = test_postform.$(OBJEXT) test_postform11_OBJECTS = $(am_test_postform11_OBJECTS) test_postform11_DEPENDENCIES = $(am__DEPENDENCIES_2) am_test_process_arguments_OBJECTS = test_process_arguments.$(OBJEXT) test_process_arguments_OBJECTS = $(am_test_process_arguments_OBJECTS) test_process_arguments_LDADD = $(LDADD) test_process_arguments_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_process_headers_OBJECTS = test_process_headers.$(OBJEXT) test_process_headers_OBJECTS = $(am_test_process_headers_OBJECTS) test_process_headers_LDADD = $(LDADD) test_process_headers_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_OBJECTS = test_put.$(OBJEXT) test_put_OBJECTS = $(am_test_put_OBJECTS) test_put_LDADD = $(LDADD) test_put_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put11_OBJECTS = test_put.$(OBJEXT) test_put11_OBJECTS = $(am_test_put11_OBJECTS) test_put11_LDADD = $(LDADD) test_put11_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_broken_len_OBJECTS = test_put_broken_len.$(OBJEXT) test_put_broken_len_OBJECTS = $(am_test_put_broken_len_OBJECTS) test_put_broken_len_LDADD = $(LDADD) test_put_broken_len_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_3 = test_put_broken_len.$(OBJEXT) am_test_put_broken_len10_OBJECTS = $(am__objects_3) test_put_broken_len10_OBJECTS = $(am_test_put_broken_len10_OBJECTS) test_put_broken_len10_LDADD = $(LDADD) test_put_broken_len10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_chunked_OBJECTS = test_put_chunked.$(OBJEXT) test_put_chunked_OBJECTS = $(am_test_put_chunked_OBJECTS) test_put_chunked_LDADD = $(LDADD) test_put_chunked_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_header_double_fold_OBJECTS = $(am__objects_1) test_put_header_double_fold_OBJECTS = \ $(am_test_put_header_double_fold_OBJECTS) test_put_header_double_fold_LDADD = $(LDADD) test_put_header_double_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_4 = $(am__objects_1) am_test_put_header_double_fold_large_OBJECTS = $(am__objects_4) test_put_header_double_fold_large_OBJECTS = \ $(am_test_put_header_double_fold_large_OBJECTS) test_put_header_double_fold_large_LDADD = $(LDADD) test_put_header_double_fold_large_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_header_double_fold_last_OBJECTS = $(am__objects_4) test_put_header_double_fold_last_OBJECTS = \ $(am_test_put_header_double_fold_last_OBJECTS) test_put_header_double_fold_last_LDADD = $(LDADD) test_put_header_double_fold_last_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_header_fold_OBJECTS = test_put_header_fold.$(OBJEXT) test_put_header_fold_OBJECTS = $(am_test_put_header_fold_OBJECTS) test_put_header_fold_LDADD = $(LDADD) test_put_header_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_header_fold_large_OBJECTS = $(am__objects_1) test_put_header_fold_large_OBJECTS = \ $(am_test_put_header_fold_large_OBJECTS) test_put_header_fold_large_LDADD = $(LDADD) test_put_header_fold_large_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_header_fold_last_OBJECTS = $(am__objects_1) test_put_header_fold_last_OBJECTS = \ $(am_test_put_header_fold_last_OBJECTS) test_put_header_fold_last_LDADD = $(LDADD) test_put_header_fold_last_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large_header_double_fold_OBJECTS = $(am__objects_4) test_put_large_header_double_fold_OBJECTS = \ $(am_test_put_large_header_double_fold_OBJECTS) test_put_large_header_double_fold_LDADD = $(LDADD) test_put_large_header_double_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large_header_fold_OBJECTS = $(am__objects_1) test_put_large_header_fold_OBJECTS = \ $(am_test_put_large_header_fold_OBJECTS) test_put_large_header_fold_LDADD = $(LDADD) test_put_large_header_fold_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_quiesce_OBJECTS = test_quiesce-test_quiesce.$(OBJEXT) test_quiesce_OBJECTS = $(am_test_quiesce_OBJECTS) test_quiesce_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_quiesce_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_quiesce_CFLAGS) \ $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_test_quiesce_stream_OBJECTS = \ test_quiesce_stream-test_quiesce_stream.$(OBJEXT) test_quiesce_stream_OBJECTS = $(am_test_quiesce_stream_OBJECTS) test_quiesce_stream_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_quiesce_stream_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_quiesce_stream_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_suspend_resume_thread_OBJECTS = test_suspend_resume_thread-test_suspend_resume_thread.$(OBJEXT) test_suspend_resume_thread_OBJECTS = \ $(am_test_suspend_resume_thread_OBJECTS) test_suspend_resume_thread_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_2) test_suspend_resume_thread_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_suspend_resume_thread_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_termination_OBJECTS = test_termination.$(OBJEXT) test_termination_OBJECTS = $(am_test_termination_OBJECTS) test_termination_LDADD = $(LDADD) test_termination_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_timeout_OBJECTS = test_timeout.$(OBJEXT) test_timeout_OBJECTS = $(am_test_timeout_OBJECTS) test_timeout_LDADD = $(LDADD) test_timeout_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_method_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_method_OBJECTS = $(am_test_toolarge_method_OBJECTS) test_toolarge_method_LDADD = $(LDADD) test_toolarge_method_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_reply_header_name_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_reply_header_name_OBJECTS = \ $(am_test_toolarge_reply_header_name_OBJECTS) test_toolarge_reply_header_name_LDADD = $(LDADD) test_toolarge_reply_header_name_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_reply_header_value_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_reply_header_value_OBJECTS = \ $(am_test_toolarge_reply_header_value_OBJECTS) test_toolarge_reply_header_value_LDADD = $(LDADD) test_toolarge_reply_header_value_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_reply_headers_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_reply_headers_OBJECTS = \ $(am_test_toolarge_reply_headers_OBJECTS) test_toolarge_reply_headers_LDADD = $(LDADD) test_toolarge_reply_headers_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_request_header_name_OBJECTS = \ test_toolarge.$(OBJEXT) test_toolarge_request_header_name_OBJECTS = \ $(am_test_toolarge_request_header_name_OBJECTS) test_toolarge_request_header_name_LDADD = $(LDADD) test_toolarge_request_header_name_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_request_header_value_OBJECTS = \ test_toolarge.$(OBJEXT) test_toolarge_request_header_value_OBJECTS = \ $(am_test_toolarge_request_header_value_OBJECTS) test_toolarge_request_header_value_LDADD = $(LDADD) test_toolarge_request_header_value_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_request_headers_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_request_headers_OBJECTS = \ $(am_test_toolarge_request_headers_OBJECTS) test_toolarge_request_headers_LDADD = $(LDADD) test_toolarge_request_headers_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_toolarge_url_OBJECTS = test_toolarge.$(OBJEXT) test_toolarge_url_OBJECTS = $(am_test_toolarge_url_OBJECTS) test_toolarge_url_LDADD = $(LDADD) test_toolarge_url_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_tricky_header2_OBJECTS = test_tricky.$(OBJEXT) test_tricky_header2_OBJECTS = $(am_test_tricky_header2_OBJECTS) test_tricky_header2_LDADD = $(LDADD) test_tricky_header2_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_tricky_url_OBJECTS = test_tricky.$(OBJEXT) test_tricky_url_OBJECTS = $(am_test_tricky_url_OBJECTS) test_tricky_url_LDADD = $(LDADD) test_tricky_url_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_urlparse_OBJECTS = test_urlparse.$(OBJEXT) test_urlparse_OBJECTS = $(am_test_urlparse_OBJECTS) test_urlparse_LDADD = $(LDADD) test_urlparse_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/perf_get.Po \ ./$(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po \ ./$(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po \ ./$(DEPDIR)/test_add_conn-test_add_conn.Po \ ./$(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po \ ./$(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po \ ./$(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po \ ./$(DEPDIR)/test_basicauth.Po ./$(DEPDIR)/test_callback.Po \ ./$(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po \ ./$(DEPDIR)/test_delete.Po ./$(DEPDIR)/test_digestauth.Po \ ./$(DEPDIR)/test_digestauth2.Po \ ./$(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po \ ./$(DEPDIR)/test_digestauth_emu_ext.Po \ ./$(DEPDIR)/test_digestauth_sha256.Po \ ./$(DEPDIR)/test_digestauth_with_arguments.Po \ ./$(DEPDIR)/test_get.Po ./$(DEPDIR)/test_get_chunked.Po \ ./$(DEPDIR)/test_get_close_keep_alive.Po \ ./$(DEPDIR)/test_get_iovec.Po \ ./$(DEPDIR)/test_get_response_cleanup.Po \ ./$(DEPDIR)/test_get_sendfile.Po \ ./$(DEPDIR)/test_get_wait-test_get_wait.Po \ ./$(DEPDIR)/test_get_wait11-test_get_wait.Po \ ./$(DEPDIR)/test_head.Po ./$(DEPDIR)/test_iplimit.Po \ ./$(DEPDIR)/test_large_put.Po ./$(DEPDIR)/test_long_header.Po \ ./$(DEPDIR)/test_parse_cookies.Po ./$(DEPDIR)/test_patch.Po \ ./$(DEPDIR)/test_post.Po ./$(DEPDIR)/test_post_loop.Po \ ./$(DEPDIR)/test_postform.Po \ ./$(DEPDIR)/test_process_arguments.Po \ ./$(DEPDIR)/test_process_headers.Po ./$(DEPDIR)/test_put.Po \ ./$(DEPDIR)/test_put_broken_len.Po \ ./$(DEPDIR)/test_put_chunked.Po \ ./$(DEPDIR)/test_put_header_fold.Po \ ./$(DEPDIR)/test_quiesce-test_quiesce.Po \ ./$(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po \ ./$(DEPDIR)/test_suspend_resume_thread-test_suspend_resume_thread.Po \ ./$(DEPDIR)/test_termination.Po ./$(DEPDIR)/test_timeout.Po \ ./$(DEPDIR)/test_toolarge.Po ./$(DEPDIR)/test_tricky.Po \ ./$(DEPDIR)/test_urlparse.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(perf_get_SOURCES) $(perf_get_concurrent_SOURCES) \ $(perf_get_concurrent11_SOURCES) $(test_add_conn_SOURCES) \ $(test_add_conn_cleanup_SOURCES) \ $(test_add_conn_cleanup_nolisten_SOURCES) \ $(test_add_conn_nolisten_SOURCES) $(test_basicauth_SOURCES) \ $(test_basicauth_oldapi_SOURCES) \ $(test_basicauth_preauth_SOURCES) \ $(test_basicauth_preauth_oldapi_SOURCES) \ $(test_callback_SOURCES) $(test_concurrent_stop_SOURCES) \ $(test_delete_SOURCES) $(test_digestauth_SOURCES) \ $(test_digestauth2_SOURCES) \ $(test_digestauth2_bind_all_SOURCES) \ $(test_digestauth2_bind_uri_SOURCES) \ $(test_digestauth2_oldapi1_SOURCES) \ $(test_digestauth2_oldapi1_bind_all_SOURCES) \ $(test_digestauth2_oldapi1_bind_uri_SOURCES) \ $(test_digestauth2_oldapi1_userdigest_SOURCES) \ $(test_digestauth2_oldapi2_SOURCES) \ $(test_digestauth2_oldapi2_sha256_SOURCES) \ $(test_digestauth2_oldapi2_sha256_userdigest_SOURCES) \ $(test_digestauth2_oldapi2_userdigest_SOURCES) \ $(test_digestauth2_rfc2069_SOURCES) \ $(test_digestauth2_rfc2069_userdigest_SOURCES) \ $(test_digestauth2_sha256_SOURCES) \ $(test_digestauth2_sha256_userdigest_SOURCES) \ $(test_digestauth2_sha256_userhash_SOURCES) \ $(test_digestauth2_sha256_userhash_userdigest_SOURCES) \ $(test_digestauth2_userdigest_SOURCES) \ $(test_digestauth2_userhash_SOURCES) \ $(test_digestauth2_userhash_userdigest_SOURCES) \ $(test_digestauth_concurrent_SOURCES) \ $(test_digestauth_emu_ext_SOURCES) \ $(test_digestauth_emu_ext_oldapi_SOURCES) \ $(test_digestauth_sha256_SOURCES) \ $(test_digestauth_with_arguments_SOURCES) $(test_get_SOURCES) \ $(test_get11_SOURCES) $(test_get_chunked_SOURCES) \ $(test_get_chunked_close_SOURCES) \ $(test_get_chunked_close_empty_SOURCES) \ $(test_get_chunked_close_empty_forced_SOURCES) \ $(test_get_chunked_close_empty_sized_SOURCES) \ $(test_get_chunked_close_forced_SOURCES) \ $(test_get_chunked_close_sized_SOURCES) \ $(test_get_chunked_close_string_SOURCES) \ $(test_get_chunked_close_string_empty_SOURCES) \ $(test_get_chunked_empty_SOURCES) \ $(test_get_chunked_empty_forced_SOURCES) \ $(test_get_chunked_empty_sized_SOURCES) \ $(test_get_chunked_forced_SOURCES) \ $(test_get_chunked_sized_SOURCES) \ $(test_get_chunked_string_SOURCES) \ $(test_get_chunked_string_empty_SOURCES) \ $(test_get_close_SOURCES) $(test_get_close10_SOURCES) \ $(test_get_header_double_fold_SOURCES) \ $(test_get_header_fold_SOURCES) $(test_get_iovec_SOURCES) \ $(test_get_iovec11_SOURCES) $(test_get_keep_alive_SOURCES) \ $(test_get_keep_alive10_SOURCES) \ $(test_get_response_cleanup_SOURCES) \ $(test_get_sendfile_SOURCES) $(test_get_sendfile11_SOURCES) \ $(test_get_wait_SOURCES) $(test_get_wait11_SOURCES) \ $(test_head_SOURCES) $(test_head10_SOURCES) \ $(test_iplimit11_SOURCES) $(test_large_put_SOURCES) \ $(test_large_put11_SOURCES) $(test_large_put_inc11_SOURCES) \ $(test_long_header_SOURCES) $(test_long_header11_SOURCES) \ $(test_parse_cookies_discp_n2_SOURCES) \ $(test_parse_cookies_discp_n3_SOURCES) \ $(test_parse_cookies_discp_p1_SOURCES) \ $(test_parse_cookies_discp_p2_SOURCES) \ $(test_parse_cookies_discp_zero_SOURCES) $(test_patch_SOURCES) \ $(test_patch11_SOURCES) $(test_post_SOURCES) \ $(test_post11_SOURCES) $(test_post_loop_SOURCES) \ $(test_post_loop11_SOURCES) $(test_postform_SOURCES) \ $(test_postform11_SOURCES) $(test_process_arguments_SOURCES) \ $(test_process_headers_SOURCES) $(test_put_SOURCES) \ $(test_put11_SOURCES) $(test_put_broken_len_SOURCES) \ $(test_put_broken_len10_SOURCES) $(test_put_chunked_SOURCES) \ $(test_put_header_double_fold_SOURCES) \ $(test_put_header_double_fold_large_SOURCES) \ $(test_put_header_double_fold_last_SOURCES) \ $(test_put_header_fold_SOURCES) \ $(test_put_header_fold_large_SOURCES) \ $(test_put_header_fold_last_SOURCES) \ $(test_put_large_header_double_fold_SOURCES) \ $(test_put_large_header_fold_SOURCES) $(test_quiesce_SOURCES) \ $(test_quiesce_stream_SOURCES) \ $(test_suspend_resume_thread_SOURCES) \ $(test_termination_SOURCES) $(test_timeout_SOURCES) \ $(test_toolarge_method_SOURCES) \ $(test_toolarge_reply_header_name_SOURCES) \ $(test_toolarge_reply_header_value_SOURCES) \ $(test_toolarge_reply_headers_SOURCES) \ $(test_toolarge_request_header_name_SOURCES) \ $(test_toolarge_request_header_value_SOURCES) \ $(test_toolarge_request_headers_SOURCES) \ $(test_toolarge_url_SOURCES) $(test_tricky_header2_SOURCES) \ $(test_tricky_url_SOURCES) $(test_urlparse_SOURCES) DIST_SOURCES = $(perf_get_SOURCES) $(perf_get_concurrent_SOURCES) \ $(perf_get_concurrent11_SOURCES) $(test_add_conn_SOURCES) \ $(test_add_conn_cleanup_SOURCES) \ $(test_add_conn_cleanup_nolisten_SOURCES) \ $(test_add_conn_nolisten_SOURCES) $(test_basicauth_SOURCES) \ $(test_basicauth_oldapi_SOURCES) \ $(test_basicauth_preauth_SOURCES) \ $(test_basicauth_preauth_oldapi_SOURCES) \ $(test_callback_SOURCES) $(test_concurrent_stop_SOURCES) \ $(test_delete_SOURCES) $(test_digestauth_SOURCES) \ $(test_digestauth2_SOURCES) \ $(test_digestauth2_bind_all_SOURCES) \ $(test_digestauth2_bind_uri_SOURCES) \ $(test_digestauth2_oldapi1_SOURCES) \ $(test_digestauth2_oldapi1_bind_all_SOURCES) \ $(test_digestauth2_oldapi1_bind_uri_SOURCES) \ $(test_digestauth2_oldapi1_userdigest_SOURCES) \ $(test_digestauth2_oldapi2_SOURCES) \ $(test_digestauth2_oldapi2_sha256_SOURCES) \ $(test_digestauth2_oldapi2_sha256_userdigest_SOURCES) \ $(test_digestauth2_oldapi2_userdigest_SOURCES) \ $(test_digestauth2_rfc2069_SOURCES) \ $(test_digestauth2_rfc2069_userdigest_SOURCES) \ $(test_digestauth2_sha256_SOURCES) \ $(test_digestauth2_sha256_userdigest_SOURCES) \ $(test_digestauth2_sha256_userhash_SOURCES) \ $(test_digestauth2_sha256_userhash_userdigest_SOURCES) \ $(test_digestauth2_userdigest_SOURCES) \ $(test_digestauth2_userhash_SOURCES) \ $(test_digestauth2_userhash_userdigest_SOURCES) \ $(test_digestauth_concurrent_SOURCES) \ $(test_digestauth_emu_ext_SOURCES) \ $(test_digestauth_emu_ext_oldapi_SOURCES) \ $(test_digestauth_sha256_SOURCES) \ $(test_digestauth_with_arguments_SOURCES) $(test_get_SOURCES) \ $(test_get11_SOURCES) $(test_get_chunked_SOURCES) \ $(test_get_chunked_close_SOURCES) \ $(test_get_chunked_close_empty_SOURCES) \ $(test_get_chunked_close_empty_forced_SOURCES) \ $(test_get_chunked_close_empty_sized_SOURCES) \ $(test_get_chunked_close_forced_SOURCES) \ $(test_get_chunked_close_sized_SOURCES) \ $(test_get_chunked_close_string_SOURCES) \ $(test_get_chunked_close_string_empty_SOURCES) \ $(test_get_chunked_empty_SOURCES) \ $(test_get_chunked_empty_forced_SOURCES) \ $(test_get_chunked_empty_sized_SOURCES) \ $(test_get_chunked_forced_SOURCES) \ $(test_get_chunked_sized_SOURCES) \ $(test_get_chunked_string_SOURCES) \ $(test_get_chunked_string_empty_SOURCES) \ $(test_get_close_SOURCES) $(test_get_close10_SOURCES) \ $(test_get_header_double_fold_SOURCES) \ $(test_get_header_fold_SOURCES) $(test_get_iovec_SOURCES) \ $(test_get_iovec11_SOURCES) $(test_get_keep_alive_SOURCES) \ $(test_get_keep_alive10_SOURCES) \ $(test_get_response_cleanup_SOURCES) \ $(test_get_sendfile_SOURCES) $(test_get_sendfile11_SOURCES) \ $(test_get_wait_SOURCES) $(test_get_wait11_SOURCES) \ $(test_head_SOURCES) $(test_head10_SOURCES) \ $(test_iplimit11_SOURCES) $(test_large_put_SOURCES) \ $(test_large_put11_SOURCES) $(test_large_put_inc11_SOURCES) \ $(test_long_header_SOURCES) $(test_long_header11_SOURCES) \ $(test_parse_cookies_discp_n2_SOURCES) \ $(test_parse_cookies_discp_n3_SOURCES) \ $(test_parse_cookies_discp_p1_SOURCES) \ $(test_parse_cookies_discp_p2_SOURCES) \ $(test_parse_cookies_discp_zero_SOURCES) $(test_patch_SOURCES) \ $(test_patch11_SOURCES) $(test_post_SOURCES) \ $(test_post11_SOURCES) $(test_post_loop_SOURCES) \ $(test_post_loop11_SOURCES) $(test_postform_SOURCES) \ $(test_postform11_SOURCES) $(test_process_arguments_SOURCES) \ $(test_process_headers_SOURCES) $(test_put_SOURCES) \ $(test_put11_SOURCES) $(test_put_broken_len_SOURCES) \ $(test_put_broken_len10_SOURCES) $(test_put_chunked_SOURCES) \ $(test_put_header_double_fold_SOURCES) \ $(test_put_header_double_fold_large_SOURCES) \ $(test_put_header_double_fold_last_SOURCES) \ $(test_put_header_fold_SOURCES) \ $(test_put_header_fold_large_SOURCES) \ $(test_put_header_fold_last_SOURCES) \ $(test_put_large_header_double_fold_SOURCES) \ $(test_put_large_header_fold_SOURCES) $(test_quiesce_SOURCES) \ $(test_quiesce_stream_SOURCES) \ $(test_suspend_resume_thread_SOURCES) \ $(test_termination_SOURCES) $(test_timeout_SOURCES) \ $(test_toolarge_method_SOURCES) \ $(test_toolarge_reply_header_name_SOURCES) \ $(test_toolarge_reply_header_value_SOURCES) \ $(test_toolarge_reply_headers_SOURCES) \ $(test_toolarge_request_header_name_SOURCES) \ $(test_toolarge_request_header_value_SOURCES) \ $(test_toolarge_request_headers_SOURCES) \ $(test_toolarge_url_SOURCES) $(test_tricky_header2_SOURCES) \ $(test_tricky_url_SOURCES) $(test_urlparse_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ check recheck distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ $$am__collect_skipped_logs \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(IGNORE_SKIPPED_LOGS)'; then \ am__collect_skipped_logs='--collect-skipped-logs no'; \ else \ am__collect_skipped_logs=''; \ fi; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DIST_SUBDIRS = . https am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ am__xargs_n = @am__xargs_n@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain EMPTY_ITEM = SUBDIRS = . $(am__append_2) AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ $(am__append_1) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ @LIBCURL@ THREAD_ONLY_TESTS = test_urlparse test_long_header test_long_header11 \ test_iplimit11 test_termination $(EMPTY_ITEM) $(am__append_3) \ $(am__append_4) $(am__append_5) $(am__append_6) \ $(am__append_7) $(am__append_8) $(am__append_13) \ $(am__append_14) @RUN_LIBCURL_TESTS_TRUE@TESTS = $(check_PROGRAMS) test_concurrent_stop_SOURCES = \ test_concurrent_stop.c test_concurrent_stop_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_concurrent_stop_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get_SOURCES = \ test_get.c mhd_has_in_name.h mhd_has_param.h test_head_SOURCES = \ test_head.c mhd_has_in_name.h mhd_has_param.h test_head10_SOURCES = \ test_head.c mhd_has_in_name.h mhd_has_param.h test_quiesce_SOURCES = \ test_quiesce.c mhd_has_param.h mhd_has_in_name.h test_quiesce_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_quiesce_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_quiesce_stream_SOURCES = \ test_quiesce_stream.c test_quiesce_stream_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_quiesce_stream_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_suspend_resume_thread_SOURCES = \ test_suspend_resume_thread.c test_suspend_resume_thread_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_suspend_resume_thread_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_callback_SOURCES = \ test_callback.c perf_get_SOURCES = \ perf_get.c \ mhd_has_in_name.h perf_get_concurrent_SOURCES = \ perf_get_concurrent.c \ mhd_has_in_name.h perf_get_concurrent_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) perf_get_concurrent_LDADD = \ $(PTHREAD_LIBS) $(LDADD) perf_get_concurrent11_SOURCES = \ perf_get_concurrent.c \ mhd_has_in_name.h perf_get_concurrent11_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) perf_get_concurrent11_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_basicauth_SOURCES = \ test_basicauth.c test_basicauth_preauth_SOURCES = \ test_basicauth.c test_basicauth_oldapi_SOURCES = \ test_basicauth.c test_basicauth_preauth_oldapi_SOURCES = \ test_basicauth.c test_digestauth_SOURCES = \ test_digestauth.c test_digestauth_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_sha256_SOURCES = \ test_digestauth_sha256.c test_digestauth_sha256_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_with_arguments_SOURCES = \ test_digestauth_with_arguments.c test_digestauth_with_arguments_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_concurrent_SOURCES = \ test_digestauth_concurrent.c test_digestauth_concurrent_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_digestauth_concurrent_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) $(PTHREAD_LIBS) $(LDADD) test_digestauth_emu_ext_SOURCES = \ test_digestauth_emu_ext.c test_digestauth_emu_ext_oldapi_SOURCES = \ test_digestauth_emu_ext.c test_digestauth2_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_rfc2069_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_rfc2069_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userhash_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_sha256_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userhash_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userhash_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_sha256_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userhash_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_bind_all_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_bind_uri_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_bind_all_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_bind_uri_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_get_iovec_SOURCES = \ test_get_iovec.c mhd_has_in_name.h test_get_sendfile_SOURCES = \ test_get_sendfile.c mhd_has_in_name.h test_get_wait_SOURCES = \ test_get_wait.c \ mhd_has_in_name.h test_get_wait_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_get_wait_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get_wait11_SOURCES = \ test_get_wait.c \ mhd_has_in_name.h test_get_wait11_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_get_wait11_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_urlparse_SOURCES = \ test_urlparse.c mhd_has_in_name.h test_get_response_cleanup_SOURCES = \ test_get_response_cleanup.c mhd_has_in_name.h test_get_chunked_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_string_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_string_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_string_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_string_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_post_SOURCES = \ test_post.c mhd_has_in_name.h test_process_headers_SOURCES = \ test_process_headers.c mhd_has_in_name.h test_parse_cookies_discp_zero_SOURCES = \ test_parse_cookies.c mhd_has_in_name.h mhd_has_param.h test_parse_cookies_discp_p2_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_p1_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_n2_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_n3_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_process_arguments_SOURCES = \ test_process_arguments.c mhd_has_in_name.h test_postform_SOURCES = \ test_postform.c mhd_has_in_name.h test_postform_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_post_loop_SOURCES = \ test_post_loop.c mhd_has_in_name.h test_delete_SOURCES = \ test_delete.c mhd_has_in_name.h test_patch_SOURCES = \ test_patch.c mhd_has_in_name.h test_patch11_SOURCES = \ test_patch.c mhd_has_in_name.h test_put_SOURCES = \ test_put.c mhd_has_in_name.h test_put_chunked_SOURCES = \ test_put_chunked.c test_add_conn_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_nolisten_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_nolisten_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_nolisten_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_cleanup_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_cleanup_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_cleanup_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_cleanup_nolisten_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_cleanup_nolisten_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_cleanup_nolisten_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get11_SOURCES = \ test_get.c mhd_has_in_name.h mhd_has_param.h test_get_iovec11_SOURCES = \ test_get_iovec.c mhd_has_in_name.h test_get_sendfile11_SOURCES = \ test_get_sendfile.c mhd_has_in_name.h test_get_close_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_close10_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_keep_alive_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_keep_alive10_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_post11_SOURCES = \ test_post.c mhd_has_in_name.h test_postform11_SOURCES = \ test_postform.c mhd_has_in_name.h test_postform11_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_post_loop11_SOURCES = \ test_post_loop.c mhd_has_in_name.h test_put11_SOURCES = \ test_put.c mhd_has_in_name.h test_large_put_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_large_put11_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_large_put_inc11_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_long_header_SOURCES = \ test_long_header.c mhd_has_in_name.h test_long_header11_SOURCES = \ test_long_header.c mhd_has_in_name.h test_iplimit11_SOURCES = \ test_iplimit.c mhd_has_in_name.h test_termination_SOURCES = \ test_termination.c test_timeout_SOURCES = \ test_timeout.c mhd_has_in_name.h test_toolarge_method_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_url_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_header_name_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_header_value_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_headers_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_header_name_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_header_value_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_headers_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_tricky_url_SOURCES = \ test_tricky.c mhd_has_in_name.h mhd_has_param.h test_tricky_header2_SOURCES = \ test_tricky.c mhd_has_in_name.h mhd_has_param.h test_put_broken_len_SOURCES = \ test_put_broken_len.c mhd_has_in_name.h mhd_has_param.h test_put_broken_len10_SOURCES = $(test_put_broken_len_SOURCES) test_put_header_fold_SOURCES = \ test_put_header_fold.c mhd_has_in_name.h mhd_has_param.h test_put_large_header_fold_SOURCES = $(test_put_header_fold_SOURCES) test_get_header_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_fold_last_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_fold_large_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_double_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_large_header_double_fold_SOURCES = $(test_put_large_header_fold_SOURCES) test_get_header_double_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_double_fold_last_SOURCES = $(test_put_header_fold_last_SOURCES) test_put_header_double_fold_large_SOURCES = $(test_put_header_fold_large_SOURCES) all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/testcurl/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/testcurl/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: $(am__rm_f) $(check_PROGRAMS) test -z "$(EXEEXT)" || $(am__rm_f) $(check_PROGRAMS:$(EXEEXT)=) perf_get$(EXEEXT): $(perf_get_OBJECTS) $(perf_get_DEPENDENCIES) $(EXTRA_perf_get_DEPENDENCIES) @rm -f perf_get$(EXEEXT) $(AM_V_CCLD)$(LINK) $(perf_get_OBJECTS) $(perf_get_LDADD) $(LIBS) perf_get_concurrent$(EXEEXT): $(perf_get_concurrent_OBJECTS) $(perf_get_concurrent_DEPENDENCIES) $(EXTRA_perf_get_concurrent_DEPENDENCIES) @rm -f perf_get_concurrent$(EXEEXT) $(AM_V_CCLD)$(perf_get_concurrent_LINK) $(perf_get_concurrent_OBJECTS) $(perf_get_concurrent_LDADD) $(LIBS) perf_get_concurrent11$(EXEEXT): $(perf_get_concurrent11_OBJECTS) $(perf_get_concurrent11_DEPENDENCIES) $(EXTRA_perf_get_concurrent11_DEPENDENCIES) @rm -f perf_get_concurrent11$(EXEEXT) $(AM_V_CCLD)$(perf_get_concurrent11_LINK) $(perf_get_concurrent11_OBJECTS) $(perf_get_concurrent11_LDADD) $(LIBS) test_add_conn$(EXEEXT): $(test_add_conn_OBJECTS) $(test_add_conn_DEPENDENCIES) $(EXTRA_test_add_conn_DEPENDENCIES) @rm -f test_add_conn$(EXEEXT) $(AM_V_CCLD)$(test_add_conn_LINK) $(test_add_conn_OBJECTS) $(test_add_conn_LDADD) $(LIBS) test_add_conn_cleanup$(EXEEXT): $(test_add_conn_cleanup_OBJECTS) $(test_add_conn_cleanup_DEPENDENCIES) $(EXTRA_test_add_conn_cleanup_DEPENDENCIES) @rm -f test_add_conn_cleanup$(EXEEXT) $(AM_V_CCLD)$(test_add_conn_cleanup_LINK) $(test_add_conn_cleanup_OBJECTS) $(test_add_conn_cleanup_LDADD) $(LIBS) test_add_conn_cleanup_nolisten$(EXEEXT): $(test_add_conn_cleanup_nolisten_OBJECTS) $(test_add_conn_cleanup_nolisten_DEPENDENCIES) $(EXTRA_test_add_conn_cleanup_nolisten_DEPENDENCIES) @rm -f test_add_conn_cleanup_nolisten$(EXEEXT) $(AM_V_CCLD)$(test_add_conn_cleanup_nolisten_LINK) $(test_add_conn_cleanup_nolisten_OBJECTS) $(test_add_conn_cleanup_nolisten_LDADD) $(LIBS) test_add_conn_nolisten$(EXEEXT): $(test_add_conn_nolisten_OBJECTS) $(test_add_conn_nolisten_DEPENDENCIES) $(EXTRA_test_add_conn_nolisten_DEPENDENCIES) @rm -f test_add_conn_nolisten$(EXEEXT) $(AM_V_CCLD)$(test_add_conn_nolisten_LINK) $(test_add_conn_nolisten_OBJECTS) $(test_add_conn_nolisten_LDADD) $(LIBS) test_basicauth$(EXEEXT): $(test_basicauth_OBJECTS) $(test_basicauth_DEPENDENCIES) $(EXTRA_test_basicauth_DEPENDENCIES) @rm -f test_basicauth$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_basicauth_OBJECTS) $(test_basicauth_LDADD) $(LIBS) test_basicauth_oldapi$(EXEEXT): $(test_basicauth_oldapi_OBJECTS) $(test_basicauth_oldapi_DEPENDENCIES) $(EXTRA_test_basicauth_oldapi_DEPENDENCIES) @rm -f test_basicauth_oldapi$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_basicauth_oldapi_OBJECTS) $(test_basicauth_oldapi_LDADD) $(LIBS) test_basicauth_preauth$(EXEEXT): $(test_basicauth_preauth_OBJECTS) $(test_basicauth_preauth_DEPENDENCIES) $(EXTRA_test_basicauth_preauth_DEPENDENCIES) @rm -f test_basicauth_preauth$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_basicauth_preauth_OBJECTS) $(test_basicauth_preauth_LDADD) $(LIBS) test_basicauth_preauth_oldapi$(EXEEXT): $(test_basicauth_preauth_oldapi_OBJECTS) $(test_basicauth_preauth_oldapi_DEPENDENCIES) $(EXTRA_test_basicauth_preauth_oldapi_DEPENDENCIES) @rm -f test_basicauth_preauth_oldapi$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_basicauth_preauth_oldapi_OBJECTS) $(test_basicauth_preauth_oldapi_LDADD) $(LIBS) test_callback$(EXEEXT): $(test_callback_OBJECTS) $(test_callback_DEPENDENCIES) $(EXTRA_test_callback_DEPENDENCIES) @rm -f test_callback$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_callback_OBJECTS) $(test_callback_LDADD) $(LIBS) test_concurrent_stop$(EXEEXT): $(test_concurrent_stop_OBJECTS) $(test_concurrent_stop_DEPENDENCIES) $(EXTRA_test_concurrent_stop_DEPENDENCIES) @rm -f test_concurrent_stop$(EXEEXT) $(AM_V_CCLD)$(test_concurrent_stop_LINK) $(test_concurrent_stop_OBJECTS) $(test_concurrent_stop_LDADD) $(LIBS) test_delete$(EXEEXT): $(test_delete_OBJECTS) $(test_delete_DEPENDENCIES) $(EXTRA_test_delete_DEPENDENCIES) @rm -f test_delete$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_delete_OBJECTS) $(test_delete_LDADD) $(LIBS) test_digestauth$(EXEEXT): $(test_digestauth_OBJECTS) $(test_digestauth_DEPENDENCIES) $(EXTRA_test_digestauth_DEPENDENCIES) @rm -f test_digestauth$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth_OBJECTS) $(test_digestauth_LDADD) $(LIBS) test_digestauth2$(EXEEXT): $(test_digestauth2_OBJECTS) $(test_digestauth2_DEPENDENCIES) $(EXTRA_test_digestauth2_DEPENDENCIES) @rm -f test_digestauth2$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_OBJECTS) $(test_digestauth2_LDADD) $(LIBS) test_digestauth2_bind_all$(EXEEXT): $(test_digestauth2_bind_all_OBJECTS) $(test_digestauth2_bind_all_DEPENDENCIES) $(EXTRA_test_digestauth2_bind_all_DEPENDENCIES) @rm -f test_digestauth2_bind_all$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_bind_all_OBJECTS) $(test_digestauth2_bind_all_LDADD) $(LIBS) test_digestauth2_bind_uri$(EXEEXT): $(test_digestauth2_bind_uri_OBJECTS) $(test_digestauth2_bind_uri_DEPENDENCIES) $(EXTRA_test_digestauth2_bind_uri_DEPENDENCIES) @rm -f test_digestauth2_bind_uri$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_bind_uri_OBJECTS) $(test_digestauth2_bind_uri_LDADD) $(LIBS) test_digestauth2_oldapi1$(EXEEXT): $(test_digestauth2_oldapi1_OBJECTS) $(test_digestauth2_oldapi1_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi1_DEPENDENCIES) @rm -f test_digestauth2_oldapi1$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi1_OBJECTS) $(test_digestauth2_oldapi1_LDADD) $(LIBS) test_digestauth2_oldapi1_bind_all$(EXEEXT): $(test_digestauth2_oldapi1_bind_all_OBJECTS) $(test_digestauth2_oldapi1_bind_all_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi1_bind_all_DEPENDENCIES) @rm -f test_digestauth2_oldapi1_bind_all$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi1_bind_all_OBJECTS) $(test_digestauth2_oldapi1_bind_all_LDADD) $(LIBS) test_digestauth2_oldapi1_bind_uri$(EXEEXT): $(test_digestauth2_oldapi1_bind_uri_OBJECTS) $(test_digestauth2_oldapi1_bind_uri_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi1_bind_uri_DEPENDENCIES) @rm -f test_digestauth2_oldapi1_bind_uri$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi1_bind_uri_OBJECTS) $(test_digestauth2_oldapi1_bind_uri_LDADD) $(LIBS) test_digestauth2_oldapi1_userdigest$(EXEEXT): $(test_digestauth2_oldapi1_userdigest_OBJECTS) $(test_digestauth2_oldapi1_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi1_userdigest_DEPENDENCIES) @rm -f test_digestauth2_oldapi1_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi1_userdigest_OBJECTS) $(test_digestauth2_oldapi1_userdigest_LDADD) $(LIBS) test_digestauth2_oldapi2$(EXEEXT): $(test_digestauth2_oldapi2_OBJECTS) $(test_digestauth2_oldapi2_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi2_DEPENDENCIES) @rm -f test_digestauth2_oldapi2$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi2_OBJECTS) $(test_digestauth2_oldapi2_LDADD) $(LIBS) test_digestauth2_oldapi2_sha256$(EXEEXT): $(test_digestauth2_oldapi2_sha256_OBJECTS) $(test_digestauth2_oldapi2_sha256_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi2_sha256_DEPENDENCIES) @rm -f test_digestauth2_oldapi2_sha256$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi2_sha256_OBJECTS) $(test_digestauth2_oldapi2_sha256_LDADD) $(LIBS) test_digestauth2_oldapi2_sha256_userdigest$(EXEEXT): $(test_digestauth2_oldapi2_sha256_userdigest_OBJECTS) $(test_digestauth2_oldapi2_sha256_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi2_sha256_userdigest_DEPENDENCIES) @rm -f test_digestauth2_oldapi2_sha256_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi2_sha256_userdigest_OBJECTS) $(test_digestauth2_oldapi2_sha256_userdigest_LDADD) $(LIBS) test_digestauth2_oldapi2_userdigest$(EXEEXT): $(test_digestauth2_oldapi2_userdigest_OBJECTS) $(test_digestauth2_oldapi2_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_oldapi2_userdigest_DEPENDENCIES) @rm -f test_digestauth2_oldapi2_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_oldapi2_userdigest_OBJECTS) $(test_digestauth2_oldapi2_userdigest_LDADD) $(LIBS) test_digestauth2_rfc2069$(EXEEXT): $(test_digestauth2_rfc2069_OBJECTS) $(test_digestauth2_rfc2069_DEPENDENCIES) $(EXTRA_test_digestauth2_rfc2069_DEPENDENCIES) @rm -f test_digestauth2_rfc2069$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_rfc2069_OBJECTS) $(test_digestauth2_rfc2069_LDADD) $(LIBS) test_digestauth2_rfc2069_userdigest$(EXEEXT): $(test_digestauth2_rfc2069_userdigest_OBJECTS) $(test_digestauth2_rfc2069_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_rfc2069_userdigest_DEPENDENCIES) @rm -f test_digestauth2_rfc2069_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_rfc2069_userdigest_OBJECTS) $(test_digestauth2_rfc2069_userdigest_LDADD) $(LIBS) test_digestauth2_sha256$(EXEEXT): $(test_digestauth2_sha256_OBJECTS) $(test_digestauth2_sha256_DEPENDENCIES) $(EXTRA_test_digestauth2_sha256_DEPENDENCIES) @rm -f test_digestauth2_sha256$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_sha256_OBJECTS) $(test_digestauth2_sha256_LDADD) $(LIBS) test_digestauth2_sha256_userdigest$(EXEEXT): $(test_digestauth2_sha256_userdigest_OBJECTS) $(test_digestauth2_sha256_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_sha256_userdigest_DEPENDENCIES) @rm -f test_digestauth2_sha256_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_sha256_userdigest_OBJECTS) $(test_digestauth2_sha256_userdigest_LDADD) $(LIBS) test_digestauth2_sha256_userhash$(EXEEXT): $(test_digestauth2_sha256_userhash_OBJECTS) $(test_digestauth2_sha256_userhash_DEPENDENCIES) $(EXTRA_test_digestauth2_sha256_userhash_DEPENDENCIES) @rm -f test_digestauth2_sha256_userhash$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_sha256_userhash_OBJECTS) $(test_digestauth2_sha256_userhash_LDADD) $(LIBS) test_digestauth2_sha256_userhash_userdigest$(EXEEXT): $(test_digestauth2_sha256_userhash_userdigest_OBJECTS) $(test_digestauth2_sha256_userhash_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_sha256_userhash_userdigest_DEPENDENCIES) @rm -f test_digestauth2_sha256_userhash_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_sha256_userhash_userdigest_OBJECTS) $(test_digestauth2_sha256_userhash_userdigest_LDADD) $(LIBS) test_digestauth2_userdigest$(EXEEXT): $(test_digestauth2_userdigest_OBJECTS) $(test_digestauth2_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_userdigest_DEPENDENCIES) @rm -f test_digestauth2_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_userdigest_OBJECTS) $(test_digestauth2_userdigest_LDADD) $(LIBS) test_digestauth2_userhash$(EXEEXT): $(test_digestauth2_userhash_OBJECTS) $(test_digestauth2_userhash_DEPENDENCIES) $(EXTRA_test_digestauth2_userhash_DEPENDENCIES) @rm -f test_digestauth2_userhash$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_userhash_OBJECTS) $(test_digestauth2_userhash_LDADD) $(LIBS) test_digestauth2_userhash_userdigest$(EXEEXT): $(test_digestauth2_userhash_userdigest_OBJECTS) $(test_digestauth2_userhash_userdigest_DEPENDENCIES) $(EXTRA_test_digestauth2_userhash_userdigest_DEPENDENCIES) @rm -f test_digestauth2_userhash_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth2_userhash_userdigest_OBJECTS) $(test_digestauth2_userhash_userdigest_LDADD) $(LIBS) test_digestauth_concurrent$(EXEEXT): $(test_digestauth_concurrent_OBJECTS) $(test_digestauth_concurrent_DEPENDENCIES) $(EXTRA_test_digestauth_concurrent_DEPENDENCIES) @rm -f test_digestauth_concurrent$(EXEEXT) $(AM_V_CCLD)$(test_digestauth_concurrent_LINK) $(test_digestauth_concurrent_OBJECTS) $(test_digestauth_concurrent_LDADD) $(LIBS) test_digestauth_emu_ext$(EXEEXT): $(test_digestauth_emu_ext_OBJECTS) $(test_digestauth_emu_ext_DEPENDENCIES) $(EXTRA_test_digestauth_emu_ext_DEPENDENCIES) @rm -f test_digestauth_emu_ext$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth_emu_ext_OBJECTS) $(test_digestauth_emu_ext_LDADD) $(LIBS) test_digestauth_emu_ext_oldapi$(EXEEXT): $(test_digestauth_emu_ext_oldapi_OBJECTS) $(test_digestauth_emu_ext_oldapi_DEPENDENCIES) $(EXTRA_test_digestauth_emu_ext_oldapi_DEPENDENCIES) @rm -f test_digestauth_emu_ext_oldapi$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth_emu_ext_oldapi_OBJECTS) $(test_digestauth_emu_ext_oldapi_LDADD) $(LIBS) test_digestauth_sha256$(EXEEXT): $(test_digestauth_sha256_OBJECTS) $(test_digestauth_sha256_DEPENDENCIES) $(EXTRA_test_digestauth_sha256_DEPENDENCIES) @rm -f test_digestauth_sha256$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth_sha256_OBJECTS) $(test_digestauth_sha256_LDADD) $(LIBS) test_digestauth_with_arguments$(EXEEXT): $(test_digestauth_with_arguments_OBJECTS) $(test_digestauth_with_arguments_DEPENDENCIES) $(EXTRA_test_digestauth_with_arguments_DEPENDENCIES) @rm -f test_digestauth_with_arguments$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digestauth_with_arguments_OBJECTS) $(test_digestauth_with_arguments_LDADD) $(LIBS) test_get$(EXEEXT): $(test_get_OBJECTS) $(test_get_DEPENDENCIES) $(EXTRA_test_get_DEPENDENCIES) @rm -f test_get$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_OBJECTS) $(test_get_LDADD) $(LIBS) test_get11$(EXEEXT): $(test_get11_OBJECTS) $(test_get11_DEPENDENCIES) $(EXTRA_test_get11_DEPENDENCIES) @rm -f test_get11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get11_OBJECTS) $(test_get11_LDADD) $(LIBS) test_get_chunked$(EXEEXT): $(test_get_chunked_OBJECTS) $(test_get_chunked_DEPENDENCIES) $(EXTRA_test_get_chunked_DEPENDENCIES) @rm -f test_get_chunked$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_OBJECTS) $(test_get_chunked_LDADD) $(LIBS) test_get_chunked_close$(EXEEXT): $(test_get_chunked_close_OBJECTS) $(test_get_chunked_close_DEPENDENCIES) $(EXTRA_test_get_chunked_close_DEPENDENCIES) @rm -f test_get_chunked_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_OBJECTS) $(test_get_chunked_close_LDADD) $(LIBS) test_get_chunked_close_empty$(EXEEXT): $(test_get_chunked_close_empty_OBJECTS) $(test_get_chunked_close_empty_DEPENDENCIES) $(EXTRA_test_get_chunked_close_empty_DEPENDENCIES) @rm -f test_get_chunked_close_empty$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_empty_OBJECTS) $(test_get_chunked_close_empty_LDADD) $(LIBS) test_get_chunked_close_empty_forced$(EXEEXT): $(test_get_chunked_close_empty_forced_OBJECTS) $(test_get_chunked_close_empty_forced_DEPENDENCIES) $(EXTRA_test_get_chunked_close_empty_forced_DEPENDENCIES) @rm -f test_get_chunked_close_empty_forced$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_empty_forced_OBJECTS) $(test_get_chunked_close_empty_forced_LDADD) $(LIBS) test_get_chunked_close_empty_sized$(EXEEXT): $(test_get_chunked_close_empty_sized_OBJECTS) $(test_get_chunked_close_empty_sized_DEPENDENCIES) $(EXTRA_test_get_chunked_close_empty_sized_DEPENDENCIES) @rm -f test_get_chunked_close_empty_sized$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_empty_sized_OBJECTS) $(test_get_chunked_close_empty_sized_LDADD) $(LIBS) test_get_chunked_close_forced$(EXEEXT): $(test_get_chunked_close_forced_OBJECTS) $(test_get_chunked_close_forced_DEPENDENCIES) $(EXTRA_test_get_chunked_close_forced_DEPENDENCIES) @rm -f test_get_chunked_close_forced$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_forced_OBJECTS) $(test_get_chunked_close_forced_LDADD) $(LIBS) test_get_chunked_close_sized$(EXEEXT): $(test_get_chunked_close_sized_OBJECTS) $(test_get_chunked_close_sized_DEPENDENCIES) $(EXTRA_test_get_chunked_close_sized_DEPENDENCIES) @rm -f test_get_chunked_close_sized$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_sized_OBJECTS) $(test_get_chunked_close_sized_LDADD) $(LIBS) test_get_chunked_close_string$(EXEEXT): $(test_get_chunked_close_string_OBJECTS) $(test_get_chunked_close_string_DEPENDENCIES) $(EXTRA_test_get_chunked_close_string_DEPENDENCIES) @rm -f test_get_chunked_close_string$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_string_OBJECTS) $(test_get_chunked_close_string_LDADD) $(LIBS) test_get_chunked_close_string_empty$(EXEEXT): $(test_get_chunked_close_string_empty_OBJECTS) $(test_get_chunked_close_string_empty_DEPENDENCIES) $(EXTRA_test_get_chunked_close_string_empty_DEPENDENCIES) @rm -f test_get_chunked_close_string_empty$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_string_empty_OBJECTS) $(test_get_chunked_close_string_empty_LDADD) $(LIBS) test_get_chunked_empty$(EXEEXT): $(test_get_chunked_empty_OBJECTS) $(test_get_chunked_empty_DEPENDENCIES) $(EXTRA_test_get_chunked_empty_DEPENDENCIES) @rm -f test_get_chunked_empty$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_empty_OBJECTS) $(test_get_chunked_empty_LDADD) $(LIBS) test_get_chunked_empty_forced$(EXEEXT): $(test_get_chunked_empty_forced_OBJECTS) $(test_get_chunked_empty_forced_DEPENDENCIES) $(EXTRA_test_get_chunked_empty_forced_DEPENDENCIES) @rm -f test_get_chunked_empty_forced$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_empty_forced_OBJECTS) $(test_get_chunked_empty_forced_LDADD) $(LIBS) test_get_chunked_empty_sized$(EXEEXT): $(test_get_chunked_empty_sized_OBJECTS) $(test_get_chunked_empty_sized_DEPENDENCIES) $(EXTRA_test_get_chunked_empty_sized_DEPENDENCIES) @rm -f test_get_chunked_empty_sized$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_empty_sized_OBJECTS) $(test_get_chunked_empty_sized_LDADD) $(LIBS) test_get_chunked_forced$(EXEEXT): $(test_get_chunked_forced_OBJECTS) $(test_get_chunked_forced_DEPENDENCIES) $(EXTRA_test_get_chunked_forced_DEPENDENCIES) @rm -f test_get_chunked_forced$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_forced_OBJECTS) $(test_get_chunked_forced_LDADD) $(LIBS) test_get_chunked_sized$(EXEEXT): $(test_get_chunked_sized_OBJECTS) $(test_get_chunked_sized_DEPENDENCIES) $(EXTRA_test_get_chunked_sized_DEPENDENCIES) @rm -f test_get_chunked_sized$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_sized_OBJECTS) $(test_get_chunked_sized_LDADD) $(LIBS) test_get_chunked_string$(EXEEXT): $(test_get_chunked_string_OBJECTS) $(test_get_chunked_string_DEPENDENCIES) $(EXTRA_test_get_chunked_string_DEPENDENCIES) @rm -f test_get_chunked_string$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_string_OBJECTS) $(test_get_chunked_string_LDADD) $(LIBS) test_get_chunked_string_empty$(EXEEXT): $(test_get_chunked_string_empty_OBJECTS) $(test_get_chunked_string_empty_DEPENDENCIES) $(EXTRA_test_get_chunked_string_empty_DEPENDENCIES) @rm -f test_get_chunked_string_empty$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_string_empty_OBJECTS) $(test_get_chunked_string_empty_LDADD) $(LIBS) test_get_close$(EXEEXT): $(test_get_close_OBJECTS) $(test_get_close_DEPENDENCIES) $(EXTRA_test_get_close_DEPENDENCIES) @rm -f test_get_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_close_OBJECTS) $(test_get_close_LDADD) $(LIBS) test_get_close10$(EXEEXT): $(test_get_close10_OBJECTS) $(test_get_close10_DEPENDENCIES) $(EXTRA_test_get_close10_DEPENDENCIES) @rm -f test_get_close10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_close10_OBJECTS) $(test_get_close10_LDADD) $(LIBS) test_get_header_double_fold$(EXEEXT): $(test_get_header_double_fold_OBJECTS) $(test_get_header_double_fold_DEPENDENCIES) $(EXTRA_test_get_header_double_fold_DEPENDENCIES) @rm -f test_get_header_double_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_header_double_fold_OBJECTS) $(test_get_header_double_fold_LDADD) $(LIBS) test_get_header_fold$(EXEEXT): $(test_get_header_fold_OBJECTS) $(test_get_header_fold_DEPENDENCIES) $(EXTRA_test_get_header_fold_DEPENDENCIES) @rm -f test_get_header_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_header_fold_OBJECTS) $(test_get_header_fold_LDADD) $(LIBS) test_get_iovec$(EXEEXT): $(test_get_iovec_OBJECTS) $(test_get_iovec_DEPENDENCIES) $(EXTRA_test_get_iovec_DEPENDENCIES) @rm -f test_get_iovec$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_iovec_OBJECTS) $(test_get_iovec_LDADD) $(LIBS) test_get_iovec11$(EXEEXT): $(test_get_iovec11_OBJECTS) $(test_get_iovec11_DEPENDENCIES) $(EXTRA_test_get_iovec11_DEPENDENCIES) @rm -f test_get_iovec11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_iovec11_OBJECTS) $(test_get_iovec11_LDADD) $(LIBS) test_get_keep_alive$(EXEEXT): $(test_get_keep_alive_OBJECTS) $(test_get_keep_alive_DEPENDENCIES) $(EXTRA_test_get_keep_alive_DEPENDENCIES) @rm -f test_get_keep_alive$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_keep_alive_OBJECTS) $(test_get_keep_alive_LDADD) $(LIBS) test_get_keep_alive10$(EXEEXT): $(test_get_keep_alive10_OBJECTS) $(test_get_keep_alive10_DEPENDENCIES) $(EXTRA_test_get_keep_alive10_DEPENDENCIES) @rm -f test_get_keep_alive10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_keep_alive10_OBJECTS) $(test_get_keep_alive10_LDADD) $(LIBS) test_get_response_cleanup$(EXEEXT): $(test_get_response_cleanup_OBJECTS) $(test_get_response_cleanup_DEPENDENCIES) $(EXTRA_test_get_response_cleanup_DEPENDENCIES) @rm -f test_get_response_cleanup$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_response_cleanup_OBJECTS) $(test_get_response_cleanup_LDADD) $(LIBS) test_get_sendfile$(EXEEXT): $(test_get_sendfile_OBJECTS) $(test_get_sendfile_DEPENDENCIES) $(EXTRA_test_get_sendfile_DEPENDENCIES) @rm -f test_get_sendfile$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_sendfile_OBJECTS) $(test_get_sendfile_LDADD) $(LIBS) test_get_sendfile11$(EXEEXT): $(test_get_sendfile11_OBJECTS) $(test_get_sendfile11_DEPENDENCIES) $(EXTRA_test_get_sendfile11_DEPENDENCIES) @rm -f test_get_sendfile11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_sendfile11_OBJECTS) $(test_get_sendfile11_LDADD) $(LIBS) test_get_wait$(EXEEXT): $(test_get_wait_OBJECTS) $(test_get_wait_DEPENDENCIES) $(EXTRA_test_get_wait_DEPENDENCIES) @rm -f test_get_wait$(EXEEXT) $(AM_V_CCLD)$(test_get_wait_LINK) $(test_get_wait_OBJECTS) $(test_get_wait_LDADD) $(LIBS) test_get_wait11$(EXEEXT): $(test_get_wait11_OBJECTS) $(test_get_wait11_DEPENDENCIES) $(EXTRA_test_get_wait11_DEPENDENCIES) @rm -f test_get_wait11$(EXEEXT) $(AM_V_CCLD)$(test_get_wait11_LINK) $(test_get_wait11_OBJECTS) $(test_get_wait11_LDADD) $(LIBS) test_head$(EXEEXT): $(test_head_OBJECTS) $(test_head_DEPENDENCIES) $(EXTRA_test_head_DEPENDENCIES) @rm -f test_head$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_head_OBJECTS) $(test_head_LDADD) $(LIBS) test_head10$(EXEEXT): $(test_head10_OBJECTS) $(test_head10_DEPENDENCIES) $(EXTRA_test_head10_DEPENDENCIES) @rm -f test_head10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_head10_OBJECTS) $(test_head10_LDADD) $(LIBS) test_iplimit11$(EXEEXT): $(test_iplimit11_OBJECTS) $(test_iplimit11_DEPENDENCIES) $(EXTRA_test_iplimit11_DEPENDENCIES) @rm -f test_iplimit11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_iplimit11_OBJECTS) $(test_iplimit11_LDADD) $(LIBS) test_large_put$(EXEEXT): $(test_large_put_OBJECTS) $(test_large_put_DEPENDENCIES) $(EXTRA_test_large_put_DEPENDENCIES) @rm -f test_large_put$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_large_put_OBJECTS) $(test_large_put_LDADD) $(LIBS) test_large_put11$(EXEEXT): $(test_large_put11_OBJECTS) $(test_large_put11_DEPENDENCIES) $(EXTRA_test_large_put11_DEPENDENCIES) @rm -f test_large_put11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_large_put11_OBJECTS) $(test_large_put11_LDADD) $(LIBS) test_large_put_inc11$(EXEEXT): $(test_large_put_inc11_OBJECTS) $(test_large_put_inc11_DEPENDENCIES) $(EXTRA_test_large_put_inc11_DEPENDENCIES) @rm -f test_large_put_inc11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_large_put_inc11_OBJECTS) $(test_large_put_inc11_LDADD) $(LIBS) test_long_header$(EXEEXT): $(test_long_header_OBJECTS) $(test_long_header_DEPENDENCIES) $(EXTRA_test_long_header_DEPENDENCIES) @rm -f test_long_header$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_long_header_OBJECTS) $(test_long_header_LDADD) $(LIBS) test_long_header11$(EXEEXT): $(test_long_header11_OBJECTS) $(test_long_header11_DEPENDENCIES) $(EXTRA_test_long_header11_DEPENDENCIES) @rm -f test_long_header11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_long_header11_OBJECTS) $(test_long_header11_LDADD) $(LIBS) test_parse_cookies_discp_n2$(EXEEXT): $(test_parse_cookies_discp_n2_OBJECTS) $(test_parse_cookies_discp_n2_DEPENDENCIES) $(EXTRA_test_parse_cookies_discp_n2_DEPENDENCIES) @rm -f test_parse_cookies_discp_n2$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_parse_cookies_discp_n2_OBJECTS) $(test_parse_cookies_discp_n2_LDADD) $(LIBS) test_parse_cookies_discp_n3$(EXEEXT): $(test_parse_cookies_discp_n3_OBJECTS) $(test_parse_cookies_discp_n3_DEPENDENCIES) $(EXTRA_test_parse_cookies_discp_n3_DEPENDENCIES) @rm -f test_parse_cookies_discp_n3$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_parse_cookies_discp_n3_OBJECTS) $(test_parse_cookies_discp_n3_LDADD) $(LIBS) test_parse_cookies_discp_p1$(EXEEXT): $(test_parse_cookies_discp_p1_OBJECTS) $(test_parse_cookies_discp_p1_DEPENDENCIES) $(EXTRA_test_parse_cookies_discp_p1_DEPENDENCIES) @rm -f test_parse_cookies_discp_p1$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_parse_cookies_discp_p1_OBJECTS) $(test_parse_cookies_discp_p1_LDADD) $(LIBS) test_parse_cookies_discp_p2$(EXEEXT): $(test_parse_cookies_discp_p2_OBJECTS) $(test_parse_cookies_discp_p2_DEPENDENCIES) $(EXTRA_test_parse_cookies_discp_p2_DEPENDENCIES) @rm -f test_parse_cookies_discp_p2$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_parse_cookies_discp_p2_OBJECTS) $(test_parse_cookies_discp_p2_LDADD) $(LIBS) test_parse_cookies_discp_zero$(EXEEXT): $(test_parse_cookies_discp_zero_OBJECTS) $(test_parse_cookies_discp_zero_DEPENDENCIES) $(EXTRA_test_parse_cookies_discp_zero_DEPENDENCIES) @rm -f test_parse_cookies_discp_zero$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_parse_cookies_discp_zero_OBJECTS) $(test_parse_cookies_discp_zero_LDADD) $(LIBS) test_patch$(EXEEXT): $(test_patch_OBJECTS) $(test_patch_DEPENDENCIES) $(EXTRA_test_patch_DEPENDENCIES) @rm -f test_patch$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_patch_OBJECTS) $(test_patch_LDADD) $(LIBS) test_patch11$(EXEEXT): $(test_patch11_OBJECTS) $(test_patch11_DEPENDENCIES) $(EXTRA_test_patch11_DEPENDENCIES) @rm -f test_patch11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_patch11_OBJECTS) $(test_patch11_LDADD) $(LIBS) test_post$(EXEEXT): $(test_post_OBJECTS) $(test_post_DEPENDENCIES) $(EXTRA_test_post_DEPENDENCIES) @rm -f test_post$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_OBJECTS) $(test_post_LDADD) $(LIBS) test_post11$(EXEEXT): $(test_post11_OBJECTS) $(test_post11_DEPENDENCIES) $(EXTRA_test_post11_DEPENDENCIES) @rm -f test_post11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post11_OBJECTS) $(test_post11_LDADD) $(LIBS) test_post_loop$(EXEEXT): $(test_post_loop_OBJECTS) $(test_post_loop_DEPENDENCIES) $(EXTRA_test_post_loop_DEPENDENCIES) @rm -f test_post_loop$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_loop_OBJECTS) $(test_post_loop_LDADD) $(LIBS) test_post_loop11$(EXEEXT): $(test_post_loop11_OBJECTS) $(test_post_loop11_DEPENDENCIES) $(EXTRA_test_post_loop11_DEPENDENCIES) @rm -f test_post_loop11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_loop11_OBJECTS) $(test_post_loop11_LDADD) $(LIBS) test_postform$(EXEEXT): $(test_postform_OBJECTS) $(test_postform_DEPENDENCIES) $(EXTRA_test_postform_DEPENDENCIES) @rm -f test_postform$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_postform_OBJECTS) $(test_postform_LDADD) $(LIBS) test_postform11$(EXEEXT): $(test_postform11_OBJECTS) $(test_postform11_DEPENDENCIES) $(EXTRA_test_postform11_DEPENDENCIES) @rm -f test_postform11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_postform11_OBJECTS) $(test_postform11_LDADD) $(LIBS) test_process_arguments$(EXEEXT): $(test_process_arguments_OBJECTS) $(test_process_arguments_DEPENDENCIES) $(EXTRA_test_process_arguments_DEPENDENCIES) @rm -f test_process_arguments$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_process_arguments_OBJECTS) $(test_process_arguments_LDADD) $(LIBS) test_process_headers$(EXEEXT): $(test_process_headers_OBJECTS) $(test_process_headers_DEPENDENCIES) $(EXTRA_test_process_headers_DEPENDENCIES) @rm -f test_process_headers$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_process_headers_OBJECTS) $(test_process_headers_LDADD) $(LIBS) test_put$(EXEEXT): $(test_put_OBJECTS) $(test_put_DEPENDENCIES) $(EXTRA_test_put_DEPENDENCIES) @rm -f test_put$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_OBJECTS) $(test_put_LDADD) $(LIBS) test_put11$(EXEEXT): $(test_put11_OBJECTS) $(test_put11_DEPENDENCIES) $(EXTRA_test_put11_DEPENDENCIES) @rm -f test_put11$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put11_OBJECTS) $(test_put11_LDADD) $(LIBS) test_put_broken_len$(EXEEXT): $(test_put_broken_len_OBJECTS) $(test_put_broken_len_DEPENDENCIES) $(EXTRA_test_put_broken_len_DEPENDENCIES) @rm -f test_put_broken_len$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_broken_len_OBJECTS) $(test_put_broken_len_LDADD) $(LIBS) test_put_broken_len10$(EXEEXT): $(test_put_broken_len10_OBJECTS) $(test_put_broken_len10_DEPENDENCIES) $(EXTRA_test_put_broken_len10_DEPENDENCIES) @rm -f test_put_broken_len10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_broken_len10_OBJECTS) $(test_put_broken_len10_LDADD) $(LIBS) test_put_chunked$(EXEEXT): $(test_put_chunked_OBJECTS) $(test_put_chunked_DEPENDENCIES) $(EXTRA_test_put_chunked_DEPENDENCIES) @rm -f test_put_chunked$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_chunked_OBJECTS) $(test_put_chunked_LDADD) $(LIBS) test_put_header_double_fold$(EXEEXT): $(test_put_header_double_fold_OBJECTS) $(test_put_header_double_fold_DEPENDENCIES) $(EXTRA_test_put_header_double_fold_DEPENDENCIES) @rm -f test_put_header_double_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_double_fold_OBJECTS) $(test_put_header_double_fold_LDADD) $(LIBS) test_put_header_double_fold_large$(EXEEXT): $(test_put_header_double_fold_large_OBJECTS) $(test_put_header_double_fold_large_DEPENDENCIES) $(EXTRA_test_put_header_double_fold_large_DEPENDENCIES) @rm -f test_put_header_double_fold_large$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_double_fold_large_OBJECTS) $(test_put_header_double_fold_large_LDADD) $(LIBS) test_put_header_double_fold_last$(EXEEXT): $(test_put_header_double_fold_last_OBJECTS) $(test_put_header_double_fold_last_DEPENDENCIES) $(EXTRA_test_put_header_double_fold_last_DEPENDENCIES) @rm -f test_put_header_double_fold_last$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_double_fold_last_OBJECTS) $(test_put_header_double_fold_last_LDADD) $(LIBS) test_put_header_fold$(EXEEXT): $(test_put_header_fold_OBJECTS) $(test_put_header_fold_DEPENDENCIES) $(EXTRA_test_put_header_fold_DEPENDENCIES) @rm -f test_put_header_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_fold_OBJECTS) $(test_put_header_fold_LDADD) $(LIBS) test_put_header_fold_large$(EXEEXT): $(test_put_header_fold_large_OBJECTS) $(test_put_header_fold_large_DEPENDENCIES) $(EXTRA_test_put_header_fold_large_DEPENDENCIES) @rm -f test_put_header_fold_large$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_fold_large_OBJECTS) $(test_put_header_fold_large_LDADD) $(LIBS) test_put_header_fold_last$(EXEEXT): $(test_put_header_fold_last_OBJECTS) $(test_put_header_fold_last_DEPENDENCIES) $(EXTRA_test_put_header_fold_last_DEPENDENCIES) @rm -f test_put_header_fold_last$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_header_fold_last_OBJECTS) $(test_put_header_fold_last_LDADD) $(LIBS) test_put_large_header_double_fold$(EXEEXT): $(test_put_large_header_double_fold_OBJECTS) $(test_put_large_header_double_fold_DEPENDENCIES) $(EXTRA_test_put_large_header_double_fold_DEPENDENCIES) @rm -f test_put_large_header_double_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large_header_double_fold_OBJECTS) $(test_put_large_header_double_fold_LDADD) $(LIBS) test_put_large_header_fold$(EXEEXT): $(test_put_large_header_fold_OBJECTS) $(test_put_large_header_fold_DEPENDENCIES) $(EXTRA_test_put_large_header_fold_DEPENDENCIES) @rm -f test_put_large_header_fold$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large_header_fold_OBJECTS) $(test_put_large_header_fold_LDADD) $(LIBS) test_quiesce$(EXEEXT): $(test_quiesce_OBJECTS) $(test_quiesce_DEPENDENCIES) $(EXTRA_test_quiesce_DEPENDENCIES) @rm -f test_quiesce$(EXEEXT) $(AM_V_CCLD)$(test_quiesce_LINK) $(test_quiesce_OBJECTS) $(test_quiesce_LDADD) $(LIBS) test_quiesce_stream$(EXEEXT): $(test_quiesce_stream_OBJECTS) $(test_quiesce_stream_DEPENDENCIES) $(EXTRA_test_quiesce_stream_DEPENDENCIES) @rm -f test_quiesce_stream$(EXEEXT) $(AM_V_CCLD)$(test_quiesce_stream_LINK) $(test_quiesce_stream_OBJECTS) $(test_quiesce_stream_LDADD) $(LIBS) test_suspend_resume_thread$(EXEEXT): $(test_suspend_resume_thread_OBJECTS) $(test_suspend_resume_thread_DEPENDENCIES) $(EXTRA_test_suspend_resume_thread_DEPENDENCIES) @rm -f test_suspend_resume_thread$(EXEEXT) $(AM_V_CCLD)$(test_suspend_resume_thread_LINK) $(test_suspend_resume_thread_OBJECTS) $(test_suspend_resume_thread_LDADD) $(LIBS) test_termination$(EXEEXT): $(test_termination_OBJECTS) $(test_termination_DEPENDENCIES) $(EXTRA_test_termination_DEPENDENCIES) @rm -f test_termination$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_termination_OBJECTS) $(test_termination_LDADD) $(LIBS) test_timeout$(EXEEXT): $(test_timeout_OBJECTS) $(test_timeout_DEPENDENCIES) $(EXTRA_test_timeout_DEPENDENCIES) @rm -f test_timeout$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_timeout_OBJECTS) $(test_timeout_LDADD) $(LIBS) test_toolarge_method$(EXEEXT): $(test_toolarge_method_OBJECTS) $(test_toolarge_method_DEPENDENCIES) $(EXTRA_test_toolarge_method_DEPENDENCIES) @rm -f test_toolarge_method$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_method_OBJECTS) $(test_toolarge_method_LDADD) $(LIBS) test_toolarge_reply_header_name$(EXEEXT): $(test_toolarge_reply_header_name_OBJECTS) $(test_toolarge_reply_header_name_DEPENDENCIES) $(EXTRA_test_toolarge_reply_header_name_DEPENDENCIES) @rm -f test_toolarge_reply_header_name$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_reply_header_name_OBJECTS) $(test_toolarge_reply_header_name_LDADD) $(LIBS) test_toolarge_reply_header_value$(EXEEXT): $(test_toolarge_reply_header_value_OBJECTS) $(test_toolarge_reply_header_value_DEPENDENCIES) $(EXTRA_test_toolarge_reply_header_value_DEPENDENCIES) @rm -f test_toolarge_reply_header_value$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_reply_header_value_OBJECTS) $(test_toolarge_reply_header_value_LDADD) $(LIBS) test_toolarge_reply_headers$(EXEEXT): $(test_toolarge_reply_headers_OBJECTS) $(test_toolarge_reply_headers_DEPENDENCIES) $(EXTRA_test_toolarge_reply_headers_DEPENDENCIES) @rm -f test_toolarge_reply_headers$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_reply_headers_OBJECTS) $(test_toolarge_reply_headers_LDADD) $(LIBS) test_toolarge_request_header_name$(EXEEXT): $(test_toolarge_request_header_name_OBJECTS) $(test_toolarge_request_header_name_DEPENDENCIES) $(EXTRA_test_toolarge_request_header_name_DEPENDENCIES) @rm -f test_toolarge_request_header_name$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_request_header_name_OBJECTS) $(test_toolarge_request_header_name_LDADD) $(LIBS) test_toolarge_request_header_value$(EXEEXT): $(test_toolarge_request_header_value_OBJECTS) $(test_toolarge_request_header_value_DEPENDENCIES) $(EXTRA_test_toolarge_request_header_value_DEPENDENCIES) @rm -f test_toolarge_request_header_value$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_request_header_value_OBJECTS) $(test_toolarge_request_header_value_LDADD) $(LIBS) test_toolarge_request_headers$(EXEEXT): $(test_toolarge_request_headers_OBJECTS) $(test_toolarge_request_headers_DEPENDENCIES) $(EXTRA_test_toolarge_request_headers_DEPENDENCIES) @rm -f test_toolarge_request_headers$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_request_headers_OBJECTS) $(test_toolarge_request_headers_LDADD) $(LIBS) test_toolarge_url$(EXEEXT): $(test_toolarge_url_OBJECTS) $(test_toolarge_url_DEPENDENCIES) $(EXTRA_test_toolarge_url_DEPENDENCIES) @rm -f test_toolarge_url$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_toolarge_url_OBJECTS) $(test_toolarge_url_LDADD) $(LIBS) test_tricky_header2$(EXEEXT): $(test_tricky_header2_OBJECTS) $(test_tricky_header2_DEPENDENCIES) $(EXTRA_test_tricky_header2_DEPENDENCIES) @rm -f test_tricky_header2$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_tricky_header2_OBJECTS) $(test_tricky_header2_LDADD) $(LIBS) test_tricky_url$(EXEEXT): $(test_tricky_url_OBJECTS) $(test_tricky_url_DEPENDENCIES) $(EXTRA_test_tricky_url_DEPENDENCIES) @rm -f test_tricky_url$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_tricky_url_OBJECTS) $(test_tricky_url_LDADD) $(LIBS) test_urlparse$(EXEEXT): $(test_urlparse_OBJECTS) $(test_urlparse_DEPENDENCIES) $(EXTRA_test_urlparse_DEPENDENCIES) @rm -f test_urlparse$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_urlparse_OBJECTS) $(test_urlparse_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/perf_get.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_add_conn-test_add_conn.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_basicauth.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_callback.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_delete.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth2.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth_emu_ext.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth_sha256.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digestauth_with_arguments.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_chunked.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_close_keep_alive.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_iovec.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_response_cleanup.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_sendfile.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_wait-test_get_wait.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_wait11-test_get_wait.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_head.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_iplimit.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_large_put.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_long_header.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_parse_cookies.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_patch.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_post.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_post_loop.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postform.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_process_arguments.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_process_headers.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put_broken_len.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put_chunked.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_put_header_fold.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_quiesce-test_quiesce.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_suspend_resume_thread-test_suspend_resume_thread.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_termination.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_timeout.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_toolarge.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_tricky.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_urlparse.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @: >>$@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< perf_get_concurrent-perf_get_concurrent.o: perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent_CFLAGS) $(CFLAGS) -MT perf_get_concurrent-perf_get_concurrent.o -MD -MP -MF $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Tpo -c -o perf_get_concurrent-perf_get_concurrent.o `test -f 'perf_get_concurrent.c' || echo '$(srcdir)/'`perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Tpo $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='perf_get_concurrent.c' object='perf_get_concurrent-perf_get_concurrent.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent_CFLAGS) $(CFLAGS) -c -o perf_get_concurrent-perf_get_concurrent.o `test -f 'perf_get_concurrent.c' || echo '$(srcdir)/'`perf_get_concurrent.c perf_get_concurrent-perf_get_concurrent.obj: perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent_CFLAGS) $(CFLAGS) -MT perf_get_concurrent-perf_get_concurrent.obj -MD -MP -MF $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Tpo -c -o perf_get_concurrent-perf_get_concurrent.obj `if test -f 'perf_get_concurrent.c'; then $(CYGPATH_W) 'perf_get_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/perf_get_concurrent.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Tpo $(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='perf_get_concurrent.c' object='perf_get_concurrent-perf_get_concurrent.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent_CFLAGS) $(CFLAGS) -c -o perf_get_concurrent-perf_get_concurrent.obj `if test -f 'perf_get_concurrent.c'; then $(CYGPATH_W) 'perf_get_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/perf_get_concurrent.c'; fi` perf_get_concurrent11-perf_get_concurrent.o: perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent11_CFLAGS) $(CFLAGS) -MT perf_get_concurrent11-perf_get_concurrent.o -MD -MP -MF $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Tpo -c -o perf_get_concurrent11-perf_get_concurrent.o `test -f 'perf_get_concurrent.c' || echo '$(srcdir)/'`perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Tpo $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='perf_get_concurrent.c' object='perf_get_concurrent11-perf_get_concurrent.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent11_CFLAGS) $(CFLAGS) -c -o perf_get_concurrent11-perf_get_concurrent.o `test -f 'perf_get_concurrent.c' || echo '$(srcdir)/'`perf_get_concurrent.c perf_get_concurrent11-perf_get_concurrent.obj: perf_get_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent11_CFLAGS) $(CFLAGS) -MT perf_get_concurrent11-perf_get_concurrent.obj -MD -MP -MF $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Tpo -c -o perf_get_concurrent11-perf_get_concurrent.obj `if test -f 'perf_get_concurrent.c'; then $(CYGPATH_W) 'perf_get_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/perf_get_concurrent.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Tpo $(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='perf_get_concurrent.c' object='perf_get_concurrent11-perf_get_concurrent.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(perf_get_concurrent11_CFLAGS) $(CFLAGS) -c -o perf_get_concurrent11-perf_get_concurrent.obj `if test -f 'perf_get_concurrent.c'; then $(CYGPATH_W) 'perf_get_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/perf_get_concurrent.c'; fi` test_add_conn-test_add_conn.o: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_CFLAGS) $(CFLAGS) -MT test_add_conn-test_add_conn.o -MD -MP -MF $(DEPDIR)/test_add_conn-test_add_conn.Tpo -c -o test_add_conn-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn-test_add_conn.Tpo $(DEPDIR)/test_add_conn-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn-test_add_conn.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_CFLAGS) $(CFLAGS) -c -o test_add_conn-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c test_add_conn-test_add_conn.obj: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_CFLAGS) $(CFLAGS) -MT test_add_conn-test_add_conn.obj -MD -MP -MF $(DEPDIR)/test_add_conn-test_add_conn.Tpo -c -o test_add_conn-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn-test_add_conn.Tpo $(DEPDIR)/test_add_conn-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn-test_add_conn.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_CFLAGS) $(CFLAGS) -c -o test_add_conn-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` test_add_conn_cleanup-test_add_conn.o: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_CFLAGS) $(CFLAGS) -MT test_add_conn_cleanup-test_add_conn.o -MD -MP -MF $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Tpo -c -o test_add_conn_cleanup-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Tpo $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_cleanup-test_add_conn.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_CFLAGS) $(CFLAGS) -c -o test_add_conn_cleanup-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c test_add_conn_cleanup-test_add_conn.obj: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_CFLAGS) $(CFLAGS) -MT test_add_conn_cleanup-test_add_conn.obj -MD -MP -MF $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Tpo -c -o test_add_conn_cleanup-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Tpo $(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_cleanup-test_add_conn.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_CFLAGS) $(CFLAGS) -c -o test_add_conn_cleanup-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` test_add_conn_cleanup_nolisten-test_add_conn.o: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_nolisten_CFLAGS) $(CFLAGS) -MT test_add_conn_cleanup_nolisten-test_add_conn.o -MD -MP -MF $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Tpo -c -o test_add_conn_cleanup_nolisten-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Tpo $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_cleanup_nolisten-test_add_conn.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_nolisten_CFLAGS) $(CFLAGS) -c -o test_add_conn_cleanup_nolisten-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c test_add_conn_cleanup_nolisten-test_add_conn.obj: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_nolisten_CFLAGS) $(CFLAGS) -MT test_add_conn_cleanup_nolisten-test_add_conn.obj -MD -MP -MF $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Tpo -c -o test_add_conn_cleanup_nolisten-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Tpo $(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_cleanup_nolisten-test_add_conn.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_cleanup_nolisten_CFLAGS) $(CFLAGS) -c -o test_add_conn_cleanup_nolisten-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` test_add_conn_nolisten-test_add_conn.o: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_nolisten_CFLAGS) $(CFLAGS) -MT test_add_conn_nolisten-test_add_conn.o -MD -MP -MF $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Tpo -c -o test_add_conn_nolisten-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Tpo $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_nolisten-test_add_conn.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_nolisten_CFLAGS) $(CFLAGS) -c -o test_add_conn_nolisten-test_add_conn.o `test -f 'test_add_conn.c' || echo '$(srcdir)/'`test_add_conn.c test_add_conn_nolisten-test_add_conn.obj: test_add_conn.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_nolisten_CFLAGS) $(CFLAGS) -MT test_add_conn_nolisten-test_add_conn.obj -MD -MP -MF $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Tpo -c -o test_add_conn_nolisten-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Tpo $(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_add_conn.c' object='test_add_conn_nolisten-test_add_conn.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_add_conn_nolisten_CFLAGS) $(CFLAGS) -c -o test_add_conn_nolisten-test_add_conn.obj `if test -f 'test_add_conn.c'; then $(CYGPATH_W) 'test_add_conn.c'; else $(CYGPATH_W) '$(srcdir)/test_add_conn.c'; fi` test_concurrent_stop-test_concurrent_stop.o: test_concurrent_stop.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_concurrent_stop_CFLAGS) $(CFLAGS) -MT test_concurrent_stop-test_concurrent_stop.o -MD -MP -MF $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Tpo -c -o test_concurrent_stop-test_concurrent_stop.o `test -f 'test_concurrent_stop.c' || echo '$(srcdir)/'`test_concurrent_stop.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Tpo $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_concurrent_stop.c' object='test_concurrent_stop-test_concurrent_stop.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_concurrent_stop_CFLAGS) $(CFLAGS) -c -o test_concurrent_stop-test_concurrent_stop.o `test -f 'test_concurrent_stop.c' || echo '$(srcdir)/'`test_concurrent_stop.c test_concurrent_stop-test_concurrent_stop.obj: test_concurrent_stop.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_concurrent_stop_CFLAGS) $(CFLAGS) -MT test_concurrent_stop-test_concurrent_stop.obj -MD -MP -MF $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Tpo -c -o test_concurrent_stop-test_concurrent_stop.obj `if test -f 'test_concurrent_stop.c'; then $(CYGPATH_W) 'test_concurrent_stop.c'; else $(CYGPATH_W) '$(srcdir)/test_concurrent_stop.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Tpo $(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_concurrent_stop.c' object='test_concurrent_stop-test_concurrent_stop.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_concurrent_stop_CFLAGS) $(CFLAGS) -c -o test_concurrent_stop-test_concurrent_stop.obj `if test -f 'test_concurrent_stop.c'; then $(CYGPATH_W) 'test_concurrent_stop.c'; else $(CYGPATH_W) '$(srcdir)/test_concurrent_stop.c'; fi` test_digestauth_concurrent-test_digestauth_concurrent.o: test_digestauth_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_digestauth_concurrent_CFLAGS) $(CFLAGS) -MT test_digestauth_concurrent-test_digestauth_concurrent.o -MD -MP -MF $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Tpo -c -o test_digestauth_concurrent-test_digestauth_concurrent.o `test -f 'test_digestauth_concurrent.c' || echo '$(srcdir)/'`test_digestauth_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Tpo $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_digestauth_concurrent.c' object='test_digestauth_concurrent-test_digestauth_concurrent.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_digestauth_concurrent_CFLAGS) $(CFLAGS) -c -o test_digestauth_concurrent-test_digestauth_concurrent.o `test -f 'test_digestauth_concurrent.c' || echo '$(srcdir)/'`test_digestauth_concurrent.c test_digestauth_concurrent-test_digestauth_concurrent.obj: test_digestauth_concurrent.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_digestauth_concurrent_CFLAGS) $(CFLAGS) -MT test_digestauth_concurrent-test_digestauth_concurrent.obj -MD -MP -MF $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Tpo -c -o test_digestauth_concurrent-test_digestauth_concurrent.obj `if test -f 'test_digestauth_concurrent.c'; then $(CYGPATH_W) 'test_digestauth_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/test_digestauth_concurrent.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Tpo $(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_digestauth_concurrent.c' object='test_digestauth_concurrent-test_digestauth_concurrent.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_digestauth_concurrent_CFLAGS) $(CFLAGS) -c -o test_digestauth_concurrent-test_digestauth_concurrent.obj `if test -f 'test_digestauth_concurrent.c'; then $(CYGPATH_W) 'test_digestauth_concurrent.c'; else $(CYGPATH_W) '$(srcdir)/test_digestauth_concurrent.c'; fi` test_get_wait-test_get_wait.o: test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait_CFLAGS) $(CFLAGS) -MT test_get_wait-test_get_wait.o -MD -MP -MF $(DEPDIR)/test_get_wait-test_get_wait.Tpo -c -o test_get_wait-test_get_wait.o `test -f 'test_get_wait.c' || echo '$(srcdir)/'`test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_get_wait-test_get_wait.Tpo $(DEPDIR)/test_get_wait-test_get_wait.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_get_wait.c' object='test_get_wait-test_get_wait.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait_CFLAGS) $(CFLAGS) -c -o test_get_wait-test_get_wait.o `test -f 'test_get_wait.c' || echo '$(srcdir)/'`test_get_wait.c test_get_wait-test_get_wait.obj: test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait_CFLAGS) $(CFLAGS) -MT test_get_wait-test_get_wait.obj -MD -MP -MF $(DEPDIR)/test_get_wait-test_get_wait.Tpo -c -o test_get_wait-test_get_wait.obj `if test -f 'test_get_wait.c'; then $(CYGPATH_W) 'test_get_wait.c'; else $(CYGPATH_W) '$(srcdir)/test_get_wait.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_get_wait-test_get_wait.Tpo $(DEPDIR)/test_get_wait-test_get_wait.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_get_wait.c' object='test_get_wait-test_get_wait.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait_CFLAGS) $(CFLAGS) -c -o test_get_wait-test_get_wait.obj `if test -f 'test_get_wait.c'; then $(CYGPATH_W) 'test_get_wait.c'; else $(CYGPATH_W) '$(srcdir)/test_get_wait.c'; fi` test_get_wait11-test_get_wait.o: test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait11_CFLAGS) $(CFLAGS) -MT test_get_wait11-test_get_wait.o -MD -MP -MF $(DEPDIR)/test_get_wait11-test_get_wait.Tpo -c -o test_get_wait11-test_get_wait.o `test -f 'test_get_wait.c' || echo '$(srcdir)/'`test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_get_wait11-test_get_wait.Tpo $(DEPDIR)/test_get_wait11-test_get_wait.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_get_wait.c' object='test_get_wait11-test_get_wait.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait11_CFLAGS) $(CFLAGS) -c -o test_get_wait11-test_get_wait.o `test -f 'test_get_wait.c' || echo '$(srcdir)/'`test_get_wait.c test_get_wait11-test_get_wait.obj: test_get_wait.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait11_CFLAGS) $(CFLAGS) -MT test_get_wait11-test_get_wait.obj -MD -MP -MF $(DEPDIR)/test_get_wait11-test_get_wait.Tpo -c -o test_get_wait11-test_get_wait.obj `if test -f 'test_get_wait.c'; then $(CYGPATH_W) 'test_get_wait.c'; else $(CYGPATH_W) '$(srcdir)/test_get_wait.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_get_wait11-test_get_wait.Tpo $(DEPDIR)/test_get_wait11-test_get_wait.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_get_wait.c' object='test_get_wait11-test_get_wait.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_get_wait11_CFLAGS) $(CFLAGS) -c -o test_get_wait11-test_get_wait.obj `if test -f 'test_get_wait.c'; then $(CYGPATH_W) 'test_get_wait.c'; else $(CYGPATH_W) '$(srcdir)/test_get_wait.c'; fi` test_quiesce-test_quiesce.o: test_quiesce.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -MT test_quiesce-test_quiesce.o -MD -MP -MF $(DEPDIR)/test_quiesce-test_quiesce.Tpo -c -o test_quiesce-test_quiesce.o `test -f 'test_quiesce.c' || echo '$(srcdir)/'`test_quiesce.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_quiesce-test_quiesce.Tpo $(DEPDIR)/test_quiesce-test_quiesce.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_quiesce.c' object='test_quiesce-test_quiesce.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -c -o test_quiesce-test_quiesce.o `test -f 'test_quiesce.c' || echo '$(srcdir)/'`test_quiesce.c test_quiesce-test_quiesce.obj: test_quiesce.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -MT test_quiesce-test_quiesce.obj -MD -MP -MF $(DEPDIR)/test_quiesce-test_quiesce.Tpo -c -o test_quiesce-test_quiesce.obj `if test -f 'test_quiesce.c'; then $(CYGPATH_W) 'test_quiesce.c'; else $(CYGPATH_W) '$(srcdir)/test_quiesce.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_quiesce-test_quiesce.Tpo $(DEPDIR)/test_quiesce-test_quiesce.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_quiesce.c' object='test_quiesce-test_quiesce.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_CFLAGS) $(CFLAGS) -c -o test_quiesce-test_quiesce.obj `if test -f 'test_quiesce.c'; then $(CYGPATH_W) 'test_quiesce.c'; else $(CYGPATH_W) '$(srcdir)/test_quiesce.c'; fi` test_quiesce_stream-test_quiesce_stream.o: test_quiesce_stream.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_stream_CFLAGS) $(CFLAGS) -MT test_quiesce_stream-test_quiesce_stream.o -MD -MP -MF $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Tpo -c -o test_quiesce_stream-test_quiesce_stream.o `test -f 'test_quiesce_stream.c' || echo '$(srcdir)/'`test_quiesce_stream.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Tpo $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_quiesce_stream.c' object='test_quiesce_stream-test_quiesce_stream.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_stream_CFLAGS) $(CFLAGS) -c -o test_quiesce_stream-test_quiesce_stream.o `test -f 'test_quiesce_stream.c' || echo '$(srcdir)/'`test_quiesce_stream.c test_quiesce_stream-test_quiesce_stream.obj: test_quiesce_stream.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_stream_CFLAGS) $(CFLAGS) -MT test_quiesce_stream-test_quiesce_stream.obj -MD -MP -MF $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Tpo -c -o test_quiesce_stream-test_quiesce_stream.obj `if test -f 'test_quiesce_stream.c'; then $(CYGPATH_W) 'test_quiesce_stream.c'; else $(CYGPATH_W) '$(srcdir)/test_quiesce_stream.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Tpo $(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_quiesce_stream.c' object='test_quiesce_stream-test_quiesce_stream.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_quiesce_stream_CFLAGS) $(CFLAGS) -c -o test_quiesce_stream-test_quiesce_stream.obj `if test -f 'test_quiesce_stream.c'; then $(CYGPATH_W) 'test_quiesce_stream.c'; else $(CYGPATH_W) '$(srcdir)/test_quiesce_stream.c'; fi` test_suspend_resume_thread-test_suspend_resume_thread.o: test_suspend_resume_thread.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_suspend_resume_thread_CFLAGS) $(CFLAGS) -MT test_suspend_resume_thread-test_suspend_resume_thread.o -MD -MP -MF $(DEPDIR)/test_suspend_resume_thread-test_suspend_resume_thread.Tpo -c -o test_suspend_resume_thread-test_suspend_resume_thread.o `test -f 'test_suspend_resume_thread.c' || echo '$(srcdir)/'`test_suspend_resume_thread.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_suspend_resume_thread-test_suspend_resume_thread.Tpo $(DEPDIR)/test_suspend_resume_thread-test_suspend_resume_thread.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_suspend_resume_thread.c' object='test_suspend_resume_thread-test_suspend_resume_thread.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_suspend_resume_thread_CFLAGS) $(CFLAGS) -c -o test_suspend_resume_thread-test_suspend_resume_thread.o `test -f 'test_suspend_resume_thread.c' || echo '$(srcdir)/'`test_suspend_resume_thread.c test_suspend_resume_thread-test_suspend_resume_thread.obj: test_suspend_resume_thread.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_suspend_resume_thread_CFLAGS) $(CFLAGS) -MT test_suspend_resume_thread-test_suspend_resume_thread.obj -MD -MP -MF $(DEPDIR)/test_suspend_resume_thread-test_suspend_resume_thread.Tpo -c -o test_suspend_resume_thread-test_suspend_resume_thread.obj `if test -f 'test_suspend_resume_thread.c'; then $(CYGPATH_W) 'test_suspend_resume_thread.c'; else $(CYGPATH_W) '$(srcdir)/test_suspend_resume_thread.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_suspend_resume_thread-test_suspend_resume_thread.Tpo $(DEPDIR)/test_suspend_resume_thread-test_suspend_resume_thread.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_suspend_resume_thread.c' object='test_suspend_resume_thread-test_suspend_resume_thread.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_suspend_resume_thread_CFLAGS) $(CFLAGS) -c -o test_suspend_resume_thread-test_suspend_resume_thread.obj `if test -f 'test_suspend_resume_thread.c'; then $(CYGPATH_W) 'test_suspend_resume_thread.c'; else $(CYGPATH_W) '$(srcdir)/test_suspend_resume_thread.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ output_system_information () \ { \ echo; \ { uname -a | $(AWK) '{ \ printf "System information (uname -a):"; \ for (i = 1; i < NF; ++i) \ { \ if (i != 2) \ printf " %s", $$i; \ } \ printf "\n"; \ }'; } 2>&1; \ if test -r /etc/os-release; then \ echo "Distribution information (/etc/os-release):"; \ sed 8q /etc/os-release; \ elif test -r /etc/issue; then \ echo "Distribution information (/etc/issue):"; \ cat /etc/issue; \ fi; \ }; \ please_report () \ { \ echo "Some test(s) failed. Please report this to $(PACKAGE_BUGREPORT),"; \ echo "together with the test-suite.log file (gzipped) and your system"; \ echo "information. Thanks."; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ output_system_information; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG) for debugging.$${std}";\ if test -n "$(PACKAGE_BUGREPORT)"; then \ please_report | sed -e "s/^/$${col}/" -e s/'$$'/"$${std}"/; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) @$(am__rm_f) $(RECHECK_LOGS) @$(am__rm_f) $(RECHECK_LOGS:.log=.trs) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_get.log: test_get$(EXEEXT) @p='test_get$(EXEEXT)'; \ b='test_get'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_head.log: test_head$(EXEEXT) @p='test_head$(EXEEXT)'; \ b='test_head'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_head10.log: test_head10$(EXEEXT) @p='test_head10$(EXEEXT)'; \ b='test_head10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_iovec.log: test_get_iovec$(EXEEXT) @p='test_get_iovec$(EXEEXT)'; \ b='test_get_iovec'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_sendfile.log: test_get_sendfile$(EXEEXT) @p='test_get_sendfile$(EXEEXT)'; \ b='test_get_sendfile'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_close.log: test_get_close$(EXEEXT) @p='test_get_close$(EXEEXT)'; \ b='test_get_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_close10.log: test_get_close10$(EXEEXT) @p='test_get_close10$(EXEEXT)'; \ b='test_get_close10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_keep_alive.log: test_get_keep_alive$(EXEEXT) @p='test_get_keep_alive$(EXEEXT)'; \ b='test_get_keep_alive'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_keep_alive10.log: test_get_keep_alive10$(EXEEXT) @p='test_get_keep_alive10$(EXEEXT)'; \ b='test_get_keep_alive10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_delete.log: test_delete$(EXEEXT) @p='test_delete$(EXEEXT)'; \ b='test_delete'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_patch.log: test_patch$(EXEEXT) @p='test_patch$(EXEEXT)'; \ b='test_patch'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put.log: test_put$(EXEEXT) @p='test_put$(EXEEXT)'; \ b='test_put'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_add_conn.log: test_add_conn$(EXEEXT) @p='test_add_conn$(EXEEXT)'; \ b='test_add_conn'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_add_conn_nolisten.log: test_add_conn_nolisten$(EXEEXT) @p='test_add_conn_nolisten$(EXEEXT)'; \ b='test_add_conn_nolisten'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_process_headers.log: test_process_headers$(EXEEXT) @p='test_process_headers$(EXEEXT)'; \ b='test_process_headers'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_process_arguments.log: test_process_arguments$(EXEEXT) @p='test_process_arguments$(EXEEXT)'; \ b='test_process_arguments'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_method.log: test_toolarge_method$(EXEEXT) @p='test_toolarge_method$(EXEEXT)'; \ b='test_toolarge_method'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_url.log: test_toolarge_url$(EXEEXT) @p='test_toolarge_url$(EXEEXT)'; \ b='test_toolarge_url'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_request_header_name.log: test_toolarge_request_header_name$(EXEEXT) @p='test_toolarge_request_header_name$(EXEEXT)'; \ b='test_toolarge_request_header_name'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_request_header_value.log: test_toolarge_request_header_value$(EXEEXT) @p='test_toolarge_request_header_value$(EXEEXT)'; \ b='test_toolarge_request_header_value'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_request_headers.log: test_toolarge_request_headers$(EXEEXT) @p='test_toolarge_request_headers$(EXEEXT)'; \ b='test_toolarge_request_headers'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_reply_header_name.log: test_toolarge_reply_header_name$(EXEEXT) @p='test_toolarge_reply_header_name$(EXEEXT)'; \ b='test_toolarge_reply_header_name'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_reply_header_value.log: test_toolarge_reply_header_value$(EXEEXT) @p='test_toolarge_reply_header_value$(EXEEXT)'; \ b='test_toolarge_reply_header_value'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_toolarge_reply_headers.log: test_toolarge_reply_headers$(EXEEXT) @p='test_toolarge_reply_headers$(EXEEXT)'; \ b='test_toolarge_reply_headers'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_tricky_url.log: test_tricky_url$(EXEEXT) @p='test_tricky_url$(EXEEXT)'; \ b='test_tricky_url'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_tricky_header2.log: test_tricky_header2$(EXEEXT) @p='test_tricky_header2$(EXEEXT)'; \ b='test_tricky_header2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_large_put.log: test_large_put$(EXEEXT) @p='test_large_put$(EXEEXT)'; \ b='test_large_put'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get11.log: test_get11$(EXEEXT) @p='test_get11$(EXEEXT)'; \ b='test_get11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_iovec11.log: test_get_iovec11$(EXEEXT) @p='test_get_iovec11$(EXEEXT)'; \ b='test_get_iovec11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_sendfile11.log: test_get_sendfile11$(EXEEXT) @p='test_get_sendfile11$(EXEEXT)'; \ b='test_get_sendfile11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_patch11.log: test_patch11$(EXEEXT) @p='test_patch11$(EXEEXT)'; \ b='test_patch11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put11.log: test_put11$(EXEEXT) @p='test_put11$(EXEEXT)'; \ b='test_put11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_large_put11.log: test_large_put11$(EXEEXT) @p='test_large_put11$(EXEEXT)'; \ b='test_large_put11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_large_put_inc11.log: test_large_put_inc11$(EXEEXT) @p='test_large_put_inc11$(EXEEXT)'; \ b='test_large_put_inc11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_broken_len10.log: test_put_broken_len10$(EXEEXT) @p='test_put_broken_len10$(EXEEXT)'; \ b='test_put_broken_len10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_broken_len.log: test_put_broken_len$(EXEEXT) @p='test_put_broken_len$(EXEEXT)'; \ b='test_put_broken_len'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked.log: test_get_chunked$(EXEEXT) @p='test_get_chunked$(EXEEXT)'; \ b='test_get_chunked'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close.log: test_get_chunked_close$(EXEEXT) @p='test_get_chunked_close$(EXEEXT)'; \ b='test_get_chunked_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_string.log: test_get_chunked_string$(EXEEXT) @p='test_get_chunked_string$(EXEEXT)'; \ b='test_get_chunked_string'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_string.log: test_get_chunked_close_string$(EXEEXT) @p='test_get_chunked_close_string$(EXEEXT)'; \ b='test_get_chunked_close_string'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_empty.log: test_get_chunked_empty$(EXEEXT) @p='test_get_chunked_empty$(EXEEXT)'; \ b='test_get_chunked_empty'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_empty.log: test_get_chunked_close_empty$(EXEEXT) @p='test_get_chunked_close_empty$(EXEEXT)'; \ b='test_get_chunked_close_empty'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_string_empty.log: test_get_chunked_string_empty$(EXEEXT) @p='test_get_chunked_string_empty$(EXEEXT)'; \ b='test_get_chunked_string_empty'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_string_empty.log: test_get_chunked_close_string_empty$(EXEEXT) @p='test_get_chunked_close_string_empty$(EXEEXT)'; \ b='test_get_chunked_close_string_empty'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_sized.log: test_get_chunked_sized$(EXEEXT) @p='test_get_chunked_sized$(EXEEXT)'; \ b='test_get_chunked_sized'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_sized.log: test_get_chunked_close_sized$(EXEEXT) @p='test_get_chunked_close_sized$(EXEEXT)'; \ b='test_get_chunked_close_sized'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_empty_sized.log: test_get_chunked_empty_sized$(EXEEXT) @p='test_get_chunked_empty_sized$(EXEEXT)'; \ b='test_get_chunked_empty_sized'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_empty_sized.log: test_get_chunked_close_empty_sized$(EXEEXT) @p='test_get_chunked_close_empty_sized$(EXEEXT)'; \ b='test_get_chunked_close_empty_sized'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_forced.log: test_get_chunked_forced$(EXEEXT) @p='test_get_chunked_forced$(EXEEXT)'; \ b='test_get_chunked_forced'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_forced.log: test_get_chunked_close_forced$(EXEEXT) @p='test_get_chunked_close_forced$(EXEEXT)'; \ b='test_get_chunked_close_forced'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_empty_forced.log: test_get_chunked_empty_forced$(EXEEXT) @p='test_get_chunked_empty_forced$(EXEEXT)'; \ b='test_get_chunked_empty_forced'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close_empty_forced.log: test_get_chunked_close_empty_forced$(EXEEXT) @p='test_get_chunked_close_empty_forced$(EXEEXT)'; \ b='test_get_chunked_close_empty_forced'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_chunked.log: test_put_chunked$(EXEEXT) @p='test_put_chunked$(EXEEXT)'; \ b='test_put_chunked'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_callback.log: test_callback$(EXEEXT) @p='test_callback$(EXEEXT)'; \ b='test_callback'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_header_fold.log: test_get_header_fold$(EXEEXT) @p='test_get_header_fold$(EXEEXT)'; \ b='test_get_header_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_fold.log: test_put_header_fold$(EXEEXT) @p='test_put_header_fold$(EXEEXT)'; \ b='test_put_header_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large_header_fold.log: test_put_large_header_fold$(EXEEXT) @p='test_put_large_header_fold$(EXEEXT)'; \ b='test_put_large_header_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_fold_last.log: test_put_header_fold_last$(EXEEXT) @p='test_put_header_fold_last$(EXEEXT)'; \ b='test_put_header_fold_last'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_fold_large.log: test_put_header_fold_large$(EXEEXT) @p='test_put_header_fold_large$(EXEEXT)'; \ b='test_put_header_fold_large'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_header_double_fold.log: test_get_header_double_fold$(EXEEXT) @p='test_get_header_double_fold$(EXEEXT)'; \ b='test_get_header_double_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_double_fold.log: test_put_header_double_fold$(EXEEXT) @p='test_put_header_double_fold$(EXEEXT)'; \ b='test_put_header_double_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large_header_double_fold.log: test_put_large_header_double_fold$(EXEEXT) @p='test_put_large_header_double_fold$(EXEEXT)'; \ b='test_put_large_header_double_fold'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_double_fold_last.log: test_put_header_double_fold_last$(EXEEXT) @p='test_put_header_double_fold_last$(EXEEXT)'; \ b='test_put_header_double_fold_last'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_header_double_fold_large.log: test_put_header_double_fold_large$(EXEEXT) @p='test_put_header_double_fold_large$(EXEEXT)'; \ b='test_put_header_double_fold_large'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_parse_cookies_discp_p2.log: test_parse_cookies_discp_p2$(EXEEXT) @p='test_parse_cookies_discp_p2$(EXEEXT)'; \ b='test_parse_cookies_discp_p2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_parse_cookies_discp_p1.log: test_parse_cookies_discp_p1$(EXEEXT) @p='test_parse_cookies_discp_p1$(EXEEXT)'; \ b='test_parse_cookies_discp_p1'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_parse_cookies_discp_zero.log: test_parse_cookies_discp_zero$(EXEEXT) @p='test_parse_cookies_discp_zero$(EXEEXT)'; \ b='test_parse_cookies_discp_zero'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_parse_cookies_discp_n2.log: test_parse_cookies_discp_n2$(EXEEXT) @p='test_parse_cookies_discp_n2$(EXEEXT)'; \ b='test_parse_cookies_discp_n2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_parse_cookies_discp_n3.log: test_parse_cookies_discp_n3$(EXEEXT) @p='test_parse_cookies_discp_n3$(EXEEXT)'; \ b='test_parse_cookies_discp_n3'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) perf_get.log: perf_get$(EXEEXT) @p='perf_get$(EXEEXT)'; \ b='perf_get'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_basicauth.log: test_basicauth$(EXEEXT) @p='test_basicauth$(EXEEXT)'; \ b='test_basicauth'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_basicauth_preauth.log: test_basicauth_preauth$(EXEEXT) @p='test_basicauth_preauth$(EXEEXT)'; \ b='test_basicauth_preauth'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_basicauth_oldapi.log: test_basicauth_oldapi$(EXEEXT) @p='test_basicauth_oldapi$(EXEEXT)'; \ b='test_basicauth_oldapi'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_basicauth_preauth_oldapi.log: test_basicauth_preauth_oldapi$(EXEEXT) @p='test_basicauth_preauth_oldapi$(EXEEXT)'; \ b='test_basicauth_preauth_oldapi'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post.log: test_post$(EXEEXT) @p='test_post$(EXEEXT)'; \ b='test_post'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postform.log: test_postform$(EXEEXT) @p='test_postform$(EXEEXT)'; \ b='test_postform'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_loop.log: test_post_loop$(EXEEXT) @p='test_post_loop$(EXEEXT)'; \ b='test_post_loop'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post11.log: test_post11$(EXEEXT) @p='test_post11$(EXEEXT)'; \ b='test_post11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postform11.log: test_postform11$(EXEEXT) @p='test_postform11$(EXEEXT)'; \ b='test_postform11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_loop11.log: test_post_loop11$(EXEEXT) @p='test_post_loop11$(EXEEXT)'; \ b='test_post_loop11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth_emu_ext.log: test_digestauth_emu_ext$(EXEEXT) @p='test_digestauth_emu_ext$(EXEEXT)'; \ b='test_digestauth_emu_ext'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth_emu_ext_oldapi.log: test_digestauth_emu_ext_oldapi$(EXEEXT) @p='test_digestauth_emu_ext_oldapi$(EXEEXT)'; \ b='test_digestauth_emu_ext_oldapi'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2.log: test_digestauth2$(EXEEXT) @p='test_digestauth2$(EXEEXT)'; \ b='test_digestauth2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_rfc2069.log: test_digestauth2_rfc2069$(EXEEXT) @p='test_digestauth2_rfc2069$(EXEEXT)'; \ b='test_digestauth2_rfc2069'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_rfc2069_userdigest.log: test_digestauth2_rfc2069_userdigest$(EXEEXT) @p='test_digestauth2_rfc2069_userdigest$(EXEEXT)'; \ b='test_digestauth2_rfc2069_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi1.log: test_digestauth2_oldapi1$(EXEEXT) @p='test_digestauth2_oldapi1$(EXEEXT)'; \ b='test_digestauth2_oldapi1'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi2.log: test_digestauth2_oldapi2$(EXEEXT) @p='test_digestauth2_oldapi2$(EXEEXT)'; \ b='test_digestauth2_oldapi2'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_userhash.log: test_digestauth2_userhash$(EXEEXT) @p='test_digestauth2_userhash$(EXEEXT)'; \ b='test_digestauth2_userhash'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_userdigest.log: test_digestauth2_userdigest$(EXEEXT) @p='test_digestauth2_userdigest$(EXEEXT)'; \ b='test_digestauth2_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi1_userdigest.log: test_digestauth2_oldapi1_userdigest$(EXEEXT) @p='test_digestauth2_oldapi1_userdigest$(EXEEXT)'; \ b='test_digestauth2_oldapi1_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi2_userdigest.log: test_digestauth2_oldapi2_userdigest$(EXEEXT) @p='test_digestauth2_oldapi2_userdigest$(EXEEXT)'; \ b='test_digestauth2_oldapi2_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_userhash_userdigest.log: test_digestauth2_userhash_userdigest$(EXEEXT) @p='test_digestauth2_userhash_userdigest$(EXEEXT)'; \ b='test_digestauth2_userhash_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_bind_all.log: test_digestauth2_bind_all$(EXEEXT) @p='test_digestauth2_bind_all$(EXEEXT)'; \ b='test_digestauth2_bind_all'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_bind_uri.log: test_digestauth2_bind_uri$(EXEEXT) @p='test_digestauth2_bind_uri$(EXEEXT)'; \ b='test_digestauth2_bind_uri'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi1_bind_all.log: test_digestauth2_oldapi1_bind_all$(EXEEXT) @p='test_digestauth2_oldapi1_bind_all$(EXEEXT)'; \ b='test_digestauth2_oldapi1_bind_all'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi1_bind_uri.log: test_digestauth2_oldapi1_bind_uri$(EXEEXT) @p='test_digestauth2_oldapi1_bind_uri$(EXEEXT)'; \ b='test_digestauth2_oldapi1_bind_uri'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_sha256.log: test_digestauth2_sha256$(EXEEXT) @p='test_digestauth2_sha256$(EXEEXT)'; \ b='test_digestauth2_sha256'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_sha256_userhash.log: test_digestauth2_sha256_userhash$(EXEEXT) @p='test_digestauth2_sha256_userhash$(EXEEXT)'; \ b='test_digestauth2_sha256_userhash'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi2_sha256.log: test_digestauth2_oldapi2_sha256$(EXEEXT) @p='test_digestauth2_oldapi2_sha256$(EXEEXT)'; \ b='test_digestauth2_oldapi2_sha256'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_sha256_userdigest.log: test_digestauth2_sha256_userdigest$(EXEEXT) @p='test_digestauth2_sha256_userdigest$(EXEEXT)'; \ b='test_digestauth2_sha256_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_oldapi2_sha256_userdigest.log: test_digestauth2_oldapi2_sha256_userdigest$(EXEEXT) @p='test_digestauth2_oldapi2_sha256_userdigest$(EXEEXT)'; \ b='test_digestauth2_oldapi2_sha256_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth2_sha256_userhash_userdigest.log: test_digestauth2_sha256_userhash_userdigest$(EXEEXT) @p='test_digestauth2_sha256_userhash_userdigest$(EXEEXT)'; \ b='test_digestauth2_sha256_userhash_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_response_cleanup.log: test_get_response_cleanup$(EXEEXT) @p='test_get_response_cleanup$(EXEEXT)'; \ b='test_get_response_cleanup'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_urlparse.log: test_urlparse$(EXEEXT) @p='test_urlparse$(EXEEXT)'; \ b='test_urlparse'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_long_header.log: test_long_header$(EXEEXT) @p='test_long_header$(EXEEXT)'; \ b='test_long_header'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_long_header11.log: test_long_header11$(EXEEXT) @p='test_long_header11$(EXEEXT)'; \ b='test_long_header11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_iplimit11.log: test_iplimit11$(EXEEXT) @p='test_iplimit11$(EXEEXT)'; \ b='test_iplimit11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_termination.log: test_termination$(EXEEXT) @p='test_termination$(EXEEXT)'; \ b='test_termination'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_add_conn_cleanup.log: test_add_conn_cleanup$(EXEEXT) @p='test_add_conn_cleanup$(EXEEXT)'; \ b='test_add_conn_cleanup'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_add_conn_cleanup_nolisten.log: test_add_conn_cleanup_nolisten$(EXEEXT) @p='test_add_conn_cleanup_nolisten$(EXEEXT)'; \ b='test_add_conn_cleanup_nolisten'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_timeout.log: test_timeout$(EXEEXT) @p='test_timeout$(EXEEXT)'; \ b='test_timeout'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) perf_get_concurrent11.log: perf_get_concurrent11$(EXEEXT) @p='perf_get_concurrent11$(EXEEXT)'; \ b='perf_get_concurrent11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_wait.log: test_get_wait$(EXEEXT) @p='test_get_wait$(EXEEXT)'; \ b='test_get_wait'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_wait11.log: test_get_wait11$(EXEEXT) @p='test_get_wait11$(EXEEXT)'; \ b='test_get_wait11'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_suspend_resume_thread.log: test_suspend_resume_thread$(EXEEXT) @p='test_suspend_resume_thread$(EXEEXT)'; \ b='test_suspend_resume_thread'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_concurrent_stop.log: test_concurrent_stop$(EXEEXT) @p='test_concurrent_stop$(EXEEXT)'; \ b='test_concurrent_stop'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_quiesce.log: test_quiesce$(EXEEXT) @p='test_quiesce$(EXEEXT)'; \ b='test_quiesce'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_quiesce_stream.log: test_quiesce_stream$(EXEEXT) @p='test_quiesce_stream$(EXEEXT)'; \ b='test_quiesce_stream'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) perf_get_concurrent.log: perf_get_concurrent$(EXEEXT) @p='perf_get_concurrent$(EXEEXT)'; \ b='perf_get_concurrent'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth.log: test_digestauth$(EXEEXT) @p='test_digestauth$(EXEEXT)'; \ b='test_digestauth'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth_with_arguments.log: test_digestauth_with_arguments$(EXEEXT) @p='test_digestauth_with_arguments$(EXEEXT)'; \ b='test_digestauth_with_arguments'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth_concurrent.log: test_digestauth_concurrent$(EXEEXT) @p='test_digestauth_concurrent$(EXEEXT)'; \ b='test_digestauth_concurrent'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digestauth_sha256.log: test_digestauth_sha256$(EXEEXT) @p='test_digestauth_sha256$(EXEEXT)'; \ b='test_digestauth_sha256'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -$(am__rm_f) $(TEST_LOGS) -$(am__rm_f) $(TEST_LOGS:.log=.trs) -$(am__rm_f) $(TEST_SUITE_LOG) clean-generic: distclean-generic: -$(am__rm_f) $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/perf_get.Po -rm -f ./$(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po -rm -f ./$(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po -rm -f ./$(DEPDIR)/test_add_conn-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po -rm -f ./$(DEPDIR)/test_basicauth.Po -rm -f ./$(DEPDIR)/test_callback.Po -rm -f ./$(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po -rm -f ./$(DEPDIR)/test_delete.Po -rm -f ./$(DEPDIR)/test_digestauth.Po -rm -f ./$(DEPDIR)/test_digestauth2.Po -rm -f ./$(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po -rm -f ./$(DEPDIR)/test_digestauth_emu_ext.Po -rm -f ./$(DEPDIR)/test_digestauth_sha256.Po -rm -f ./$(DEPDIR)/test_digestauth_with_arguments.Po -rm -f ./$(DEPDIR)/test_get.Po -rm -f ./$(DEPDIR)/test_get_chunked.Po -rm -f ./$(DEPDIR)/test_get_close_keep_alive.Po -rm -f ./$(DEPDIR)/test_get_iovec.Po -rm -f ./$(DEPDIR)/test_get_response_cleanup.Po -rm -f ./$(DEPDIR)/test_get_sendfile.Po -rm -f ./$(DEPDIR)/test_get_wait-test_get_wait.Po -rm -f ./$(DEPDIR)/test_get_wait11-test_get_wait.Po -rm -f ./$(DEPDIR)/test_head.Po -rm -f ./$(DEPDIR)/test_iplimit.Po -rm -f ./$(DEPDIR)/test_large_put.Po -rm -f ./$(DEPDIR)/test_long_header.Po -rm -f ./$(DEPDIR)/test_parse_cookies.Po -rm -f ./$(DEPDIR)/test_patch.Po -rm -f ./$(DEPDIR)/test_post.Po -rm -f ./$(DEPDIR)/test_post_loop.Po -rm -f ./$(DEPDIR)/test_postform.Po -rm -f ./$(DEPDIR)/test_process_arguments.Po -rm -f ./$(DEPDIR)/test_process_headers.Po -rm -f ./$(DEPDIR)/test_put.Po -rm -f ./$(DEPDIR)/test_put_broken_len.Po -rm -f ./$(DEPDIR)/test_put_chunked.Po -rm -f ./$(DEPDIR)/test_put_header_fold.Po -rm -f ./$(DEPDIR)/test_quiesce-test_quiesce.Po -rm -f ./$(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po -rm -f ./$(DEPDIR)/test_suspend_resume_thread-test_suspend_resume_thread.Po -rm -f ./$(DEPDIR)/test_termination.Po -rm -f ./$(DEPDIR)/test_timeout.Po -rm -f ./$(DEPDIR)/test_toolarge.Po -rm -f ./$(DEPDIR)/test_tricky.Po -rm -f ./$(DEPDIR)/test_urlparse.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/perf_get.Po -rm -f ./$(DEPDIR)/perf_get_concurrent-perf_get_concurrent.Po -rm -f ./$(DEPDIR)/perf_get_concurrent11-perf_get_concurrent.Po -rm -f ./$(DEPDIR)/test_add_conn-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_cleanup-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_cleanup_nolisten-test_add_conn.Po -rm -f ./$(DEPDIR)/test_add_conn_nolisten-test_add_conn.Po -rm -f ./$(DEPDIR)/test_basicauth.Po -rm -f ./$(DEPDIR)/test_callback.Po -rm -f ./$(DEPDIR)/test_concurrent_stop-test_concurrent_stop.Po -rm -f ./$(DEPDIR)/test_delete.Po -rm -f ./$(DEPDIR)/test_digestauth.Po -rm -f ./$(DEPDIR)/test_digestauth2.Po -rm -f ./$(DEPDIR)/test_digestauth_concurrent-test_digestauth_concurrent.Po -rm -f ./$(DEPDIR)/test_digestauth_emu_ext.Po -rm -f ./$(DEPDIR)/test_digestauth_sha256.Po -rm -f ./$(DEPDIR)/test_digestauth_with_arguments.Po -rm -f ./$(DEPDIR)/test_get.Po -rm -f ./$(DEPDIR)/test_get_chunked.Po -rm -f ./$(DEPDIR)/test_get_close_keep_alive.Po -rm -f ./$(DEPDIR)/test_get_iovec.Po -rm -f ./$(DEPDIR)/test_get_response_cleanup.Po -rm -f ./$(DEPDIR)/test_get_sendfile.Po -rm -f ./$(DEPDIR)/test_get_wait-test_get_wait.Po -rm -f ./$(DEPDIR)/test_get_wait11-test_get_wait.Po -rm -f ./$(DEPDIR)/test_head.Po -rm -f ./$(DEPDIR)/test_iplimit.Po -rm -f ./$(DEPDIR)/test_large_put.Po -rm -f ./$(DEPDIR)/test_long_header.Po -rm -f ./$(DEPDIR)/test_parse_cookies.Po -rm -f ./$(DEPDIR)/test_patch.Po -rm -f ./$(DEPDIR)/test_post.Po -rm -f ./$(DEPDIR)/test_post_loop.Po -rm -f ./$(DEPDIR)/test_postform.Po -rm -f ./$(DEPDIR)/test_process_arguments.Po -rm -f ./$(DEPDIR)/test_process_headers.Po -rm -f ./$(DEPDIR)/test_put.Po -rm -f ./$(DEPDIR)/test_put_broken_len.Po -rm -f ./$(DEPDIR)/test_put_chunked.Po -rm -f ./$(DEPDIR)/test_put_header_fold.Po -rm -f ./$(DEPDIR)/test_quiesce-test_quiesce.Po -rm -f ./$(DEPDIR)/test_quiesce_stream-test_quiesce_stream.Po -rm -f ./$(DEPDIR)/test_suspend_resume_thread-test_suspend_resume_thread.Po -rm -f ./$(DEPDIR)/test_termination.Po -rm -f ./$(DEPDIR)/test_timeout.Po -rm -f ./$(DEPDIR)/test_toolarge.Po -rm -f ./$(DEPDIR)/test_tricky.Po -rm -f ./$(DEPDIR)/test_urlparse.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) check-am install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am .PRECIOUS: Makefile @HEAVY_TESTS_NOTPARALLEL@ $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: # Tell GNU make to disable its built-in pattern rules. %:: %,v %:: RCS/%,v %:: RCS/% %:: s.% %:: SCCS/s.% libmicrohttpd-1.0.10/src/testcurl/test_quiesce.c0000664000175000017500000005667715232103064015436 /* This file is part of libmicrohttpd Copyright (C) 2013, 2015 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_quiesce.c * @brief Testcase for libmicrohttpd quiescing * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include #include #include "mhd_sockets.h" /* only macros used */ #include "mhd_has_in_name.h" #include "mhd_has_param.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 4 #define MHD_URI_BASE_PATH "/hello_world" /* Global parameters */ static int verbose; /**< Be verbose */ static int oneone; /**< If false use HTTP/1.0 for requests*/ static uint16_t global_port; /**< MHD daemons listen port number */ struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) { fprintf (stderr, "Unexpected HTTP method '%s'. ", method); externalErrorExit (); } if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); if (NULL == response) mhdErrorExitDesc ("MHD_create_response failed"); /* Make sure that connection will not be reused */ if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close")) mhdErrorExitDesc ("MHD_add_response_header() failed"); if (MHD_NO == MHD_queue_response (connection, MHD_HTTP_OK, response)) mhdErrorExitDesc ("MHD_queue_response() failed"); MHD_destroy_response (response); return MHD_YES; } static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode code) { int *done = (int *) cls; (void) connection; (void) req_cls; (void) code; /* Unused. Silent compiler warning. */ if (MHD_REQUEST_TERMINATED_COMPLETED_OK != code) { fprintf (stderr, "Unexpected termination code: %d. ", (int) code); mhdErrorExit (); } *done = 1; if (verbose) printf ("Notify callback has been called with OK code.\n"); } static void * ServeOneRequest (void *param) { struct MHD_Daemon *d; fd_set rs; fd_set ws; fd_set es; MHD_socket fd, max; time_t start; struct timeval tv; volatile int done = 0; if (NULL == param) externalErrorExit (); fd = *((MHD_socket *) param); d = MHD_start_daemon (MHD_USE_ERROR_LOG, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_LISTEN_SOCKET, fd, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, &done, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) mhdErrorExit (); if (verbose) printf ("Started MHD daemon in ServeOneRequest().\n"); start = time (NULL); while ((time (NULL) - start < TIMEOUTS_VAL * 2) && done == 0) { max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) mhdErrorExit ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 100000; if (-1 == MHD_SYS_select_ (max + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif } MHD_run (d); } if (! done) mhdErrorExit ("ServeOneRequest() failed and finished by timeout"); fd = MHD_quiesce_daemon (d); if (MHD_INVALID_SOCKET == fd) mhdErrorExit ("MHD_quiesce_daemon() failed in ServeOneRequest()"); MHD_stop_daemon (d); return NULL; } static CURL * setupCURL (void *cbc) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" MHD_URI_BASE_PATH)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) global_port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) (TIMEOUTS_VAL / 2))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) TIMEOUTS_VAL)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); return c; } static unsigned int testGet (unsigned int type, int pool_count, uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; MHD_socket fd; pthread_t thrd; char *thrdRet; if (verbose) printf ("testGet(%u, %d, %u) test started.\n", type, pool_count, (unsigned int) poll_flag); cbc.buf = buf; cbc.size = sizeof(buf); cbc.pos = 0; if (pool_count > 0) { d = MHD_start_daemon (type | MHD_USE_ERROR_LOG | MHD_USE_ITC | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) pool_count, MHD_OPTION_END); } else { d = MHD_start_daemon (type | MHD_USE_ERROR_LOG | MHD_USE_ITC | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); } if (d == NULL) mhdErrorExitDesc ("MHD_start_daemon() failed"); if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); global_port = dinfo->port; } c = setupCURL (&cbc); checkCURLE_OK (curl_easy_perform (c)); if (cbc.pos != strlen (MHD_URI_BASE_PATH)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf, strlen (MHD_URI_BASE_PATH))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } if (verbose) printf ("Received valid response data.\n"); fd = MHD_quiesce_daemon (d); if (MHD_INVALID_SOCKET == fd) mhdErrorExitDesc ("MHD_quiesce_daemon failed"); if (0 != pthread_create (&thrd, NULL, &ServeOneRequest, (void *) &fd)) externalErrorExitDesc ("pthread_create() failed"); /* No need for the thread sync as socket is already listening, * so libcurl may start connecting before MHD is started in another thread */ cbc.pos = 0; checkCURLE_OK (curl_easy_perform (c)); if (cbc.pos != strlen (MHD_URI_BASE_PATH)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf, strlen (MHD_URI_BASE_PATH))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } if (0 != pthread_join (thrd, (void **) &thrdRet)) externalErrorExitDesc ("pthread_join() failed"); if (NULL != thrdRet) externalErrorExitDesc ("ServeOneRequest() returned non-NULL result"); if (verbose) { printf ("ServeOneRequest() thread was joined.\n"); fflush (stdout); } /* at this point, the forked server quiesced and quit, * so new requests should fail */ cbc.pos = 0; if (CURLE_OK == curl_easy_perform (c)) { fprintf (stderr, "curl_easy_perform() succeed while it should fail. "); fprintf (stderr, "Got %u bytes ('%.*s'), " "valid data would be %u bytes (%s). ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH), MHD_URI_BASE_PATH); mhdErrorExitDesc ("Unexpected succeed request"); } if (verbose) printf ("curl_easy_perform() failed as expected.\n"); curl_easy_cleanup (c); MHD_stop_daemon (d); MHD_socket_close_chk_ (fd); if (verbose) { printf ("testGet(%u, %d, %u) test succeed.\n", type, pool_count, (unsigned int) poll_flag); fflush (stdout); } return 0; } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; int running; struct CURLMsg *msg; time_t start; struct timeval tv; int i; MHD_socket fd = MHD_INVALID_SOCKET; if (verbose) printf ("testExternalGet test started.\n"); fd = MHD_INVALID_SOCKET; multi = NULL; cbc.buf = buf; cbc.size = sizeof(buf); cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) mhdErrorExitDesc ("Failed to start MHD daemon"); if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); global_port = dinfo->port; } for (i = 0; i < 2; i++) { c = setupCURL (&cbc); multi = curl_multi_init (); if (multi == NULL) libcurlErrorExit (); mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) libcurlErrorExit (); start = time (NULL); while ( (time (NULL) - start < TIMEOUTS_VAL * 2) && (NULL != multi) ) { MHD_socket maxsock; int maxposixs; maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) libcurlErrorExit (); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) mhdErrorExit (); #ifndef MHD_WINSOCK_SOCKETS if (maxsock > maxposixs) maxposixs = maxsock; #endif /* MHD_POSIX_SOCKETS */ tv.tv_sec = 0; tv.tv_usec = 100000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) { curl_fine = 1; if (verbose) printf ("libcurl reported success.\n"); } else if (i == 0) { fprintf (stderr, "curl_multi_perform() failed with '%s'. ", curl_easy_strerror (msg->data.result)); mhdErrorExit (); } } } if (i == 0) { if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); mhdErrorExit (); } /* MHD is running, result should be correct */ if (cbc.pos != strlen (MHD_URI_BASE_PATH)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf, strlen (MHD_URI_BASE_PATH))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } if (verbose) { printf ("First request was successful.\n"); fflush (stdout); } } else if (i == 1) { if (curl_fine) { fprintf (stderr, "libcurl returned OK code, while it shouldn't\n"); mhdErrorExit (); } if (verbose) printf ("Second request failed as expected.\n"); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; break; } MHD_run (d); } if (NULL != multi) mhdErrorExitDesc ("Test failed and finished by timeout"); if (0 == i) { /* quiesce the daemon on the 1st iteration, so the 2nd should fail */ fd = MHD_quiesce_daemon (d); if (MHD_INVALID_SOCKET == fd) mhdErrorExitDesc ("MHD_quiesce_daemon() failed"); } } MHD_stop_daemon (d); if (MHD_INVALID_SOCKET == fd) { fprintf (stderr, "Failed to MHD_quiesce_daemon() at some point. "); externalErrorExit (); } MHD_socket_close_chk_ (fd); if (verbose) { printf ("testExternalGet succeed.\n"); fflush (stdout); } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; oneone = ! has_in_name (argv[0], "10"); verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) global_port = 0; else global_port = 1480 + (oneone ? 1 : 0); errorCount += testExternalGet (); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, 0); errorCount += testGet (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, 0, 0); errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT, 0); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, MHD_USE_POLL); errorCount += testGet (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, 0, MHD_USE_POLL); errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT, MHD_USE_POLL); } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, MHD_USE_EPOLL); errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT, MHD_USE_EPOLL); } } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_get_sendfile.c0000664000175000017500000004366515232103064016421 /* This file is part of libmicrohttpd Copyright (C) 2007, 2009 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get_sendfile.c * @brief Testcase for libmicrohttpd response from FD * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include #include #include "mhd_sockets.h" #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define TESTSTR \ "This is the content of the test file we are sending using sendfile (if available)" static char *sourcefile; static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; int fd; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; fd = open (sourcefile, O_RDONLY); if (fd == -1) { fprintf (stderr, "Failed to open `%s': %s\n", sourcefile, strerror (errno)); exit (1); } response = MHD_create_response_from_fd (strlen (TESTSTR), fd); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1200; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (TESTSTR)) return 4; if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR))) return 8; return 0; } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1201; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (TESTSTR)) return 64; if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR))) return 128; return 0; } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1202; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (TESTSTR)) return 64; if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR))) return 128; return 0; } static unsigned int testExternalGet (int thread_unsafe) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1203; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | (thread_unsafe ? MHD_USE_NO_THREAD_SAFETY : 0), port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen (TESTSTR)) { fprintf (stderr, "Got %.*s instead of %s!\n", (int) cbc.pos, cbc.buf, TESTSTR); return 8192; } if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR))) return 16384; return 0; } static unsigned int testUnknownPortGet (void) { struct MHD_Daemon *d; const union MHD_DaemonInfo *di; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; struct sockaddr_in addr; socklen_t addr_len = sizeof(addr); memset (&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR, &addr, MHD_OPTION_END); if (d == NULL) return 32768; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) { di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (di == NULL) return 65536; if (0 != getsockname (di->listen_fd, (struct sockaddr *) &addr, &addr_len)) return 131072; if (addr.sin_family != AF_INET) return 26214; port = (uint16_t) ntohs (addr.sin_port); } else { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (buf, sizeof(buf), "http://127.0.0.1:%u/", (unsigned int) port); c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, buf); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 524288; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (TESTSTR)) return 1048576; if (0 != strncmp (TESTSTR, cbc.buf, strlen (TESTSTR))) return 2097152; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; const char *tmp; FILE *f; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if ( (NULL == (tmp = getenv ("TMPDIR"))) && (NULL == (tmp = getenv ("TMP"))) && (NULL == (tmp = getenv ("TEMP"))) ) tmp = "/tmp"; sourcefile = malloc (strlen (tmp) + 32); snprintf (sourcefile, strlen (tmp) + 32, "%s/%s%s", tmp, "test-mhd-sendfile", oneone ? "11" : ""); f = fopen (sourcefile, "w"); if (NULL == f) { fprintf (stderr, "failed to write test file\n"); free (sourcefile); return 1; } if (1 != fwrite (TESTSTR, strlen (TESTSTR), 1, f)) abort (); fclose (f); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (); errorCount += testMultithreadedGet (); errorCount += testMultithreadedPoolGet (); errorCount += testUnknownPortGet (); errorCount += testExternalGet (0); } errorCount += testExternalGet (! 0); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); unlink (sourcefile); free (sourcefile); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_postform.c0000664000175000017500000005066515232103064015640 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2023 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_postform.c * @brief Testcase for libmicrohttpd POST operations using multipart/postform data * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #ifdef MHD_HTTPS_REQUIRE_GCRYPT #ifdef HAVE_GCRYPT_H #include #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #include #ifndef WINDOWS #include #endif #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #if CURL_AT_LEAST_VERSION (7,56,0) #define HAS_CURL_MIME 1 #endif /* CURL_AT_LEAST_VERSION(7,56,0) */ #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static void completed_cb (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct MHD_PostProcessor *pp = *req_cls; (void) cls; (void) connection; (void) toe; /* Unused. Silent compiler warning. */ if (NULL != pp) MHD_destroy_post_processor (pp); *req_cls = NULL; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } /** * Note that this post_iterator is not perfect * in that it fails to support incremental processing. * (to be fixed in the future) */ static enum MHD_Result post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *value, uint64_t off, size_t size) { int *eok = cls; (void) kind; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; (void) off; /* Unused. Silent compiler warning. */ #if 0 fprintf (stderr, "PI sees %s-%.*s\n", key, size, value); #endif if ((0 == strcmp (key, "name")) && (size == strlen ("daniel")) && (0 == strncmp (value, "daniel", size))) (*eok) |= 1; if ((0 == strcmp (key, "project")) && (size == strlen ("curl")) && (0 == strncmp (value, "curl", size))) (*eok) |= 2; return MHD_YES; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int eok; struct MHD_Response *response; struct MHD_PostProcessor *pp; enum MHD_Result ret; (void) cls; (void) version; /* Unused. Silent compiler warning. */ if (0 != strcmp ("POST", method)) { printf ("METHOD: %s\n", method); return MHD_NO; /* unexpected method */ } pp = *req_cls; if (pp == NULL) { eok = 0; pp = MHD_create_post_processor (connection, 1024, &post_iterator, &eok); if (NULL == pp) abort (); *req_cls = pp; } if (MHD_YES != MHD_post_process (pp, upload_data, *upload_data_size)) abort (); if ((eok == 3) && (0 == *upload_data_size)) { response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); MHD_destroy_post_processor (pp); *req_cls = NULL; return ret; } *upload_data_size = 0; return MHD_YES; } struct mhd_test_postdata { #if defined(HAS_CURL_MIME) curl_mime *mime; #else /* ! HAS_CURL_MIME */ struct curl_httppost *post; #endif /* ! HAS_CURL_MIME */ }; /* Return non-zero if succeed */ static int add_test_form (CURL *handle, struct mhd_test_postdata *postdata) { #if defined(HAS_CURL_MIME) postdata->mime = curl_mime_init (handle); if (NULL == postdata->mime) return 0; else { curl_mimepart *part; part = curl_mime_addpart (postdata->mime); if (NULL != part) { if ( (CURLE_OK == curl_mime_data (part, "daniel", CURL_ZERO_TERMINATED)) && (CURLE_OK == curl_mime_name (part, "name")) ) { part = curl_mime_addpart (postdata->mime); if (NULL != part) { if ( (CURLE_OK == curl_mime_data (part, "curl", CURL_ZERO_TERMINATED)) && (CURLE_OK == curl_mime_name (part, "project")) ) { if (CURLE_OK == curl_easy_setopt (handle, CURLOPT_MIMEPOST, postdata->mime)) { return ! 0; } } } } } } curl_mime_free (postdata->mime); postdata->mime = NULL; return 0; #else /* ! HAS_CURL_MIME */ postdata->post = NULL; struct curl_httppost *last = NULL; if (0 == curl_formadd (&postdata->post, &last, CURLFORM_COPYNAME, "name", CURLFORM_COPYCONTENTS, "daniel", CURLFORM_END)) { if (0 == curl_formadd (&postdata->post, &last, CURLFORM_COPYNAME, "project", CURLFORM_COPYCONTENTS, "curl", CURLFORM_END)) { if (CURLE_OK == curl_easy_setopt (handle, CURLOPT_HTTPPOST, postdata->post)) { return ! 0; } } } curl_formfree (postdata->post); return 0; #endif /* ! HAS_CURL_MIME */ } static void free_test_form (struct mhd_test_postdata *postdata) { #if defined(HAS_CURL_MIME) if (NULL != postdata->mime) curl_mime_free (postdata->mime); #else /* ! HAS_CURL_MIME */ if (NULL != postdata->post) curl_formfree (postdata->post); #endif /* ! HAS_CURL_MIME */ } static unsigned int testInternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; struct mhd_test_postdata form; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1390; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (! add_test_form (c, &form)) { fprintf (stderr, "libcurl form initialisation error.\n"); curl_easy_cleanup (c); return 2; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; struct mhd_test_postdata form; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1390; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 5L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (! add_test_form (c, &form)) { fprintf (stderr, "libcurl form initialisation error.\n"); curl_easy_cleanup (c); return 2; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; struct mhd_test_postdata form; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1391; if (oneone) port += 10; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 5L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (! add_test_form (c, &form)) { fprintf (stderr, "libcurl form initialisation error.\n"); curl_easy_cleanup (c); return 2; } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalPost (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; struct mhd_test_postdata form; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1392; if (oneone) port += 10; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_cb, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (! add_test_form (c, &form)) { fprintf (stderr, "libcurl form initialisation error.\n"); curl_easy_cleanup (c); return 2; } multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); free_test_form (&form); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); free_test_form (&form); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); free_test_form (&form); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } free_test_form (&form); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT #ifdef HAVE_GCRYPT_H gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalPost (); errorCount += testMultithreadedPost (); errorCount += testMultithreadedPoolPost (); } errorCount += testExternalPost (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_delete.c0000664000175000017500000003762615232103064015233 /* This file is part of libmicrohttpd Copyright (C) 2007, 2016 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_delete.c * @brief Testcase for libmicrohttpd DELETE operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; struct CBC { char *buf; size_t pos; size_t size; }; static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = ptr; size_t wrt; wrt = size * nmemb; if (wrt > 8 - (*pos)) wrt = 8 - (*pos); memcpy (stream, &("Hello123"[*pos]), wrt); (*pos) += wrt; return wrt; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { int *done = cls; struct MHD_Response *response; enum MHD_Result ret; (void) version; (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp ("DELETE", method)) return MHD_NO; /* unexpected method */ if ((*done) == 0) { if (*upload_data_size != 8) return MHD_YES; /* not yet ready */ if (0 == memcmp (upload_data, "Hello123", 8)) { *upload_data_size = 0; } else { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } *done = 1; return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testInternalDelete (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1152; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedDelete (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1153; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolDelete (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1154; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalDelete (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; size_t pos = 0; int done_flag = 0; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1154; multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalDelete (); errorCount += testMultithreadedDelete (); errorCount += testMultithreadedPoolDelete (); } errorCount += testExternalDelete (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_parse_cookies.c0000664000175000017500000011426015232103064016605 /* This file is part of GNU libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_parse_cookies.c * @brief Testcase for HTTP cookie parsing * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #ifndef _WIN32 #include #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 500000 #define EXPECTED_URI_BASE_PATH "/" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST URL_SCHEME URL_HOST #define PAGE \ "libmicrohttpd test page" \ "Success!" #define PAGE_ERROR \ "Cookies parsing error" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ struct strct_str_len { const char *str; const size_t len; }; #define STR_LEN_(str) {str, MHD_STATICSTR_LEN_ (str)} #define STR_NULL_ {NULL, 0} struct strct_cookie { struct strct_str_len name; struct strct_str_len value; }; #define COOKIE_(name,value) {STR_LEN_ (name), STR_LEN_ (value)} #define COOKIE_NULL {STR_NULL_, STR_NULL_} struct strct_test_data { unsigned int line_num; const char *header_str; unsigned int num_cookies_strict_p2; unsigned int num_cookies_strict_p1; unsigned int num_cookies_strict_zero; unsigned int num_cookies_strict_n2; unsigned int num_cookies_strict_n3; struct strct_cookie cookies[5]; }; static const struct strct_test_data test_data[] = { { __LINE__, "name1=value1", 1, 1, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1;", 0, 1, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; ", 0, 1, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "; name1=value1", 0, 0, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, ";name1=value1", 0, 0, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1 ", 1, 1, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1 ;", 0, 0, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1 ; ", 0, 0, 1, 1, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name2=\"value 2\"", 0, 0, 0, 1, 1, { COOKIE_ ("name2", "value 2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1;\tname2=value2", 0, 1, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; name1=value1", 2, 2, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name1", "value1"), /* The second value is not checked actually */ COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; name2=value2", 2, 2, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; name2=value2 ", 2, 2, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; name2=value2", 0, 1, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1;name2=value2", 0, 1, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1;\tname2=value2", 0, 1, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1 ; name2=value2", 0, 0, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, " name1=value1; name2=value2", 2, 2, 2, 2, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\"; " \ "name5=var_with_=_char", 0, 3, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1;name2=var2;name3=;" \ "name4=\"var4 with spaces\";" \ "name5=var_with_=_char", 0, 1, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\"; " \ "name5=var_with_=_char\t \t", 0, 1, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1;;name2=var2;;name3=;;" \ "name4=\"var4 with spaces\";;" \ "name5=var_with_=_char;\t \t", 0, 1, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name3=; name1=var1; name2=var2; " \ "name5=var_with_=_char;" \ "name4=\"var4 with spaces\"", 0, 4, 4, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name2=var2; name1=var1; " \ "name5=var_with_=_char; name3=; " \ "name4=\"var4 with spaces\";", 0, 4, 4, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name2=var2; name1=var1; " \ "name5=var_with_=_char; " \ "name4=\"var4 with spaces\"; name3=", 0, 3, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name2=var2; name1=var1; " \ "name4=\"var4 with spaces\"; " \ "name5=var_with_=_char; name3=;", 0, 2, 2, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, ";;;;;;;;name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\"; " \ "name5=var_with_=_char", 0, 0, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\"; ; ; ; ; " \ "name5=var_with_=_char", 0, 3, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\"; " \ "name5=var_with_=_char;;;;;;;;", 0, 3, 3, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces"), COOKIE_ ("name5", "var_with_=_char") } }, { __LINE__, "name1=var1; name2=var2; " \ "name4=\"var4 with spaces\";" \ "name5=var_with_=_char; ; ; ; ; name3=", 0, 2, 2, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name5=var_with_=_char ;" \ "name1=var1; name2=var2; name3=; " \ "name4=\"var4 with spaces\" ", 0, 0, 4, 5, 5, { COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name5=var_with_=_char; name4=\"var4 with spaces\";" \ "name1=var1; name2=var2; name3=", 0, 1, 1, 5, 5, { COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4 with spaces") } }, { __LINE__, "name5=var_with_=_char; name4=\"var4_without_spaces\"; " \ "name1=var1; name2=var2; name3=", 5, 5, 5, 5, 5, { COOKIE_ ("name5", "var_with_=_char"), COOKIE_ ("name1", "var1"), COOKIE_ ("name2", "var2"), COOKIE_ ("name3", ""), COOKIE_ ("name4", "var4_without_spaces") } }, { __LINE__, "name1 = value1", 0, 0, 0, 0, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1\t=\tvalue1", 0, 0, 0, 0, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1\t = \tvalue1", 0, 0, 0, 0, 1, { COOKIE_ ("name1", "value1"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1 = value1; name2 =\tvalue2", 0, 0, 0, 0, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1=value1; name2 =\tvalue2", 0, 1, 1, 1, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "name1 = value1; name2=value2", 0, 0, 0, 0, 2, { COOKIE_ ("name1", "value1"), COOKIE_ ("name2", "value2"), COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, " ", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "\t", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "var=,", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "var=\"\\ \"", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "var=value space", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "var=value\ttab", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "=", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "====", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, ";=", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "var", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "=;", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, "= ;", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } }, { __LINE__, ";= ;", 0, 0, 0, 0, 0, { COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL, COOKIE_NULL } } }; /* Global parameters */ static int verbose; static int oneone; /**< If false use HTTP/1.0 for requests*/ static int use_discp_n3; static int use_discp_n2; static int use_discp_zero; static int use_discp_p1; static int use_discp_p2; static int discp_level; static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); } static void test_global_cleanup (void) { curl_global_cleanup (); } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } struct ahc_cls_type { const char *rq_method; const char *rq_url; const struct strct_test_data *check; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; unsigned int expected_num_cookies; unsigned int i; int cookie_failed; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (use_discp_p2) expected_num_cookies = param->check->num_cookies_strict_p2; else if (use_discp_p1) expected_num_cookies = param->check->num_cookies_strict_p1; else if (use_discp_zero) expected_num_cookies = param->check->num_cookies_strict_zero; else if (use_discp_n2) expected_num_cookies = param->check->num_cookies_strict_n2; else if (use_discp_n3) expected_num_cookies = param->check->num_cookies_strict_n3; else externalErrorExit (); if (oneone) { if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); } else { if (0 != strcmp (version, MHD_HTTP_VERSION_1_0)) mhdErrorExitDesc ("Unexpected HTTP version"); } if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (NULL != upload_data) mhdErrorExitDesc ("'upload_data' is not NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); cookie_failed = 0; for (i = 0; i < expected_num_cookies; ++i) { const char *cookie_val; size_t cookie_val_len; const struct strct_cookie *const cookie_data = param->check->cookies + i; if (NULL == cookie_data->name.str) externalErrorExitDesc ("Broken test data"); if (NULL == cookie_data->value.str) externalErrorExitDesc ("Broken test data"); cookie_val = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, cookie_data->name.str); if (cookie_val == NULL) { fprintf (stderr, "'%s' cookie not found.\n", cookie_data->name.str); cookie_failed = 1; } else if (0 != strcmp (cookie_val, cookie_data->value.str)) { fprintf (stderr, "'%s' cookie decoded incorrectly.\n" "Expected: %s\nGot: %s\n", cookie_data->name.str, cookie_data->value.str, cookie_val); cookie_failed = 1; } else if (MHD_YES != MHD_lookup_connection_value_n (connection, MHD_COOKIE_KIND, cookie_data->name.str, cookie_data->name.len, &cookie_val, &cookie_val_len)) { fprintf (stderr, "'%s' (length %lu) cookie not found.\n", cookie_data->name.str, (unsigned long) cookie_data->name.len); cookie_failed = 1; } else { if (cookie_data->value.len != cookie_val_len) { fprintf (stderr, "'%s' (length %lu) cookie has wrong value length.\n" "Expected: %lu\nGot: %lu\n", cookie_data->name.str, (unsigned long) cookie_data->name.len, (unsigned long) cookie_data->value.len, (unsigned long) cookie_val_len); cookie_failed = 1; } else if (0 != memcmp (cookie_val, cookie_data->value.str, cookie_val_len)) { fprintf (stderr, "'%s' (length %lu) cookie has wrong value.\n" "Expected: %.*s\nGot: %.*s\n", cookie_data->name.str, (unsigned long) cookie_data->name.len, (int) cookie_data->value.len, cookie_data->value.str, (int) cookie_val_len, cookie_val); cookie_failed = 1; } } } if (((int) expected_num_cookies) != MHD_get_connection_values_n (connection, MHD_COOKIE_KIND, NULL, NULL)) { fprintf (stderr, "Wrong total number of cookies.\n" "Expected: %u\nGot: %d\n", expected_num_cookies, MHD_get_connection_values_n (connection, MHD_COOKIE_KIND, NULL, NULL)); cookie_failed = 1; } if (cookie_failed) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE_ERROR), PAGE_ERROR); ret = MHD_queue_response (connection, MHD_HTTP_BAD_REQUEST, response); MHD_destroy_response (response); return ret; } if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } *req_cls = NULL; response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), PAGE); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } static int libcurl_debug_cb (CURL *handle, curl_infotype type, char *data, size_t size, void *userptr) { static const char excess_mark[] = "Excess found"; static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark); (void) handle; (void) userptr; #ifdef _DEBUG switch (type) { case CURLINFO_TEXT: fprintf (stderr, "* %.*s", (int) size, data); break; case CURLINFO_HEADER_IN: fprintf (stderr, "< %.*s", (int) size, data); break; case CURLINFO_HEADER_OUT: fprintf (stderr, "> %.*s", (int) size, data); break; case CURLINFO_DATA_IN: #if 0 fprintf (stderr, "<| %.*s\n", (int) size, data); #endif break; case CURLINFO_DATA_OUT: case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: case CURLINFO_END: default: break; } #endif /* _DEBUG */ if (CURLINFO_TEXT == type) { if ((size >= excess_mark_len) && (0 == memcmp (data, excess_mark, excess_mark_len))) mhdErrorExitDesc ("Extra data has been detected in MHD reply"); } return 0; } static CURL * setupCURL (void *cbc, uint16_t port) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &libcurl_debug_cb)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, URL_SCHEME_HOST EXPECTED_URI_BASE_PATH)) libcurlErrorExitDesc ("Cannot set request URL"); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ if (NULL != *multi_reuse) multi = *multi_reuse; else { multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); *multi_reuse = multi; } if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; if (0 == MHD_get_timeout64s (d)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((unsigned long) tv.tv_usec / 1000); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, long expected_code, struct CBC *pcbc) { long code; if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (expected_code != code) { fprintf (stderr, "### The response has wrong HTTP code: %ld\t" "Expected: %ld.\n", code, expected_code); return 0; } else if (verbose) printf ("### The response has expected HTTP code: %ld\n", expected_code); if (pcbc->pos != MHD_STATICSTR_LEN_ (PAGE)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf, (unsigned) MHD_STATICSTR_LEN_ (PAGE)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != memcmp (PAGE, pcbc->buf, pcbc->pos)) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) pcbc->pos, pcbc->buf); mhdErrorExitDesc ("Wrong returned data"); } fflush (stderr); fflush (stdout); return 1; } static unsigned int testExternalPolling (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; struct ahc_cls_type ahc_param; char buf[2048]; CURL *c; CURLM *multi_reuse; size_t i; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1340 + oneone ? 0 : 6 + (uint16_t) (1 + discp_level); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahcCheck, &ahc_param, MHD_OPTION_CLIENT_DISCIPLINE_LVL, (int) (discp_level), MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } ahc_param.rq_method = MHD_HTTP_METHOD_GET; ahc_param.rq_url = EXPECTED_URI_BASE_PATH; cbc.buf = buf; cbc.size = sizeof (buf); memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port); multi_reuse = NULL; for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); ++i) { cbc.pos = 0; ahc_param.check = test_data + i; if (CURLE_OK != curl_easy_setopt (c, CURLOPT_COOKIE, ahc_param.check->header_str)) libcurlErrorExitDesc ("Cannot set request cookies"); if (check_result (performQueryExternal (d, c, &multi_reuse), c, MHD_HTTP_OK, &cbc)) { if (verbose) printf ("### Got expected response for the check at line %u.\n", test_data[i].line_num); fflush (stdout); } else { fprintf (stderr, "### FAILED request for the check at line %u.\n", test_data[i].line_num); fflush (stderr); failed = 1; } } curl_easy_cleanup (c); if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; /* Test type and test parameters */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); oneone = ! has_in_name (argv[0], "10"); use_discp_n3 = has_in_name (argv[0], "_discp_n3"); use_discp_n2 = has_in_name (argv[0], "_discp_n2"); use_discp_zero = has_in_name (argv[0], "_discp_zero"); use_discp_p1 = has_in_name (argv[0], "_discp_p1"); use_discp_p2 = has_in_name (argv[0], "_discp_p2"); if (1 != ((use_discp_n3 ? 1 : 0) + (use_discp_n2 ? 1 : 0) + (use_discp_zero ? 1 : 0) + (use_discp_p1 ? 1 : 0) + (use_discp_p2 ? 1 : 0))) return 99; if (use_discp_n3) discp_level = -3; else if (use_discp_n2) discp_level = -2; else if (use_discp_zero) discp_level = 0; else if (use_discp_p1) discp_level = 1; else if (use_discp_p2) discp_level = 2; test_global_init (); errorCount += testExternalPolling (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_digestauth_concurrent.c0000664000175000017500000005403115232103064020361 /* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_digestauth_concurrent.c * @brief Testcase for libmicrohttpd concurrent Digest Authorisation * @author Amr Ali * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ #include #ifndef WINDOWS #include #include #else #include #endif #include #include "mhd_has_param.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } /* Not actually used in this test */ static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } #if 0 /* Function unused in this test */ static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } #endif /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define MHD_URI_BASE_PATH "/bar%20foo?key=value" #define PAGE \ "libmicrohttpd demoAccess granted" #define DENIED \ "libmicrohttpd demoAccess denied" #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" struct CBC { char *buf; size_t pos; size_t size; }; static int verbose; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) mhdErrorExitDesc ("Wrong too large data"); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; char *username; const char *password = "testpass"; const char *realm = "test@example.com"; enum MHD_Result ret; enum MHD_DigestAuthResult ret_e; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } username = MHD_digest_auth_get_username (connection); if ( (username == NULL) || (0 != strcmp (username, "testuser")) ) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer failed"); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, MHD_NO, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2 failed"); MHD_destroy_response (response); return ret; } ret_e = MHD_digest_auth_check3 (connection, realm, username, password, 50 * TIMEOUTS_VAL, 0, MHD_DIGEST_AUTH_MULT_QOP_AUTH, MHD_DIGEST_AUTH_MULT_ALGO3_MD5); MHD_free (username); if (ret_e != MHD_DAUTH_OK) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer() failed"); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, (MHD_DAUTH_NONCE_STALE == ret_e) ? MHD_YES : MHD_NO, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed"); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); if (NULL == response) mhdErrorExitDesc ("MHD_create_response_from_buffer() failed"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (MHD_YES != ret) mhdErrorExitDesc ("MHD_queue_auth_fail_response2() failed"); MHD_destroy_response (response); return ret; } static CURL * setupCURL (void *cbc, uint16_t port, char *errbuf) { CURL *c; char url[512]; if (1) { int res; /* A workaround for some old libcurl versions, which ignore the specified * port by CURLOPT_PORT when digest authorisation is used. */ res = snprintf (url, (sizeof(url) / sizeof(url[0])), "http://127.0.0.1:%u%s", (unsigned int) port, MHD_URI_BASE_PATH); if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res)) externalErrorExitDesc ("Cannot form request URL"); } c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass"))) libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed"); return c; } static void getRnd (void *buf, size_t size) { #ifndef WINDOWS int fd; size_t off = 0; fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) externalErrorExitDesc ("Failed to open '/dev/urandom'"); do { ssize_t res; res = read (fd, ((uint8_t *) buf) + off, size - off); if (0 > res) externalErrorExitDesc ("Failed to read '/dev/urandom'"); off += (size_t) res; } while (off < size); (void) close (fd); #else HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); if (b == 0) externalErrorExitDesc ("CryptAcquireContext() failed"); b = CryptGenRandom (cc, (DWORD) size, (BYTE *) buf); if (b == 0) externalErrorExitDesc ("CryptGenRandom() failed"); CryptReleaseContext (cc, 0); #endif /* ! WINDOWS */ } struct curlWokerInfo { int workerNumber; struct CBC cbc; pthread_t tid; /** * The libcurl handle to run in thread */ CURL *c; char *libcurl_errbuf; /** * Non-zero if worker is finished */ volatile int finished; /** * The number of successful worker results */ volatile unsigned int success; }; static void * worker_func (void *param) { struct curlWokerInfo *const w = (struct curlWokerInfo *) param; CURLcode req_result; if (NULL == w) externalErrorExit (); req_result = curl_easy_perform (w->c); if (CURLE_OK != req_result) { if (0 != w->libcurl_errbuf[0]) fprintf (stderr, "Worker %d: first request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", w->workerNumber, curl_easy_strerror (req_result), w->libcurl_errbuf); else fprintf (stderr, "Worker %d: first request failed. " "libcurl error: '%s'.\n", w->workerNumber, curl_easy_strerror (req_result)); } else { if (w->cbc.pos != strlen (PAGE)) { fprintf (stderr, "Worker %d: Got %u bytes ('%.*s'), expected %u bytes. ", w->workerNumber, (unsigned) w->cbc.pos, (int) w->cbc.pos, w->cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (PAGE, w->cbc.buf, strlen (PAGE))) { fprintf (stderr, "Worker %d: Got invalid response '%.*s'. ", w->workerNumber, (int) w->cbc.pos, w->cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } if (verbose) printf ("Worker %d: first request successful.\n", w->workerNumber); w->success++; } #ifdef _DEBUG fflush (stderr); fflush (stdout); #endif /* _DEBUG */ /* Second request */ w->cbc.pos = 0; req_result = curl_easy_perform (w->c); if (CURLE_OK != req_result) { if (0 != w->libcurl_errbuf[0]) fprintf (stderr, "Worker %d: second request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", w->workerNumber, curl_easy_strerror (req_result), w->libcurl_errbuf); else fprintf (stderr, "Worker %d: second request failed. " "libcurl error: '%s'.\n", w->workerNumber, curl_easy_strerror (req_result)); } else { if (w->cbc.pos != strlen (PAGE)) { fprintf (stderr, "Worker %d: Got %u bytes ('%.*s'), expected %u bytes. ", w->workerNumber, (unsigned) w->cbc.pos, (int) w->cbc.pos, w->cbc.buf, (unsigned) strlen (MHD_URI_BASE_PATH)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp (PAGE, w->cbc.buf, strlen (PAGE))) { fprintf (stderr, "Worker %d: Got invalid response '%.*s'. ", w->workerNumber, (int) w->cbc.pos, w->cbc.buf); mhdErrorExitDesc ("Wrong returned data"); } if (verbose) printf ("Worker %d: second request successful.\n", w->workerNumber); w->success++; } #ifdef _DEBUG fflush (stderr); fflush (stdout); #endif /* _DEBUG */ w->finished = ! 0; return NULL; } #define CLIENT_BUF_SIZE 2048 static unsigned int testDigestAuth (void) { struct MHD_Daemon *d; char rnd[8]; uint16_t port; size_t i; /* Run three workers in parallel so at least two workers would start within * the same monotonic clock second.*/ struct curlWokerInfo workers[3]; unsigned int ret; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4200; getRnd (rnd, sizeof(rnd)); d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) (sizeof(workers) / sizeof(workers[0])), MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC, (uint32_t) 999, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } /* Initialise all workers */ for (i = 0; i < sizeof(workers) / sizeof(workers[0]); i++) { struct curlWokerInfo *const w = workers + i; w->workerNumber = (int) i + 1; /* Use 1-based numbering */ w->cbc.buf = malloc (CLIENT_BUF_SIZE); if (NULL == w->cbc.buf) externalErrorExitDesc ("malloc() failed"); w->cbc.size = CLIENT_BUF_SIZE; w->cbc.pos = 0; w->libcurl_errbuf = malloc (CURL_ERROR_SIZE); if (NULL == w->libcurl_errbuf) externalErrorExitDesc ("malloc() failed"); w->libcurl_errbuf[0] = 0; w->c = setupCURL (&w->cbc, port, w->libcurl_errbuf); w->finished = 0; w->success = 0; } /* Fire already initialised workers */ for (i = 0; i < sizeof(workers) / sizeof(workers[0]); i++) { struct curlWokerInfo *const w = workers + i; if (0 != pthread_create (&w->tid, NULL, &worker_func, w)) externalErrorExitDesc ("pthread_create() failed"); } /* Collect results, cleanup workers */ ret = 0; for (i = 0; i < sizeof(workers) / sizeof(workers[0]); i++) { struct curlWokerInfo *const w = workers + i; if (0 != pthread_join (w->tid, NULL)) externalErrorExitDesc ("pthread_join() failed"); curl_easy_cleanup (w->c); free (w->libcurl_errbuf); free (w->cbc.buf); if (! w->finished) externalErrorExitDesc ("The worker thread did't signal 'finished' state"); ret += 2 - w->success; } MHD_stop_daemon (d); return ret; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #if (LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR == 62) if (1) { fprintf (stderr, "libcurl version 7.62.x has bug in processing " "URI with GET arguments for Digest Auth.\n"); fprintf (stderr, "This test cannot be performed.\n"); exit (77); } #endif /* libcurl version 7.62.x */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testDigestAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_digestauth_emu_ext.c0000664000175000017500000007027515232103064017655 /* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_digest_emu_ext.c * @brief Testcase for MHD Digest Authorisation client's header parsing * @author Karlson2k (Evgeny Grin) * * libcurl does not support extended notation for username, so this test * "emulates" client request will all valid fields except nonce, cnonce and * response (however syntactically these fields valid as well). */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #include #else #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } /* Not actually used in this test */ static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } #if 0 /* Function unused in this test */ static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } #endif /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 10 #define MHD_URI_BASE_PATH "/bar%20foo?key=value" #define REALM "TestRealm" /* "titkos szuperügynök" in UTF-8 */ #define USERNAME "titkos szuper" "\xC3\xBC" "gyn" "\xC3\xB6" "k" /* percent-encoded username */ #define USERNAME_PCTENC "titkos%20szuper%C3%BCgyn%C3%B6k" #define PASSWORD_VALUE "fake pass" #define OPAQUE_VALUE "opaque-content" #define NONCE_EMU "badbadbadbadbadbadbadbadbadbadbadbadbadbadba" #define CNONCE_EMU "utututututututututututututututututututututs=" #define RESPONSE_EMU "badbadbadbadbadbadbadbadbadbadba" #define PAGE \ "libmicrohttpd demo page" \ "Access granted" #define DENIED \ "libmicrohttpd - Access denied" \ "Access denied" struct CBC { char *buf; size_t pos; size_t size; }; /* Global parameters */ static int verbose; static int oldapi; /* Static helper variables */ static struct curl_slist *curl_headers; static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); curl_headers = NULL; curl_headers = curl_slist_append (curl_headers, "Authorization: " "Digest username*=UTF-8''" USERNAME_PCTENC ", " "realm=\"" REALM "\", " "nonce=\"" NONCE_EMU "\", " "uri=\"" MHD_URI_BASE_PATH "\", " "cnonce=\"" CNONCE_EMU "\", " "nc=00000001, " "qop=auth, " "response=\"" RESPONSE_EMU "\", " "opaque=\"" OPAQUE_VALUE "\", " "algorithm=MD5"); if (NULL == curl_headers) externalErrorExit (); } static void test_global_cleanup (void) { curl_slist_free_all (curl_headers); curl_headers = NULL; curl_global_cleanup (); } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) mhdErrorExitDesc ("Wrong too large data"); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) mhdErrorExitDesc ("Unexpected HTTP method"); if (! oldapi) { struct MHD_DigestAuthUsernameInfo *creds; struct MHD_DigestAuthInfo *dinfo; enum MHD_DigestAuthResult check_res; creds = MHD_digest_auth_get_username3 (connection); if (NULL == creds) mhdErrorExitDesc ("MHD_digest_auth_get_username3() returned NULL"); else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED != creds->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED, (int) creds->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (NULL == creds->username) mhdErrorExitDesc ("'username' is NULL"); else if (creds->username_len != MHD_STATICSTR_LEN_ (USERNAME)) { fprintf (stderr, "'username_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (USERNAME), (unsigned) creds->username_len); mhdErrorExitDesc ("Wrong 'username_len'"); } else if (0 != memcmp (creds->username, USERNAME, creds->username_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", USERNAME, (int) creds->username_len, creds->username); mhdErrorExitDesc ("Wrong 'username'"); } else if (NULL != creds->userhash_hex) mhdErrorExitDesc ("'userhash_hex' is NOT NULL"); else if (0 != creds->userhash_hex_len) mhdErrorExitDesc ("'userhash_hex' is NOT zero"); else if (NULL != creds->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NOT NULL"); dinfo = MHD_digest_auth_get_request_info3 (connection); if (NULL == dinfo) mhdErrorExitDesc ("MHD_digest_auth_get_username3() returned NULL"); else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED != dinfo->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED, (int) creds->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (NULL == dinfo->username) mhdErrorExitDesc ("'username' is NULL"); else if (dinfo->username_len != MHD_STATICSTR_LEN_ (USERNAME)) { fprintf (stderr, "'username_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (USERNAME), (unsigned) dinfo->username_len); mhdErrorExitDesc ("Wrong 'username_len'"); } else if (0 != memcmp (dinfo->username, USERNAME, dinfo->username_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", USERNAME, (int) dinfo->username_len, dinfo->username); mhdErrorExitDesc ("Wrong 'username'"); } else if (NULL != dinfo->userhash_hex) mhdErrorExitDesc ("'userhash_hex' is NOT NULL"); else if (0 != dinfo->userhash_hex_len) mhdErrorExitDesc ("'userhash_hex' is NOT zero"); else if (NULL != dinfo->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NOT NULL"); else if (MHD_DIGEST_AUTH_ALGO3_MD5 != dinfo->algo3) { fprintf (stderr, "Unexpected 'algo'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_ALGO3_MD5, (int) dinfo->algo3); mhdErrorExitDesc ("Wrong 'algo'"); } else if (MHD_STATICSTR_LEN_ (CNONCE_EMU) != dinfo->cnonce_len) { fprintf (stderr, "Unexpected 'cnonce_len'.\n" "Expected: %d\tRecieved: %ld. ", (int) MHD_STATICSTR_LEN_ (CNONCE_EMU), (long) dinfo->cnonce_len); mhdErrorExitDesc ("Wrong 'cnonce_len'"); } else if (NULL == dinfo->opaque) mhdErrorExitDesc ("'opaque' is NULL"); else if (dinfo->opaque_len != MHD_STATICSTR_LEN_ (OPAQUE_VALUE)) { fprintf (stderr, "'opaque_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (OPAQUE_VALUE), (unsigned) dinfo->opaque_len); mhdErrorExitDesc ("Wrong 'opaque_len'"); } else if (0 != memcmp (dinfo->opaque, OPAQUE_VALUE, dinfo->opaque_len)) { fprintf (stderr, "'opaque' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", OPAQUE_VALUE, (int) dinfo->opaque_len, dinfo->opaque); mhdErrorExitDesc ("Wrong 'opaque'"); } else if (MHD_DIGEST_AUTH_QOP_AUTH != dinfo->qop) { fprintf (stderr, "Unexpected 'qop'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_QOP_AUTH, (int) dinfo->qop); mhdErrorExitDesc ("Wrong 'qop'"); } else if (NULL == dinfo->realm) mhdErrorExitDesc ("'realm' is NULL"); else if (dinfo->realm_len != MHD_STATICSTR_LEN_ (REALM)) { fprintf (stderr, "'realm_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (REALM), (unsigned) dinfo->realm_len); mhdErrorExitDesc ("Wrong 'realm_len'"); } else if (0 != memcmp (dinfo->realm, REALM, dinfo->realm_len)) { fprintf (stderr, "'realm' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", OPAQUE_VALUE, (int) dinfo->realm_len, dinfo->realm); mhdErrorExitDesc ("Wrong 'realm'"); } MHD_free (creds); MHD_free (dinfo); check_res = MHD_digest_auth_check3 (connection, REALM, USERNAME, PASSWORD_VALUE, 50 * TIMEOUTS_VAL, 0, MHD_DIGEST_AUTH_MULT_QOP_AUTH, MHD_DIGEST_AUTH_MULT_ALGO3_MD5); switch (check_res) { /* Valid results */ case MHD_DAUTH_NONCE_STALE: if (verbose) printf ("Got valid auth check result: MHD_DAUTH_NONCE_STALE.\n"); break; case MHD_DAUTH_NONCE_WRONG: if (verbose) printf ("Got valid auth check result: MHD_DAUTH_NONCE_WRONG.\n"); break; /* Invalid results */ case MHD_DAUTH_OK: mhdErrorExitDesc ("'MHD_digest_auth_check3()' succeed, " \ "but it should not"); break; case MHD_DAUTH_ERROR: externalErrorExitDesc ("General error returned " \ "by 'MHD_digest_auth_check3()'"); break; case MHD_DAUTH_WRONG_USERNAME: mhdErrorExitDesc ("MHD_digest_auth_check3()' returned " \ "MHD_DAUTH_WRONG_USERNAME"); break; case MHD_DAUTH_RESPONSE_WRONG: mhdErrorExitDesc ("MHD_digest_auth_check3()' returned " \ "MHD_DAUTH_RESPONSE_WRONG"); break; case MHD_DAUTH_WRONG_HEADER: case MHD_DAUTH_WRONG_REALM: case MHD_DAUTH_WRONG_URI: case MHD_DAUTH_WRONG_QOP: case MHD_DAUTH_WRONG_ALGO: case MHD_DAUTH_TOO_LARGE: case MHD_DAUTH_NONCE_OTHER_COND: fprintf (stderr, "'MHD_digest_auth_check3()' returned " "unexpected result: %d. ", check_res); mhdErrorExitDesc ("Wrong returned code"); break; default: fprintf (stderr, "'MHD_digest_auth_check3()' returned " "impossible result code: %d. ", check_res); mhdErrorExitDesc ("Impossible returned code"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_auth_fail_response2 (connection, REALM, OPAQUE_VALUE, response, 0, MHD_DIGEST_ALG_MD5); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_auth_fail_response2()' failed"); } else { char *username; int check_res; username = MHD_digest_auth_get_username (connection); if (NULL == username) mhdErrorExitDesc ("'MHD_digest_auth_get_username()' returned NULL"); else if (0 != strcmp (username, USERNAME)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%s'. ", USERNAME, username); mhdErrorExitDesc ("Wrong 'username'"); } MHD_free (username); check_res = MHD_digest_auth_check (connection, REALM, USERNAME, PASSWORD_VALUE, 300); if (MHD_INVALID_NONCE != check_res) { fprintf (stderr, "'MHD_digest_auth_check()' returned unexpected" " result: %d. ", check_res); mhdErrorExitDesc ("Wrong 'MHD_digest_auth_check()' result"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_auth_fail_response (connection, REALM, OPAQUE_VALUE, response, 0); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_auth_fail_response()' failed"); } MHD_destroy_response (response); return ret; } static CURL * setupCURL (void *cbc, uint16_t port) { CURL *c; char url[512]; if (1) { int res; /* A workaround for some old libcurl versions, which ignore the specified * port by CURLOPT_PORT when authorisation is used. */ res = snprintf (url, (sizeof(url) / sizeof(url[0])), "http://127.0.0.1:%u%s", (unsigned int) port, MHD_URI_BASE_PATH); if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res)) externalErrorExitDesc ("Cannot form request URL"); } c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || /* (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_headers)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ multi = NULL; multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep (200); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, struct CBC *pcbc) { long code; if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (401 != code) { fprintf (stderr, "Request returned wrong code: %ld.\n", code); return 0; } if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (pcbc->pos != strlen (DENIED)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf, (unsigned) strlen (DENIED)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != memcmp (DENIED, pcbc->buf, pcbc->pos)) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) pcbc->pos, pcbc->buf); mhdErrorExitDesc ("Wrong returned data"); } return 1; } static unsigned int testDigestAuthEmu (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; char buf[2048]; CURL *c; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4210; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = (uint16_t) dinfo->port; } /* First request */ cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port); if (check_result (performQueryExternal (d, c), c, &cbc)) { if (verbose) printf ("Got expected response.\n"); } else { fprintf (stderr, "Request FAILED.\n"); failed = 1; } curl_easy_cleanup (c); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); oldapi = has_in_name (argv[0], "_oldapi"); test_global_init (); errorCount += testDigestAuthEmu (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_digestauth2.c0000664000175000017500000015274615232103064016215 /* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_digest2.c * @brief Testcase for MHD Digest Authorisation * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ #ifndef _WIN32 #include #include #else #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func (NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func (NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func ((libcurlcall), _MHD_STRMACRO (libcurlcall), NULL, \ __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } /* Not actually used in this test */ static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } #if 0 /* Function unused in this test */ static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } #endif /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 10 #define MHD_URI_BASE_PATH "/bar%20foo?key=value" #define MHD_URI_BASE_PATH2 "/another_path" /* Should not fit buffer in the stack */ #define MHD_URI_BASE_PATH3 \ "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long/long/long/long" \ "/path?with%20some=parameters" #define REALM_VAL "TestRealm" #define USERNAME1 "test_user" /* The hex form of MD5("test_user:TestRealm") */ #define USERHASH1_MD5_HEX "c53c601503ff176f18f623725fba4281" #define USERHASH1_MD5_BIN 0xc5, 0x3c, 0x60, 0x15, 0x03, 0xff, 0x17, 0x6f, \ 0x18, 0xf6, 0x23, 0x72, 0x5f, 0xba, 0x42, 0x81 /* The hex form of SHA-256("test_user:TestRealm") */ #define USERHASH1_SHA256_HEX \ "090c7e06b77d6614cf5fe6cafa004d2e5f8fb36ba45a0e35eacb2eb7728f34de" /* The binary form of SHA-256("test_user:TestRealm") */ #define USERHASH1_SHA256_BIN 0x09, 0x0c, 0x7e, 0x06, 0xb7, 0x7d, 0x66, 0x14, \ 0xcf, 0x5f, 0xe6, 0xca, 0xfa, 0x00, 0x4d, 0x2e, 0x5f, 0x8f, 0xb3, 0x6b, \ 0xa4, 0x5a, 0x0e, 0x35, 0xea, 0xcb, 0x2e, 0xb7, 0x72, 0x8f, 0x34, 0xde /* The hex form of MD5("test_user:TestRealm:test pass") */ #define USERDIGEST1_MD5_BIN 0xd8, 0xb4, 0xa6, 0xd0, 0x01, 0x13, 0x07, 0xb7, \ 0x67, 0x94, 0xea, 0x66, 0x86, 0x03, 0x6b, 0x43 /* The binary form of SHA-256("test_user:TestRealm:test pass") */ #define USERDIGEST1_SHA256_BIN 0xc3, 0x4e, 0x16, 0x5a, 0x17, 0x0f, 0xe5, \ 0xac, 0x04, 0xf1, 0x6e, 0x46, 0x48, 0x2b, 0xa0, 0xc6, 0x56, 0xc1, 0xfb, \ 0x8f, 0x66, 0xa6, 0xd6, 0x3f, 0x91, 0x12, 0xf8, 0x56, 0xa5, 0xec, 0x6d, \ 0x6d #define PASSWORD_VALUE "test pass" #define OPAQUE_VALUE "opaque+content" /* Base64 character set */ #define PAGE \ "libmicrohttpd demo page" \ "Access granted" #define DENIED \ "libmicrohttpd - Access denied" \ "Access denied" /* Global parameters */ static int verbose; static int test_oldapi; static int test_userhash; static int test_userdigest; static int test_sha256; static int test_rfc2069; /* Bind DAuth nonces to everything except URI */ static int test_bind_all; /* Bind DAuth nonces to URI */ static int test_bind_uri; static int curl_uses_usehash; /* Static helper variables */ static const char userhash1_md5_hex[] = USERHASH1_MD5_HEX; static const uint8_t userhash1_md5_bin[] = { USERHASH1_MD5_BIN }; static const char userhash1_sha256_hex[] = USERHASH1_SHA256_HEX; static const uint8_t userhash1_sha256_bin[] = { USERHASH1_SHA256_BIN }; static const char *userhash_hex; static size_t userhash_hex_len; static const uint8_t *userhash_bin; static const uint8_t userdigest1_md5_bin[] = { USERDIGEST1_MD5_BIN }; static const uint8_t userdigest1_sha256_bin[] = { USERDIGEST1_SHA256_BIN }; static const uint8_t *userdigest_bin; static size_t userdigest_bin_size; static const char *username_ptr; static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); username_ptr = USERNAME1; if (! test_sha256) { userhash_hex = userhash1_md5_hex; userhash_hex_len = MHD_STATICSTR_LEN_ (userhash1_md5_hex); userhash_bin = userhash1_md5_bin; if ((userhash_hex_len / 2) != \ (sizeof(userhash1_md5_bin) / sizeof(userhash1_md5_bin[0]))) externalErrorExitDesc ("Wrong size of the 'userhash1_md5_bin' array"); userdigest_bin = userdigest1_md5_bin; userdigest_bin_size = (sizeof(userdigest1_md5_bin) / sizeof(userdigest1_md5_bin[0])); } else { userhash_hex = userhash1_sha256_hex; userhash_hex_len = MHD_STATICSTR_LEN_ (userhash1_sha256_hex); userhash_bin = userhash1_sha256_bin; if ((userhash_hex_len / 2) != \ (sizeof(userhash1_sha256_bin) \ / sizeof(userhash1_sha256_bin[0]))) externalErrorExitDesc ("Wrong size of the 'userhash1_sha256_bin' array"); userdigest_bin = userdigest1_sha256_bin; userdigest_bin_size = (sizeof(userdigest1_sha256_bin) / sizeof(userdigest1_sha256_bin[0])); } } static void test_global_cleanup (void) { curl_global_cleanup (); } static int gen_good_rnd (void *rnd_buf, size_t rnd_buf_size) { if (1024 < rnd_buf_size) externalErrorExitDesc ("Too large amount of random data " \ "is requested"); #ifndef _WIN32 if (1) { const int urand_fd = open ("/dev/urandom", O_RDONLY); if (0 <= urand_fd) { size_t pos = 0; do { ssize_t res = read (urand_fd, ((uint8_t *) rnd_buf) + pos, rnd_buf_size - pos); if (0 > res) break; pos += (size_t) res; } while (rnd_buf_size > pos); (void) close (urand_fd); if (rnd_buf_size == pos) return ! 0; /* Success */ } } #else /* _WIN32 */ if (1) { HCRYPTPROV cpr_hndl; if (CryptAcquireContextW (&cpr_hndl, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { if (CryptGenRandom (cpr_hndl, (DWORD) rnd_buf_size, (BYTE *) rnd_buf)) { (void) CryptReleaseContext (cpr_hndl, 0); return ! 0; /* Success */ } (void) CryptReleaseContext (cpr_hndl, 0); } } #endif /* _WIN32 */ return 0; /* Failure */ } struct CBC { char *buf; size_t pos; size_t size; }; struct req_track { /** * The number of used URI, zero-based */ unsigned int uri_num; /** * The number of request for URI. * This includes number of unauthorised requests. */ unsigned int req_num; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) mhdErrorExitDesc ("Wrong too large data"); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result res; static int already_called_marker; struct req_track *const tr_p = (struct req_track *) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) mhdErrorExitDesc ("Unexpected HTTP method"); tr_p->req_num++; if (2 < tr_p->req_num) mhdErrorExitDesc ("Received more than two requests for the same URI"); response = NULL; if (! test_oldapi) { struct MHD_DigestAuthInfo *dinfo; const enum MHD_DigestAuthAlgo3 algo3 = test_sha256 ? MHD_DIGEST_AUTH_ALGO3_SHA256 : MHD_DIGEST_AUTH_ALGO3_MD5; const enum MHD_DigestAuthQOP qop = test_rfc2069 ? MHD_DIGEST_AUTH_QOP_NONE : MHD_DIGEST_AUTH_QOP_AUTH; dinfo = MHD_digest_auth_get_request_info3 (connection); if (NULL != dinfo) { /* Got any kind of Digest response. Check it, it must be valid */ struct MHD_DigestAuthUsernameInfo *uname; enum MHD_DigestAuthResult check_res; enum MHD_DigestAuthResult expect_res; if (curl_uses_usehash) { if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH != dinfo->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH, (int) dinfo->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (dinfo->userhash_hex_len != userhash_hex_len) { fprintf (stderr, "'userhash_hex_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) userhash_hex_len, (unsigned) dinfo->userhash_hex_len); mhdErrorExitDesc ("Wrong 'userhash_hex_len'"); } else if (0 != memcmp (dinfo->userhash_hex, userhash_hex, dinfo->userhash_hex_len)) { fprintf (stderr, "'userhash_hex' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", userhash_hex, (int) dinfo->userhash_hex_len, dinfo->userhash_hex); mhdErrorExitDesc ("Wrong 'userhash_hex'"); } else if (NULL == dinfo->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NULL"); else if (0 != memcmp (dinfo->userhash_bin, userhash_bin, dinfo->username_len / 2)) mhdErrorExitDesc ("Wrong 'userhash_bin'"); else if (NULL != dinfo->username) mhdErrorExitDesc ("'username' is NOT NULL"); else if (0 != dinfo->username_len) mhdErrorExitDesc ("'username_len' is NOT zero"); } else { if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD != dinfo->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD, (int) dinfo->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (NULL == dinfo->username) mhdErrorExitDesc ("'username' is NULL"); else if (dinfo->username_len != strlen (username_ptr)) { fprintf (stderr, "'username_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) strlen (username_ptr), (unsigned) dinfo->username_len); mhdErrorExitDesc ("Wrong 'username_len'"); } else if (0 != memcmp (dinfo->username, username_ptr, dinfo->username_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", username_ptr, (int) dinfo->username_len, dinfo->username); mhdErrorExitDesc ("Wrong 'username'"); } else if (NULL != dinfo->userhash_hex) mhdErrorExitDesc ("'userhash_hex' is NOT NULL"); else if (0 != dinfo->userhash_hex_len) mhdErrorExitDesc ("'userhash_hex_len' is NOT zero"); else if (NULL != dinfo->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NOT NULL"); } if (algo3 != dinfo->algo3) { fprintf (stderr, "Unexpected 'algo3'.\n" "Expected: %d\tRecieved: %d. ", (int) algo3, (int) dinfo->algo3); mhdErrorExitDesc ("Wrong 'algo3'"); } if (! test_rfc2069) { if ( #if CURL_AT_LEAST_VERSION (7,37,1) 10 >= dinfo->cnonce_len #else /* libcurl before 7.37.1 */ 8 > dinfo->cnonce_len #endif /* libcurl before 7.37.1 */ ) { fprintf (stderr, "Unexpected small 'cnonce_len': %ld. ", (long) dinfo->cnonce_len); mhdErrorExitDesc ("Wrong 'cnonce_len'"); } } else { if (0 != dinfo->cnonce_len) { fprintf (stderr, "'cnonce_len' is not zero: %ld. ", (long) dinfo->cnonce_len); mhdErrorExitDesc ("Wrong 'cnonce_len'"); } } if (NULL == dinfo->opaque) mhdErrorExitDesc ("'opaque' is NULL"); else if (dinfo->opaque_len != MHD_STATICSTR_LEN_ (OPAQUE_VALUE)) { fprintf (stderr, "'opaque_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (OPAQUE_VALUE), (unsigned) dinfo->opaque_len); mhdErrorExitDesc ("Wrong 'opaque_len'"); } else if (0 != memcmp (dinfo->opaque, OPAQUE_VALUE, dinfo->opaque_len)) { fprintf (stderr, "'opaque' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", OPAQUE_VALUE, (int) dinfo->opaque_len, dinfo->opaque); mhdErrorExitDesc ("Wrong 'opaque'"); } else if (qop != dinfo->qop) { fprintf (stderr, "Unexpected 'qop'.\n" "Expected: %d\tRecieved: %d. ", (int) qop, (int) dinfo->qop); mhdErrorExitDesc ("Wrong 'qop'"); } else if (NULL == dinfo->realm) mhdErrorExitDesc ("'realm' is NULL"); else if (dinfo->realm_len != MHD_STATICSTR_LEN_ (REALM_VAL)) { fprintf (stderr, "'realm_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (REALM_VAL), (unsigned) dinfo->realm_len); mhdErrorExitDesc ("Wrong 'realm_len'"); } else if (0 != memcmp (dinfo->realm, REALM_VAL, dinfo->realm_len)) { fprintf (stderr, "'realm' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", OPAQUE_VALUE, (int) dinfo->realm_len, dinfo->realm); mhdErrorExitDesc ("Wrong 'realm'"); } MHD_free (dinfo); uname = MHD_digest_auth_get_username3 (connection); if (NULL == uname) mhdErrorExitDesc ("MHD_digest_auth_get_username3() returned NULL"); if (curl_uses_usehash) { if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH != uname->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH, (int) uname->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (uname->userhash_hex_len != userhash_hex_len) { fprintf (stderr, "'userhash_hex_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) userhash_hex_len, (unsigned) uname->userhash_hex_len); mhdErrorExitDesc ("Wrong 'userhash_hex_len'"); } else if (0 != memcmp (uname->userhash_hex, userhash_hex, uname->userhash_hex_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", userhash_hex, (int) uname->userhash_hex_len, uname->userhash_hex); mhdErrorExitDesc ("Wrong 'userhash_hex'"); } else if (NULL == uname->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NULL"); else if (0 != memcmp (uname->userhash_bin, userhash_bin, uname->username_len / 2)) mhdErrorExitDesc ("Wrong 'userhash_bin'"); else if (NULL != uname->username) mhdErrorExitDesc ("'username' is NOT NULL"); else if (0 != uname->username_len) mhdErrorExitDesc ("'username_len' is NOT zero"); } else { if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD != uname->uname_type) { fprintf (stderr, "Unexpected 'uname_type'.\n" "Expected: %d\tRecieved: %d. ", (int) MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD, (int) uname->uname_type); mhdErrorExitDesc ("Wrong 'uname_type'"); } else if (NULL == uname->username) mhdErrorExitDesc ("'username' is NULL"); else if (uname->username_len != strlen (username_ptr)) { fprintf (stderr, "'username_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) strlen (username_ptr), (unsigned) uname->username_len); mhdErrorExitDesc ("Wrong 'username_len'"); } else if (0 != memcmp (uname->username, username_ptr, uname->username_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", username_ptr, (int) uname->username_len, uname->username); mhdErrorExitDesc ("Wrong 'username'"); } else if (NULL != uname->userhash_hex) mhdErrorExitDesc ("'userhash_hex' is NOT NULL"); else if (0 != uname->userhash_hex_len) mhdErrorExitDesc ("'userhash_hex_len' is NOT zero"); else if (NULL != uname->userhash_bin) mhdErrorExitDesc ("'userhash_bin' is NOT NULL"); } if (algo3 != uname->algo3) { fprintf (stderr, "Unexpected 'algo3'.\n" "Expected: %d\tRecieved: %d. ", (int) algo3, (int) uname->algo3); mhdErrorExitDesc ("Wrong 'algo3'"); } MHD_free (uname); if (! test_userdigest) check_res = MHD_digest_auth_check3 (connection, REALM_VAL, username_ptr, PASSWORD_VALUE, 50 * TIMEOUTS_VAL, 0, (enum MHD_DigestAuthMultiQOP) qop, (enum MHD_DigestAuthMultiAlgo3) algo3); else check_res = MHD_digest_auth_check_digest3 (connection, REALM_VAL, username_ptr, userdigest_bin, userdigest_bin_size, 50 * TIMEOUTS_VAL, 0, (enum MHD_DigestAuthMultiQOP) qop, (enum MHD_DigestAuthMultiAlgo3) algo3); if (test_rfc2069) { if ((0 != tr_p->uri_num) && (1 == tr_p->req_num)) expect_res = MHD_DAUTH_NONCE_STALE; else expect_res = MHD_DAUTH_OK; } else if (test_bind_uri) { if ((0 != tr_p->uri_num) && (1 == tr_p->req_num)) expect_res = MHD_DAUTH_NONCE_OTHER_COND; else expect_res = MHD_DAUTH_OK; } else expect_res = MHD_DAUTH_OK; switch (check_res) { /* Conditionally valid results */ case MHD_DAUTH_OK: if (expect_res == MHD_DAUTH_OK) { if (verbose) printf ("Got valid auth check result: MHD_DAUTH_OK.\n"); } else mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_OK"); break; case MHD_DAUTH_NONCE_STALE: if (expect_res == MHD_DAUTH_NONCE_STALE) { if (verbose) printf ("Got expected auth check result: MHD_DAUTH_NONCE_STALE.\n"); } else mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_NONCE_STALE"); break; case MHD_DAUTH_NONCE_OTHER_COND: if (expect_res == MHD_DAUTH_NONCE_OTHER_COND) { if (verbose) printf ("Got expected auth check result: " "MHD_DAUTH_NONCE_OTHER_COND.\n"); } else mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_NONCE_OTHER_COND"); break; /* Invalid results */ case MHD_DAUTH_NONCE_WRONG: mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_NONCE_WRONG"); break; case MHD_DAUTH_ERROR: externalErrorExitDesc ("General error returned " \ "by 'MHD_digest_auth_check[_digest]3()'"); break; case MHD_DAUTH_WRONG_USERNAME: mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_WRONG_USERNAME"); break; case MHD_DAUTH_RESPONSE_WRONG: mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_RESPONSE_WRONG"); break; case MHD_DAUTH_WRONG_HEADER: mhdErrorExitDesc ("MHD_digest_auth_check[_digest]3()' returned " \ "MHD_DAUTH_WRONG_HEADER"); break; case MHD_DAUTH_WRONG_REALM: case MHD_DAUTH_WRONG_URI: case MHD_DAUTH_WRONG_QOP: case MHD_DAUTH_WRONG_ALGO: case MHD_DAUTH_TOO_LARGE: fprintf (stderr, "'MHD_digest_auth_check[_digest]3()' returned " "unexpected result: %d. ", check_res); mhdErrorExitDesc ("Wrong returned code"); break; default: fprintf (stderr, "'MHD_digest_auth_check[_digest]3()' returned " "impossible result code: %d. ", check_res); mhdErrorExitDesc ("Impossible returned code"); } fflush (stderr); fflush (stdout); if (MHD_DAUTH_OK == check_res) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), (const void *) PAGE); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); if (MHD_YES != MHD_queue_response (connection, MHD_HTTP_OK, response)) mhdErrorExitDesc ("'MHD_queue_response()' failed"); } else if ((MHD_DAUTH_NONCE_STALE == check_res) || (MHD_DAUTH_NONCE_OTHER_COND == check_res)) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); res = MHD_queue_auth_required_response3 (connection, REALM_VAL, OPAQUE_VALUE, "/", response, 1, (enum MHD_DigestAuthMultiQOP) qop, (enum MHD_DigestAuthMultiAlgo3) algo3, test_userhash, 0); if (MHD_YES != res) mhdErrorExitDesc ("'MHD_queue_auth_required_response3()' failed"); } else externalErrorExitDesc ("Wrong 'check_res' value"); } else { /* No Digest auth header */ if ((1 != tr_p->req_num) || (0 != tr_p->uri_num)) { fprintf (stderr, "Received request number %u for URI number %u " "without Digest Authorisation header. ", tr_p->req_num, tr_p->uri_num + 1); mhdErrorExitDesc ("Wrong requests sequence"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); res = MHD_queue_auth_required_response3 ( connection, REALM_VAL, OPAQUE_VALUE, "/", response, 0, (enum MHD_DigestAuthMultiQOP) qop, (enum MHD_DigestAuthMultiAlgo3) algo3, test_userhash, 0); if (MHD_YES != res) mhdErrorExitDesc ("'MHD_queue_auth_required_response3()' failed"); } } else if (2 == test_oldapi) { /* Use old API v2 */ char *username; int check_res; int expect_res; username = MHD_digest_auth_get_username (connection); if (NULL != username) { /* Has a valid username in header */ if (0 != strcmp (username, username_ptr)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%s'. ", username_ptr, username); mhdErrorExitDesc ("Wrong 'username'"); } MHD_free (username); if (! test_userdigest) check_res = MHD_digest_auth_check2 (connection, REALM_VAL, username_ptr, PASSWORD_VALUE, 50 * TIMEOUTS_VAL, test_sha256 ? MHD_DIGEST_ALG_SHA256 : MHD_DIGEST_ALG_MD5); else check_res = MHD_digest_auth_check_digest2 (connection, REALM_VAL, username_ptr, userdigest_bin, userdigest_bin_size, 50 * TIMEOUTS_VAL, test_sha256 ? MHD_DIGEST_ALG_SHA256 : MHD_DIGEST_ALG_MD5); if (test_bind_uri) { if ((0 != tr_p->uri_num) && (1 == tr_p->req_num)) expect_res = MHD_INVALID_NONCE; else expect_res = MHD_YES; } else expect_res = MHD_YES; if (expect_res != check_res) { fprintf (stderr, "'MHD_digest_auth_check[_digest]2()' returned " "unexpected result '%d', while expected is '%d. ", check_res, expect_res); mhdErrorExitDesc ("Wrong 'MHD_digest_auth_check[_digest]2()' result"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), (const void *) PAGE); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); if (MHD_YES == expect_res) { if (MHD_YES != MHD_queue_response (connection, MHD_HTTP_OK, response)) mhdErrorExitDesc ("'MHD_queue_response()' failed"); } else if (MHD_INVALID_NONCE == expect_res) { if (MHD_YES != MHD_queue_auth_fail_response2 (connection, REALM_VAL, OPAQUE_VALUE, response, 1, test_sha256 ? MHD_DIGEST_ALG_SHA256 : MHD_DIGEST_ALG_MD5)) mhdErrorExitDesc ("'MHD_queue_auth_fail_response2()' failed"); } else externalErrorExitDesc ("Wrong 'check_res' value"); } else { /* Has no valid username in header */ if ((1 != tr_p->req_num) || (0 != tr_p->uri_num)) { fprintf (stderr, "Received request number %u for URI number %u " "without Digest Authorisation header. ", tr_p->req_num, tr_p->uri_num + 1); mhdErrorExitDesc ("Wrong requests sequence"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); res = MHD_queue_auth_fail_response2 (connection, REALM_VAL, OPAQUE_VALUE, response, 0, test_sha256 ? MHD_DIGEST_ALG_SHA256 : MHD_DIGEST_ALG_MD5); if (MHD_YES != res) mhdErrorExitDesc ("'MHD_queue_auth_fail_response2()' failed"); } } else if (1 == test_oldapi) { /* Use old API v1 */ char *username; int check_res; int expect_res; username = MHD_digest_auth_get_username (connection); if (NULL != username) { /* Has a valid username in header */ if (0 != strcmp (username, username_ptr)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%s'. ", username_ptr, username); mhdErrorExitDesc ("Wrong 'username'"); } MHD_free (username); if (! test_userdigest) check_res = MHD_digest_auth_check (connection, REALM_VAL, username_ptr, PASSWORD_VALUE, 50 * TIMEOUTS_VAL); else check_res = MHD_digest_auth_check_digest (connection, REALM_VAL, username_ptr, userdigest_bin, 50 * TIMEOUTS_VAL); if (test_bind_uri) { if ((0 != tr_p->uri_num) && (1 == tr_p->req_num)) expect_res = MHD_INVALID_NONCE; else expect_res = MHD_YES; } else expect_res = MHD_YES; if (expect_res != check_res) { fprintf (stderr, "'MHD_digest_auth_check[_digest]()' returned " "unexpected result '%d', while expected is '%d. ", check_res, expect_res); mhdErrorExitDesc ("Wrong 'MHD_digest_auth_check[_digest]()' result"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), (const void *) PAGE); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); if (MHD_YES == expect_res) { if (MHD_YES != MHD_queue_response (connection, MHD_HTTP_OK, response)) mhdErrorExitDesc ("'MHD_queue_response()' failed"); } else if (MHD_INVALID_NONCE == expect_res) { if (MHD_YES != MHD_queue_auth_fail_response (connection, REALM_VAL, OPAQUE_VALUE, response, 1)) mhdErrorExitDesc ("'MHD_queue_auth_fail_response()' failed"); } else externalErrorExitDesc ("Wrong 'check_res' value"); } else { /* Has no valid username in header */ if ((1 != tr_p->req_num) || (0 != tr_p->uri_num)) { fprintf (stderr, "Received request number %u for URI number %u " "without Digest Authorisation header. ", tr_p->req_num, tr_p->uri_num + 1); mhdErrorExitDesc ("Wrong requests sequence"); } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); res = MHD_queue_auth_fail_response (connection, REALM_VAL, OPAQUE_VALUE, response, 0); if (MHD_YES != res) mhdErrorExitDesc ("'MHD_queue_auth_fail_response()' failed"); } } else externalErrorExitDesc ("Wrong 'test_oldapi' value"); MHD_destroy_response (response); return MHD_YES; } /** * * @param c the CURL handle to use * @param port the port to set * @param uri_num the number of URI, should be 0, 1 or 2 */ static void setCURL_rq_path (CURL *c, uint16_t port, unsigned int uri_num) { const char *req_path; char uri[512]; int res; if (0 == uri_num) req_path = MHD_URI_BASE_PATH; else if (1 == uri_num) req_path = MHD_URI_BASE_PATH2; else req_path = MHD_URI_BASE_PATH3; /* A workaround for some old libcurl versions, which ignore the specified * port by CURLOPT_PORT when authorisation is used. */ res = snprintf (uri, (sizeof(uri) / sizeof(uri[0])), "http://127.0.0.1:%u%s", (unsigned int) port, req_path); if ((0 >= res) || ((sizeof(uri) / sizeof(uri[0])) <= (size_t) res)) externalErrorExitDesc ("Cannot form request URL"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, uri)) libcurlErrorExitDesc ("Cannot set request URL"); } static CURL * setupCURL (void *cbc, uint16_t port) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, (long) CURLAUTH_DIGEST)) || #if CURL_AT_LEAST_VERSION (7,19,1) /* Need version 7.19.1 for separate username and password */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERNAME, username_ptr)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PASSWORD, PASSWORD_VALUE)) || #endif /* CURL_AT_LEAST_VERSION(7,19,1) */ #ifdef _DEBUG (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || #endif /* _DEBUG */ #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); setCURL_rq_path (c, port, 0); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c, CURLM **multi_reuse) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ if (NULL != *multi_reuse) multi = *multi_reuse; else { multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); *multi_reuse = multi; } if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep (200); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, CURL *c, struct CBC *pcbc) { long code; if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code)) libcurlErrorExit (); if (MHD_HTTP_OK != code) { fprintf (stderr, "Request returned wrong code: %ld.\n", code); return 0; } if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "Request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (pcbc->pos != MHD_STATICSTR_LEN_ (PAGE)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf, (unsigned) MHD_STATICSTR_LEN_ (PAGE)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != memcmp (PAGE, pcbc->buf, pcbc->pos)) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) pcbc->pos, pcbc->buf); mhdErrorExitDesc ("Wrong returned data"); } return 1; } static unsigned int testDigestAuth (void) { unsigned int dauth_nonce_bind; struct MHD_Daemon *d; uint16_t port; struct CBC cbc; struct req_track rq_tr; char buf[2048]; CURL *c; CURLM *multi_reuse; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4210; if (1) { uint8_t salt[8]; /* Use local variable to test MHD "copy" function */ if (! gen_good_rnd (salt, sizeof(salt))) { fprintf (stderr, "WARNING: the random buffer (used as salt value) is not " "initialised completely, nonce generation may be " "predictable in this test.\n"); fflush (stderr); } dauth_nonce_bind = MHD_DAUTH_BIND_NONCE_NONE; if (test_bind_all) dauth_nonce_bind |= (MHD_DAUTH_BIND_NONCE_CLIENT_IP | MHD_DAUTH_BIND_NONCE_REALM); if (test_bind_uri) dauth_nonce_bind |= MHD_DAUTH_BIND_NONCE_URI_PARAMS; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, &rq_tr, MHD_OPTION_DIGEST_AUTH_RANDOM_COPY, sizeof (salt), salt, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE, dauth_nonce_bind, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); } if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = dinfo->port; } /* First request */ rq_tr.req_num = 0; rq_tr.uri_num = 0; cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port); multi_reuse = NULL; /* First request */ if (check_result (performQueryExternal (d, c, &multi_reuse), c, &cbc)) { fflush (stderr); if (verbose) printf ("Got first expected response.\n"); fflush (stdout); } else { fprintf (stderr, "First request FAILED.\n"); failed = 1; } cbc.pos = 0; /* Reset buffer position */ rq_tr.req_num = 0; /* Second request */ setCURL_rq_path (c, port, ++rq_tr.uri_num); if (check_result (performQueryExternal (d, c, &multi_reuse), c, &cbc)) { fflush (stderr); if (verbose) printf ("Got second expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Second request FAILED.\n"); failed = 1; } cbc.pos = 0; /* Reset buffer position */ rq_tr.req_num = 0; /* Third request */ if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); multi_reuse = NULL; /* Force new connection */ setCURL_rq_path (c, port, ++rq_tr.uri_num); if (check_result (performQueryExternal (d, c, &multi_reuse), c, &cbc)) { fflush (stderr); if (verbose) printf ("Got third expected response.\n"); fflush (stdout); } else { fprintf (stderr, "Third request FAILED.\n"); failed = 1; } curl_easy_cleanup (c); if (NULL != multi_reuse) curl_multi_cleanup (multi_reuse); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { #if ! CURL_AT_LEAST_VERSION (7,19,1) (void) argc; (void) argv; /* Unused. Silent compiler warning. */ /* Need version 7.19.1 or newer for separate username and password */ fprintf (stderr, "Required libcurl at least version 7.19.1" " to run this test.\n"); return 77; #else /* CURL_AT_LEAST_VERSION(7,19,1) */ unsigned int errorCount = 0; const curl_version_info_data *const curl_info = curl_version_info (CURLVERSION_NOW); int curl_sspi; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ /* Test type and test parameters */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); test_oldapi = 0; if (has_in_name (argv[0], "_oldapi1")) test_oldapi = 1; if (has_in_name (argv[0], "_oldapi2")) test_oldapi = 2; test_userhash = has_in_name (argv[0], "_userhash"); test_userdigest = has_in_name (argv[0], "_userdigest"); test_sha256 = has_in_name (argv[0], "_sha256"); test_rfc2069 = has_in_name (argv[0], "_rfc2069"); test_bind_all = has_in_name (argv[0], "_bind_all"); test_bind_uri = has_in_name (argv[0], "_bind_uri"); /* Wrong test types combinations */ if (1 == test_oldapi) { if (test_sha256) return 99; } if (test_oldapi) { if (test_userhash || test_rfc2069) return 99; } if (test_rfc2069) { if (test_userhash) return 99; } /* Curl version and known bugs checks */ curl_sspi = 0; #ifdef CURL_VERSION_SSPI if (0 != (curl_info->features & CURL_VERSION_SSPI)) curl_sspi = 1; #endif /* CURL_VERSION_SSPI */ if ((CURL_VERSION_BITS (7,63,0) > curl_info->version_num) && (CURL_VERSION_BITS (7,62,0) <= curl_info->version_num) ) { fprintf (stderr, "libcurl version 7.62.x has bug in processing " "URI with GET arguments for Digest Auth.\n"); fprintf (stderr, "This test with libcurl %u.%u.%u cannot be performed.\n", 0xFF & (curl_info->version_num >> 16), 0xFF & (curl_info->version_num >> 8), 0xFF & (curl_info->version_num >> 0)); return 77; } if (test_sha256) { if (curl_sspi) { fprintf (stderr, "Windows SSPI API does not support SHA-256 digests.\n"); return 77; } else if (CURL_VERSION_BITS (7,57,0) > curl_info->version_num) { fprintf (stderr, "Required libcurl at least version 7.57.0 " "to run this test with SHA-256.\n"); fprintf (stderr, "This libcurl version %u.%u.%u " "does not support SHA-256.\n", 0xFF & (curl_info->version_num >> 16), 0xFF & (curl_info->version_num >> 8), 0xFF & (curl_info->version_num >> 0)); return 77; } } if (test_userhash) { if (curl_sspi) { printf ("WARNING: Windows SSPI API does not support 'userhash'.\n"); printf ("This test just checks Digest Auth compatibility with " "the clients without 'userhash' support " "when 'userhash=true' is specified by MHD.\n"); curl_uses_usehash = 0; } else if (CURL_VERSION_BITS (7,57,0) > curl_info->version_num) { printf ("WARNING: libcurl before version 7.57.0 does not " "support 'userhash'.\n"); printf ("This test just checks Digest Auth compatibility with " "libcurl version %u.%u.%u without 'userhash' support " "when 'userhash=true' is specified by MHD.\n", 0xFF & (curl_info->version_num >> 16), 0xFF & (curl_info->version_num >> 8), 0xFF & (curl_info->version_num >> 0)); curl_uses_usehash = 0; } else if (CURL_VERSION_BITS (7,81,0) > curl_info->version_num) { fprintf (stderr, "Required libcurl at least version 7.81.0 " "to run this test with userhash.\n"); fprintf (stderr, "This libcurl version %u.%u.%u has broken digest " "calculation when userhash is used.\n", 0xFF & (curl_info->version_num >> 16), 0xFF & (curl_info->version_num >> 8), 0xFF & (curl_info->version_num >> 0)); return 77; } else curl_uses_usehash = ! 0; } else curl_uses_usehash = 0; test_global_init (); errorCount += testDigestAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); test_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ #endif /* CURL_AT_LEAST_VERSION(7,19,1) */ } libmicrohttpd-1.0.10/src/testcurl/test_get_close_keep_alive.c0000664000175000017500000011213315232103064020104 /* This file is part of libmicrohttpd Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) Copyright (C) 2007, 2009, 2011 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get_close_keep_alive.c * @brief Testcase for libmicrohttpd "Close" and "Keep-Alive" connection. * @details Testcases for testing of MHD automatic choice between "Close" and * "Keep-Alive" connections. Also tested selected HTTP version and * "Connection:" headers. * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #include "mhd_has_param.h" #include "mhd_sockets.h" /* only macros used */ /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define EXPECTED_URI_BASE_PATH "/hello_world" #define EXPECTED_URI_QUERY "a=%26&b=c" #define EXPECTED_URI_FULL_PATH EXPECTED_URI_BASE_PATH "?" EXPECTED_URI_QUERY #define HDR_CONN_CLOSE_VALUE "close" #define HDR_CONN_CLOSE MHD_HTTP_HEADER_CONNECTION ": " \ HDR_CONN_CLOSE_VALUE #define HDR_CONN_KEEP_ALIVE_VALUE "Keep-Alive" #define HDR_CONN_KEEP_ALIVE MHD_HTTP_HEADER_CONNECTION ": " \ HDR_CONN_KEEP_ALIVE_VALUE /* Global parameters */ static int oneone; /**< Use HTTP/1.1 instead of HTTP/1.0 for requests*/ static int conn_close; /**< Don't use Keep-Alive */ static uint16_t global_port; /**< MHD daemons listen port number */ static int slow_reply = 0; /**< Slowdown MHD replies */ static int ignore_response_errors = 0; /**< Do not fail test if CURL returns error */ static int response_timeout_val = TIMEOUTS_VAL; /* Current test parameters */ /* Poor thread sync, but enough for the testing */ static volatile int mhd_add_close; /**< Add "Connection: close" header by MHD */ static volatile int mhd_set_10_cmptbl; /**< Set MHD_RF_HTTP_1_0_COMPATIBLE_STRICT response flag */ static volatile int mhd_set_10_server; /**< Set MHD_RF_HTTP_1_0_SERVER response flag */ static volatile int mhd_set_k_a_send; /**< Set MHD_RF_SEND_KEEP_ALIVE_HEADER response flag */ /* Static helper variables */ static struct curl_slist *curl_close_hdr; /**< CURL "Connection: close" header */ static struct curl_slist *curl_k_alive_hdr; /**< CURL "Connection: keep-alive" header */ static struct curl_slist *curl_both_hdrs; /**< CURL both "Connection: keep-alive" and "close" headers */ static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); curl_close_hdr = NULL; curl_close_hdr = curl_slist_append (curl_close_hdr, HDR_CONN_CLOSE); if (NULL == curl_close_hdr) externalErrorExit (); curl_k_alive_hdr = NULL; curl_k_alive_hdr = curl_slist_append (curl_k_alive_hdr, HDR_CONN_KEEP_ALIVE); if (NULL == curl_k_alive_hdr) externalErrorExit (); curl_both_hdrs = NULL; curl_both_hdrs = curl_slist_append (curl_both_hdrs, HDR_CONN_KEEP_ALIVE); if (NULL == curl_both_hdrs) externalErrorExit (); curl_both_hdrs = curl_slist_append (curl_both_hdrs, HDR_CONN_CLOSE); if (NULL == curl_both_hdrs) externalErrorExit (); } static void test_global_cleanup (void) { curl_slist_free_all (curl_both_hdrs); curl_slist_free_all (curl_k_alive_hdr); curl_slist_free_all (curl_close_hdr); curl_global_cleanup (); } struct headers_check_result { int found_http11; int found_http10; int found_conn_close; int found_conn_keep_alive; }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; if ((strlen (MHD_HTTP_VERSION_1_1) < data_size) && (0 == memcmp (MHD_HTTP_VERSION_1_1, buffer, strlen (MHD_HTTP_VERSION_1_1)))) check_res->found_http11 = 1; else if ((strlen (MHD_HTTP_VERSION_1_0) < data_size) && (0 == memcmp (MHD_HTTP_VERSION_1_0, buffer, strlen (MHD_HTTP_VERSION_1_0)))) check_res->found_http10 = 1; else if ((data_size == strlen (HDR_CONN_CLOSE) + 2) && (0 == memcmp (buffer, HDR_CONN_CLOSE "\r\n", data_size))) check_res->found_conn_close = 1; else if ((data_size == strlen (HDR_CONN_KEEP_ALIVE) + 2) && (0 == memcmp (buffer, HDR_CONN_KEEP_ALIVE "\r\n", data_size))) check_res->found_conn_keep_alive = 1; return data_size; } struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) externalErrorExit (); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static void * log_cb (void *cls, const char *uri, struct MHD_Connection *con) { (void) cls; (void) con; if (0 != strcmp (uri, EXPECTED_URI_FULL_PATH)) { fprintf (stderr, "Wrong URI: `%s', line: %d\n", uri, __LINE__); exit (22); } return NULL; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silence compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; if (slow_reply) usleep (200000); response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); if (NULL == response) { fprintf (stderr, "Failed to create response. Line: %d\n", __LINE__); exit (19); } if (mhd_add_close) { if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, HDR_CONN_CLOSE_VALUE)) { fprintf (stderr, "Failed to add header. Line: %d\n", __LINE__); exit (19); } } if (MHD_YES != MHD_set_response_options (response, (mhd_set_10_cmptbl ? MHD_RF_HTTP_1_0_COMPATIBLE_STRICT : 0) | (mhd_set_10_server ? MHD_RF_HTTP_1_0_SERVER : 0) | (mhd_set_k_a_send ? MHD_RF_SEND_KEEP_ALIVE_HEADER : 0), MHD_RO_END)) { fprintf (stderr, "Failed to set response flags. Line: %d\n", __LINE__); exit (19); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) { fprintf (stderr, "Failed to queue response. Line: %d\n", __LINE__); exit (19); } return ret; } struct curlQueryParams { /* Destination path for CURL query */ const char *queryPath; /* Destination port for CURL query */ uint16_t queryPort; /* CURL query result error flag */ volatile unsigned int queryError; }; static CURL * curlEasyInitForTest (const char *queryPath, uint16_t port, struct CBC *pcbc, struct headers_check_result *hdr_chk_result, int add_hdr_close, int add_hdr_k_alive) { CURL *c; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); externalErrorExit (); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, queryPath)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA, hdr_chk_result)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); externalErrorExit (); } if (add_hdr_close && add_hdr_k_alive) { /* This combination is actually incorrect */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_both_hdrs)) { fprintf (stderr, "Set libcurl HTTP header failed.\n"); externalErrorExit (); } } else if (add_hdr_close) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_close_hdr)) { fprintf (stderr, "Set libcurl HTTP header failed.\n"); externalErrorExit (); } } else if (add_hdr_k_alive) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, curl_k_alive_hdr)) { fprintf (stderr, "Set libcurl HTTP header failed.\n"); externalErrorExit (); } } return c; } static int print_test_params (int add_hdr_close, int add_hdr_k_alive) { fprintf (stderr, "Request HTTP/%s| ", oneone ? "1.1" : "1.0"); fprintf (stderr, "Connection must be: %s| ", conn_close ? "close" : "keep-alive"); fprintf (stderr, "Request \"close\": %s| ", add_hdr_close ? " used" : "NOT used"); fprintf (stderr, "Request \"keep-alive\": %s| ", add_hdr_k_alive ? " used" : "NOT used"); fprintf (stderr, "MHD response \"close\": %s| ", mhd_add_close ? " used" : "NOT used"); fprintf (stderr, "MHD response 1.0 strict compatible: %s| ", mhd_set_10_cmptbl ? "yes" : " NO"); fprintf (stderr, "MHD response 1.0 server: %s| ", mhd_set_10_server ? "yes" : " NO"); fprintf (stderr, "MHD response send \"Keep-Alive\": %s|", mhd_set_k_a_send ? "yes" : " NO"); fprintf (stderr, "\n"); return ! 0; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ multi = NULL; multi = curl_multi_init (); if (multi == NULL) { fprintf (stderr, "curl_multi_init() failed.\n"); externalErrorExit (); } if (CURLM_OK != curl_multi_add_handle (multi, c)) { fprintf (stderr, "curl_multi_add_handle() failed.\n"); externalErrorExit (); } start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) { fprintf (stderr, "curl_multi_info_read failed, NULL returned.\n"); externalErrorExit (); } totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) { fprintf (stderr, "curl_multi_fdset() failed.\n"); externalErrorExit (); } } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) { fprintf (stderr, "MHD_get_fdset() failed. Line: %d\n", __LINE__); exit (11); break; } tv.tv_sec = 0; tv.tv_usec = 1000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) { fprintf (stderr, "MHD_run_from_select() failed. Line: %d\n", __LINE__); exit (11); } } return ret; } static unsigned int getMhdActiveConnections (struct MHD_Daemon *d) { const union MHD_DaemonInfo *dinfo; /* The next method is unreliable unless it's known that no * connections are started or finished in parallel */ dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_CURRENT_CONNECTIONS); if (NULL == dinfo) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } return dinfo->num_connections; } static unsigned int doCurlQueryInThread (struct MHD_Daemon *d, struct curlQueryParams *p, int add_hdr_close, int add_hdr_k_alive) { const union MHD_DaemonInfo *dinfo; CURL *c; char buf[2048]; struct CBC cbc; struct headers_check_result hdr_res; CURLcode errornum; int use_external_poll; int params_printed; params_printed = 0; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } use_external_poll = (0 == (dinfo->flags & MHD_USE_INTERNAL_POLLING_THREAD)); if (NULL == p->queryPath) abort (); if (0 == p->queryPort) abort (); cbc.buf = buf; cbc.size = sizeof(buf); cbc.pos = 0; hdr_res.found_http11 = 0; hdr_res.found_http10 = 0; hdr_res.found_conn_close = 0; hdr_res.found_conn_keep_alive = 0; c = curlEasyInitForTest (p->queryPath, p->queryPort, &cbc, &hdr_res, add_hdr_close, add_hdr_k_alive); if (! use_external_poll) errornum = curl_easy_perform (c); else errornum = performQueryExternal (d, c); if (ignore_response_errors) { p->queryError = 0; curl_easy_cleanup (c); return p->queryError; } if (CURLE_OK != errornum) { p->queryError = 1; fprintf (stderr, "libcurl query failed: `%s'\n", curl_easy_strerror (errornum)); libcurlErrorExit (); } else { if (cbc.pos != strlen (EXPECTED_URI_BASE_PATH)) { fprintf (stderr, "curl reports wrong size of MHD reply body data.\n"); p->queryError = 1; } else if (0 != strncmp (EXPECTED_URI_BASE_PATH, cbc.buf, strlen (EXPECTED_URI_BASE_PATH))) { fprintf (stderr, "curl reports wrong MHD reply body data.\n"); p->queryError = 1; } else p->queryError = 0; } if (! hdr_res.found_http11 && ! hdr_res.found_http10) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "No know HTTP versions were found in the " "reply header. Line: %d\n", __LINE__); exit (24); } else if (hdr_res.found_http11 && hdr_res.found_http10) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "Both HTTP/1.1 and HTTP/1.0 were found in the " "reply header. Line: %d\n", __LINE__); exit (24); } if (conn_close) { if (! hdr_res.found_conn_close) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "\"Connection: close\" was not found in" " MHD reply headers.\n"); p->queryError |= 2; exit (42); } if (hdr_res.found_conn_keep_alive) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "\"Connection: keep-alive\" was found in" " MHD reply headers.\n"); p->queryError |= 2; } if (use_external_poll) { /* The number of MHD connection can queried only with external poll. * otherwise it creates a race condition. */ if (0 != getMhdActiveConnections (d)) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "MHD still has active connection " "after response has been sent.\n"); p->queryError |= 2; } } } else { /* Keep-Alive */ if (! oneone || mhd_set_10_server || mhd_set_k_a_send) { /* Should have "Connection: Keep-Alive" */ if (! hdr_res.found_conn_keep_alive) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "\"Connection: keep-alive\" was not found in" " MHD reply headers.\n"); p->queryError |= 2; } } else { /* Should NOT have "Connection: Keep-Alive" */ if (hdr_res.found_conn_keep_alive) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "\"Connection: keep-alive\" was found in" " MHD reply headers.\n"); p->queryError |= 2; } } if (hdr_res.found_conn_close) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "\"Connection: close\" was found in" " MHD reply headers.\n"); p->queryError |= 2; } if (use_external_poll) { /* The number of MHD connection can be queried only with external poll. * otherwise it creates a race condition. */ unsigned int num_conn = getMhdActiveConnections (d); if (0 == num_conn) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "MHD has no active connection " "after response has been sent.\n"); p->queryError |= 2; } else if (1 != num_conn) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "MHD has wrong number of active connection (%u) " "after response has been sent. Line: %d\n", num_conn, __LINE__); exit (23); } } } #if defined(CURL_AT_LEAST_VERSION) && CURL_AT_LEAST_VERSION (7, 45, 0) if (! use_external_poll) { /* libcurl closes connection socket with curl_multi_remove_handle () / curl_multi_cleanup() */ curl_socket_t curl_sckt; if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_ACTIVESOCKET, &curl_sckt)) { fprintf (stderr, "Failed to get libcurl active socket.\n"); libcurlErrorExit (); } if (conn_close && (CURL_SOCKET_BAD != curl_sckt)) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "libcurl still has active connection " "after performing the test query.\n"); p->queryError |= 2; } else if (! conn_close && (CURL_SOCKET_BAD == curl_sckt)) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "libcurl has no active connection " "after performing the test query.\n"); p->queryError |= 2; } } #endif if (! mhd_set_10_server) { /* Response must be HTTP/1.1 */ if (hdr_res.found_http10) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "Reply has HTTP/1.0 version, while it " "must be HTTP/1.1.\n"); p->queryError |= 4; } } else { /* Response must be HTTP/1.0 */ if (hdr_res.found_http11) { if (! params_printed) params_printed = print_test_params (add_hdr_close, add_hdr_k_alive); fprintf (stderr, "Reply has HTTP/1.1 version, while it " "must be HTTP/1.0.\n"); p->queryError |= 4; } } curl_easy_cleanup (c); if (0 != p->queryError) { fprintf (stderr, "======\n"); fflush (stderr); } return p->queryError; } /* Perform test queries and shut down MHD daemon */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port) { struct curlQueryParams qParam; unsigned int ret = 0; /* Return value */ int i = 0; /* masks */ const int m_mhd_close = 1 << (i++); const int m_10_cmptbl = 1 << (i++); const int m_10_server = 1 << (i++); const int m_k_a_send = 1 << (i++); const int m_client_close = 1 << (i++); const int m_client_k_alive = 1 << (i++); qParam.queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH; qParam.queryPort = d_port; /* Connect to the daemon */ for (i = (1 << i) - 1; 0 <= i; i--) { const int f_mhd_close = (0 == (i & m_mhd_close)); /**< Use MHD "close" header */ const int f_10_cmptbl = (0 == (i & m_10_cmptbl)); /**< Use MHD MHD_RF_HTTP_1_0_COMPATIBLE_STRICT flag */ const int f_10_server = (0 == (i & m_10_server)); /**< Use MHD MHD_RF_HTTP_1_0_SERVER flag */ const int f_k_a_send = (0 == (i & m_k_a_send)); /**< Use MHD MHD_RF_SEND_KEEP_ALIVE_HEADER flag */ const int f_client_close = (0 == (i & m_client_close)); /**< Use libcurl "close" header */ const int f_client_k_alive = (0 == (i & m_client_k_alive)); /**< Use libcurl "Keep-Alive" header */ int res_close; /**< Indicate the result of the test query should be closed connection */ if (f_mhd_close) /* Connection with server's "close" header must be always closed */ res_close = 1; else if (f_client_close) /* Connection with client's "close" header must be always closed */ res_close = 1; else if (f_10_cmptbl) /* Connection in strict HTTP/1.0 compatible mode must be always closed */ res_close = 1; else if (! oneone || f_10_server) /* With HTTP/1.0 client or server connection must be close unless client use "keep-alive" header */ res_close = ! f_client_k_alive; else res_close = 0; /* HTTP/1.1 is "keep-alive" by default */ if ((! ! res_close) != (! ! conn_close)) continue; /* Another mode is in test currently */ #if CURL_AT_LEAST_VERSION (8,16,0) if ((f_client_close) && (f_client_k_alive)) continue; #endif /* CURL >= 8.16.0 */ mhd_add_close = f_mhd_close; mhd_set_10_cmptbl = f_10_cmptbl; mhd_set_10_server = f_10_server; mhd_set_k_a_send = f_k_a_send; ret <<= 3; /* Remember errors for each step */ ret |= doCurlQueryInThread (d, &qParam, f_client_close, f_client_k_alive); } MHD_stop_daemon (d); return ret; } enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; (void) pollType; /* Don't care about pollType for this test */ return numThreads; /* No practical limit for non-cleanup test */ } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 4050; if (oneone) *pport += 1; if (! conn_close) *pport += 2; } if (testMhdThreadExternal == thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); else if (testMhdThreadInternalPool != thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); else d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | MHD_USE_ERROR_LOG, *pport, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno); abort (); } if (0 == *pport) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } *pport = dinfo->port; if (0 == global_port) global_port = *pport; /* Reuse the same port for all tests */ } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port); return performTestQueries (d, d_port); } static unsigned int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port); return performTestQueries (d, d_port); } static unsigned int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port); return performTestQueries (d, d_port); } static unsigned int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port); return performTestQueries (d, d_port); } int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; int verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = ! has_in_name (argv[0], "10"); conn_close = has_in_name (argv[0], "_close"); if (! conn_close && ! has_in_name (argv[0], "_keep_alive")) return 99; verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); test_global_init (); /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; test_result = testExternalGet (); if (test_result) { fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result); return test_result; } else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; } } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); test_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/perf_get_concurrent.c0000664000175000017500000003560015232103064016755 /* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file perf_get_concurrent.c * @brief benchmark concurrent GET operations * Note that we run libcurl on the machine at the * same time, so the execution time may be influenced * by the concurrent activity; it is quite possible * that more time is spend with libcurl than with MHD, * so the performance scores calculated with this code * should NOT be used to compare with other HTTP servers * (since MHD is actually better); only the relative * scores between MHD versions are meaningful. * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif /** * How many rounds of operations do we do for each * test (total number of requests will be ROUNDS * PAR). * Ensure that free ports are not exhausted during test. */ #if MHD_CPU_COUNT > 8 #ifndef _WIN32 #define ROUNDS (1 + (30000 / 12) / MHD_CPU_COUNT) #else /* _WIN32 */ #define ROUNDS (1 + (3000 / 12) / MHD_CPU_COUNT) #endif /* _WIN32 */ #else #define ROUNDS 500 #endif /** * How many requests do we do in parallel? */ #define PAR MHD_CPU_COUNT /** * Do we use HTTP 1.1? */ static int oneone; /** * Response to return (re-used). */ static struct MHD_Response *response; /** * Time this round was started. */ static unsigned long long start_time; /** * Set to 1 if the worker threads are done. */ static volatile int signal_done; /** * Get the current timestamp * * @return current time in ms */ static unsigned long long now (void) { struct timeval tv; gettimeofday (&tv, NULL); return (((unsigned long long) tv.tv_sec * 1000LL) + ((unsigned long long) tv.tv_usec / 1000LL)); } /** * Start the timer. */ static void start_timer (void) { start_time = now (); } /** * Stop the timer and report performance * * @param desc description of the threading mode we used */ static void stop (const char *desc) { double rps = ((double) (PAR * ROUNDS * 1000)) / ((double) (now () - start_time)); fprintf (stderr, "Parallel GETs using %s: %f %s\n", desc, rps, "requests/s"); } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; (void) ctx; /* Unused. Silent compiler warning. */ return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (ret == MHD_NO) abort (); return ret; } static void * thread_gets (void *param) { CURL *c; CURLcode errornum; unsigned int i; char *const url = (char *) param; static char curl_err_marker[] = "curl error"; c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, NULL); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); for (i = 0; i < ROUNDS; i++) { if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); return curl_err_marker; } } curl_easy_cleanup (c); return NULL; } static void * do_gets (void *param) { int j; pthread_t par[PAR]; char url[64]; uint16_t port = (uint16_t) (intptr_t) param; char *err = NULL; static char pthr_err_marker[] = "pthread_create error"; snprintf (url, sizeof (url), "http://127.0.0.1:%u/hello_world", (unsigned int) port); for (j = 0; j < PAR; j++) { if (0 != pthread_create (&par[j], NULL, &thread_gets, (void *) url)) { for (j--; j >= 0; j--) pthread_join (par[j], NULL); return pthr_err_marker; } } for (j = 0; j < PAR; j++) { char *ret_val; if ((0 != pthread_join (par[j], (void **) &ret_val)) || (NULL != ret_val) ) err = ret_val; } signal_done = 1; return err; } static unsigned int testInternalGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ? "internal thread with 'auto'" : (poll_flag & MHD_USE_POLL) ? "internal thread with poll()" : (poll_flag & MHD_USE_EPOLL) ? "internal thread with epoll" : "internal thread with select()"); const char *ret_val; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; signal_done = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } start_timer (); ret_val = do_gets ((void *) (intptr_t) port); if (! ret_val) stop (test_desc); MHD_stop_daemon (d); if (ret_val) { fprintf (stderr, "Error performing %s test: %s\n", test_desc, ret_val); return 4; } return 0; } static unsigned int testMultithreadedGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ? "internal thread with 'auto' and thread per connection" : (poll_flag & MHD_USE_POLL) ? "internal thread with poll() and thread per connection" : (poll_flag & MHD_USE_EPOLL) ? "internal thread with epoll and thread per connection" : "internal thread with select() and thread per connection"); const char *ret_val; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; signal_done = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } start_timer (); ret_val = do_gets ((void *) (intptr_t) port); if (! ret_val) stop (test_desc); MHD_stop_daemon (d); if (ret_val) { fprintf (stderr, "Error performing %s test: %s\n", test_desc, ret_val); return 4; } return 0; } static unsigned int testMultithreadedPoolGet (uint16_t port, uint32_t poll_flag) { struct MHD_Daemon *d; const char *const test_desc = ((poll_flag & MHD_USE_AUTO) ? "internal thread pool with 'auto'" : (poll_flag & MHD_USE_POLL) ? "internal thread pool with poll()" : (poll_flag & MHD_USE_EPOLL) ? "internal thread poll with epoll" : "internal thread pool with select()"); const char *ret_val; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; signal_done = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } start_timer (); ret_val = do_gets ((void *) (intptr_t) port); if (! ret_val) stop (test_desc); MHD_stop_daemon (d); if (ret_val) { fprintf (stderr, "Error performing %s test: %s\n", test_desc, ret_val); return 4; } return 0; } static unsigned int testExternalGet (uint16_t port) { struct MHD_Daemon *d; pthread_t tid; fd_set rs; fd_set ws; fd_set es; MHD_socket max; struct timeval tv; uint64_t tt64; char *ret_val; int ret = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; signal_done = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } if (0 != pthread_create (&tid, NULL, &do_gets, (void *) (intptr_t) port)) { MHD_stop_daemon (d); return 512; } start_timer (); while (0 == signal_done) { max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) { MHD_stop_daemon (d); return 4096; } if (MHD_NO == MHD_get_timeout64 (d, &tt64)) tt64 = 1; #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (tt64 / 1000); #else /* Native W32 */ tv.tv_sec = (long) (tt64 / 1000); #endif /* Native W32 */ tv.tv_usec = ((long) (tt64 % 1000)) * 1000; if (-1 == select (max + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } ret |= 1024; break; #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } MHD_run_from_select (d, &rs, &ws, &es); } stop ("external select"); MHD_stop_daemon (d); if ((0 != pthread_join (tid, (void **) &ret_val)) || (NULL != ret_val) ) { fprintf (stderr, "%s\n", ret_val); ret |= 8; } if (ret) fprintf (stderr, "Error performing test.\n"); return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; uint16_t port = 1100; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (oneone) port += 15; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; response = MHD_create_response_from_buffer_copy (strlen ("/hello_world"), "/hello_world"); errorCount += testInternalGet (port++, 0); errorCount += testMultithreadedGet (port++, 0); errorCount += testMultithreadedPoolGet (port++, 0); errorCount += testExternalGet (port++); errorCount += testInternalGet (port++, MHD_USE_AUTO); errorCount += testMultithreadedGet (port++, MHD_USE_AUTO); errorCount += testMultithreadedPoolGet (port++, MHD_USE_AUTO); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { errorCount += testInternalGet (port++, MHD_USE_POLL); errorCount += testMultithreadedGet (port++, MHD_USE_POLL); errorCount += testMultithreadedPoolGet (port++, MHD_USE_POLL); } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { errorCount += testInternalGet (port++, MHD_USE_EPOLL); errorCount += testMultithreadedPoolGet (port++, MHD_USE_EPOLL); } MHD_destroy_response (response); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return errorCount != 0; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_basicauth.c0000664000175000017500000005667015232103064015734 /* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_basicauth.c * @brief Testcase for libmicrohttpd Basic Authorisation * @author Amr Ali * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #include #else #include #endif #include "mhd_has_param.h" #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \ __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #define checkCURLE_OK(libcurlcall) \ _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } /* Not actually used in this test */ static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (8); } #if 0 /* Function unused in this test */ static void _checkCURLE_OK_func (CURLcode code, const char *curlFunc, const char *funcName, int lineNum) { if (CURLE_OK == code) return; fflush (stdout); if ((NULL != curlFunc) && (0 != curlFunc[0])) fprintf (stderr, "'%s' resulted in '%s'", curlFunc, curl_easy_strerror (code)); else fprintf (stderr, "libcurl function call resulted in '%s'", curl_easy_strerror (code)); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf); fflush (stderr); exit (9); } #endif /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 10 #define MHD_URI_BASE_PATH "/bar%20foo%3Fkey%3Dvalue" #define REALM "TestRealm" #define USERNAME "Aladdin" #define PASSWORD "open sesame" #define PAGE \ "libmicrohttpd demo page" \ "Access granted" #define DENIED \ "libmicrohttpd - Access denied" \ "Access denied" struct CBC { char *buf; size_t pos; size_t size; }; static int verbose; static int preauth; static int oldapi; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) mhdErrorExitDesc ("Wrong too large data"); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) mhdErrorExitDesc ("Unexpected HTTP method"); /* require: USERNAME with password PASSWORD */ if (! oldapi) { struct MHD_BasicAuthInfo *creds; creds = MHD_basic_auth_get_username_password3 (connection); if (NULL != creds) { if (NULL == creds->username) mhdErrorExitDesc ("'username' is NULL"); else if (MHD_STATICSTR_LEN_ (USERNAME) != creds->username_len) { fprintf (stderr, "'username_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (USERNAME), (unsigned) creds->username_len); mhdErrorExitDesc ("Wrong 'username_len'"); } else if (0 != memcmp (creds->username, USERNAME, creds->username_len)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", USERNAME, (int) creds->username_len, creds->username); mhdErrorExitDesc ("Wrong 'username'"); } else if (0 != creds->username[creds->username_len]) mhdErrorExitDesc ("'username' is not zero-terminated"); else if (NULL == creds->password) mhdErrorExitDesc ("'password' is NULL"); else if (MHD_STATICSTR_LEN_ (PASSWORD) != creds->password_len) { fprintf (stderr, "'password_len' does not match.\n" "Expected: %u\tRecieved: %u. ", (unsigned) MHD_STATICSTR_LEN_ (PASSWORD), (unsigned) creds->password_len); mhdErrorExitDesc ("Wrong 'password_len'"); } else if (0 != memcmp (creds->password, PASSWORD, creds->password_len)) { fprintf (stderr, "'password' does not match.\n" "Expected: '%s'\tRecieved: '%.*s'. ", PASSWORD, (int) creds->password_len, creds->password); mhdErrorExitDesc ("Wrong 'username'"); } else if (0 != creds->password[creds->password_len]) mhdErrorExitDesc ("'password' is not zero-terminated"); MHD_free (creds); response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), (const void *) PAGE); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_response()' failed"); } else { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_basic_auth_required_response3 (connection, REALM, MHD_YES, response); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_basic_auth_required_response3()' failed"); } } else { char *username; char *password; password = NULL; username = MHD_basic_auth_get_username_password (connection, &password); if (NULL != username) { if (0 != strcmp (username, USERNAME)) { fprintf (stderr, "'username' does not match.\n" "Expected: '%s'\tRecieved: '%s'. ", USERNAME, username); mhdErrorExitDesc ("Wrong 'username'"); } if (NULL == password) mhdErrorExitDesc ("The password pointer is NULL"); if (0 != strcmp (password, PASSWORD)) fprintf (stderr, "'password' does not match.\n" "Expected: '%s'\tRecieved: '%s'. ", PASSWORD, password); response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (PAGE), (const void *) PAGE); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_response()' failed"); } else { if (NULL != password) mhdErrorExitDesc ("The password pointer is NOT NULL"); response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED), (const void *) DENIED); if (NULL == response) mhdErrorExitDesc ("Response creation failed"); ret = MHD_queue_basic_auth_fail_response (connection, REALM, response); if (MHD_YES != ret) mhdErrorExitDesc ("'MHD_queue_basic_auth_fail_response()' failed"); } if (NULL != username) MHD_free (username); if (NULL != password) MHD_free (password); } MHD_destroy_response (response); return ret; } static CURL * setupCURL (void *cbc, uint16_t port, char *errbuf) { CURL *c; char url[512]; if (1) { int res; /* A workaround for some old libcurl versions, which ignore the specified * port by CURLOPT_PORT when authorisation is used. */ res = snprintf (url, (sizeof(url) / sizeof(url[0])), "http://127.0.0.1:%u%s", (unsigned int) port, MHD_URI_BASE_PATH); if ((0 >= res) || ((sizeof(url) / sizeof(url[0])) <= (size_t) res)) externalErrorExitDesc ("Cannot form request URL"); } c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1)) || /* (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) || */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) || #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) || #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) || #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) port))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, url))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); #if CURL_AT_LEAST_VERSION (7,21,3) if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC | (preauth ? 0 : CURLAUTH_ONLY))) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD, USERNAME ":" PASSWORD))) libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed"); #else /* libcurl version before 7.21.3 */ if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD, USERNAME ":" PASSWORD))) libcurlErrorExitDesc ("curl_easy_setopt() authorization options failed"); #endif /* libcurl version before 7.21.3 */ return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ multi = NULL; multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 200000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep (200); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } /** * Check request result * @param curl_code the CURL easy return code * @param pcbc the pointer struct CBC * @return non-zero if success, zero if failed */ static unsigned int check_result (CURLcode curl_code, struct CBC *pcbc) { if (CURLE_OK != curl_code) { fflush (stdout); if (0 != libcurl_errbuf[0]) fprintf (stderr, "First request failed. " "libcurl error: '%s'.\n" "libcurl error description: '%s'.\n", curl_easy_strerror (curl_code), libcurl_errbuf); else fprintf (stderr, "First request failed. " "libcurl error: '%s'.\n", curl_easy_strerror (curl_code)); fflush (stderr); return 0; } if (pcbc->pos != strlen (PAGE)) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) pcbc->pos, (int) pcbc->pos, pcbc->buf, (unsigned) strlen (PAGE)); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != memcmp (PAGE, pcbc->buf, pcbc->pos)) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) pcbc->pos, pcbc->buf); mhdErrorExitDesc ("Wrong returned data"); } return 1; } static unsigned int testBasicAuth (void) { struct MHD_Daemon *d; uint16_t port; struct CBC cbc; char buf[2048]; CURL *c; int failed = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 4210; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); port = (uint16_t) dinfo->port; } /* First request */ cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port, libcurl_errbuf); if (check_result (performQueryExternal (d, c), &cbc)) { if (verbose) printf ("First request successful.\n"); } else { fprintf (stderr, "First request FAILED.\n"); failed = 1; } curl_easy_cleanup (c); /* Second request */ cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; memset (cbc.buf, 0, cbc.size); c = setupCURL (&cbc, port, libcurl_errbuf); if (check_result (performQueryExternal (d, c), &cbc)) { if (verbose) printf ("Second request successful.\n"); } else { fprintf (stderr, "Second request FAILED.\n"); failed = 1; } curl_easy_cleanup (c); MHD_stop_daemon (d); return failed ? 1 : 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); preauth = has_in_name (argv[0], "_preauth"); #if ! CURL_AT_LEAST_VERSION (7,21,3) if (preauth) { fprintf (stderr, "libcurl version 7.21.3 or later is " "required to run this test.\n"); return 77; } #endif /* libcurl version before 7.21.3 */ #ifdef MHD_HTTPS_REQUIRE_GCRYPT #ifdef HAVE_GCRYPT_H gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ oldapi = has_in_name (argv[0], "_oldapi"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testBasicAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_callback.c0000664000175000017500000001707615232103064015522 /* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_callback.c * @brief Testcase for MHD not calling the callback too often * @author Jan Seeger * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" struct callback_closure { unsigned int called; }; static ssize_t called_twice (void *cls, uint64_t pos, char *buf, size_t max) { struct callback_closure *cls2 = cls; (void) pos; /* Unused. Silence compiler warning. */ (void) max; if (cls2->called == 0) { memcpy (buf, "test", 5); cls2->called = 1; return (ssize_t) strlen (buf); } if (cls2->called == 1) { cls2->called = 2; return MHD_CONTENT_READER_END_OF_STREAM; } fprintf (stderr, "Handler called after returning END_OF_STREAM!\n"); abort (); return MHD_CONTENT_READER_END_WITH_ERROR; } static enum MHD_Result callback (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct callback_closure *cbc = calloc (1, sizeof(struct callback_closure)); struct MHD_Response *r; enum MHD_Result ret; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (NULL == cbc) return MHD_NO; r = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, &called_twice, cbc, &free); if (NULL == r) { free (cbc); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, r); MHD_destroy_response (r); return ret; } static size_t discard_buffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; (void) ctx; /* Unused. Silent compiler warning. */ return size * nmemb; } int main (int argc, char **argv) { struct MHD_Daemon *d; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ CURL *c; CURLM *multi; CURLMcode mret; struct CURLMsg *msg; int running; struct timeval tv; int extra; uint16_t port; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1140; d = MHD_start_daemon (MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &callback, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 32; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 48; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &discard_buffer); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 99; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 99; } extra = 10; while ( (c != NULL) || (--extra > 0) ) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&ws); FD_ZERO (&rs); FD_ZERO (&es); curl_multi_perform (multi, &running); if (NULL != multi) { mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 99; } } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } } MHD_run (d); } MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/testcurl/test_get_iovec.c0000664000175000017500000005106315232103064015724 /* This file is part of libmicrohttpd Copyright (C) 2007-2021 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get_iovec.c * @brief Testcase for libmicrohttpd response from scatter/gather array * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) * @author Lawrence Sebald */ /* * This test is largely derived from the test_get_sendfile.c file, with the * daemon using MHD_create_response_from_iovec instead of working from an fd. */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #include #ifdef HAVE_STDBOOL_H #include #endif #include #include "mhd_sockets.h" #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define TESTSTR_IOVLEN 20480 #define TESTSTR_IOVCNT 20 #define TESTSTR_SIZE (TESTSTR_IOVCNT * TESTSTR_IOVLEN) static int oneone; static int readbuf[TESTSTR_SIZE * 2 / sizeof(int)]; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) _exit (7); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static void iov_free_callback (void *cls) { free (cls); } struct iovncont_data { void *ptrs[TESTSTR_IOVCNT]; }; static void iovncont_free_callback (void *cls) { struct iovncont_data *data = (struct iovncont_data *) cls; unsigned int i; for (i = 0; i < TESTSTR_IOVCNT; ++i) free (data->ptrs[i]); free (data); } static int check_read_data (const void *ptr, size_t len) { const int *buf; size_t i; if (len % sizeof(int)) return -1; buf = (const int *) ptr; for (i = 0; i < len / sizeof(int); ++i) { if (buf[i] != (int) i) return -1; } return 0; } static enum MHD_Result ahc_cont (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; int *data; struct MHD_IoVec iov[TESTSTR_IOVCNT]; int i; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; /* Create some test data. */ if (NULL == (data = malloc (TESTSTR_SIZE))) return MHD_NO; for (i = 0; i < (int) (TESTSTR_SIZE / sizeof(int)); ++i) { data[i] = i; } for (i = 0; i < TESTSTR_IOVCNT; ++i) { iov[i].iov_base = data + (((size_t) i) * (TESTSTR_SIZE / TESTSTR_IOVCNT / sizeof(int))); iov[i].iov_len = TESTSTR_SIZE / TESTSTR_IOVCNT; } response = MHD_create_response_from_iovec (iov, TESTSTR_IOVCNT, &iov_free_callback, data); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static enum MHD_Result ahc_ncont (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; struct MHD_IoVec iov[TESTSTR_IOVCNT]; struct iovncont_data *clear_cls; int i, j; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; clear_cls = malloc (sizeof(struct iovncont_data)); if (NULL == clear_cls) abort (); memset (iov, 0, sizeof(struct MHD_IoVec) * TESTSTR_IOVCNT); /* Create some test data. */ for (j = TESTSTR_IOVCNT - 1; j >= 0; --j) { int *data; data = malloc (TESTSTR_IOVLEN); if (NULL == data) abort (); clear_cls->ptrs[j] = (void *) data; for (i = 0; i < (int) (TESTSTR_IOVLEN / sizeof(int)); ++i) { data[i] = i + (j * (int) (TESTSTR_IOVLEN / sizeof(int))); } iov[j].iov_base = (const void *) data; iov[j].iov_len = TESTSTR_IOVLEN; } response = MHD_create_response_from_iovec (iov, TESTSTR_IOVCNT, &iovncont_free_callback, clear_cls); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (bool contiguous) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1200; if (oneone) port += 10; } cbc.buf = (char *) readbuf; cbc.size = sizeof(readbuf); cbc.pos = 0; if (contiguous) { d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_END); } else { d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_ncont, NULL, MHD_OPTION_END); } if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != TESTSTR_SIZE) return 4; if (0 != check_read_data (cbc.buf, cbc.pos)) return 8; return 0; } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1201; if (oneone) port += 10; } cbc.buf = (char *) readbuf; cbc.size = sizeof(readbuf); cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_AUTO, port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != TESTSTR_SIZE) return 64; if (0 != check_read_data (cbc.buf, cbc.pos)) return 128; return 0; } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1202; if (oneone) port += 10; } cbc.buf = (char *) readbuf; cbc.size = sizeof(readbuf); cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_AUTO, port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != TESTSTR_SIZE) return 64; if (0 != check_read_data (cbc.buf, cbc.pos)) return 128; return 0; } static unsigned int testExternalGet (int thread_unsafe) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1203; if (oneone) port += 10; } multi = NULL; cbc.buf = (char *) readbuf; cbc.size = sizeof(readbuf); cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | (thread_unsafe ? MHD_USE_NO_THREAD_SAFETY : 0), port, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != TESTSTR_SIZE) return 8192; if (0 != check_read_data (cbc.buf, cbc.pos)) return 16384; return 0; } static unsigned int testUnknownPortGet (void) { struct MHD_Daemon *d; const union MHD_DaemonInfo *di; CURL *c; struct CBC cbc; CURLcode errornum; uint16_t port; char buf[2048]; struct sockaddr_in addr; socklen_t addr_len = sizeof(addr); memset (&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; cbc.buf = (char *) readbuf; cbc.size = sizeof(readbuf); cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, 0, NULL, NULL, &ahc_cont, NULL, MHD_OPTION_SOCK_ADDR, &addr, MHD_OPTION_END); if (d == NULL) return 32768; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) { di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (di == NULL) return 65536; if (0 != getsockname (di->listen_fd, (struct sockaddr *) &addr, &addr_len)) return 131072; if (addr.sin_family != AF_INET) return 26214; port = ntohs (addr.sin_port); } else { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (buf, sizeof(buf), "http://127.0.0.1:%u/", (unsigned int) port); c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, buf); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 524288; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != TESTSTR_SIZE) return 1048576; if (0 != check_read_data (cbc.buf, cbc.pos)) return 2097152; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (true); errorCount += testInternalGet (false); errorCount += testMultithreadedGet (); errorCount += testMultithreadedPoolGet (); errorCount += testUnknownPortGet (); errorCount += testExternalGet (0); } errorCount += testExternalGet (! 0); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_long_header.c0000664000175000017500000003507515232103064016234 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2016-2023 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_long_header.c * @brief Testcase for libmicrohttpd handling of very long headers * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ /** * We will set the memory available per connection to * half of this value, so the actual value does not have * to be big at all... */ #define VERY_LONG (1024 * 8) /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define EXPECTED_URI_BASE_PATH "/" #define URL_SCHEME "http:/" "/" #define URL_HOST "127.0.0.1" #define URL_SCHEME_HOST_PATH URL_SCHEME URL_HOST EXPECTED_URI_BASE_PATH static int oneone; static uint16_t daemon_port; static char libcurl_err_buf[CURL_ERROR_SIZE]; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { (void) ptr; (void) ctx; /* Unused. Silent compiler warning. */ return size * nmemb; } /* Return non-zero on success, zero on failure */ static int setup_easy_handler_params (CURL *c, struct CBC *pcbc, const char *url, struct curl_slist *header) { libcurl_err_buf[0] = 0; /* Reset error message */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_err_buf)) { fprintf (stderr, "Failed to set CURLOPT_ERRORBUFFER option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) { fprintf (stderr, "Failed to set CURLOPT_NOSIGNAL option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) { fprintf (stderr, "Failed to set CURLOPT_WRITEFUNCTION option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc)) { fprintf (stderr, "Failed to set CURLOPT_WRITEDATA option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) TIMEOUTS_VAL))) { fprintf (stderr, "Failed to set CURLOPT_CONNECTTIMEOUT option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) TIMEOUTS_VAL))) { fprintf (stderr, "Failed to set CURLOPT_TIMEOUT option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0)) { fprintf (stderr, "Failed to set CURLOPT_HTTP_VERSION option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L)) { fprintf (stderr, "Failed to set CURLOPT_FAILONERROR option.\n"); return 0; } #ifdef _DEBUG if (CURLE_OK != curl_easy_setopt (c, CURLOPT_VERBOSE, 1L)) { fprintf (stderr, "Failed to set CURLOPT_VERBOSE option.\n"); return 0; } #endif /* _DEBUG */ #if CURL_AT_LEAST_VERSION (7, 45, 0) if (CURLE_OK != curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http")) { fprintf (stderr, "Failed to set CURLOPT_DEFAULT_PROTOCOL option.\n"); return 0; } #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ #if CURL_AT_LEAST_VERSION (7, 85, 0) if (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http")) { fprintf (stderr, "Failed to set CURLOPT_PROTOCOLS_STR option.\n"); return 0; } #elif CURL_AT_LEAST_VERSION (7, 19, 4) if (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP)) { fprintf (stderr, "Failed to set CURLOPT_PROTOCOLS option.\n"); return 0; } #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ if (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, (NULL != url) ? url : URL_SCHEME_HOST_PATH)) { fprintf (stderr, "Failed to set CURLOPT_PROTOCOLS option.\n"); return 0; } if (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, ((long) daemon_port))) { fprintf (stderr, "Failed to set CURLOPT_PROTOCOLS option.\n"); return 0; } if (NULL != header) { if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, header)) { fprintf (stderr, "Failed to set CURLOPT_HTTPHEADER option.\n"); return 0; } } return ! 0; } static CURL * setup_easy_handler (struct CBC *pcbc, const char *url, struct curl_slist *header) { CURL *c; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() error.\n"); return NULL; } if (setup_easy_handler_params (c, pcbc, url, header)) { return c; /* Success exit point */ } curl_easy_cleanup (c); return NULL; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; static int marker; (void) cls; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (&marker != *req_cls) { *req_cls = ▮ return MHD_YES; } if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testLongUrlGet (size_t buff_size) { struct MHD_Daemon *d; unsigned int ret; ret = 1; /* Error value, shall be reset to zero if succeed */ d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */, daemon_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) buff_size, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, "MHD_start_daemon() failed.\n"); return 16; } if (0 == daemon_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) fprintf (stderr, "MHD_get_daemon_info(d, MHD_DAEMON_INFO_BIND_PORT) " \ "failed.\n"); else daemon_port = dinfo->port; } if (0 != daemon_port) { char *url_str; url_str = malloc (VERY_LONG); if (NULL == url_str) fprintf (stderr, "malloc (VERY_LONG) failed.\n"); else { CURL *c; char buf[2048]; struct CBC cbc; memset (url_str, 'a', VERY_LONG); url_str[VERY_LONG - 1] = '\0'; memcpy (url_str, URL_SCHEME_HOST_PATH, MHD_STATICSTR_LEN_ (URL_SCHEME_HOST_PATH)); cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; c = setup_easy_handler (&cbc, url_str, NULL); if (NULL != c) { CURLcode r; r = curl_easy_perform (c); if (CURLE_OK != r) { fprintf (stderr, "curl_easy_perform() failed. Error message: %s\n", curl_easy_strerror (r)); if (0 != libcurl_err_buf[0]) fprintf (stderr, "Detailed error message: %s\n", libcurl_err_buf); } else { long code; r = curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code); if (CURLE_OK != r) { fprintf (stderr, "curl_easy_getinfo() failed. " "Error message: %s\n", curl_easy_strerror (r)); if (0 != libcurl_err_buf[0]) fprintf (stderr, "Detailed error message: %s\n", libcurl_err_buf); } else { if (code != MHD_HTTP_URI_TOO_LONG) { fprintf (stderr, "testLongHeaderGet(%lu) failed. HTTP " "response code is %ld, while it should be %ld.\n", (unsigned long) buff_size, code, (long) MHD_HTTP_URI_TOO_LONG); } else { printf ("testLongHeaderGet(%lu) succeed. HTTP " "response code is %ld, as expected.\n", (unsigned long) buff_size, (long) MHD_HTTP_URI_TOO_LONG); ret = 0; /* Success */ } } } curl_easy_cleanup (c); } free (url_str); } } MHD_stop_daemon (d); return ret; } static unsigned int testLongHeaderGet (size_t buff_size) { struct MHD_Daemon *d; unsigned int ret; ret = 1; /* Error value, shall be reset to zero if succeed */ d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD /* | MHD_USE_ERROR_LOG */, daemon_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) buff_size, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, "MHD_start_daemon() failed.\n"); return 16; } if (0 == daemon_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) fprintf (stderr, "MHD_get_daemon_info(d, MHD_DAEMON_INFO_BIND_PORT) " \ "failed.\n"); else daemon_port = dinfo->port; } if (0 != daemon_port) { char *header_str; header_str = malloc (VERY_LONG); if (NULL == header_str) fprintf (stderr, "malloc (VERY_LONG) failed.\n"); else { struct curl_slist *header = NULL; memset (header_str, 'a', VERY_LONG); header_str[VERY_LONG - 1] = '\0'; header_str[VERY_LONG / 2] = ':'; header_str[VERY_LONG / 2 + 1] = ' '; header = curl_slist_append (header, header_str); if (NULL == header) fprintf (stderr, "curl_slist_append () failed.\n"); else { CURL *c; char buf[2048]; struct CBC cbc; cbc.buf = buf; cbc.size = sizeof (buf); cbc.pos = 0; c = setup_easy_handler (&cbc, NULL, header); if (NULL != c) { CURLcode r; r = curl_easy_perform (c); if (CURLE_OK != r) { fprintf (stderr, "curl_easy_perform() failed. Error message: %s\n", curl_easy_strerror (r)); if (0 != libcurl_err_buf[0]) fprintf (stderr, "Detailed error message: %s\n", libcurl_err_buf); } else { long code; r = curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &code); if (CURLE_OK != r) { fprintf (stderr, "curl_easy_getinfo() failed. " "Error message: %s\n", curl_easy_strerror (r)); if (0 != libcurl_err_buf[0]) fprintf (stderr, "Detailed error message: %s\n", libcurl_err_buf); } else { if (code != MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE) { fprintf (stderr, "testLongHeaderGet(%lu) failed. HTTP " "response code is %ld, while it should be %ld.\n", (unsigned long) buff_size, code, (long) MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE); } else { printf ("testLongHeaderGet(%lu) succeed. HTTP " "response code is %ld, as expected.\n", (unsigned long) buff_size, (long) MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE); ret = 0; /* Success */ } } } curl_easy_cleanup (c); } curl_slist_free_all (header); } free (header_str); } } MHD_stop_daemon (d); return ret; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) daemon_port = 0; else daemon_port = oneone ? 1336 : 1331; errorCount += testLongUrlGet (VERY_LONG / 2); errorCount += testLongUrlGet (VERY_LONG / 2 + 978); errorCount += testLongHeaderGet (VERY_LONG / 2); errorCount += testLongHeaderGet (VERY_LONG / 2 + 1893); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); else printf ("Test succeed.\n"); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/Makefile.am0000664000175000017500000004071415235436227014627 # This Makefile.am is in the public domain EMPTY_ITEM = @HEAVY_TESTS_NOTPARALLEL@ SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) if USE_COVERAGE AM_CFLAGS += -fprofile-arcs -ftest-coverage endif if ENABLE_HTTPS SUBDIRS += https endif LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ @LIBCURL@ $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la THREAD_ONLY_TESTS = \ test_urlparse \ test_long_header \ test_long_header11 \ test_iplimit11 \ test_termination \ $(EMPTY_ITEM) if HEAVY_TESTS THREAD_ONLY_TESTS += \ test_add_conn_cleanup \ test_add_conn_cleanup_nolisten \ test_timeout \ $(EMPTY_ITEM) endif if HAVE_POSIX_THREADS if HEAVY_TESTS THREAD_ONLY_TESTS += \ perf_get_concurrent11 \ $(EMPTY_ITEM) endif THREAD_ONLY_TESTS += \ test_get_wait \ test_get_wait11 \ test_suspend_resume_thread \ $(EMPTY_ITEM) if HEAVY_TESTS THREAD_ONLY_TESTS += \ test_concurrent_stop \ test_quiesce \ $(EMPTY_ITEM) endif if HAVE_CURL_BINARY THREAD_ONLY_TESTS += \ test_quiesce_stream endif endif if HEAVY_TESTS if HAVE_POSIX_THREADS THREAD_ONLY_TESTS += \ perf_get_concurrent endif endif if RUN_LIBCURL_TESTS check_PROGRAMS = \ test_get \ test_head \ test_head10 \ test_get_iovec \ test_get_sendfile \ test_get_close \ test_get_close10 \ test_get_keep_alive \ test_get_keep_alive10 \ test_delete \ test_patch \ test_put \ test_add_conn \ test_add_conn_nolisten \ test_process_headers \ test_process_arguments \ test_toolarge_method \ test_toolarge_url \ test_toolarge_request_header_name \ test_toolarge_request_header_value \ test_toolarge_request_headers \ test_toolarge_reply_header_name \ test_toolarge_reply_header_value \ test_toolarge_reply_headers \ test_tricky_url \ test_tricky_header2 \ test_large_put \ test_get11 \ test_get_iovec11 \ test_get_sendfile11 \ test_patch11 \ test_put11 \ test_large_put11 \ test_large_put_inc11 \ test_put_broken_len10 \ test_put_broken_len \ test_get_chunked \ test_get_chunked_close \ test_get_chunked_string \ test_get_chunked_close_string \ test_get_chunked_empty \ test_get_chunked_close_empty \ test_get_chunked_string_empty \ test_get_chunked_close_string_empty \ test_get_chunked_sized \ test_get_chunked_close_sized \ test_get_chunked_empty_sized \ test_get_chunked_close_empty_sized \ test_get_chunked_forced \ test_get_chunked_close_forced \ test_get_chunked_empty_forced \ test_get_chunked_close_empty_forced \ test_put_chunked \ test_callback \ test_get_header_fold \ test_put_header_fold \ test_put_large_header_fold \ test_put_header_fold_last \ test_put_header_fold_large \ test_get_header_double_fold \ test_put_header_double_fold \ test_put_large_header_double_fold \ test_put_header_double_fold_last \ test_put_header_double_fold_large \ $(EMPTY_ITEM) if ENABLE_COOKIE check_PROGRAMS += \ test_parse_cookies_discp_p2 \ test_parse_cookies_discp_p1 \ test_parse_cookies_discp_zero \ test_parse_cookies_discp_n2 \ test_parse_cookies_discp_n3 endif if HEAVY_TESTS check_PROGRAMS += \ perf_get endif if ENABLE_BAUTH check_PROGRAMS += \ test_basicauth test_basicauth_preauth \ test_basicauth_oldapi test_basicauth_preauth_oldapi endif if HAVE_POSTPROCESSOR check_PROGRAMS += \ test_post \ test_postform \ test_post_loop \ test_post11 \ test_postform11 \ test_post_loop11 endif if ENABLE_DAUTH if ENABLE_MD5 THREAD_ONLY_TESTS += \ test_digestauth \ test_digestauth_with_arguments \ test_digestauth_concurrent endif if ENABLE_SHA256 THREAD_ONLY_TESTS += \ test_digestauth_sha256 endif if ENABLE_MD5 check_PROGRAMS += \ test_digestauth_emu_ext \ test_digestauth_emu_ext_oldapi \ test_digestauth2 \ test_digestauth2_rfc2069 \ test_digestauth2_rfc2069_userdigest \ test_digestauth2_oldapi1 \ test_digestauth2_oldapi2 \ test_digestauth2_userhash \ test_digestauth2_userdigest \ test_digestauth2_oldapi1_userdigest \ test_digestauth2_oldapi2_userdigest \ test_digestauth2_userhash_userdigest \ test_digestauth2_bind_all \ test_digestauth2_bind_uri \ test_digestauth2_oldapi1_bind_all \ test_digestauth2_oldapi1_bind_uri endif if ENABLE_SHA256 check_PROGRAMS += \ test_digestauth2_sha256 \ test_digestauth2_sha256_userhash \ test_digestauth2_oldapi2_sha256 \ test_digestauth2_sha256_userdigest \ test_digestauth2_oldapi2_sha256_userdigest \ test_digestauth2_sha256_userhash_userdigest endif endif if HEAVY_TESTS if HAVE_FORK_WAITPID if HAVE_CURL_BINARY check_PROGRAMS += test_get_response_cleanup endif endif endif if USE_POSIX_THREADS check_PROGRAMS += \ $(THREAD_ONLY_TESTS) endif if USE_W32_THREADS check_PROGRAMS += \ $(THREAD_ONLY_TESTS) endif TESTS = $(check_PROGRAMS) endif test_concurrent_stop_SOURCES = \ test_concurrent_stop.c test_concurrent_stop_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_concurrent_stop_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get_SOURCES = \ test_get.c mhd_has_in_name.h mhd_has_param.h test_head_SOURCES = \ test_head.c mhd_has_in_name.h mhd_has_param.h test_head10_SOURCES = \ test_head.c mhd_has_in_name.h mhd_has_param.h test_quiesce_SOURCES = \ test_quiesce.c mhd_has_param.h mhd_has_in_name.h test_quiesce_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_quiesce_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_quiesce_stream_SOURCES = \ test_quiesce_stream.c test_quiesce_stream_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_quiesce_stream_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_suspend_resume_thread_SOURCES = \ test_suspend_resume_thread.c test_suspend_resume_thread_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_suspend_resume_thread_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_callback_SOURCES = \ test_callback.c perf_get_SOURCES = \ perf_get.c \ mhd_has_in_name.h perf_get_concurrent_SOURCES = \ perf_get_concurrent.c \ mhd_has_in_name.h perf_get_concurrent_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) perf_get_concurrent_LDADD = \ $(PTHREAD_LIBS) $(LDADD) perf_get_concurrent11_SOURCES = \ perf_get_concurrent.c \ mhd_has_in_name.h perf_get_concurrent11_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) perf_get_concurrent11_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_basicauth_SOURCES = \ test_basicauth.c test_basicauth_preauth_SOURCES = \ test_basicauth.c test_basicauth_oldapi_SOURCES = \ test_basicauth.c test_basicauth_preauth_oldapi_SOURCES = \ test_basicauth.c test_digestauth_SOURCES = \ test_digestauth.c test_digestauth_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_sha256_SOURCES = \ test_digestauth_sha256.c test_digestauth_sha256_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_with_arguments_SOURCES = \ test_digestauth_with_arguments.c test_digestauth_with_arguments_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_digestauth_concurrent_SOURCES = \ test_digestauth_concurrent.c test_digestauth_concurrent_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_digestauth_concurrent_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) $(PTHREAD_LIBS) $(LDADD) test_digestauth_emu_ext_SOURCES = \ test_digestauth_emu_ext.c test_digestauth_emu_ext_oldapi_SOURCES = \ test_digestauth_emu_ext.c test_digestauth2_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_rfc2069_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_rfc2069_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userhash_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_sha256_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userhash_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_userhash_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi2_sha256_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_sha256_userhash_userdigest_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_bind_all_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_bind_uri_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_bind_all_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_digestauth2_oldapi1_bind_uri_SOURCES = \ test_digestauth2.c mhd_has_param.h mhd_has_in_name.h test_get_iovec_SOURCES = \ test_get_iovec.c mhd_has_in_name.h test_get_sendfile_SOURCES = \ test_get_sendfile.c mhd_has_in_name.h test_get_wait_SOURCES = \ test_get_wait.c \ mhd_has_in_name.h test_get_wait_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_get_wait_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get_wait11_SOURCES = \ test_get_wait.c \ mhd_has_in_name.h test_get_wait11_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_get_wait11_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_urlparse_SOURCES = \ test_urlparse.c mhd_has_in_name.h test_get_response_cleanup_SOURCES = \ test_get_response_cleanup.c mhd_has_in_name.h test_get_chunked_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_string_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_string_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_string_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_string_empty_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_sized_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_empty_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_get_chunked_close_empty_forced_SOURCES = \ test_get_chunked.c mhd_has_in_name.h test_post_SOURCES = \ test_post.c mhd_has_in_name.h test_process_headers_SOURCES = \ test_process_headers.c mhd_has_in_name.h test_parse_cookies_discp_zero_SOURCES = \ test_parse_cookies.c mhd_has_in_name.h mhd_has_param.h test_parse_cookies_discp_p2_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_p1_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_n2_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_parse_cookies_discp_n3_SOURCES = \ $(test_parse_cookies_discp_zero_SOURCES) test_process_arguments_SOURCES = \ test_process_arguments.c mhd_has_in_name.h test_postform_SOURCES = \ test_postform.c mhd_has_in_name.h test_postform_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_post_loop_SOURCES = \ test_post_loop.c mhd_has_in_name.h test_delete_SOURCES = \ test_delete.c mhd_has_in_name.h test_patch_SOURCES = \ test_patch.c mhd_has_in_name.h test_patch11_SOURCES = \ test_patch.c mhd_has_in_name.h test_put_SOURCES = \ test_put.c mhd_has_in_name.h test_put_chunked_SOURCES = \ test_put_chunked.c test_add_conn_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_nolisten_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_nolisten_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_nolisten_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_cleanup_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_cleanup_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_cleanup_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_add_conn_cleanup_nolisten_SOURCES = \ test_add_conn.c mhd_has_in_name.h mhd_has_param.h test_add_conn_cleanup_nolisten_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) test_add_conn_cleanup_nolisten_LDADD = \ $(PTHREAD_LIBS) $(LDADD) test_get11_SOURCES = \ test_get.c mhd_has_in_name.h mhd_has_param.h test_get_iovec11_SOURCES = \ test_get_iovec.c mhd_has_in_name.h test_get_sendfile11_SOURCES = \ test_get_sendfile.c mhd_has_in_name.h test_get_close_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_close10_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_keep_alive_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_get_keep_alive10_SOURCES = \ test_get_close_keep_alive.c mhd_has_in_name.h mhd_has_param.h test_post11_SOURCES = \ test_post.c mhd_has_in_name.h test_postform11_SOURCES = \ test_postform.c mhd_has_in_name.h test_postform11_LDADD = \ @LIBGCRYPT_LIBS@ $(LDADD) test_post_loop11_SOURCES = \ test_post_loop.c mhd_has_in_name.h test_put11_SOURCES = \ test_put.c mhd_has_in_name.h test_large_put_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_large_put11_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_large_put_inc11_SOURCES = \ test_large_put.c mhd_has_in_name.h mhd_has_param.h test_long_header_SOURCES = \ test_long_header.c mhd_has_in_name.h test_long_header11_SOURCES = \ test_long_header.c mhd_has_in_name.h test_iplimit11_SOURCES = \ test_iplimit.c mhd_has_in_name.h test_termination_SOURCES = \ test_termination.c test_timeout_SOURCES = \ test_timeout.c mhd_has_in_name.h test_toolarge_method_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_url_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_header_name_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_header_value_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_request_headers_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_header_name_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_header_value_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_toolarge_reply_headers_SOURCES = \ test_toolarge.c mhd_has_in_name.h mhd_has_param.h test_tricky_url_SOURCES = \ test_tricky.c mhd_has_in_name.h mhd_has_param.h test_tricky_header2_SOURCES = \ test_tricky.c mhd_has_in_name.h mhd_has_param.h test_put_broken_len_SOURCES = \ test_put_broken_len.c mhd_has_in_name.h mhd_has_param.h test_put_broken_len10_SOURCES = $(test_put_broken_len_SOURCES) test_put_header_fold_SOURCES = \ test_put_header_fold.c mhd_has_in_name.h mhd_has_param.h test_put_large_header_fold_SOURCES = $(test_put_header_fold_SOURCES) test_get_header_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_fold_last_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_fold_large_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_double_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_large_header_double_fold_SOURCES = $(test_put_large_header_fold_SOURCES) test_get_header_double_fold_SOURCES = $(test_put_header_fold_SOURCES) test_put_header_double_fold_last_SOURCES = $(test_put_header_fold_last_SOURCES) test_put_header_double_fold_large_SOURCES = $(test_put_header_fold_large_SOURCES) libmicrohttpd-1.0.10/src/testcurl/test_large_put.c0000664000175000017500000006711415232103064015746 /* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_large_put.c * @brief Testcase for libmicrohttpd PUT operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #endif #include "mhd_has_in_name.h" #include "mhd_has_param.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } static int oneone; static int incr_read; /* Use incremental read */ static int verbose; /* Be verbose */ #define PUT_SIZE (256 * 1024) static char *put_buffer; struct CBC { char *buf; size_t pos; size_t size; }; static char * alloc_init (size_t buf_size) { static const char template[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz"; static const size_t templ_size = sizeof(template) / sizeof(char) - 1; char *buf; char *fill_ptr; size_t to_fill; buf = malloc (buf_size); if (NULL == buf) externalErrorExit (); fill_ptr = buf; to_fill = buf_size; while (to_fill > 0) { const size_t to_copy = to_fill > templ_size ? templ_size : to_fill; memcpy (fill_ptr, template, to_copy); fill_ptr += to_copy; to_fill -= to_copy; } return buf; } static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = (size_t *) ptr; size_t wrt; wrt = size * nmemb; /* Check for overflow. */ if (wrt / size != nmemb) libcurlErrorExitDesc ("Too large buffer size"); if (wrt > PUT_SIZE - (*pos)) wrt = PUT_SIZE - (*pos); memcpy (stream, &put_buffer[*pos], wrt); (*pos) += wrt; return wrt; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) libcurlErrorExitDesc ("Too large buffer size"); memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { int *done = cls; struct MHD_Response *response; enum MHD_Result ret; static size_t processed; if (NULL == cls) mhdErrorExitDesc ("cls parameter is NULL"); if (0 != strcmp (version, oneone ? MHD_HTTP_VERSION_1_1 : MHD_HTTP_VERSION_1_0)) mhdErrorExitDesc ("Unexpected HTTP version"); if (NULL == url) mhdErrorExitDesc ("url parameter is NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != strcmp ("PUT", method)) mhdErrorExitDesc ("Unexpected request method"); /* unexpected method */ if ((*done) == 0) { size_t *pproc; if (NULL == *req_cls) { processed = 0; /* Safe as long as only one parallel request served. */ *req_cls = &processed; } pproc = (size_t *) *req_cls; if (0 == *upload_data_size) return MHD_YES; /* No data to process. */ if (*pproc + *upload_data_size > PUT_SIZE) mhdErrorExitDesc ("Incoming data larger than expected"); if ( (! incr_read) && (*upload_data_size != PUT_SIZE) ) return MHD_YES; /* Wait until whole request is received. */ if (0 != memcmp (upload_data, put_buffer + (*pproc), *upload_data_size)) mhdErrorExitDesc ("Incoming data does not match sent data"); *pproc += *upload_data_size; *upload_data_size = 0; /* Current block of data is fully processed. */ if (PUT_SIZE == *pproc) *done = 1; /* Whole request is processed. */ return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testPutInternalThread (unsigned int add_flag) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; char buf[2048]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1270; if (oneone) port += 10; if (incr_read) port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | add_flag, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (incr_read ? 1024 : (PUT_SIZE * 4 / 3)), MHD_OPTION_END); if (d == NULL) mhdErrorExit (); if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); port = dinfo->port; } c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); externalErrorExit (); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world")) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); externalErrorExit (); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen ("/hello_world")); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data length"); } return 0; } static unsigned int testPutThreadPerConn (unsigned int add_flag) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; char buf[2048]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1271; if (oneone) port += 10; if (incr_read) port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | add_flag, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (incr_read ? 1024 : (PUT_SIZE * 4)), MHD_OPTION_END); if (d == NULL) mhdErrorExit (); if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); port = dinfo->port; } c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); externalErrorExit (); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world")) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); externalErrorExit (); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen ("/hello_world")); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data length"); } return 0; } static unsigned int testPutThreadPool (unsigned int add_flag) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; size_t pos = 0; int done_flag = 0; CURLcode errornum; char buf[2048]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1272; if (oneone) port += 10; if (incr_read) port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | add_flag, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (incr_read ? 1024 : (PUT_SIZE * 4)), MHD_OPTION_END); if (d == NULL) mhdErrorExit (); if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); port = dinfo->port; } c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); externalErrorExit (); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world")) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); externalErrorExit (); } if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen ("/hello_world")); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data length"); } return 0; } static unsigned int testPutExternal (void) { struct MHD_Daemon *d; CURL *c; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; int running; struct CURLMsg *msg; time_t start; struct timeval tv; size_t pos = 0; int done_flag = 0; char buf[2048]; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1273; if (oneone) port += 10; if (incr_read) port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; multi = NULL; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (incr_read ? 1024 : (PUT_SIZE * 4)), MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) mhdErrorExit (); if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExit (); port = dinfo->port; } c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed.\n"); externalErrorExit (); } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world")) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_READDATA, &pos)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_UPLOAD, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_INFILESIZE, (long) PUT_SIZE)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) 150)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) { fprintf (stderr, "curl_easy_setopt() failed.\n"); externalErrorExit (); } multi = curl_multi_init (); if (multi == NULL) libcurlErrorExit (); mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) libcurlErrorExit (); start = time (NULL); while ((time (NULL) - start < 45) && (multi != NULL)) { MHD_socket maxMHDsock; int maxcurlsock; maxMHDsock = MHD_INVALID_SOCKET; maxcurlsock = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); mret = curl_multi_perform (multi, &running); if ((CURLM_OK != mret) && (CURLM_CALL_MULTI_PERFORM != mret)) { fprintf (stderr, "curl_multi_perform() failed. Error: '%s'. ", curl_multi_strerror (mret)); libcurlErrorExit (); } if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxcurlsock)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMHDsock)) mhdErrorExit (); tv.tv_sec = 0; tv.tv_usec = 1000; #ifndef MHD_WINSOCK_SOCKETS if (maxMHDsock > maxcurlsock) maxcurlsock = maxMHDsock; #endif /* MHD_WINSOCK_SOCKETS */ if (-1 == select (maxcurlsock + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif } mret = curl_multi_perform (multi, &running); if ((CURLM_OK != mret) && (CURLM_CALL_MULTI_PERFORM != mret)) { fprintf (stderr, "curl_multi_perform() failed. Error: '%s'. ", curl_multi_strerror (mret)); libcurlErrorExit (); } if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "curl_multi_perform() failed: '%s' ", curl_easy_strerror (msg->data.result)); libcurlErrorExit (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code "); mhdErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) mhdErrorExitDesc ("Request has been aborted by timeout"); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) { fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ", (unsigned) cbc.pos, (int) cbc.pos, cbc.buf, (unsigned) strlen ("/hello_world")); mhdErrorExitDesc ("Wrong returned data length"); } if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) { fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf); mhdErrorExitDesc ("Wrong returned data length"); } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int lastErr; oneone = has_in_name (argv[0], "11"); incr_read = has_in_name (argv[0], "_inc"); verbose = has_param (argc, argv, "-v"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 99; put_buffer = alloc_init (PUT_SIZE); if (NULL == put_buffer) return 99; lastErr = testPutExternal (); if (verbose && (0 != lastErr)) fprintf (stderr, "Error during testing with external select().\n"); errorCount += lastErr; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { lastErr = testPutInternalThread (0); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with internal thread with select().\n"); errorCount += lastErr; lastErr = testPutThreadPerConn (0); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with internal thread per connection with select().\n"); errorCount += lastErr; lastErr = testPutThreadPool (0); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with thread pool per connection with select().\n"); errorCount += lastErr; if (MHD_is_feature_supported (MHD_FEATURE_POLL)) { lastErr = testPutInternalThread (MHD_USE_POLL); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with internal thread with poll().\n"); errorCount += lastErr; lastErr = testPutThreadPerConn (MHD_USE_POLL); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with internal thread per connection with poll().\n"); errorCount += lastErr; lastErr = testPutThreadPool (MHD_USE_POLL); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with thread pool per connection with poll().\n"); errorCount += lastErr; } if (MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { lastErr = testPutInternalThread (MHD_USE_EPOLL); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with internal thread with epoll.\n"); errorCount += lastErr; lastErr = testPutThreadPool (MHD_USE_EPOLL); if (verbose && (0 != lastErr) ) fprintf (stderr, "Error during testing with thread pool per connection with epoll.\n"); errorCount += lastErr; } } free (put_buffer); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All checks passed successfully.\n"); curl_global_cleanup (); return (errorCount == 0) ? 0 : 1; } libmicrohttpd-1.0.10/src/testcurl/test_toolarge.c0000664000175000017500000016036015232103064015575 /* This file is part of libmicrohttpd Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) Copyright (C) 2007, 2009, 2011 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_toolarge.c * @brief Testcase for handling of data larger then buffers. * @details Testcases for handling of various situations when data cannot fit * the buffers. Address sanitizers and debug asserts should increase * number of problems detected by this test (detect actual overrun). * Tests start with valid sizes to ensure that normal data is processed * correctly and then sizes are monotonically increased to ensure that * overflow is handled correctly at all stages in all codepaths. * Tests with valid sizes are repeated several times to ensure that * tests are failed because of overflow, but because of second run. * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #include "mhd_has_param.h" #include "mhd_sockets.h" /* only macros used */ /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __func__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define libcurlErrorExit(ignore) \ _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__) #define libcurlErrorExitDesc(errDesc) \ _libcurlErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } static char libcurl_errbuf[CURL_ERROR_SIZE] = ""; _MHD_NORETURN static void _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "CURL library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); if (0 != libcurl_errbuf[0]) fprintf (stderr, "Last libcurl error details: %s\n", libcurl_errbuf); fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 #define EXPECTED_URI_BASE_PATH "/a" #define URL_SCHEME_HOST "http:/" "/127.0.0.1" #define N1_HEADER_NAME "n" #define N1_HEADER_VALUE "1" #define N1_HEADER N1_HEADER_NAME ": " N1_HEADER_VALUE #define N1_HEADER_CRLF N1_HEADER "\r\n" #define BUFFER_SIZE 1024 /* The size of the test element that must pass the test */ #ifndef MHD_ASAN_POISON_ACTIVE #define TEST_OK_SIZE (BUFFER_SIZE - 384) #else /* MHD_ASAN_POISON_ACTIVE */ #define TEST_OK_SIZE (BUFFER_SIZE - 384 - 80) #endif /* MHD_ASAN_POISON_ACTIVE */ /* The size of the test element where tests are started */ #define TEST_START_SIZE (TEST_OK_SIZE - 16) /* The size of the test element that must definitely fail */ #define TEST_FAIL_SIZE (BUFFER_SIZE + 32) /* Special value for request many headers test. * MHD uses the same buffer to store headers strings and pointers to the strings * so allocation is multiplied for small request header. */ /* The size of the test element that must pass the test */ #define TEST_RQ_N1_OK_SIZE 50 /* The size of the test element where tests are started */ #define TEST_RQ_N1_START_SIZE (TEST_RQ_N1_OK_SIZE - 32) /* Global parameters */ static int verbose; /**< Be verbose */ static int oneone; /**< If false use HTTP/1.0 for requests*/ static uint16_t global_port; /**< MHD daemons listen port number */ static int large_req_method; /**< Large request method */ static int large_req_url; /**< Large request URL */ static int large_req_header_name; /**< Large request single header name */ static int large_req_header_value; /**< Large request single header value */ static int large_req_headers; /**< Large request headers */ static int large_rsp_header_name; /**< Large response single header name */ static int large_rsp_header_value; /**< Large response single header value */ static int large_rsp_headers; /**< Large response headers */ static int response_timeout_val = TIMEOUTS_VAL; /* Current test parameters */ /* * Moved to local variables * */ /* Static helper variables */ /* * None for this test * */ static void test_global_init (void) { libcurl_errbuf[0] = 0; if (0 != curl_global_init (CURL_GLOBAL_WIN32)) externalErrorExit (); } static void test_global_cleanup (void) { curl_global_cleanup (); } struct headers_check_result { unsigned int num_n1_headers; size_t large_header_name_size; size_t large_header_value_size; int large_header_valid; }; static size_t lcurl_hdr_callback (char *buffer, size_t size, size_t nitems, void *userdata) { const size_t data_size = size * nitems; struct headers_check_result *check_res = (struct headers_check_result *) userdata; if ((6 == data_size) && (0 == memcmp (N1_HEADER_CRLF, buffer, 6))) check_res->num_n1_headers++; else if ((5 <= data_size) && ('0' == buffer[0])) { const char *const col_ptr = memchr (buffer, ':', data_size); if (0 != check_res->large_header_value_size) mhdErrorExitDesc ("Expected only one large header, " \ "but found two large headers in the reply"); if (NULL == col_ptr) check_res->large_header_valid = 0; else if ((size_t) (col_ptr - buffer) >= data_size - 2) check_res->large_header_valid = 0; else if (*(col_ptr + 1) != ' ') check_res->large_header_valid = 0; else { const char *const name = buffer; const size_t name_len = (size_t) (col_ptr - buffer); const size_t val_pos = name_len + 2; const size_t val_len = data_size - val_pos - 2; /* 2 = strlen("\r\n") */ const char *const value = buffer + val_pos; size_t i; check_res->large_header_name_size = name_len; check_res->large_header_value_size = val_len; check_res->large_header_valid = 1; /* To be reset if any problem found */ for (i = 1; i < name_len; i++) if ('a' + (char) (i % ('z' - 'a' + 1)) != name[i]) { fprintf (stderr, "Wrong sequence in reply header name " \ "at position %u. Expected '%c', got '%c'\n", (unsigned int) i, 'a' + (char) (i % ('z' - 'a' + 1)), name[i]); check_res->large_header_valid = 0; break; } for (i = 0; i < val_len; i++) if ('Z' - (char) (i % ('Z' - 'A' + 1)) != value[i]) { fprintf (stderr, "Wrong sequence in reply header value " \ "at position %u. Expected '%c', got '%c'\n", (unsigned int) i, 'Z' - (char) (i % ('Z' - 'A' + 1)), value[i]); check_res->large_header_valid = 0; break; } } } return data_size; } struct lcurl_data_cb_param { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct lcurl_data_cb_param *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) externalErrorExit (); /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } struct check_uri_cls { const char *volatile uri; }; static void * check_uri_cb (void *cls, const char *uri, struct MHD_Connection *con) { struct check_uri_cls *param = (struct check_uri_cls *) cls; (void) con; if (0 != strcmp (param->uri, uri)) { fprintf (stderr, "Wrong URI: `%s', line: %d\n", uri, __LINE__); exit (22); } return NULL; } struct mhd_header_checker_param { unsigned int num_n1_headers; size_t large_header_name_size; size_t large_header_value_size; int large_header_valid; }; static enum MHD_Result headerCheckerInterator (void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct mhd_header_checker_param *const param = (struct mhd_header_checker_param *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (MHD_HEADER_KIND != kind) return MHD_YES; /* Continue iteration */ if (0 == key_size) mhdErrorExitDesc ("Zero key length"); if ((1 == key_size) && (1 == value_size) && ('n' == key[0]) && ('1' == value[0])) param->num_n1_headers++; else if ('0' == key[0]) { /* Found 'large' header */ size_t i; param->large_header_name_size = key_size; param->large_header_value_size = value_size; param->large_header_valid = 1; for (i = 1; i < key_size; i++) if ('a' + (char) (i % ('z' - 'a' + 1)) != key[i]) { fprintf (stderr, "Wrong sequence in request header name " \ "at position %u. Expected '%c', got '%c'\n", (unsigned int) i, 'a' + (char) (i % ('z' - 'a' + 1)), key[i]); param->large_header_valid = 0; break; } for (i = 0; i < value_size; i++) if ('Z' - (char) (i % ('Z' - 'A' + 1)) != value[i]) { fprintf (stderr, "Wrong sequence in request header value " \ "at position %u. Expected '%c', got '%c'\n", (unsigned int) i, 'Z' - (char) (i % ('Z' - 'A' + 1)), value[i]); param->large_header_valid = 0; break; } } return MHD_YES; } struct ahc_cls_type { const char *volatile rp_data; volatile size_t rp_data_size; volatile size_t rp_num_n1_hdrs; volatile size_t rp_large_hdr_name_size; volatile size_t rp_large_hdr_value_size; struct mhd_header_checker_param header_check_param; const char *volatile rq_method; const char *volatile rq_url; }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; size_t i; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (NULL != upload_data) mhdErrorExitDesc ("'upload_data' is not NULL"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) mhdErrorExitDesc ("'*upload_data_size' value is not zero"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; if (1 > MHD_get_connection_values_n (connection, MHD_HEADER_KIND, &headerCheckerInterator, ¶m->header_check_param)) mhdErrorExitDesc ("Wrong number of headers in the request"); response = MHD_create_response_from_buffer_copy (param->rp_data_size, (const void *) param->rp_data); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); for (i = 0; i < param->rp_num_n1_hdrs; i++) if (MHD_YES != MHD_add_response_header (response, N1_HEADER_NAME, N1_HEADER_VALUE)) mhdErrorExitDesc ("Cannot add header"); if (0 != param->rp_large_hdr_name_size) { const size_t large_hdr_name_size = param->rp_large_hdr_name_size; char *large_hrd_name; const size_t large_hdr_value_size = param->rp_large_hdr_value_size; char *large_hrd_value; large_hrd_name = malloc (large_hdr_name_size + 1); if (NULL == large_hrd_name) externalErrorExit (); if (0 != large_hdr_value_size) large_hrd_value = malloc (large_hdr_value_size + 1); else large_hrd_value = NULL; if ((0 != large_hdr_value_size) && (NULL == large_hrd_value)) externalErrorExit (); large_hrd_name[0] = '0'; /* Name starts with zero for unique identification */ for (i = 1; i < large_hdr_name_size; i++) large_hrd_name[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1)); large_hrd_name[large_hdr_name_size] = 0; for (i = 0; i < large_hdr_value_size; i++) large_hrd_value[i] = 'Z' - (char) (unsigned char) (i % ('Z' - 'A' + 1)); if (NULL != large_hrd_value) large_hrd_value[large_hdr_value_size] = 0; if (MHD_YES != MHD_add_response_header (response, large_hrd_name, large_hrd_value)) mhdErrorExitDesc ("Cannot add large header"); if (NULL != large_hrd_value) free (large_hrd_value); free (large_hrd_name); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); return ret; } static CURL * curlEasyInitForTest (const char *queryPath, const char *method, uint16_t port, struct lcurl_data_cb_param *dcbp, struct headers_check_result *hdr_chk_result, struct curl_slist *headers) { CURL *c; c = curl_easy_init (); if (NULL == c) libcurlErrorExitDesc ("curl_easy_init() failed"); if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, queryPath)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, dcbp)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, (long) response_timeout_val)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER, libcurl_errbuf)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERFUNCTION, lcurl_hdr_callback)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HEADERDATA, hdr_chk_result)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, (oneone) ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_CUSTOMREQUEST, method)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); if (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPHEADER, headers)) libcurlErrorExitDesc ("curl_easy_setopt() failed"); return c; } static CURLcode performQueryExternal (struct MHD_Daemon *d, CURL *c) { CURLM *multi; time_t start; struct timeval tv; CURLcode ret; ret = CURLE_FAILED_INIT; /* will be replaced with real result */ multi = NULL; multi = curl_multi_init (); if (multi == NULL) libcurlErrorExitDesc ("curl_multi_init() failed"); if (CURLM_OK != curl_multi_add_handle (multi, c)) libcurlErrorExitDesc ("curl_multi_add_handle() failed"); start = time (NULL); while (time (NULL) - start <= TIMEOUTS_VAL) { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int maxCurlSk; int running; maxMhdSk = MHD_INVALID_SOCKET; maxCurlSk = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL != multi) { curl_multi_perform (multi, &running); if (0 == running) { struct CURLMsg *msg; int msgLeft; int totalMsgs = 0; do { msg = curl_multi_info_read (multi, &msgLeft); if (NULL == msg) libcurlErrorExitDesc ("curl_multi_info_read() failed"); totalMsgs++; if (CURLMSG_DONE == msg->msg) ret = msg->data.result; } while (msgLeft > 0); if (1 != totalMsgs) { fprintf (stderr, "curl_multi_info_read returned wrong " "number of results (%d).\n", totalMsgs); externalErrorExit (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); multi = NULL; } else { if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) libcurlErrorExitDesc ("curl_multi_fdset() failed"); } } if (NULL == multi) { /* libcurl has finished, check whether MHD still needs to perform cleanup */ if (0 != MHD_get_timeout64s (d)) break; /* MHD finished as well */ } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); tv.tv_sec = 0; tv.tv_usec = 1000; #ifdef MHD_POSIX_SOCKETS if (maxMhdSk > maxCurlSk) maxCurlSk = maxMhdSk; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep (1); #endif } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); } return ret; } struct curlQueryParams { /* Destination path for CURL query */ const char *queryPath; /* Custom query method, NULL for default */ const char *method; /* Destination port for CURL query */ uint16_t queryPort; /* List of additional request headers */ struct curl_slist *headers; /* CURL query result error flag */ volatile unsigned int queryError; /* Response HTTP code, zero if no response */ volatile int responseCode; }; /* Returns zero for successful response and non-zero for failed response */ static unsigned int doCurlQueryInThread (struct MHD_Daemon *d, struct curlQueryParams *p, struct headers_check_result *hdr_res, const char *expected_data, size_t expected_data_size) { const union MHD_DaemonInfo *dinfo; CURL *c; struct lcurl_data_cb_param dcbp; CURLcode errornum; int use_external_poll; long resp_code; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); use_external_poll = (0 == (dinfo->flags & MHD_USE_INTERNAL_POLLING_THREAD)); if (NULL == p->queryPath) abort (); if (0 == p->queryPort) abort (); /* Test must not fail due to test's internal buffer shortage */ dcbp.size = TEST_FAIL_SIZE * 2 + 1; dcbp.buf = malloc (dcbp.size); if (NULL == dcbp.buf) externalErrorExit (); dcbp.pos = 0; memset (hdr_res, 0, sizeof(*hdr_res)); c = curlEasyInitForTest (p->queryPath, p->method, p->queryPort, &dcbp, hdr_res, p->headers); if (! use_external_poll) errornum = curl_easy_perform (c); else errornum = performQueryExternal (d, c); if (CURLE_OK != curl_easy_getinfo (c, CURLINFO_RESPONSE_CODE, &resp_code)) libcurlErrorExitDesc ("curl_easy_getinfo() failed"); p->responseCode = (int) resp_code; if ((CURLE_OK == errornum) && (200 != resp_code)) { fprintf (stderr, "Got reply with unexpected status code: %d\n", p->responseCode); mhdErrorExit (); } if (CURLE_OK != errornum) { if ((CURLE_GOT_NOTHING != errornum) && (CURLE_RECV_ERROR != errornum) && (CURLE_HTTP_RETURNED_ERROR != errornum)) { if (CURLE_OPERATION_TIMEDOUT == errornum) mhdErrorExitDesc ("Request was aborted due to timeout"); fprintf (stderr, "libcurl returned unexpected error: %s\n", curl_easy_strerror (errornum)); mhdErrorExitDesc ("Request failed due to unexpected error"); } p->queryError = 1; switch (resp_code) { case 0: /* No parsed response */ case 413: /* "Content Too Large" */ case 414: /* "URI Too Long" */ case 431: /* "Request Header Fields Too Large" */ case 501: /* "Not Implemented" */ /* Expected error codes */ break; default: fprintf (stderr, "Got reply with unexpected status code: %ld\n", resp_code); mhdErrorExit (); } } else { if (dcbp.pos != expected_data_size) mhdErrorExit ("libcurl reports wrong size of MHD reply body data"); else if (0 != memcmp (expected_data, dcbp.buf, expected_data_size)) mhdErrorExit ("libcurl reports wrong MHD reply body data"); else p->queryError = 0; } curl_easy_cleanup (c); free (dcbp.buf); return p->queryError; } /* Perform test queries, shut down MHD daemon, and free parameters */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port, struct ahc_cls_type *ahc_param, struct check_uri_cls *uri_cb_param) { struct curlQueryParams qParam; unsigned int ret = 0; /* Return value */ struct headers_check_result rp_headers_check; char *buf; size_t i; size_t first_failed_at = 0; buf = malloc (TEST_FAIL_SIZE + 1 + strlen (URL_SCHEME_HOST)); if (NULL == buf) externalErrorExit (); /* Common parameters, to be individually overridden by specific test cases */ qParam.queryPort = d_port; qParam.method = NULL; /* Use libcurl default: GET */ qParam.queryPath = URL_SCHEME_HOST EXPECTED_URI_BASE_PATH; qParam.headers = NULL; /* No additional headers */ uri_cb_param->uri = EXPECTED_URI_BASE_PATH; ahc_param->rq_url = EXPECTED_URI_BASE_PATH; ahc_param->rq_method = "GET"; /* Default expected method */ ahc_param->rp_data = "~"; ahc_param->rp_data_size = 1; ahc_param->rp_large_hdr_name_size = 0; ahc_param->rp_large_hdr_value_size = 0; ahc_param->rp_num_n1_hdrs = 0; if (large_req_method) { for (i = 0; i < TEST_START_SIZE; i++) buf[i] = 'A' + (char) (unsigned char) (i % ('Z' - 'A' + 1)); for (; i <= TEST_FAIL_SIZE; i++) { buf[i] = 0; qParam.method = buf; ahc_param->rq_method = buf; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { if ((0 != qParam.responseCode) && (501 != qParam.responseCode)) { fprintf (stderr, "Got reply with status code %d, " "while code 501 (\"Not Implemented\") is expected.\n", qParam.responseCode); mhdErrorExit (); } if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); buf[i] = 'A' + (char) (unsigned char) (i % ('Z' - 'A' + 1)); } } else if (large_req_url) { const size_t base_size = strlen (URL_SCHEME_HOST); char *const url = buf + base_size; memcpy (buf, URL_SCHEME_HOST, base_size); url[0] = '/'; for (i = 1; i < TEST_START_SIZE; i++) url[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1)); for (; i <= TEST_FAIL_SIZE; i++) { url[i] = 0; qParam.queryPath = buf; uri_cb_param->uri = url; ahc_param->rq_url = url; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { if ((0 != qParam.responseCode) && (414 != qParam.responseCode)) { fprintf (stderr, "Got reply with status code %d, " "while code 414 (\"URI Too Long\") is expected.\n", qParam.responseCode); mhdErrorExit (); } if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); url[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1)); } } else if (large_req_header_name) { buf[0] = '0'; /* Name starts with zero for unique identification */ for (i = 1; i < TEST_START_SIZE; i++) buf[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1)); for (; i <= TEST_FAIL_SIZE; i++) { struct curl_slist *curl_headers; curl_headers = NULL; memcpy (buf + i, ": Z", 3); /* Note: strlen(": Z") is less than strlen(URL_SCHEME_HOST) */ buf[i + 3] = 0; curl_headers = curl_slist_append (curl_headers, buf); if (NULL == curl_headers) externalErrorExit (); qParam.headers = curl_headers; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { if ((0 != qParam.responseCode) && (431 != qParam.responseCode)) { fprintf (stderr, "Got reply with status code %d, while code 431 " "(\"Request Header Fields Too Large\") is expected.\n", qParam.responseCode); mhdErrorExit (); } if (0 != ahc_param->header_check_param.large_header_name_size) { /* If large header was processed, it must be valid */ if (i != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected wrong large request header name size"); if (1 != ahc_param->header_check_param.large_header_value_size) mhdErrorExitDesc ("Detected wrong large request header value size"); if (0 == ahc_param->header_check_param.large_header_valid) mhdErrorExitDesc ("Detected wrong large request header"); } if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (i != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected wrong large request header name size"); if (1 != ahc_param->header_check_param.large_header_value_size) mhdErrorExitDesc ("Detected wrong large request header value size"); if (0 == ahc_param->header_check_param.large_header_valid) mhdErrorExitDesc ("Detected wrong large request header"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); curl_slist_free_all (curl_headers); buf[i] = 'a' + (char) (unsigned char) (i % ('z' - 'a' + 1)); } } else if (large_req_header_value) { char *const hdr_value = buf + 3; /* Name starts with zero for unique identification */ memcpy (buf, "0: ", 3); /* Note: strlen(": Z") is less than strlen(URL_SCHEME_HOST) */ for (i = 0; i < TEST_START_SIZE; i++) hdr_value[i] = 'Z' - (char) (unsigned char) (i % ('Z' - 'A' + 1)); for (; i <= TEST_FAIL_SIZE; i++) { struct curl_slist *curl_headers; curl_headers = NULL; hdr_value[i] = 0; curl_headers = curl_slist_append (curl_headers, buf); if (NULL == curl_headers) externalErrorExit (); qParam.headers = curl_headers; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { if ((0 != qParam.responseCode) && (431 != qParam.responseCode)) { fprintf (stderr, "Got reply with status code %d, while code 431 " "(\"Request Header Fields Too Large\") is expected.\n", qParam.responseCode); mhdErrorExit (); } if (0 != ahc_param->header_check_param.large_header_name_size) { /* If large header was processed, it must be valid */ if (1 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected wrong large request header name size"); if (i != ahc_param->header_check_param.large_header_value_size) mhdErrorExitDesc ("Detected wrong large request header value size"); if (0 == ahc_param->header_check_param.large_header_valid) mhdErrorExitDesc ("Detected wrong large request header"); } if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (1 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected wrong large request header name size"); if (i != ahc_param->header_check_param.large_header_value_size) mhdErrorExitDesc ("Detected wrong large request header value size"); if (0 == ahc_param->header_check_param.large_header_valid) mhdErrorExitDesc ("Detected wrong large request header"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); curl_slist_free_all (curl_headers); hdr_value[i] = 'Z' - (char) (unsigned char) (i % ('Z' - 'A' + 1)); } } else if (large_req_headers) { unsigned int num_hdrs = 0; struct curl_slist *curl_headers; const size_t hdr_size = strlen (N1_HEADER_CRLF); curl_headers = NULL; for (i = 0; i < TEST_RQ_N1_START_SIZE; i += hdr_size) { curl_headers = curl_slist_append (curl_headers, N1_HEADER); if (NULL == curl_headers) externalErrorExit (); num_hdrs++; } for (; i <= TEST_FAIL_SIZE; i += hdr_size) { qParam.headers = curl_headers; ahc_param->header_check_param.num_n1_headers = num_hdrs; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { if ((0 != qParam.responseCode) && (431 != qParam.responseCode)) { fprintf (stderr, "Got reply with status code %d, while code 431 " "(\"Request Header Fields Too Large\") is expected.\n", qParam.responseCode); mhdErrorExit (); } if (0 != ahc_param->header_check_param.num_n1_headers) { /* If headers were processed, they must be valid */ if (num_hdrs != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected wrong number of request headers"); } if (TEST_RQ_N1_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (num_hdrs != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected wrong number of request headers"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); curl_headers = curl_slist_append (curl_headers, N1_HEADER); if (NULL == curl_headers) externalErrorExit (); num_hdrs++; } curl_slist_free_all (curl_headers); } else if (large_rsp_header_name) { for (i = TEST_START_SIZE; i <= TEST_FAIL_SIZE; i++) { ahc_param->rp_large_hdr_name_size = i; ahc_param->rp_large_hdr_value_size = 1; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { (void) qParam.responseCode; /* TODO: check for the right response code */ if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (i != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected wrong large reply header name size"); if (1 != rp_headers_check.large_header_value_size) mhdErrorExitDesc ("Detected wrong large reply header value size"); if (0 == rp_headers_check.large_header_valid) mhdErrorExitDesc ("Detected wrong large reply header"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); } } else if (large_rsp_header_value) { for (i = TEST_START_SIZE; i <= TEST_FAIL_SIZE; i++) { ahc_param->rp_large_hdr_name_size = 1; ahc_param->rp_large_hdr_value_size = i; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { (void) qParam.responseCode; /* TODO: check for the right response code */ if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (1 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected wrong large reply header name size"); if (i != rp_headers_check.large_header_value_size) mhdErrorExitDesc ("Detected wrong large reply header value size"); if (0 == rp_headers_check.large_header_valid) mhdErrorExitDesc ("Detected wrong large reply header"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); } } else if (large_rsp_headers) { size_t num_hrds; const size_t hdr_size = strlen (N1_HEADER_CRLF); for (num_hrds = TEST_START_SIZE / hdr_size; num_hrds * hdr_size <= TEST_FAIL_SIZE; num_hrds++) { i = num_hrds * hdr_size; ahc_param->rp_num_n1_hdrs = num_hrds; memset (&ahc_param->header_check_param, 0, sizeof (ahc_param->header_check_param)); if (0 != doCurlQueryInThread (d, &qParam, &rp_headers_check, ahc_param->rp_data, ahc_param->rp_data_size)) { (void) qParam.responseCode; /* TODO: check for the right response code */ if (0 != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected unexpected reply headers"); if (TEST_OK_SIZE >= i) { fprintf (stderr, "Request failed when running with the valid value size.\n"); ret = 1; /* Failed too early */ } if (0 == first_failed_at) { if (verbose) fprintf (stderr, "First failed size is %u.\n", (unsigned int) i); first_failed_at = i; } } else { if (num_hrds != rp_headers_check.num_n1_headers) mhdErrorExitDesc ("Detected wrong number of reply headers"); if (TEST_FAIL_SIZE == i) { fprintf (stderr, "Request succeed with the largest size.\n"); ret = 1; /* Succeed with largest value */ } } if (0 != ahc_param->header_check_param.num_n1_headers) mhdErrorExitDesc ("Detected unexpected request headers"); if (0 != ahc_param->header_check_param.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large request header"); if (0 != rp_headers_check.large_header_name_size) mhdErrorExitDesc ("Detected unexpected large reply header"); } } else externalErrorExitDesc ("No valid test test was selected"); MHD_stop_daemon (d); free (buf); free (uri_cb_param); free (ahc_param); return ret; } enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; (void) pollType; /* Don't care about pollType for this test */ return numThreads; /* No practical limit for non-cleanup test */ } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport, struct ahc_cls_type **ahc_param, struct check_uri_cls **uri_cb_param) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; if ((NULL == ahc_param) || (NULL == uri_cb_param)) abort (); *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type)); if (NULL == *ahc_param) externalErrorExit (); *uri_cb_param = (struct check_uri_cls *) malloc (sizeof(struct check_uri_cls)); if (NULL == *uri_cb_param) externalErrorExit (); if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 4100; if (large_req_method) *pport += 1; if (large_req_url) *pport += 2; if (large_req_header_name) *pport += 3; if (large_req_header_value) *pport += 4; if (large_req_headers) *pport += 5; if (large_rsp_header_name) *pport += 6; if (large_rsp_header_value) *pport += 7; if (large_rsp_headers) *pport += 8; if (! oneone) *pport += 16; } if (testMhdThreadExternal == thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0) | MHD_USE_NO_THREAD_SAFETY, *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) BUFFER_SIZE, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); else if (testMhdThreadInternalPool != thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) BUFFER_SIZE, MHD_OPTION_END); else d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) BUFFER_SIZE, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno); abort (); } if (0 == *pport) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed.\n"); abort (); } *pport = dinfo->port; if (0 == global_port) global_port = *pport; /* Reuse the same port for all tests */ } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } static unsigned int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param); } int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = ! has_in_name (argv[0], "10"); large_req_method = has_in_name (argv[0], "_method") ? 1 : 0; large_req_url = has_in_name (argv[0], "_url") ? 1 : 0; large_req_header_name = has_in_name (argv[0], "_request_header_name") ? 1 : 0; large_req_header_value = has_in_name (argv[0], "_request_header_value") ? 1 : 0; large_req_headers = has_in_name (argv[0], "_request_headers") ? 1 : 0; large_rsp_header_name = has_in_name (argv[0], "_reply_header_name") ? 1 : 0; large_rsp_header_value = has_in_name (argv[0], "_reply_header_value") ? 1 : 0; large_rsp_headers = has_in_name (argv[0], "_reply_headers") ? 1 : 0; if (large_req_method + large_req_url + large_req_header_name + large_req_header_value + large_req_headers + large_rsp_header_name + large_rsp_header_value + large_rsp_headers != 1) return 99; verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); test_global_init (); /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollAuto); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; #ifdef _MHD_HEAVY_TESTS /* Actually tests are not heavy, but took too long to complete while * not really provide any additional results. */ test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; } #else /* Mute compiler warnings */ (void) testMultithreadedGet; (void) testMultithreadedPoolGet; #endif /* _MHD_HEAVY_TESTS */ } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); test_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_get_response_cleanup.c0000664000175000017500000002623215232103064020164 /* This file is part of libmicrohttpd Copyright (C) 2007, 2009 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_get_response_cleanup.c * @brief Testcase for libmicrohttpd response cleanup * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include #include #include #ifndef _WIN32 #include #endif /* _WIN32 */ #ifndef WINDOWS #include #include #endif #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #include "mhd_has_in_name.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; static int ok; static pid_t fork_curl (const char *url) { pid_t ret; ret = fork (); if (ret != 0) return ret; execlp ("curl", "curl", "-s", "-N", "-o", "/dev/null", "-GET", url, NULL); fprintf (stderr, "Failed to exec curl: %s\n", strerror (errno)); _exit (-1); } static void kill_curl (pid_t pid) { int status; /* fprintf (stderr, "Killing curl\n"); */ kill (pid, SIGTERM); waitpid (pid, &status, 0); } static ssize_t push_callback (void *cls, uint64_t pos, char *buf, size_t max) { (void) cls; (void) pos; /* Unused. Silent compiler warning. */ if (max == 0) return 0; buf[0] = 'd'; return 1; } static void push_free_callback (void *cls) { int *ok_p = cls; /* fprintf (stderr, "Cleanup callback called!\n"); */ *ok_p = 0; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 32 * 1024, &push_callback, &ok, &push_free_callback); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) abort (); return ret; } static unsigned int testInternalGet (void) { struct MHD_Daemon *d; pid_t curl; uint16_t port; char url[127]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1180; if (oneone) port += 10; } ok = 1; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/", (unsigned int) port); curl = fork_curl (url); (void) sleep (1); kill_curl (curl); (void) sleep (1); /* fprintf (stderr, "Stopping daemon!\n"); */ MHD_stop_daemon (d); if (ok != 0) return 2; return 0; } static unsigned int testMultithreadedGet (void) { struct MHD_Daemon *d; pid_t curl; uint16_t port; char url[127]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1181; if (oneone) port += 10; } ok = 1; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 2, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/", (unsigned int) port); /* fprintf (stderr, "Forking cURL!\n"); */ curl = fork_curl (url); (void) sleep (1); kill_curl (curl); (void) sleep (1); curl = fork_curl (url); (void) sleep (1); if (ok != 0) { kill_curl (curl); MHD_stop_daemon (d); return 64; } kill_curl (curl); (void) sleep (1); /* fprintf (stderr, "Stopping daemon!\n"); */ MHD_stop_daemon (d); if (ok != 0) return 32; return 0; } static unsigned int testMultithreadedPoolGet (void) { struct MHD_Daemon *d; pid_t curl; uint16_t port; char url[127]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1182; if (oneone) port += 10; } ok = 1; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 64; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/", (unsigned int) port); curl = fork_curl (url); (void) sleep (1); kill_curl (curl); (void) sleep (1); /* fprintf (stderr, "Stopping daemon!\n"); */ MHD_stop_daemon (d); if (ok != 0) return 128; return 0; } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; fd_set rs; fd_set ws; fd_set es; MHD_socket max; time_t start; struct timeval tv; pid_t curl; uint16_t port; char url[127]; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else { port = 1183; if (oneone) port += 10; } ok = 1; d = MHD_start_daemon (MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/", (unsigned int) port); curl = fork_curl (url); start = time (NULL); while ((time (NULL) - start < 2)) { max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) { MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (max + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } MHD_run (d); } kill_curl (curl); start = time (NULL); while ((time (NULL) - start < 2)) { max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) { MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (max + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } MHD_run (d); } /* fprintf (stderr, "Stopping daemon!\n"); */ MHD_stop_daemon (d); if (ok != 0) return 1024; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; /* Unused. Silent compiler warning. */ #ifndef _WIN32 /* Solaris has no way to disable SIGPIPE on socket disconnect. */ if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE)) { struct sigaction act; act.sa_handler = SIG_IGN; sigaction (SIGPIPE, &act, NULL); } #endif /* _WIN32 */ if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalGet (); errorCount += testMultithreadedGet (); errorCount += testMultithreadedPoolGet (); } errorCount += testExternalGet (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_get.c0000664000175000017500000007360215232103064014542 /* This file is part of libmicrohttpd Copyright (C) 2007, 2009, 2011 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_get.c * @brief Testcase for libmicrohttpd GET operations * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include "mhd_has_in_name.h" #include "mhd_has_param.h" #include "mhd_sockets.h" /* only macros used */ /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #define EXPECTED_URI_PATH "/hello_world?a=%26&b=c" #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static int oneone; static uint16_t global_port; struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static void * log_cb (void *cls, const char *uri, struct MHD_Connection *con) { (void) cls; (void) con; if (0 != strcmp (uri, EXPECTED_URI_PATH)) { fprintf (stderr, "Wrong URI: `%s'\n", uri); _exit (22); } return NULL; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; const char *v; (void) cls; (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silence compiler warning. */ if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; v = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "a"); if ( (NULL == v) || (0 != strcmp ("&", v)) ) { fprintf (stderr, "Found while looking for 'a=&': 'a=%s'\n", NULL == v ? "NULL" : v); _exit (17); } v = NULL; if (MHD_YES != MHD_lookup_connection_value_n (connection, MHD_GET_ARGUMENT_KIND, "b", 1, &v, NULL)) { fprintf (stderr, "Not found 'b' GET argument.\n"); _exit (18); } if ( (NULL == v) || (0 != strcmp ("c", v)) ) { fprintf (stderr, "Found while looking for 'b=c': 'b=%s'\n", NULL == v ? "NULL" : v); _exit (19); } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) { fprintf (stderr, "Failed to queue response.\n"); _exit (19); } return ret; } static unsigned int testInternalGet (uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1220; if (oneone) global_port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (d == NULL) return 1; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedGet (uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1221; if (oneone) global_port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolGet (uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1222; if (oneone) global_port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalGet (int thread_unsafe) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; int maxposixs; int running; struct CURLMsg *msg; time_t start; struct timeval tv; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1223; if (oneone) global_port += 20; } multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | (thread_unsafe ? MHD_USE_NO_THREAD_SAFETY : 0), global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; #ifdef MHD_POSIX_SOCKETS if (maxsock > maxposixs) maxposixs = maxsock; #endif /* MHD_POSIX_SOCKETS */ if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } static unsigned int testUnknownPortGet (uint32_t poll_flag) { struct MHD_Daemon *d; const union MHD_DaemonInfo *di; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; uint16_t port; struct sockaddr_in addr; socklen_t addr_len = sizeof(addr); memset (&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR, &addr, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) { di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (di == NULL) return 65536; if (0 != getsockname (di->listen_fd, (struct sockaddr *) &addr, &addr_len)) return 131072; if (addr.sin_family != AF_INET) return 26214; port = ntohs (addr.sin_port); } else { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (buf, sizeof(buf), "http://127.0.0.1:%u%s", (unsigned int) port, EXPECTED_URI_PATH); c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, buf); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 524288; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 1048576; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 2097152; return 0; } static unsigned int testStopRace (uint32_t poll_flag) { struct sockaddr_in sin; MHD_socket fd; struct MHD_Daemon *d; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1224; if (oneone) global_port += 20; } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (d == NULL) return 16; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } fd = socket (PF_INET, SOCK_STREAM, 0); if (fd == MHD_INVALID_SOCKET) { fprintf (stderr, "socket error\n"); return 256; } memset (&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons (global_port); sin.sin_addr.s_addr = htonl (0x7f000001); if (connect (fd, (struct sockaddr *) (&sin), sizeof(sin)) < 0) { fprintf (stderr, "connect error\n"); MHD_socket_close_chk_ (fd); return 512; } /* printf("Waiting\n"); */ /* Let the thread get going. */ usleep (500000); /* printf("Stopping daemon\n"); */ MHD_stop_daemon (d); MHD_socket_close_chk_ (fd); /* printf("good\n"); */ return 0; } static enum MHD_Result ahc_empty (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int ptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; (void) url; (void) url; (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp ("GET", method)) return MHD_NO; /* unexpected method */ if (&ptr != *req_cls) { *req_cls = &ptr; return MHD_YES; } *req_cls = NULL; response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (ret == MHD_NO) { fprintf (stderr, "Failed to queue response.\n"); _exit (20); } return ret; } static int curlExcessFound (CURL *c, curl_infotype type, char *data, size_t size, void *cls) { static const char *excess_found = "Excess found"; const size_t str_size = strlen (excess_found); (void) c; /* Unused. Silent compiler warning. */ if ((CURLINFO_TEXT == type) && (size >= str_size) && (0 == strncmp (excess_found, data, str_size))) *(int *) cls = 1; return 0; } static unsigned int testEmptyGet (uint32_t poll_flag) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLcode errornum; int excess_found = 0; if ( (0 == global_port) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { global_port = 1225; if (oneone) global_port += 20; } cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | (enum MHD_FLAG) poll_flag, global_port, NULL, NULL, &ahc_empty, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_END); if (d == NULL) return 4194304; if (0 == global_port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } global_port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1" EXPECTED_URI_PATH); curl_easy_setopt (c, CURLOPT_PORT, (long) global_port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &curlExcessFound); curl_easy_setopt (c, CURLOPT_DEBUGDATA, &excess_found); curl_easy_setopt (c, CURLOPT_VERBOSE, 1L); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); if (oneone) curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); else curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 8388608; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != 0) return 16777216; if (excess_found) return 33554432; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; int verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = has_in_name (argv[0], "11"); verbose = has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose"); if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; global_port = 0; test_result = testExternalGet (! 0); if (test_result) fprintf (stderr, "FAILED: testExternalGet (!0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result += testExternalGet (0); if (test_result) fprintf (stderr, "FAILED: testExternalGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; test_result += testInternalGet (0); if (test_result) fprintf (stderr, "FAILED: testInternalGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (0).\n"); errorCount += test_result; test_result += testMultithreadedGet (0); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (0).\n"); errorCount += test_result; test_result += testMultithreadedPoolGet (0); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (0).\n"); errorCount += test_result; test_result += testUnknownPortGet (0); if (test_result) fprintf (stderr, "FAILED: testUnknownPortGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testUnknownPortGet (0).\n"); errorCount += test_result; test_result += testStopRace (0); if (test_result) fprintf (stderr, "FAILED: testStopRace (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testStopRace (0).\n"); errorCount += test_result; test_result += testEmptyGet (0); if (test_result) fprintf (stderr, "FAILED: testEmptyGet (0) - %u.\n", test_result); else if (verbose) printf ("PASSED: testEmptyGet (0).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result += testInternalGet (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testInternalGet (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (MHD_USE_POLL).\n"); errorCount += test_result; test_result += testMultithreadedGet (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (MHD_USE_POLL).\n"); errorCount += test_result; test_result += testMultithreadedPoolGet (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (MHD_USE_POLL).\n"); errorCount += test_result; test_result += testUnknownPortGet (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testUnknownPortGet (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testUnknownPortGet (MHD_USE_POLL).\n"); errorCount += test_result; test_result += testStopRace (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testStopRace (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testStopRace (MHD_USE_POLL).\n"); errorCount += test_result; test_result += testEmptyGet (MHD_USE_POLL); if (test_result) fprintf (stderr, "FAILED: testEmptyGet (MHD_USE_POLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testEmptyGet (MHD_USE_POLL).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result += testInternalGet (MHD_USE_EPOLL); if (test_result) fprintf (stderr, "FAILED: testInternalGet (MHD_USE_EPOLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (MHD_USE_EPOLL).\n"); errorCount += test_result; test_result += testMultithreadedPoolGet (MHD_USE_EPOLL); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (MHD_USE_EPOLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (MHD_USE_EPOLL).\n"); errorCount += test_result; test_result += testUnknownPortGet (MHD_USE_EPOLL); if (test_result) fprintf (stderr, "FAILED: testUnknownPortGet (MHD_USE_EPOLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testUnknownPortGet (MHD_USE_EPOLL).\n"); errorCount += test_result; test_result += testEmptyGet (MHD_USE_EPOLL); if (test_result) fprintf (stderr, "FAILED: testEmptyGet (MHD_USE_EPOLL) - %u.\n", test_result); else if (verbose) printf ("PASSED: testEmptyGet (MHD_USE_EPOLL).\n"); errorCount += test_result; } } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_digestauth_sha256.c0000664000175000017500000002411515232103064017207 /* This file is part of libmicrohttpd Copyright (C) 2010, 2018 Christian Grothoff Copyright (C) 2019-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_digestauth_sha256.c * @brief Testcase for libmicrohttpd Digest Auth with SHA256 * @author Amr Ali * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include #include #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ #ifndef WINDOWS #include #include #else #include #endif #define PAGE \ "libmicrohttpd demoAccess granted" #define DENIED \ "libmicrohttpd demoAccess denied" #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" struct CBC { char *buf; size_t pos; size_t size; }; static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; char *username; const char *password = "testpass"; const char *realm = "test@example.com"; enum MHD_Result ret; int ret_i; static int already_called_marker; (void) cls; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } username = MHD_digest_auth_get_username (connection); if ( (username == NULL) || (0 != strcmp (username, "testuser")) ) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, MHD_NO, MHD_DIGEST_ALG_SHA256); MHD_destroy_response (response); return ret; } ret_i = MHD_digest_auth_check2 (connection, realm, username, password, 300, MHD_DIGEST_ALG_SHA256); MHD_free (username); if (ret_i != MHD_YES) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) return MHD_NO; ret = MHD_queue_auth_fail_response2 (connection, realm, MY_OPAQUE, response, (MHD_INVALID_NONCE == ret_i) ? MHD_YES : MHD_NO, MHD_DIGEST_ALG_SHA256); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testDigestAuth (void) { CURL *c; CURLcode errornum; struct MHD_Daemon *d; struct CBC cbc; char buf[2048]; char rnd[8]; uint16_t port; char url[128]; #ifndef WINDOWS int fd; size_t len; size_t off = 0; #endif /* ! WINDOWS */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1167; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; #ifndef WINDOWS fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) { fprintf (stderr, "Failed to open `%s': %s\n", "/dev/urandom", strerror (errno)); return 1; } while (off < 8) { len = (size_t) read (fd, rnd + off, 8 - off); if (len == (size_t) -1) { fprintf (stderr, "Failed to read `%s': %s\n", "/dev/urandom", strerror (errno)); (void) close (fd); return 1; } off += len; } (void) close (fd); #else { HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (b == 0) { fprintf (stderr, "Failed to acquire crypto provider context: %lu\n", GetLastError ()); return 1; } b = CryptGenRandom (cc, 8, (BYTE *) rnd); if (b == 0) { fprintf (stderr, "Failed to generate 8 random bytes: %lu\n", GetLastError ()); } CryptReleaseContext (cc, 0); if (b == 0) return 1; } #endif d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof (rnd), rnd, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC, (uint32_t) 999, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } snprintf (url, sizeof (url), "http://127.0.0.1:%u/bar%%20foo?key=value", (unsigned int) port); c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, url); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); curl_easy_setopt (c, CURLOPT_USERPWD, "testuser:testpass"); curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); /* NOTE: use of CONNECTTIMEOUT without also setting NOSIGNAL results in really weird crashes on my system!*/ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen (PAGE)) return 4; if (0 != strncmp (PAGE, cbc.buf, strlen (PAGE))) return 8; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; curl_version_info_data *d = curl_version_info (CURLVERSION_NOW); (void) argc; (void) argv; /* Unused. Silent compiler warning. */ #if (LIBCURL_VERSION_MAJOR == 7) && (LIBCURL_VERSION_MINOR == 62) if (1) { fprintf (stderr, "libcurl version 7.62.x has bug in processing" "URI with GET arguments for Digest Auth.\n"); fprintf (stderr, "This test cannot be performed.\n"); exit (77); } #endif /* libcurl version 7.62.x */ #ifdef CURL_VERSION_SSPI if (0 != (d->features & CURL_VERSION_SSPI)) return 77; /* Skip test, W32 SSPI doesn't support sha256 digest */ #endif /* CURL_VERSION_SSPI */ /* curl added SHA256 support in 7.57 = 7.0x39 */ if (d->version_num < 0x073900) return 77; /* skip test, curl is too old */ #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; errorCount += testDigestAuth (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testcurl/test_put_chunked.c0000664000175000017500000003742515232103064016277 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file daemontest_put_chunked.c * @brief Testcase for libmicrohttpd PUT operations with chunked encoding * for the upload data * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif struct CBC { char *buf; size_t pos; size_t size; }; static size_t putBuffer (void *stream, size_t size, size_t nmemb, void *ptr) { size_t *pos = ptr; size_t wrt; wrt = size * nmemb; if (wrt > 8 - (*pos)) wrt = 8 - (*pos); if (wrt > 4) wrt = 4; /* only send half at first => force multiple chunks! */ memcpy (stream, &("Hello123"[*pos]), wrt); (*pos) += wrt; return wrt; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > cbc->size) return 0; /* overflow */ memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { size_t *done = cls; struct MHD_Response *response; enum MHD_Result ret; size_t have; (void) version; (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp ("PUT", method)) return MHD_NO; /* unexpected method */ if ((*done) < 8) { have = *upload_data_size; if (have + *done > 8) { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } if (0 == have) return MHD_YES; if (0 == memcmp (upload_data, &"Hello123"[*done], have)) { *done += have; *upload_data_size = 0; } else { printf ("Invalid upload data `%8s'!\n", upload_data); return MHD_NO; } #if 0 fprintf (stderr, "Not ready for response: %u/%u\n", *done, 8); #endif return MHD_YES; } response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int testInternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; size_t done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1440; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 1; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); /* by not giving the file size, we force chunking! */ /* curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); */ curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 4; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 8; return 0; } static unsigned int testMultithreadedPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; size_t done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1441; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); /* by not giving the file size, we force chunking! */ /* curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); */ curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testMultithreadedPoolPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; size_t pos = 0; size_t done_flag = 0; CURLcode errornum; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1442; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 16; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); /* by not giving the file size, we force chunking! */ /* curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); */ curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); if (CURLE_OK != (errornum = curl_easy_perform (c))) { fprintf (stderr, "curl_easy_perform failed: `%s'\n", curl_easy_strerror (errornum)); curl_easy_cleanup (c); MHD_stop_daemon (d); return 32; } curl_easy_cleanup (c); MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 64; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 128; return 0; } static unsigned int testExternalPut (void) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; CURLM *multi; CURLMcode mret; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef MHD_WINSOCK_SOCKETS int maxposixs; /* Max socket number unused on W32 */ #else /* MHD_POSIX_SOCKETS */ #define maxposixs maxsock #endif /* MHD_POSIX_SOCKETS */ int running; struct CURLMsg *msg; time_t start; struct timeval tv; size_t pos = 0; size_t done_flag = 0; uint16_t port; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = 1443; multi = NULL; cbc.buf = buf; cbc.size = 2048; cbc.pos = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG, port, NULL, NULL, &ahc_echo, &done_flag, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 256; if (0 == port) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (d); return 32; } port = dinfo->port; } c = curl_easy_init (); curl_easy_setopt (c, CURLOPT_URL, "http://127.0.0.1/hello_world"); curl_easy_setopt (c, CURLOPT_PORT, (long) port); curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer); curl_easy_setopt (c, CURLOPT_WRITEDATA, &cbc); curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer); curl_easy_setopt (c, CURLOPT_READDATA, &pos); curl_easy_setopt (c, CURLOPT_UPLOAD, 1L); /* by not giving the file size, we force chunking! */ /* curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, (curl_off_t) 8L); */ curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L); curl_easy_setopt (c, CURLOPT_TIMEOUT, 150L); curl_easy_setopt (c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 150L); /* NOTE: use of CONNECTTIMEOUT without also * setting NOSIGNAL results in really weird * crashes on my system! */ curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L); multi = curl_multi_init (); if (multi == NULL) { curl_easy_cleanup (c); MHD_stop_daemon (d); return 512; } mret = curl_multi_add_handle (multi, c); if (mret != CURLM_OK) { curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 1024; } start = time (NULL); while ((time (NULL) - start < 5) && (multi != NULL)) { maxsock = MHD_INVALID_SOCKET; maxposixs = -1; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs); if (mret != CURLM_OK) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 2048; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock)) { curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); MHD_stop_daemon (d); return 4096; } tv.tv_sec = 0; tv.tv_usec = 1000; if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) errno, __LINE__); fflush (stderr); exit (99); } #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) { fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", (int) WSAGetLastError (), __LINE__); fflush (stderr); exit (99); } Sleep (1); #endif } curl_multi_perform (multi, &running); if (0 == running) { int pending; int curl_fine = 0; while (NULL != (msg = curl_multi_info_read (multi, &pending))) { if (msg->msg == CURLMSG_DONE) { if (msg->data.result == CURLE_OK) curl_fine = 1; else { fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); abort (); } } } if (! curl_fine) { fprintf (stderr, "libcurl haven't returned OK code\n"); abort (); } curl_multi_remove_handle (multi, c); curl_multi_cleanup (multi); curl_easy_cleanup (c); c = NULL; multi = NULL; } MHD_run (d); } if (multi != NULL) { curl_multi_remove_handle (multi, c); curl_easy_cleanup (c); curl_multi_cleanup (multi); } MHD_stop_daemon (d); if (cbc.pos != strlen ("/hello_world")) return 8192; if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) return 16384; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ if (0 != curl_global_init (CURL_GLOBAL_WIN32)) return 2; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { errorCount += testInternalPut (); errorCount += testMultithreadedPut (); errorCount += testMultithreadedPoolPut (); } errorCount += testExternalPut (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); curl_global_cleanup (); return (0 == errorCount) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/examples/0000775000175000017500000000000015235437006012612 5libmicrohttpd-1.0.10/src/examples/upgrade_example.c0000644000175000017500000002237614760713574016061 /* This file is part of libmicrohttpd Copyright (C) 2016 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file upgrade_example.c * @brief example for how to use libmicrohttpd upgrade * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) * * Telnet to the HTTP server, use this in the request: * GET / http/1.1 * Connection: Upgrade * * After this, whatever you type will be echo'ed back to you. */ #include "platform.h" #include #include #include #define PAGE \ "libmicrohttpd demolibmicrohttpd demo" /** * Change socket to blocking. * * @param fd the socket to manipulate */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) abort (); if ((flags & ~O_NONBLOCK) != flags) if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) abort (); #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) abort (); #endif /* MHD_WINSOCK_SOCKETS */ } static void send_all (MHD_socket sock, const char *buf, size_t len) { ssize_t ret; size_t off; make_blocking (sock); for (off = 0; off < len; off += (size_t) ret) { ret = send (sock, &buf[off], #if ! defined(_WIN32) || defined(__CYGWIN__) len - off, #else /* Native W32 */ (int) (len - off), #endif /* Native W32 */ 0); if (0 > ret) { if (EAGAIN == errno) { ret = 0; continue; } break; } if (0 == ret) break; } } struct MyData { struct MHD_UpgradeResponseHandle *urh; char *extra_in; size_t extra_in_size; MHD_socket sock; }; /** * Main function for the thread that runs the interaction with * the upgraded socket. Writes what it reads. * * @param cls the `struct MyData` */ static void * run_usock (void *cls) { struct MyData *md = cls; struct MHD_UpgradeResponseHandle *urh = md->urh; char buf[128]; ssize_t got; make_blocking (md->sock); /* start by sending extra data MHD may have already read, if any */ if (0 != md->extra_in_size) { send_all (md->sock, md->extra_in, md->extra_in_size); free (md->extra_in); } /* now echo in a loop */ while (1) { got = recv (md->sock, buf, sizeof (buf), 0); if (0 >= got) break; send_all (md->sock, buf, (size_t) got); } free (md); MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); return NULL; } /** * Function called after a protocol "upgrade" response was sent * successfully and the socket should now be controlled by some * protocol other than HTTP. * * Any data already received on the socket will be made available in * @e extra_in. This can happen if the application sent extra data * before MHD send the upgrade response. The application should * treat data from @a extra_in as if it had read it from the socket. * * Note that the application must not close() @a sock directly, * but instead use #MHD_upgrade_action() for special operations * on @a sock. * * Data forwarding to "upgraded" @a sock will be started as soon * as this function return. * * Except when in 'thread-per-connection' mode, implementations * of this function should never block (as it will still be called * from within the main event loop). * * @param cls closure, whatever was given to #MHD_create_response_for_upgrade(). * @param connection original HTTP connection handle, * giving the function a last chance * to inspect the original HTTP request * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback` * @param extra_in if we happened to have read bytes after the * HTTP header already (because the client sent * more than the HTTP header of the request before * we sent the upgrade response), * these are the extra bytes already read from @a sock * by MHD. The application should treat these as if * it had read them from @a sock. * @param extra_in_size number of bytes in @a extra_in * @param sock socket to use for bi-directional communication * with the client. For HTTPS, this may not be a socket * that is directly connected to the client and thus certain * operations (TCP-specific setsockopt(), getsockopt(), etc.) * may not work as expected (as the socket could be from a * socketpair() or a TCP-loopback). The application is expected * to perform read()/recv() and write()/send() calls on the socket. * The application may also call shutdown(), but must not call * close() directly. * @param urh argument for #MHD_upgrade_action()s on this @a connection. * Applications must eventually use this callback to (indirectly) * perform the close() action on the @a sock. */ static void uh_cb (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) { struct MyData *md; pthread_t pt; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ md = malloc (sizeof (struct MyData)); if (NULL == md) abort (); memset (md, 0, sizeof (struct MyData)); if (0 != extra_in_size) { md->extra_in = malloc (extra_in_size); if (NULL == md->extra_in) abort (); memcpy (md->extra_in, extra_in, extra_in_size); } md->extra_in_size = extra_in_size; md->sock = sock; md->urh = urh; if (0 != pthread_create (&pt, NULL, &run_usock, md)) abort (); /* Note that by detaching like this we make it impossible to ensure a clean shutdown, as the we stop the daemon even if a worker thread is still running. Alas, this is a simple example... */ pthread_detach (pt); /* This callback must return as soon as possible. */ /* Data forwarding to "upgraded" socket will be started * after return from this callback. */ } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_for_upgrade (&uh_cb, NULL); MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, "Echo Server"); ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (65535 < port) ) { printf ("%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_ALLOW_UPGRADE | MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/fileserver_example.c0000644000175000017500000001042714760713574016572 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file fileserver_example.c * @brief minimal example for how to use libmicrohttpd to serve files * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_SYS_STAT_H #include #endif /* HAVE_SYS_STAT_H */ #ifdef HAVE_FCNTL_H #include #endif /* HAVE_FCNTL_H */ #define PAGE \ "File not foundFile not found" #ifndef S_ISREG #define S_ISREG(x) (S_IFREG == (x & S_IFREG)) #endif /* S_ISREG */ static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; int fd; struct stat buf; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if ( (0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD)) ) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ /* WARNING: direct usage of url as filename is for example only! * NEVER pass received data directly as parameter to file manipulation * functions. Always check validity of data before using. */ if (NULL != strstr (url, "../")) /* Very simplified check! */ fd = -1; /* Do not allow usage of parent directories. */ else fd = open (url + 1, O_RDONLY); if (-1 != fd) { if ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) { /* not a regular file, refuse to serve */ if (0 != close (fd)) abort (); fd = -1; } } if (-1 == fd) { response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); } else { response = MHD_create_response_from_fd64 ((uint64_t) buf.st_size, fd); if (NULL == response) { if (0 != close (fd)) abort (); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/benchmark.c0000644000175000017500000001313014760713574014635 /* This file is part of libmicrohttpd Copyright (C) 2007, 2013 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file benchmark.c * @brief minimal code to benchmark MHD GET performance * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #ifdef HAVE_INTTYPES_H #include #endif /* HAVE_INTTYPES_H */ #ifndef PRIu64 #define PRIu64 "llu" #endif /* ! PRIu64 */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define PAGE \ "libmicrohttpd demolibmicrohttpd demo" #define SMALL (1024 * 128) /** * Number of threads to run in the thread pool. Should (roughly) match * the number of cores on your system. */ #define NUMBER_OF_THREADS MHD_CPU_COUNT static unsigned int small_deltas[SMALL]; static struct MHD_Response *response; /** * Signature of the callback used by MHD to notify the * application about completed requests. * * @param cls client-defined closure * @param connection connection handle * @param req_cls value as set by the last call to * the MHD_AccessHandlerCallback * @param toe reason for request termination * @see MHD_OPTION_NOTIFY_COMPLETED */ static void completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct timeval *tv = *req_cls; struct timeval tve; uint64_t delta; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == tv) return; gettimeofday (&tve, NULL); delta = ((uint64_t) (tve.tv_sec - tv->tv_sec)) * 1000000LL + (uint64_t) tve.tv_usec - (uint64_t) tv->tv_usec; if (delta < SMALL) small_deltas[delta]++; else fprintf (stdout, "D: %" PRIu64 " 1\n", delta); free (tv); } static void * uri_logger_cb (void *cls, const char *uri) { struct timeval *tv = malloc (sizeof (struct timeval)); (void) cls; /* Unused. Silent compiler warning. */ (void) uri; /* Unused. Silent compiler warning. */ if (NULL != tv) gettimeofday (tv, NULL); return tv; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ return MHD_queue_response (connection, MHD_HTTP_OK, response); } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int i; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } response = MHD_create_response_from_buffer_static (strlen (PAGE), (const void *) PAGE); #if 0 (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); #endif d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_SUPPRESS_DATE_NO_CLOCK #ifdef EPOLL_SUPPORT | MHD_USE_EPOLL | MHD_USE_TURBO #endif , (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS, MHD_OPTION_URI_LOG_CALLBACK, &uri_logger_cb, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_callback, NULL, MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 1000, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); MHD_destroy_response (response); for (i = 0; i < SMALL; i++) if (0 != small_deltas[i]) fprintf (stdout, "D: %u %u\n", i, small_deltas[i]); return 0; } libmicrohttpd-1.0.10/src/examples/suspend_resume_epoll.c0000644000175000017500000001310514760713574017141 /* This file is part of libmicrohttpd Copyright (C) 2018 Christian Grothoff (and other contributing authors) Copyright (C) 2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file suspend_resume_epoll.c * @brief example for how to use libmicrohttpd with epoll() and * resume a suspended connection * @author Robert D Kocisko * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #include #define TIMEOUT_INFINITE -1 struct Request { struct MHD_Connection *connection; int timerfd; }; static int epfd; static struct epoll_event evt; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; struct Request *req; struct itimerspec ts; (void) cls; (void) method; (void) version; /* Unused. Silence compiler warning. */ (void) upload_data; /* Unused. Silence compiler warning. */ (void) upload_data_size; /* Unused. Silence compiler warning. */ req = *req_cls; if (NULL == req) { req = malloc (sizeof(struct Request)); if (NULL == req) return MHD_NO; req->connection = connection; req->timerfd = -1; *req_cls = req; return MHD_YES; } if (-1 != req->timerfd) { /* send response (echo request url) */ response = MHD_create_response_from_buffer_copy (strlen (url), (const void *) url); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /* create timer and suspend connection */ req->timerfd = timerfd_create (CLOCK_MONOTONIC, TFD_NONBLOCK); if (-1 == req->timerfd) { printf ("timerfd_create: %s", strerror (errno)); return MHD_NO; } evt.events = EPOLLIN; evt.data.ptr = req; if (-1 == epoll_ctl (epfd, EPOLL_CTL_ADD, req->timerfd, &evt)) { printf ("epoll_ctl: %s", strerror (errno)); return MHD_NO; } ts.it_value.tv_sec = 1; ts.it_value.tv_nsec = 0; ts.it_interval.tv_sec = 0; ts.it_interval.tv_nsec = 0; if (-1 == timerfd_settime (req->timerfd, 0, &ts, NULL)) { printf ("timerfd_settime: %s", strerror (errno)); return MHD_NO; } MHD_suspend_connection (connection); return MHD_YES; } static void connection_done (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct Request *req = *req_cls; (void) cls; (void) connection; (void) toe; if (-1 != req->timerfd) if (0 != close (req->timerfd)) abort (); free (req); } int main (int argc, char *const *argv) { struct MHD_Daemon *d; const union MHD_DaemonInfo *info; int current_event_count; struct epoll_event events_list[1]; struct Request *req; uint64_t timer_expirations; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (MHD_USE_EPOLL | MHD_ALLOW_SUSPEND_RESUME, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_NOTIFY_COMPLETED, &connection_done, NULL, MHD_OPTION_END); if (d == NULL) return 1; info = MHD_get_daemon_info (d, MHD_DAEMON_INFO_EPOLL_FD); if (info == NULL) return 1; epfd = epoll_create1 (EPOLL_CLOEXEC); if (-1 == epfd) return 1; evt.events = EPOLLIN; evt.data.ptr = NULL; if (-1 == epoll_ctl (epfd, EPOLL_CTL_ADD, info->epoll_fd, &evt)) return 1; while (1) { current_event_count = epoll_wait (epfd, events_list, 1, MHD_get_timeout_i (d)); if (1 == current_event_count) { if (events_list[0].data.ptr) { /* A timer has timed out */ req = events_list[0].data.ptr; /* read from the fd so the system knows we heard the notice */ if (-1 == read (req->timerfd, &timer_expirations, sizeof(timer_expirations))) { return 1; } /* Now resume the connection */ MHD_resume_connection (req->connection); } } else if (0 == current_event_count) { /* no events: continue */ } else { /* error */ return 1; } if (! MHD_run (d)) return 1; } return 0; } libmicrohttpd-1.0.10/src/examples/querystring_example.c0000644000175000017500000000756514760713574017031 /* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file querystring_example.c * @brief example for how to get the query string from libmicrohttpd * Call with an URI ending with something like "?q=QUERY" * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #define PAGE \ "libmicrohttpd demoQuery string for "%s" was "%s"" static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; const char *val; char *me; struct MHD_Response *response; enum MHD_Result ret; int resp_len; size_t buf_size; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ val = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "q"); if (NULL == val) return MHD_NO; /* No "q" argument was found */ resp_len = snprintf (NULL, 0, PAGE, "q", val); if (0 >= resp_len) return MHD_NO; /* Error calculating response size */ buf_size = (size_t) resp_len + 1; /* Add one byte for zero-termination */ me = malloc (buf_size); if (me == NULL) return MHD_NO; /* Error allocating memory */ if (resp_len != snprintf (me, buf_size, PAGE, "q", val)) { free (me); return MHD_NO; /* Error forming the response body */ } response = MHD_create_response_from_buffer_with_free_callback (buf_size - 1, (void *) me, &free); if (response == NULL) { free (me); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (port < 0) || (port > UINT16_MAX) ) { printf ("%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/digest_auth_example.c0000644000175000017500000001401214760713574016716 /* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file digest_auth_example.c * @brief minimal example for how to use digest auth with libmicrohttpd * @author Amr Ali * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #if defined(_WIN32) && ! defined(__CYGWIN__) # include #endif /* _WIN32 && ! __CYGWIN__ */ #define PAGE \ "libmicrohttpd demo" \ "Access granted" #define DENIED \ "libmicrohttpd demo" \ "Access denied" #define MY_OPAQUE_STR "11733b200778ce33060f31c9af70a870ba96ddd4" static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; /* Only one user has access to the page */ static const char *username = "testuser"; static const char *password = "testpass"; static const char *realm = "test@example.com"; enum MHD_DigestAuthResult res_e; enum MHD_Result ret; static int already_called_marker; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) method; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } /* No need to call MHD_digest_auth_get_username3() as the only * one user has an access. The username match is checked by * MHD_digest_auth_check3() function. */ res_e = MHD_digest_auth_check3 ( connection, realm, username, password, 0, 0, MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT, MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION); if (res_e != MHD_DAUTH_OK) { response = MHD_create_response_from_buffer_static (strlen (DENIED), DENIED); if (NULL == response) return MHD_NO; ret = MHD_queue_auth_required_response3 ( connection, realm, MY_OPAQUE_STR, NULL, response, (res_e == MHD_DAUTH_NONCE_STALE) ? MHD_YES : MHD_NO, MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT, MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION, MHD_NO, MHD_YES); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { char rnd[8]; struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (65535 < port) ) { fprintf (stderr, "%s PORT\n", argv[0]); return 1; } if (1) { #if ! defined(_WIN32) || defined(__CYGWIN__) int fd; ssize_t len; size_t off; fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) { fprintf (stderr, "Failed to open `%s': %s\n", "/dev/urandom", strerror (errno)); return 1; } for (off = 0; off < sizeof(rnd); off += (size_t) len) { len = read (fd, rnd, 8); if (0 > len) { fprintf (stderr, "Failed to read `%s': %s\n", "/dev/urandom", strerror (errno)); (void) close (fd); return 1; } } (void) close (fd); #else /* Native W32 */ HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (FALSE == b) { fprintf (stderr, "Failed to acquire crypto provider context: %lu\n", (unsigned long) GetLastError ()); return 1; } b = CryptGenRandom (cc, sizeof(rnd), (BYTE *) rnd); if (FALSE == b) { fprintf (stderr, "Failed to generate 8 random bytes: %lu\n", GetLastError ()); } CryptReleaseContext (cc, 0); if (FALSE == b) return 1; #endif /* Native W32 */ } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof(rnd), rnd, MHD_OPTION_NONCE_NC_SIZE, 300, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } /* end of digest_auth_example.c */ libmicrohttpd-1.0.10/src/examples/authorization_example.c0000644000175000017500000001076414760713574017330 /* This file is part of libmicrohttpd Copyright (C) 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file authorization_example.c * @brief example for how to use libmicrohttpd with HTTP authentication * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #define PAGE \ "libmicrohttpd demolibmicrohttpd demo" #define DENIED \ "Access deniedAccess denied" static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; struct MHD_BasicAuthInfo *auth_info; int fail; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ /* require: "Aladdin" with password "open sesame" */ auth_info = MHD_basic_auth_get_username_password3 (connection); fail = ( (NULL == auth_info) || (strlen ("Aladdin") != auth_info->username_len) || (0 != memcmp (auth_info->username, "Aladdin", auth_info->username_len)) || /* The next check against NULL is optional, * if 'password' is NULL then 'password_len' is always zero. */ (NULL == auth_info->password) || (strlen ("open sesame") != auth_info->password_len) || (0 != memcmp (auth_info->password, "open sesame", auth_info->password_len)) ); if (fail) { response = MHD_create_response_from_buffer_static (strlen (DENIED), (const void *) DENIED); ret = MHD_queue_basic_auth_required_response3 (connection, "TestRealm", MHD_NO, response); } else { response = MHD_create_response_from_buffer_static (strlen (PAGE), (const void *) PAGE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); } if (NULL != auth_info) MHD_free (auth_info); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (65535 < port) ) { fprintf (stderr, "%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; fprintf (stderr, "HTTP server running. Press ENTER to stop the server.\n"); (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/minimal_example_comet.c0000644000175000017500000000645214760713574017244 /* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file minimal_example.c * @brief minimal example for how to generate an infinite stream with libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include static ssize_t data_generator (void *cls, uint64_t pos, char *buf, size_t max) { (void) cls; /* Unused. Silent compiler warning. */ (void) pos; /* Unused. Silent compiler warning. */ if (max < 80) return 0; memset (buf, 'A', max - 1); buf[79] = '\n'; return 80; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 80, &data_generator, NULL, NULL); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/chunked_example.c0000644000175000017500000001356214760713574016050 /* This file is part of libmicrohttpd Copyright (C) 2015 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file chunked_example.c * @brief example for generating chunked encoding with libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include struct ResponseContentCallbackParam { const char *response_data; size_t response_size; }; static ssize_t callback (void *cls, uint64_t pos, char *buf, size_t buf_size) { size_t size_to_copy; struct ResponseContentCallbackParam *const param = (struct ResponseContentCallbackParam *) cls; /* Note: 'pos' will never exceed size of transmitted data. */ /* You can use 'pos == param->response_size' in next check. */ if (pos >= param->response_size) { /* Whole response was sent. Signal end of response. */ return MHD_CONTENT_READER_END_OF_STREAM; } /* Pseudo code. * if (data_not_ready) { // Callback will be called again on next loop. // Consider suspending connection until data will be ready. return 0; } * End of pseudo code. */ if (buf_size < (param->response_size - pos)) size_to_copy = buf_size; else size_to_copy = (size_t) (param->response_size - pos); memcpy (buf, param->response_data + pos, size_to_copy); /* Pseudo code. * if (error_preparing_response) { // Close connection with error. return MHD_CONTENT_READER_END_WITH_ERROR; } * End of pseudo code. */ /* Return amount of data copied to buffer. */ /* The 'buf_size' is always smaller than SSIZE_MAX therefore it's safe * to cast 'size_to_copy' to 'ssize_t'. */ /* assert (size_to_copy <= buf_size); */ return (ssize_t) size_to_copy; } static void free_callback_param (void *cls) { free (cls); } static const char simple_response_text[] = "Simple response" "Simple response text"; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct ResponseContentCallbackParam *callback_param; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } callback_param = malloc (sizeof(struct ResponseContentCallbackParam)); if (NULL == callback_param) return MHD_NO; /* Not enough memory. */ callback_param->response_data = simple_response_text; callback_param->response_size = (sizeof(simple_response_text) / sizeof(char)) - 1; *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, &callback, callback_param, &free_callback_param); if (NULL == response) { free (callback_param); return MHD_NO; } /* Enforce chunked response, even for non-keep-alive connection. */ if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked")) { free (callback_param); MHD_destroy_response (response); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > UINT16_MAX) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); if (NULL == d) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/demo.c0000644000175000017500000007111315035214301013610 /* This file is part of libmicrohttpd Copyright (C) 2013 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file demo.c * @brief complex demonstration site: create directory index, offer * upload via form and HTTP POST, download with mime type detection * and error reporting (403, etc.) --- and all of this with * high-performance settings (large buffers, thread pool). * If you want to benchmark MHD, this code should be used to * run tests against. Note that the number of threads may need * to be adjusted depending on the number of available cores. * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifdef MHD_HAVE_LIBMAGIC #include #endif /* MHD_HAVE_LIBMAGIC */ #include #include #include #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #ifndef PATH_MAX /* Some platforms (namely: GNU Hurd) do no define PATH_MAX. As it is only example for MHD, just use reasonable value for PATH_MAX. */ #define PATH_MAX 16384 #endif /** * Number of threads to run in the thread pool. Should (roughly) match * the number of cores on your system. */ #define NUMBER_OF_THREADS MHD_CPU_COUNT #ifdef MHD_HAVE_LIBMAGIC /** * How many bytes of a file do we give to libmagic to determine the mime type? * 16k might be a bit excessive, but ought not hurt performance much anyway, * and should definitively be on the safe side. */ #define MAGIC_HEADER_SIZE (16 * 1024) #endif /* MHD_HAVE_LIBMAGIC */ /** * Page returned for file-not-found. */ #define FILE_NOT_FOUND_PAGE \ "File not foundFile not found" /** * Page returned for internal errors. */ #define INTERNAL_ERROR_PAGE \ "Internal errorInternal error" /** * Page returned for refused requests. */ #define REQUEST_REFUSED_PAGE \ "Request refusedRequest refused (file exists?)" /** * Head of index page. */ #define INDEX_PAGE_HEADER \ "\nWelcome\n\n" \ "

Upload

\n" \ "
\n" \ "
Content type:
" \ "Book" \ "Image" \ "Music" \ "Software" \ "Videos\n" \ "Other
" \ "
Language:
" \ "none" \ "English" \ "German" \ "French" \ "Spanish
\n" \ "
File:
" \ "
" \ "\n" \ "
\n" \ "

Download

\n" \ "
    \n" /** * Footer of index page. */ #define INDEX_PAGE_FOOTER "
\n\n" /** * NULL-terminated array of supported upload categories. Should match HTML * in the form. */ static const char *const categories[] = { "books", "images", "music", "software", "videos", "other", NULL, }; /** * Specification of a supported language. */ struct Language { /** * Directory name for the language. */ const char *dirname; /** * Long name for humans. */ const char *longname; }; /** * NULL-terminated array of supported upload categories. Should match HTML * in the form. */ static const struct Language languages[] = { { "no-lang", "No language specified" }, { "en", "English" }, { "de", "German" }, { "fr", "French" }, { "es", "Spanish" }, { NULL, NULL }, }; /** * Response returned if the requested file does not exist (or is not accessible). */ static struct MHD_Response *file_not_found_response; /** * Response returned for internal errors. */ static struct MHD_Response *internal_error_response; /** * Response returned for '/' (GET) to list the contents of the directory and allow upload. */ static struct MHD_Response *cached_directory_response; /** * Response returned for refused uploads. */ static struct MHD_Response *request_refused_response; /** * Mutex used when we update the cached directory response object. */ static pthread_mutex_t mutex; #ifdef MHD_HAVE_LIBMAGIC /** * Global handle to MAGIC data. */ static magic_t magic; #endif /* MHD_HAVE_LIBMAGIC */ /** * Mark the given response as HTML for the browser. * * @param response response to mark */ static void mark_as_html (struct MHD_Response *response) { (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); } /** * Replace the existing 'cached_directory_response' with the * given response. * * @param response new directory response */ static void update_cached_response (struct MHD_Response *response) { (void) pthread_mutex_lock (&mutex); if (NULL != cached_directory_response) MHD_destroy_response (cached_directory_response); cached_directory_response = response; (void) pthread_mutex_unlock (&mutex); } /** * Context keeping the data for the response we're building. */ struct ResponseDataContext { /** * Response data string. */ char *buf; /** * Number of bytes allocated for 'buf'. */ size_t buf_len; /** * Current position where we append to 'buf'. Must be smaller or equal to 'buf_len'. */ size_t off; }; /** * Create a listing of the files in 'dirname' in HTML. * * @param rdc where to store the list of files * @param dirname name of the directory to list * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result list_directory (struct ResponseDataContext *rdc, const char *dirname) { char fullname[PATH_MAX]; struct stat sbuf; DIR *dir; struct dirent *de; if (NULL == (dir = opendir (dirname))) return MHD_NO; while (NULL != (de = readdir (dir))) { int res; if ('.' == de->d_name[0]) continue; if (sizeof (fullname) <= (unsigned int) snprintf (fullname, sizeof (fullname), "%s/%s", dirname, de->d_name)) continue; /* ugh, file too long? how can this be!? */ if (0 != stat (fullname, &sbuf)) continue; /* ugh, failed to 'stat' */ if (! S_ISREG (sbuf.st_mode)) continue; /* not a regular file, skip */ if (rdc->off + 1024 > rdc->buf_len) { void *r; if ( (2 * rdc->buf_len + 1024) < rdc->buf_len) break; /* more than SIZE_T _index_ size? Too big for us */ rdc->buf_len = 2 * rdc->buf_len + 1024; if (NULL == (r = realloc (rdc->buf, rdc->buf_len))) break; /* out of memory */ rdc->buf = r; } res = snprintf (&rdc->buf[rdc->off], rdc->buf_len - rdc->off, "
  • %s
  • \n", fullname, de->d_name); if (0 >= res) continue; /* snprintf() error */ if (rdc->buf_len - rdc->off <= (size_t) res) continue; /* buffer too small?? */ rdc->off += (size_t) res; } (void) closedir (dir); return MHD_YES; } /** * Re-scan our local directory and re-build the index. */ static void update_directory (void) { static size_t initial_allocation = 32 * 1024; /* initial size for response buffer */ struct MHD_Response *response; struct ResponseDataContext rdc; unsigned int language_idx; unsigned int category_idx; const struct Language *language; const char *category; char dir_name[128]; struct stat sbuf; int res; size_t len; rdc.buf_len = initial_allocation; if (NULL == (rdc.buf = malloc (rdc.buf_len))) { update_cached_response (NULL); return; } len = strlen (INDEX_PAGE_HEADER); if (rdc.buf_len <= len) { /* buffer too small */ free (rdc.buf); update_cached_response (NULL); return; } memcpy (rdc.buf, INDEX_PAGE_HEADER, len); rdc.off = len; for (language_idx = 0; NULL != languages[language_idx].dirname; language_idx++) { language = &languages[language_idx]; if (0 != stat (language->dirname, &sbuf)) continue; /* empty */ /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the header without need for an additional reallocation check. */ res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off, "

    %s

    \n", language->longname); if (0 >= res) continue; /* snprintf() error */ if (rdc.buf_len - rdc.off <= (size_t) res) continue; /* buffer too small?? */ rdc.off += (size_t) res; for (category_idx = 0; NULL != categories[category_idx]; category_idx++) { category = categories[category_idx]; res = snprintf (dir_name, sizeof (dir_name), "%s/%s", language->dirname, category); if ((0 >= res) || (sizeof (dir_name) <= (size_t) res)) continue; /* cannot print dir name */ if (0 != stat (dir_name, &sbuf)) continue; /* empty */ /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the header without need for an additional reallocation check. */ res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off, "

    %s

    \n", category); if (0 >= res) continue; /* snprintf() error */ if (rdc.buf_len - rdc.off <= (size_t) res) continue; /* buffer too small?? */ rdc.off += (size_t) res; if (MHD_NO == list_directory (&rdc, dir_name)) { free (rdc.buf); update_cached_response (NULL); return; } } } /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the footer without need for a final reallocation check. */ len = strlen (INDEX_PAGE_FOOTER); if (rdc.buf_len - rdc.off <= len) { /* buffer too small */ free (rdc.buf); update_cached_response (NULL); return; } memcpy (&rdc.buf[rdc.off], INDEX_PAGE_FOOTER, len); rdc.off += len; initial_allocation = rdc.buf_len; /* remember for next time */ response = MHD_create_response_from_buffer_with_free_callback (rdc.off, rdc.buf, &free); mark_as_html (response); #ifdef FORCE_CLOSE (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); #endif update_cached_response (response); } /** * Context we keep for an upload. */ struct UploadContext { /** * Handle where we write the uploaded file to. */ int fd; /** * Name of the file on disk (used to remove on errors). */ char *filename; /** * Language for the upload. */ char *language; /** * Category for the upload. */ char *category; /** * Post processor we're using to process the upload. */ struct MHD_PostProcessor *pp; /** * Handle to connection that we're processing the upload for. */ struct MHD_Connection *connection; /** * Response to generate, NULL to use directory. */ struct MHD_Response *response; }; /** * Append the 'size' bytes from 'data' to '*ret', adding * 0-termination. If '*ret' is NULL, allocate an empty string first. * * @param ret string to update, NULL or 0-terminated * @param data data to append * @param size number of bytes in 'data' * @return #MHD_NO on allocation failure, #MHD_YES on success */ static enum MHD_Result do_append (char **ret, const char *data, size_t size) { char *buf; size_t old_len; if (NULL == *ret) old_len = 0; else old_len = strlen (*ret); if (NULL == (buf = malloc (old_len + size + 1))) return MHD_NO; if (NULL != *ret) { memcpy (buf, *ret, old_len); free (*ret); } memcpy (&buf[old_len], data, size); buf[old_len + size] = '\0'; *ret = buf; return MHD_YES; } /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value, always MHD_POSTDATA_KIND when called from MHD * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration */ static enum MHD_Result process_upload_data (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct UploadContext *uc = cls; size_t i; int res; (void) kind; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ (void) off; /* Unused. Silent compiler warning. */ if (0 == strcmp (key, "category")) return do_append (&uc->category, data, size); if (0 == strcmp (key, "language")) return do_append (&uc->language, data, size); if (0 != strcmp (key, "upload")) { fprintf (stderr, "Ignoring unexpected form value `%s'\n", key); return MHD_YES; /* ignore */ } if (NULL == filename) { fprintf (stderr, "No filename, aborting upload.\n"); return MHD_NO; /* no filename, error */ } if ( (NULL == uc->category) || (NULL == uc->language) ) { fprintf (stderr, "Missing form data for upload `%s'\n", filename); uc->response = request_refused_response; return MHD_NO; } if (-1 == uc->fd) { char fn[PATH_MAX]; if ( (NULL != strstr (filename, "..")) || (NULL != strchr (filename, '/')) || (NULL != strchr (filename, '\\')) ) { uc->response = request_refused_response; return MHD_NO; } /* create directories -- if they don't exist already */ #ifdef WINDOWS (void) mkdir (uc->language); #else (void) mkdir (uc->language, S_IRWXU); #endif snprintf (fn, sizeof (fn), "%s/%s", uc->language, uc->category); #ifdef WINDOWS (void) mkdir (fn); #else (void) mkdir (fn, S_IRWXU); #endif /* open file */ res = snprintf (fn, sizeof (fn), "%s/%s/%s", uc->language, uc->category, filename); if ((0 >= res) || (sizeof (fn) <= (size_t) res)) { uc->response = request_refused_response; return MHD_NO; } for (i = 0; i < (size_t) res; i++) if (! isprint ((unsigned char) fn[i])) fn[i] = '_'; uc->fd = open (fn, O_CREAT | O_EXCL #ifdef O_LARGEFILE | O_LARGEFILE #endif | O_WRONLY, S_IRUSR | S_IWUSR); if (-1 == uc->fd) { fprintf (stderr, "Error opening file `%s' for upload: %s\n", fn, strerror (errno)); uc->response = request_refused_response; return MHD_NO; } uc->filename = strdup (fn); } if ( (0 != size) && #if ! defined(_WIN32) || defined(__CYGWIN__) (size != (size_t) write (uc->fd, data, size)) #else /* Native W32 */ (size != (size_t) write (uc->fd, data, (unsigned int) size)) #endif /* Native W32 */ ) { /* write failed; likely: disk full */ fprintf (stderr, "Error writing to file `%s': %s\n", uc->filename, strerror (errno)); uc->response = internal_error_response; (void) close (uc->fd); uc->fd = -1; if (NULL != uc->filename) { unlink (uc->filename); free (uc->filename); uc->filename = NULL; } return MHD_NO; } return MHD_YES; } /** * Function called whenever a request was completed. * Used to clean up 'struct UploadContext' objects. * * @param cls client-defined closure, NULL * @param connection connection handle * @param req_cls value as set by the last call to * the MHD_AccessHandlerCallback, points to NULL if this was * not an upload * @param toe reason for request termination */ static void response_completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct UploadContext *uc = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == uc) return; /* this request wasn't an upload request */ if (NULL != uc->pp) { MHD_destroy_post_processor (uc->pp); uc->pp = NULL; } if (-1 != uc->fd) { (void) close (uc->fd); if (NULL != uc->filename) { fprintf (stderr, "Upload of file `%s' failed (incomplete or aborted), removing file.\n", uc->filename); (void) unlink (uc->filename); } } if (NULL != uc->filename) free (uc->filename); free (uc); } /** * Return the current directory listing. * * @param connection connection to return the directory for * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result return_directory_response (struct MHD_Connection *connection) { enum MHD_Result ret; (void) pthread_mutex_lock (&mutex); if (NULL == cached_directory_response) ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, internal_error_response); else ret = MHD_queue_response (connection, MHD_HTTP_OK, cached_directory_response); (void) pthread_mutex_unlock (&mutex); return ret; } /** * Main callback from MHD, used to generate the page. * * @param cls NULL * @param connection connection handle * @param url requested URL * @param method GET, PUT, POST, etc. * @param version HTTP version * @param upload_data data from upload (PUT/POST) * @param upload_data_size number of bytes in @a upload_data * @param req_cls our context * @return #MHD_YES on success, #MHD_NO to drop connection */ static enum MHD_Result generate_page (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; int fd; struct stat buf; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ if (0 != strcmp (url, "/")) { /* should be file download */ #ifdef MHD_HAVE_LIBMAGIC char file_data[MAGIC_HEADER_SIZE]; ssize_t got; #endif /* MHD_HAVE_LIBMAGIC */ const char *mime; if ( (0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD)) ) return MHD_NO; /* unexpected method (we're not polite...) */ fd = -1; if ( (NULL == strstr (&url[1], "..")) && ('/' != url[1]) ) { fd = open (&url[1], O_RDONLY); if ( (-1 != fd) && ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) ) { (void) close (fd); fd = -1; } } if (-1 == fd) return MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, file_not_found_response); #ifdef MHD_HAVE_LIBMAGIC /* read beginning of the file to determine mime type */ got = read (fd, file_data, sizeof (file_data)); (void) lseek (fd, 0, SEEK_SET); if (0 < got) mime = magic_buffer (magic, file_data, (size_t) got); else #endif /* MHD_HAVE_LIBMAGIC */ mime = NULL; { /* Set mime-type by file-extension in some cases */ const char *ldot = strrchr (&url[1], '.'); if (NULL != ldot) { if (0 == strcasecmp (ldot, ".html")) mime = "text/html"; if (0 == strcasecmp (ldot, ".css")) mime = "text/css"; if (0 == strcasecmp (ldot, ".css3")) mime = "text/css"; if (0 == strcasecmp (ldot, ".js")) mime = "application/javascript"; } } if (NULL == (response = MHD_create_response_from_fd ((size_t) buf.st_size, fd))) { /* internal error (i.e. out of memory) */ (void) close (fd); return MHD_NO; } /* add mime type if we had one */ if (NULL != mime) (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { /* upload! */ struct UploadContext *uc = *req_cls; if (NULL == uc) { if (NULL == (uc = malloc (sizeof (struct UploadContext)))) return MHD_NO; /* out of memory, close connection */ memset (uc, 0, sizeof (struct UploadContext)); uc->fd = -1; uc->connection = connection; uc->pp = MHD_create_post_processor (connection, 64 * 1024 /* buffer size */, &process_upload_data, uc); if (NULL == uc->pp) { /* out of memory, close connection */ free (uc); return MHD_NO; } *req_cls = uc; return MHD_YES; } if (0 != *upload_data_size) { if (NULL == uc->response) (void) MHD_post_process (uc->pp, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } /* end of upload, finish it! */ MHD_destroy_post_processor (uc->pp); uc->pp = NULL; if (-1 != uc->fd) { close (uc->fd); uc->fd = -1; } if (NULL != uc->response) { return MHD_queue_response (connection, MHD_HTTP_FORBIDDEN, uc->response); } else { update_directory (); return return_directory_response (connection); } } if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) || (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) ) { return return_directory_response (connection); } /* unexpected request, refuse */ return MHD_queue_response (connection, MHD_HTTP_FORBIDDEN, request_refused_response); } #ifndef MINGW /** * Function called if we get a SIGPIPE. Does nothing. * * @param sig will be SIGPIPE (ignored) */ static void catcher (int sig) { (void) sig; /* Unused. Silent compiler warning. */ /* do nothing */ } /** * setup handlers to ignore SIGPIPE. */ static void ignore_sigpipe (void) { struct sigaction oldsig; struct sigaction sig; sig.sa_handler = &catcher; sigemptyset (&sig.sa_mask); #ifdef SA_INTERRUPT sig.sa_flags = SA_INTERRUPT; /* SunOS */ #else sig.sa_flags = SA_RESTART; #endif if (0 != sigaction (SIGPIPE, &sig, &oldsig)) fprintf (stderr, "Failed to install SIGPIPE handler: %s\n", strerror (errno)); } #endif /** * Entry point to demo. Note: this HTTP server will make all * files in the current directory and its subdirectories available * to anyone. Press ENTER to stop the server once it has started. * * @param argc number of arguments in argv * @param argv first and only argument should be the port number * @return 0 on success */ int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (UINT16_MAX < port) ) { fprintf (stderr, "%s PORT\n", argv[0]); return 1; } #ifndef MINGW ignore_sigpipe (); #endif #ifdef MHD_HAVE_LIBMAGIC magic = magic_open (MAGIC_MIME_TYPE); (void) magic_load (magic, NULL); #endif /* MHD_HAVE_LIBMAGIC */ (void) pthread_mutex_init (&mutex, NULL); file_not_found_response = MHD_create_response_from_buffer_static (strlen (FILE_NOT_FOUND_PAGE), (const void *) FILE_NOT_FOUND_PAGE); mark_as_html (file_not_found_response); request_refused_response = MHD_create_response_from_buffer_static (strlen (REQUEST_REFUSED_PAGE), (const void *) REQUEST_REFUSED_PAGE); mark_as_html (request_refused_response); internal_error_response = MHD_create_response_from_buffer_static (strlen (INTERNAL_ERROR_PAGE), (const void *) INTERNAL_ERROR_PAGE); mark_as_html (internal_error_response); update_directory (); d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &generate_page, NULL, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (256 * 1024), #ifdef PRODUCTION MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) (64), #endif MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) (120 /* seconds */) , MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS, MHD_OPTION_NOTIFY_COMPLETED, &response_completed_callback, NULL, MHD_OPTION_END); if (NULL == d) return 1; fprintf (stderr, "HTTP server running. Press ENTER to stop the server.\n"); (void) getc (stdin); MHD_stop_daemon (d); MHD_destroy_response (file_not_found_response); MHD_destroy_response (request_refused_response); MHD_destroy_response (internal_error_response); update_cached_response (NULL); (void) pthread_mutex_destroy (&mutex); #ifdef MHD_HAVE_LIBMAGIC magic_close (magic); #endif /* MHD_HAVE_LIBMAGIC */ return 0; } /* end of demo.c */ libmicrohttpd-1.0.10/src/examples/fileserver_example_external_select.c0000644000175000017500000001343114760713574022031 /* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file fileserver_example_external_select.c * @brief minimal example for how to use libmicrohttpd to server files * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #define PAGE \ "File not foundFile not found" static ssize_t file_reader (void *cls, uint64_t pos, char *buf, size_t max) { FILE *file = (FILE *) cls; size_t bytes_read; /* 'fseek' may not support files larger 2GiB, depending on platform. * For production code, make sure that 'pos' has valid values, supported by * 'fseek', or use 'fseeko' or similar function. */ if (0 != fseek (file, (long) pos, SEEK_SET)) return MHD_CONTENT_READER_END_WITH_ERROR; bytes_read = fread (buf, 1, max, file); if (0 == bytes_read) return (0 != ferror (file)) ? MHD_CONTENT_READER_END_WITH_ERROR : MHD_CONTENT_READER_END_OF_STREAM; return (ssize_t) bytes_read; } static void free_callback (void *cls) { FILE *file = cls; fclose (file); } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; FILE *file; int fd; struct stat buf; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ file = fopen (&url[1], "rb"); if (NULL != file) { fd = fileno (file); if (-1 == fd) { (void) fclose (file); return MHD_NO; /* internal error */ } if ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) { /* not a regular file, refuse to serve */ fclose (file); file = NULL; } } if (NULL == file) { response = MHD_create_response_from_buffer_static (strlen (PAGE), PAGE); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); } else { response = MHD_create_response_from_callback ((size_t) buf.st_size, 32 * 1024, /* 32k page size */ &file_reader, file, &free_callback); if (NULL == response) { fclose (file); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; time_t end; time_t t; struct timeval tv; fd_set rs; fd_set ws; fd_set es; MHD_socket max; uint64_t mhd_timeout; int port; if (argc != 3) { printf ("%s PORT SECONDS-TO-RUN\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (d == NULL) return 1; end = time (NULL) + atoi (argv[2]); while ((t = time (NULL)) < end) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = end - t; #else /* Native W32 */ tv.tv_sec = (long) (end - t); #endif /* Native W32 */ tv.tv_usec = 0; max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) break; /* fatal internal error */ if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES) { if (((uint64_t) tv.tv_sec) < mhd_timeout / 1000LL) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (mhd_timeout / 1000LL); #else /* Native W32 */ tv.tv_sec = (long) (mhd_timeout / 1000LL); #endif /* Native W32 */ tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000; } } if (-1 == select ((int) max + 1, &rs, &ws, &es, &tv)) { if (EINTR != errno) abort (); } MHD_run (d); } MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/http_chunked_compression.c0000644000175000017500000001422614760713574020013 /* This file is part of libmicrohttpd Copyright (C) 2019 Christian Grothoff (and other contributing authors) Copyright (C) 2019-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file http_chunked_compression.c * @brief example for how to compress a chunked HTTP response * @author Silvio Clecio (silvioprog) * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #ifndef ZLIB_CONST /* Correct API with const pointer for input data is required */ #define ZLIB_CONST 1 #endif /* ! ZLIB_CONST */ #include #include #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #include #include #ifndef SSIZE_MAX #ifdef __SSIZE_MAX__ #define SSIZE_MAX __SSIZE_MAX__ #elif defined(PTRDIFF_MAX) #define SSIZE_MAX PTRDIFF_MAX #elif defined(INTPTR_MAX) #define SSIZE_MAX INTPTR_MAX #else #define SSIZE_MAX ((ssize_t) (((size_t) -1) >> 1)) #endif #endif /* ! SSIZE_MAX */ #define CHUNK 16384 struct Holder { FILE *file; z_stream stream; void *buf; }; static enum MHD_Result compress_buf (z_stream *strm, const void *src, size_t src_size, size_t *offset, void **dest, size_t *dest_size, void *tmp) { unsigned int have; enum MHD_Result ret; int flush; void *tmp_dest; *dest = NULL; *dest_size = 0; do { if (src_size > CHUNK) { strm->avail_in = CHUNK; src_size -= CHUNK; flush = Z_NO_FLUSH; } else { strm->avail_in = (uInt) src_size; flush = Z_SYNC_FLUSH; } *offset += strm->avail_in; strm->next_in = (const Bytef *) src; do { strm->avail_out = CHUNK; strm->next_out = tmp; ret = (Z_OK == deflate (strm, flush)) ? MHD_YES : MHD_NO; have = CHUNK - strm->avail_out; *dest_size += have; tmp_dest = realloc (*dest, *dest_size); if (NULL == tmp_dest) { free (*dest); *dest = NULL; return MHD_NO; } *dest = tmp_dest; memcpy (((uint8_t *) (*dest)) + ((*dest_size) - have), tmp, have); } while (0 == strm->avail_out); } while (flush != Z_SYNC_FLUSH); return ret; } static ssize_t read_cb (void *cls, uint64_t pos, char *mem, size_t size) { struct Holder *holder = cls; void *src; void *buf; ssize_t ret; size_t offset; size_t r_size; if (pos > SSIZE_MAX) return MHD_CONTENT_READER_END_WITH_ERROR; offset = (size_t) pos; src = malloc (size); if (NULL == src) return MHD_CONTENT_READER_END_WITH_ERROR; r_size = fread (src, 1, size, holder->file); if (0 == r_size) { ret = (0 != ferror (holder->file)) ? MHD_CONTENT_READER_END_WITH_ERROR : MHD_CONTENT_READER_END_OF_STREAM; goto done; } if (MHD_YES != compress_buf (&holder->stream, src, r_size, &offset, &buf, &size, holder->buf)) ret = MHD_CONTENT_READER_END_WITH_ERROR; else { memcpy (mem, buf, size); ret = (ssize_t) size; } free (buf); /* Buf may be set even on error return. */ done: free (src); return ret; } static void free_cb (void *cls) { struct Holder *holder = cls; fclose (holder->file); deflateEnd (&holder->stream); free (holder->buf); free (holder); } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *con, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_size, void **req_cls) { struct Holder *holder; struct MHD_Response *res; enum MHD_Result ret; (void) cls; (void) url; (void) method; (void) version; (void) upload_data; (void) upload_size; if (NULL == *req_cls) { *req_cls = (void *) 1; return MHD_YES; } *req_cls = NULL; holder = calloc (1, sizeof (struct Holder)); if (! holder) return MHD_NO; holder->file = fopen (__FILE__, "rb"); if (NULL == holder->file) goto file_error; if (Z_OK != deflateInit (&holder->stream, Z_BEST_COMPRESSION)) goto stream_error; holder->buf = malloc (CHUNK); if (NULL == holder->buf) goto buf_error; res = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, &read_cb, holder, &free_cb); if (NULL == res) goto error; ret = MHD_add_response_header (res, MHD_HTTP_HEADER_CONTENT_ENCODING, "deflate"); if (MHD_YES != ret) goto res_error; ret = MHD_add_response_header (res, MHD_HTTP_HEADER_CONTENT_TYPE, "text/x-c"); if (MHD_YES != ret) goto res_error; ret = MHD_queue_response (con, MHD_HTTP_OK, res); res_error: MHD_destroy_response (res); return ret; error: free (holder->buf); buf_error: deflateEnd (&holder->stream); stream_error: fclose (holder->file); file_error: free (holder); return MHD_NO; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ((argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (UINT16_MAX < port)) { fprintf (stderr, "%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 1; if (0 == port) MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT, &port); fprintf (stdout, "HTTP server running at http://localhost:%u\n\nPress ENTER to stop the server ...\n", port); (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/refuse_post_example.c0000644000175000017500000001013614760713574016757 /* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file refuse_post_example.c * @brief example for how to refuse a POST request properly * @author Christian Grothoff and Sebastian Gerhardt * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include struct handler_param { const char *response_page; }; static const char *askpage = "\n\ Upload a file, please!
    \n\
    \n\ \n\
    \n\ "; #define BUSYPAGE \ "Webserver busy" \ "We are too busy to process POSTs right now." static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct handler_param *param = (struct handler_param *) cls; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if ((0 != strcmp (method, "GET")) && (0 != strcmp (method, "POST"))) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { *req_cls = &aptr; /* always to busy for POST requests */ if (0 == strcmp (method, "POST")) { response = MHD_create_response_from_buffer_static (strlen (BUSYPAGE), (const void *) BUSYPAGE); ret = MHD_queue_response (connection, MHD_HTTP_SERVICE_UNAVAILABLE, response); MHD_destroy_response (response); return ret; } } *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_buffer_static (strlen (param->response_page), (const void *) param->response_page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct handler_param data_for_handler; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } data_for_handler.response_page = askpage; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, &data_for_handler, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } /* end of refuse_post_example.c */ libmicrohttpd-1.0.10/src/examples/test_suspend_resume_epoll.c0000664000175000017500000004142215232215632020170 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff (and other contributing authors) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file test_suspend_resume_epoll.c * @brief Test for the suspend_resume_epoll example. The example itself * is started as a child process and then driven over HTTP, so * what is tested is exactly the code that ships as the example. * * The example parks every request for one second on a timerfd * that lives in the application's own epoll set, next to the * daemon's epoll FD. Checking that the right bytes come back is * the easy part; the checks that matter are that the process * burns no CPU while a connection is suspended, and that two * requests are parked at the same time rather than one after the * other. Both would still deliver identical bytes if suspending * were broken. * @author Christian Grothoff */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include /** * How long the example parks a request, in milliseconds. This is the * one-second timer hard-coded in suspend_resume_epoll.c. */ #define PARK_MS 1000 /** * Upper bound for any single request, in seconds. */ #define REQUEST_TIMEOUT 30 /** * How long to wait for the freshly started example to answer, in * milliseconds. */ #define STARTUP_TIMEOUT_MS 5000 /** * How often to retry with a different port if the one we picked turned * out to be taken after all. */ #define PORT_ATTEMPTS 5 /** * Largest response body we are prepared to keep. */ #define MAX_BODY 4096 /** * What one HTTP request collected. */ struct Fetch { /** * The body, as far as it was received. */ char body[MAX_BODY]; /** * Number of valid bytes in @e body. */ size_t len; /** * Result of the transfer. */ CURLcode res; }; /** * The example's process ID, or -1 once it has been reaped. */ static pid_t server_pid = -1; /** * The port the example was told to bind. */ static unsigned int server_port; /** * Number of checks that failed. */ static unsigned int failures; /** * Report the outcome of one check. * * @param ok non-zero if the check passed * @param what what was being checked */ static void check (int ok, const char *what) { if (! ok) failures++; fprintf (stderr, "%s: %s\n", ok ? "PASS" : "FAIL", what); } /** * @return the current value of the monotonic clock, in milliseconds */ static long now_ms (void) { struct timespec ts; if (0 != clock_gettime (CLOCK_MONOTONIC, &ts)) return 0; return (long) ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } /** * Read the CPU time consumed by process @a pid so far. Only * implemented for Linux; everywhere else the test simply skips the * check that uses it. * * @param pid the process to look at * @param[out] ms where to store the sum of user and system time in * milliseconds * @return non-zero on success */ static int cpu_time_ms (pid_t pid, long *ms) { #ifdef __linux__ char path[64]; char buf[1024]; char *p; FILE *f; size_t got; unsigned long utime; unsigned long stime; long ticks; snprintf (path, sizeof (path), "/proc/%ld/stat", (long) pid); f = fopen (path, "r"); if (NULL == f) return 0; got = fread (buf, 1, sizeof (buf) - 1, f); fclose (f); if (0 == got) return 0; buf[got] = '\0'; /* The second field is the executable name and may contain spaces and parentheses, so start parsing behind its closing one. */ p = strrchr (buf, ')'); if (NULL == p) return 0; if (2 != sscanf (p + 1, " %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu", &utime, &stime)) return 0; ticks = sysconf (_SC_CLK_TCK); if (0 >= ticks) return 0; *ms = (long) ((utime + stime) * 1000 / (unsigned long) ticks); return 1; #else (void) pid; (void) ms; return 0; #endif } static size_t write_cb (void *ptr, size_t size, size_t nmemb, void *cls) { struct Fetch *f = cls; size_t total = size * nmemb; if (total > sizeof (f->body) - f->len - 1) total = sizeof (f->body) - f->len - 1; memcpy (&f->body[f->len], ptr, total); f->len += total; f->body[f->len] = '\0'; return size * nmemb; } /** * Create an easy handle that will GET @a path from the example. * * @param path the path to request * @param[out] f where to store what is received; cleared here * @return the handle, or NULL on error */ static CURL * make_handle (const char *path, struct Fetch *f) { CURL *curl; char url[128]; memset (f, 0, sizeof (struct Fetch)); f->res = CURLE_FAILED_INIT; snprintf (url, sizeof (url), "http://127.0.0.1:%u%s", server_port, path); curl = curl_easy_init (); if (NULL == curl) return NULL; curl_easy_setopt (curl, CURLOPT_URL, url); curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, &write_cb); curl_easy_setopt (curl, CURLOPT_WRITEDATA, f); curl_easy_setopt (curl, CURLOPT_TIMEOUT, (long) REQUEST_TIMEOUT); curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1L); return curl; } /** * Perform one GET against the example. * * @param path the path to request * @param[out] f where to store what was received * @return milliseconds the request took */ static long fetch (const char *path, struct Fetch *f) { CURL *curl; long start; curl = make_handle (path, f); if (NULL == curl) return 0; start = now_ms (); f->res = curl_easy_perform (curl); curl_easy_cleanup (curl); return now_ms () - start; } /** * Perform two GETs against the example at the same time. * * @param path1 the path for the first request * @param path2 the path for the second request * @param[out] f1 where to store what the first request received * @param[out] f2 where to store what the second request received * @return milliseconds until both were done */ static long fetch_both (const char *path1, const char *path2, struct Fetch *f1, struct Fetch *f2) { CURLM *multi; CURL *c1; CURL *c2; CURLMsg *msg; int running; int left; long start; c1 = make_handle (path1, f1); c2 = make_handle (path2, f2); multi = curl_multi_init (); if ( (NULL == c1) || (NULL == c2) || (NULL == multi) ) { if (NULL != c1) curl_easy_cleanup (c1); if (NULL != c2) curl_easy_cleanup (c2); if (NULL != multi) curl_multi_cleanup (multi); return 0; } curl_multi_add_handle (multi, c1); curl_multi_add_handle (multi, c2); start = now_ms (); running = 1; while (0 != running) { if (CURLM_OK != curl_multi_perform (multi, &running)) break; if (0 == running) break; if (CURLM_OK != curl_multi_wait (multi, NULL, 0, 100, NULL)) break; if (now_ms () - start > REQUEST_TIMEOUT * 1000) break; } while (NULL != (msg = curl_multi_info_read (multi, &left))) { if (CURLMSG_DONE != msg->msg) continue; if (msg->easy_handle == c1) f1->res = msg->data.result; else if (msg->easy_handle == c2) f2->res = msg->data.result; } curl_multi_remove_handle (multi, c1); curl_multi_remove_handle (multi, c2); curl_easy_cleanup (c1); curl_easy_cleanup (c2); curl_multi_cleanup (multi); return now_ms () - start; } /** * Ask the operating system for a port that is currently free. The * example insists on being given a port number, so the test has to pick * one; if the guess goes stale between here and the child's bind() the * child exits at once and the caller simply tries again. * * @param[out] port where to store the port number * @return non-zero on success */ static int pick_free_port (unsigned int *port) { struct sockaddr_in addr; socklen_t addrlen = sizeof (addr); int sock; sock = socket (AF_INET, SOCK_STREAM, 0); if (-1 == sock) return 0; memset (&addr, 0, sizeof (addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl (INADDR_ANY); addr.sin_port = 0; if ( (0 != bind (sock, (struct sockaddr *) &addr, sizeof (addr))) || (0 != getsockname (sock, (struct sockaddr *) &addr, &addrlen)) ) { close (sock); return 0; } close (sock); *port = ntohs (addr.sin_port); return (0 != *port); } /** * Start the example and wait until it answers. * * @return 1 on success, 0 if it could not be started, -1 if the binary * could not be executed at all (in which case the test skips) */ static int start_server (void) { unsigned int attempt; for (attempt = 0; attempt < PORT_ATTEMPTS; attempt++) { char port_arg[16]; long deadline; if (! pick_free_port (&server_port)) return 0; snprintf (port_arg, sizeof (port_arg), "%u", server_port); server_pid = fork (); if (-1 == server_pid) return 0; if (0 == server_pid) { execl ("./suspend_resume_epoll", "suspend_resume_epoll", port_arg, (char *) NULL); fprintf (stderr, "Failed to exec ./suspend_resume_epoll: %s\n", strerror (errno)); _exit (77); } deadline = now_ms () + STARTUP_TIMEOUT_MS; while (now_ms () < deadline) { struct Fetch f; int status; if (server_pid == waitpid (server_pid, &status, WNOHANG)) { /* The example gave up, most likely because the port was taken after all. Unless it could not even be started, try again. */ if (WIFEXITED (status) && (77 == WEXITSTATUS (status))) { server_pid = -1; return -1; } server_pid = -1; break; } (void) fetch ("/startup", &f); if (CURLE_OK == f.res) return 1; usleep (100 * 1000); } if (-1 != server_pid) { kill (server_pid, SIGKILL); waitpid (server_pid, NULL, 0); server_pid = -1; return 0; /* it is running but not answering; retrying will not help */ } } return 0; } /** * The example echoes the requested URL back, but only after the timer * it armed has fired. */ static void test_echo (void) { struct Fetch f; long ms; ms = fetch ("/hello/world", &f); check (CURLE_OK == f.res, "request completed"); check (0 == strcmp (f.body, "/hello/world"), "example echoed the requested URL"); /* Only a lower bound is checked: a loaded machine may take longer, but nothing can make the one-second timer fire early. */ fprintf (stderr, "request was parked for %ld ms\n", ms); check (ms >= PARK_MS / 2, "answer waited for the timer to fire"); } /** * While the connection is parked the process must be asleep in * epoll_wait(). This is the check that tells a suspended connection * apart from an access handler that is polled in a loop --- both return * the same bytes after the same delay. */ static void test_idle_while_suspended (void) { struct Fetch f; long cpu_before; long cpu_after; long ms; if (! cpu_time_ms (server_pid, &cpu_before)) { fprintf (stderr, "SKIP: no way to read the server's CPU time on this " "platform\n"); return; } ms = fetch ("/idle", &f); check (CURLE_OK == f.res, "request completed"); if (! cpu_time_ms (server_pid, &cpu_after)) { fprintf (stderr, "SKIP: could not read the server's CPU time\n"); return; } fprintf (stderr, "server used %ld ms of CPU during %ld ms of waiting\n", cpu_after - cpu_before, ms); /* "<=" rather than "<" so that a degenerate run in which nothing was waited for at all is left for test_echo() to report, instead of being blamed on CPU usage here. */ check ((cpu_after - cpu_before) * 4 <= ms, "server stayed idle while the connection was suspended"); } /** * Suspending must not serialise requests: two connections parked at the * same time have to come back after one timer period, not two. With a * single-threaded daemon this only works because the connection is * taken out of the event loop rather than blocking it. */ static void test_two_at_once (void) { struct Fetch f1; struct Fetch f2; long ms; ms = fetch_both ("/first", "/second", &f1, &f2); check ( (CURLE_OK == f1.res) && (CURLE_OK == f2.res), "both concurrent requests completed"); check ( (0 == strcmp (f1.body, "/first")) && (0 == strcmp (f2.body, "/second")), "each concurrent request got its own answer"); fprintf (stderr, "two concurrent requests took %ld ms\n", ms); check (ms < 2 * PARK_MS - PARK_MS / 4, "the two requests were parked at the same time"); } /** * A client that hangs up while its connection is parked must not take * the server down, and must not leak the timer either. */ static void test_client_hangs_up (void) { struct sockaddr_in addr; struct Fetch f; static const char *req = "GET /gone HTTP/1.1\r\nHost: localhost\r\n\r\n"; int sock; sock = socket (AF_INET, SOCK_STREAM, 0); if (-1 == sock) { check (0, "could not create a socket"); return; } memset (&addr, 0, sizeof (addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); addr.sin_port = htons ((uint16_t) server_port); if (0 != connect (sock, (struct sockaddr *) &addr, sizeof (addr))) { close (sock); check (0, "could not connect to the example"); return; } if (-1 == send (sock, req, strlen (req), 0)) { close (sock); check (0, "could not send a request"); return; } /* Hang up well before the timer fires, so that the connection is still suspended when the FIN arrives. */ usleep ((useconds_t) (PARK_MS / 4) * 1000); close (sock); (void) fetch ("/still/here", &f); check ( (CURLE_OK == f.res) && (0 == strcmp (f.body, "/still/here")), "server survived a client that hung up while suspended"); } int main (void) { int started; if (0 != curl_global_init (CURL_GLOBAL_ALL)) return 77; started = start_server (); if (1 != started) { fprintf (stderr, "Could not start ./suspend_resume_epoll\n"); curl_global_cleanup (); return (-1 == started) ? 77 : 1; } fprintf (stderr, "example listening on port %u\n", server_port); test_echo (); test_idle_while_suspended (); test_two_at_once (); test_client_hangs_up (); /* The example runs an endless loop by design, so there is nothing to ask it to do but die. */ kill (server_pid, SIGKILL); waitpid (server_pid, NULL, 0); server_pid = -1; curl_global_cleanup (); if (0 != failures) fprintf (stderr, "%u check(s) failed\n", failures); return (0 == failures) ? 0 : 1; } libmicrohttpd-1.0.10/src/examples/benchmark_https.c0000644000175000017500000002303114760713574016060 /* This file is part of libmicrohttpd Copyright (C) 2007, 2013 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file benchmark_https.c * @brief minimal code to benchmark MHD GET performance with HTTPS * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #ifdef HAVE_INTTYPES_H #include #endif /* HAVE_INTTYPES_H */ #ifndef PRIu64 #define PRIu64 "llu" #endif /* ! PRIu64 */ #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #define PAGE \ "libmicrohttpd demolibmicrohttpd demo" #define SMALL (1024 * 128) /** * Number of threads to run in the thread pool. Should (roughly) match * the number of cores on your system. */ #define NUMBER_OF_THREADS MHD_CPU_COUNT static unsigned int small_deltas[SMALL]; static struct MHD_Response *response; /** * Signature of the callback used by MHD to notify the * application about completed requests. * * @param cls client-defined closure * @param connection connection handle * @param req_cls value as set by the last call to * the MHD_AccessHandlerCallback * @param toe reason for request termination * @see MHD_OPTION_NOTIFY_COMPLETED */ static void completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct timeval *tv = *req_cls; struct timeval tve; uint64_t delta; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == tv) return; gettimeofday (&tve, NULL); delta = ((uint64_t) (tve.tv_sec - tv->tv_sec)) * 1000000LL + (uint64_t) tve.tv_usec - (uint64_t) tv->tv_usec; if (delta < SMALL) small_deltas[delta]++; else fprintf (stdout, "D: %" PRIu64 " 1\n", delta); free (tv); } static void * uri_logger_cb (void *cls, const char *uri) { struct timeval *tv = malloc (sizeof (struct timeval)); (void) cls; /* Unused. Silent compiler warning. */ (void) uri; /* Unused. Silent compiler warning. */ if (NULL != tv) gettimeofday (tv, NULL); return tv; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ return MHD_queue_response (connection, MHD_HTTP_OK, response); } /* test server key */ static const char srv_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n\ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\ rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\ UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\ +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\ HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\ CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\ dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\ +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\ XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\ znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\ pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\ D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\ pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\ zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\ pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\ KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\ OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\ XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\ wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\ ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\ 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\ ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\ QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\ qdJNJ1DkyUc9dN2cliX4R+rG\n\ -----END PRIVATE KEY-----"; /* test server CA signed certificates */ static const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\ NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\ TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\ c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\ psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\ atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\ 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\ n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\ qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\ kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\ AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\ c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\ 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\ IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\ Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\ X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\ aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\ HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\ hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\ 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\ UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\ B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\ SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\ WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\ OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\ /w0gW9EVWzFhsFeGEssi\n\ -----END CERTIFICATE-----"; int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int i; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } response = MHD_create_response_from_buffer_static (strlen (PAGE), (const void *) PAGE); d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS #ifdef EPOLL_SUPPORT | MHD_USE_EPOLL | MHD_USE_TURBO #endif , (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS, MHD_OPTION_URI_LOG_CALLBACK, &uri_logger_cb, NULL, MHD_OPTION_NOTIFY_COMPLETED, &completed_callback, NULL, MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 1000, /* Optionally, the gnutls_load_file() can be used to load the key and the certificate from file. */ MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); MHD_destroy_response (response); for (i = 0; i < SMALL; i++) if (0 != small_deltas[i]) fprintf (stdout, "D: %u %u\n", i, small_deltas[i]); return 0; } libmicrohttpd-1.0.10/src/examples/minimal_example_empty.c0000644000175000017500000000635314760713574017273 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff (and other contributing authors) Copyright (C) 2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file minimal_example.c * @brief minimal example for how to use libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, MHD_HTTP_NO_CONTENT, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/demo_https.c0000644000175000017500000010031115035214301015023 /* This file is part of libmicrohttpd Copyright (C) 2013 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file demo_https.c * @brief complex demonstration site: create directory index, offer * upload via form and HTTP POST, download with mime type detection * and error reporting (403, etc.) --- and all of this with * high-performance settings (large buffers, thread pool). * If you want to benchmark MHD, this code should be used to * run tests against. Note that the number of threads may need * to be adjusted depending on the number of available cores. * Logic is identical to demo.c, just adds HTTPS support. * This demonstration uses key/cert stored in static string. Optionally, * use gnutls_load_file() to load them from file. * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #include #include #ifdef MHD_HAVE_LIBMAGIC #include #endif /* MHD_HAVE_LIBMAGIC */ #include #include #include #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #ifndef PATH_MAX /* Some platforms (namely: GNU Hurd) do no define PATH_MAX. As it is only example for MHD, just use reasonable value for PATH_MAX. */ #define PATH_MAX 16384 #endif /** * Number of threads to run in the thread pool. Should (roughly) match * the number of cores on your system. */ #define NUMBER_OF_THREADS MHD_CPU_COUNT #ifdef MHD_HAVE_LIBMAGIC /** * How many bytes of a file do we give to libmagic to determine the mime type? * 16k might be a bit excessive, but ought not hurt performance much anyway, * and should definitively be on the safe side. */ #define MAGIC_HEADER_SIZE (16 * 1024) #endif /* MHD_HAVE_LIBMAGIC */ /** * Page returned for file-not-found. */ #define FILE_NOT_FOUND_PAGE \ "File not foundFile not found" /** * Page returned for internal errors. */ #define INTERNAL_ERROR_PAGE \ "Internal errorInternal error" /** * Page returned for refused requests. */ #define REQUEST_REFUSED_PAGE \ "Request refusedRequest refused (file exists?)" /** * Head of index page. */ #define INDEX_PAGE_HEADER \ "\nWelcome\n\n" \ "

    Upload

    \n" \ "
    \n" \ "
    Content type:
    " \ "Book" \ "Image" \ "Music" \ "Software" \ "Videos\n" \ "Other
    " \ "
    Language:
    " \ "none" \ "English" \ "German" \ "French" \ "Spanish
    \n" \ "
    File:
    " \ "
    " \ "\n" \ "
    \n" \ "

    Download

    \n" \ "
      \n" /** * Footer of index page. */ #define INDEX_PAGE_FOOTER "
    \n\n" /** * NULL-terminated array of supported upload categories. Should match HTML * in the form. */ static const char *const categories[] = { "books", "images", "music", "software", "videos", "other", NULL, }; /** * Specification of a supported language. */ struct Language { /** * Directory name for the language. */ const char *dirname; /** * Long name for humans. */ const char *longname; }; /** * NULL-terminated array of supported upload categories. Should match HTML * in the form. */ static const struct Language languages[] = { { "no-lang", "No language specified" }, { "en", "English" }, { "de", "German" }, { "fr", "French" }, { "es", "Spanish" }, { NULL, NULL }, }; /** * Response returned if the requested file does not exist (or is not accessible). */ static struct MHD_Response *file_not_found_response; /** * Response returned for internal errors. */ static struct MHD_Response *internal_error_response; /** * Response returned for '/' (GET) to list the contents of the directory and allow upload. */ static struct MHD_Response *cached_directory_response; /** * Response returned for refused uploads. */ static struct MHD_Response *request_refused_response; /** * Mutex used when we update the cached directory response object. */ static pthread_mutex_t mutex; #ifdef MHD_HAVE_LIBMAGIC /** * Global handle to MAGIC data. */ static magic_t magic; #endif /* MHD_HAVE_LIBMAGIC */ /** * Mark the given response as HTML for the browser. * * @param response response to mark */ static void mark_as_html (struct MHD_Response *response) { (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); } /** * Replace the existing 'cached_directory_response' with the * given response. * * @param response new directory response */ static void update_cached_response (struct MHD_Response *response) { (void) pthread_mutex_lock (&mutex); if (NULL != cached_directory_response) MHD_destroy_response (cached_directory_response); cached_directory_response = response; (void) pthread_mutex_unlock (&mutex); } /** * Context keeping the data for the response we're building. */ struct ResponseDataContext { /** * Response data string. */ char *buf; /** * Number of bytes allocated for 'buf'. */ size_t buf_len; /** * Current position where we append to 'buf'. Must be smaller or equal to 'buf_len'. */ size_t off; }; /** * Create a listing of the files in 'dirname' in HTML. * * @param rdc where to store the list of files * @param dirname name of the directory to list * @return MHD_YES on success, MHD_NO on error */ static enum MHD_Result list_directory (struct ResponseDataContext *rdc, const char *dirname) { char fullname[PATH_MAX]; struct stat sbuf; DIR *dir; struct dirent *de; if (NULL == (dir = opendir (dirname))) return MHD_NO; while (NULL != (de = readdir (dir))) { int res; if ('.' == de->d_name[0]) continue; if (sizeof (fullname) <= (size_t) snprintf (fullname, sizeof (fullname), "%s/%s", dirname, de->d_name)) continue; /* ugh, file too long? how can this be!? */ if (0 != stat (fullname, &sbuf)) continue; /* ugh, failed to 'stat' */ if (! S_ISREG (sbuf.st_mode)) continue; /* not a regular file, skip */ if (rdc->off + 1024 > rdc->buf_len) { void *r; if ( (2 * rdc->buf_len + 1024) < rdc->buf_len) break; /* more than SIZE_T _index_ size? Too big for us */ rdc->buf_len = 2 * rdc->buf_len + 1024; if (NULL == (r = realloc (rdc->buf, rdc->buf_len))) break; /* out of memory */ rdc->buf = r; } res = snprintf (&rdc->buf[rdc->off], rdc->buf_len - rdc->off, "
  • %s
  • \n", fullname, de->d_name); if (0 >= res) continue; /* snprintf() error */ if (rdc->buf_len - rdc->off <= (size_t) res) continue; /* buffer too small?? */ rdc->off += (size_t) res; } (void) closedir (dir); return MHD_YES; } /** * Re-scan our local directory and re-build the index. */ static void update_directory (void) { static size_t initial_allocation = 32 * 1024; /* initial size for response buffer */ struct MHD_Response *response; struct ResponseDataContext rdc; unsigned int language_idx; unsigned int category_idx; const struct Language *language; const char *category; char dir_name[128]; struct stat sbuf; int res; size_t len; rdc.buf_len = initial_allocation; if (NULL == (rdc.buf = malloc (rdc.buf_len))) { update_cached_response (NULL); return; } len = strlen (INDEX_PAGE_HEADER); if (rdc.buf_len <= len) { /* buffer too small */ free (rdc.buf); update_cached_response (NULL); return; } memcpy (rdc.buf, INDEX_PAGE_HEADER, len); rdc.off = len; for (language_idx = 0; NULL != languages[language_idx].dirname; language_idx++) { language = &languages[language_idx]; if (0 != stat (language->dirname, &sbuf)) continue; /* empty */ /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the header without need for an additional reallocation check. */ res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off, "

    %s

    \n", language->longname); if (0 >= res) continue; /* snprintf() error */ if (rdc.buf_len - rdc.off <= (size_t) res) continue; /* buffer too small?? */ rdc.off += (size_t) res; for (category_idx = 0; NULL != categories[category_idx]; category_idx++) { category = categories[category_idx]; res = snprintf (dir_name, sizeof (dir_name), "%s/%s", language->dirname, category); if ((0 >= res) || (sizeof (dir_name) <= (size_t) res)) continue; /* cannot print dir name */ if (0 != stat (dir_name, &sbuf)) continue; /* empty */ /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the header without need for an additional reallocation check. */ res = snprintf (&rdc.buf[rdc.off], rdc.buf_len - rdc.off, "

    %s

    \n", category); if (0 >= res) continue; /* snprintf() error */ if (rdc.buf_len - rdc.off <= (size_t) res) continue; /* buffer too small?? */ rdc.off += (size_t) res; if (MHD_NO == list_directory (&rdc, dir_name)) { free (rdc.buf); update_cached_response (NULL); return; } } } /* we ensured always +1k room, filenames are ~256 bytes, so there is always still enough space for the footer without need for a final reallocation check. */ len = strlen (INDEX_PAGE_FOOTER); if (rdc.buf_len - rdc.off <= len) { /* buffer too small */ free (rdc.buf); update_cached_response (NULL); return; } memcpy (&rdc.buf[rdc.off], INDEX_PAGE_FOOTER, len); rdc.off += len; initial_allocation = rdc.buf_len; /* remember for next time */ response = MHD_create_response_from_buffer_with_free_callback (rdc.off, rdc.buf, &free); mark_as_html (response); #ifdef FORCE_CLOSE (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); #endif update_cached_response (response); } /** * Context we keep for an upload. */ struct UploadContext { /** * Handle where we write the uploaded file to. */ int fd; /** * Name of the file on disk (used to remove on errors). */ char *filename; /** * Language for the upload. */ char *language; /** * Category for the upload. */ char *category; /** * Post processor we're using to process the upload. */ struct MHD_PostProcessor *pp; /** * Handle to connection that we're processing the upload for. */ struct MHD_Connection *connection; /** * Response to generate, NULL to use directory. */ struct MHD_Response *response; }; /** * Append the 'size' bytes from 'data' to '*ret', adding * 0-termination. If '*ret' is NULL, allocate an empty string first. * * @param ret string to update, NULL or 0-terminated * @param data data to append * @param size number of bytes in 'data' * @return #MHD_NO on allocation failure, #MHD_YES on success */ static enum MHD_Result do_append (char **ret, const char *data, size_t size) { char *buf; size_t old_len; if (NULL == *ret) old_len = 0; else old_len = strlen (*ret); if (NULL == (buf = malloc (old_len + size + 1))) return MHD_NO; if (NULL != *ret) { memcpy (buf, *ret, old_len); free (*ret); } memcpy (&buf[old_len], data, size); buf[old_len + size] = '\0'; *ret = buf; return MHD_YES; } /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value, always MHD_POSTDATA_KIND when called from MHD * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration */ static enum MHD_Result process_upload_data (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct UploadContext *uc = cls; size_t i; int res; (void) kind; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ (void) off; /* Unused. Silent compiler warning. */ if (0 == strcmp (key, "category")) return do_append (&uc->category, data, size); if (0 == strcmp (key, "language")) return do_append (&uc->language, data, size); if (0 != strcmp (key, "upload")) { fprintf (stderr, "Ignoring unexpected form value `%s'\n", key); return MHD_YES; /* ignore */ } if (NULL == filename) { fprintf (stderr, "No filename, aborting upload.\n"); return MHD_NO; /* no filename, error */ } if ( (NULL == uc->category) || (NULL == uc->language) ) { fprintf (stderr, "Missing form data for upload `%s'\n", filename); uc->response = request_refused_response; return MHD_NO; } if (-1 == uc->fd) { char fn[PATH_MAX]; if ( (NULL != strstr (filename, "..")) || (NULL != strchr (filename, '/')) || (NULL != strchr (filename, '\\')) ) { uc->response = request_refused_response; return MHD_NO; } /* create directories -- if they don't exist already */ #ifdef WINDOWS (void) mkdir (uc->language); #else (void) mkdir (uc->language, S_IRWXU); #endif snprintf (fn, sizeof (fn), "%s/%s", uc->language, uc->category); #ifdef WINDOWS (void) mkdir (fn); #else (void) mkdir (fn, S_IRWXU); #endif /* open file */ res = snprintf (fn, sizeof (fn), "%s/%s/%s", uc->language, uc->category, filename); if ((0 >= res) || (sizeof (fn) <= (size_t) res)) { uc->response = request_refused_response; return MHD_NO; } for (i = 0; i < (size_t) res; i++) if (! isprint ((unsigned char) fn[i])) fn[i] = '_'; uc->fd = open (fn, O_CREAT | O_EXCL #ifdef O_LARGEFILE | O_LARGEFILE #endif | O_WRONLY, S_IRUSR | S_IWUSR); if (-1 == uc->fd) { fprintf (stderr, "Error opening file `%s' for upload: %s\n", fn, strerror (errno)); uc->response = request_refused_response; return MHD_NO; } uc->filename = strdup (fn); } if ( (0 != size) && #if ! defined(_WIN32) || defined(__CYGWIN__) (size != (size_t) write (uc->fd, data, size)) #else /* Native W32 */ (size != (size_t) write (uc->fd, data, (unsigned int) size)) #endif /* Native W32 */ ) { /* write failed; likely: disk full */ fprintf (stderr, "Error writing to file `%s': %s\n", uc->filename, strerror (errno)); uc->response = internal_error_response; (void) close (uc->fd); uc->fd = -1; if (NULL != uc->filename) { unlink (uc->filename); free (uc->filename); uc->filename = NULL; } return MHD_NO; } return MHD_YES; } /** * Function called whenever a request was completed. * Used to clean up 'struct UploadContext' objects. * * @param cls client-defined closure, NULL * @param connection connection handle * @param req_cls value as set by the last call to * the MHD_AccessHandlerCallback, points to NULL if this was * not an upload * @param toe reason for request termination */ static void response_completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct UploadContext *uc = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == uc) return; /* this request wasn't an upload request */ if (NULL != uc->pp) { MHD_destroy_post_processor (uc->pp); uc->pp = NULL; } if (-1 != uc->fd) { (void) close (uc->fd); if (NULL != uc->filename) { fprintf (stderr, "Upload of file `%s' failed (incomplete or aborted), removing file.\n", uc->filename); (void) unlink (uc->filename); } } if (NULL != uc->filename) free (uc->filename); free (uc); } /** * Return the current directory listing. * * @param connection connection to return the directory for * @return MHD_YES on success, MHD_NO on error */ static enum MHD_Result return_directory_response (struct MHD_Connection *connection) { enum MHD_Result ret; (void) pthread_mutex_lock (&mutex); if (NULL == cached_directory_response) ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, internal_error_response); else ret = MHD_queue_response (connection, MHD_HTTP_OK, cached_directory_response); (void) pthread_mutex_unlock (&mutex); return ret; } /** * Main callback from MHD, used to generate the page. * * @param cls NULL * @param connection connection handle * @param url requested URL * @param method GET, PUT, POST, etc. * @param version HTTP version * @param upload_data data from upload (PUT/POST) * @param upload_data_size number of bytes in "upload_data" * @param req_cls our context * @return #MHD_YES on success, #MHD_NO to drop connection */ static enum MHD_Result generate_page (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; int fd; struct stat buf; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ if (0 != strcmp (url, "/")) { /* should be file download */ #ifdef MHD_HAVE_LIBMAGIC char file_data[MAGIC_HEADER_SIZE]; ssize_t got; #endif /* MHD_HAVE_LIBMAGIC */ const char *mime; if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method (we're not polite...) */ fd = -1; if ( (NULL == strstr (&url[1], "..")) && ('/' != url[1]) ) { fd = open (&url[1], O_RDONLY); if ( (-1 != fd) && ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) ) { (void) close (fd); fd = -1; } } if (-1 == fd) return MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, file_not_found_response); #ifdef MHD_HAVE_LIBMAGIC /* read beginning of the file to determine mime type */ got = read (fd, file_data, sizeof (file_data)); (void) lseek (fd, 0, SEEK_SET); if (0 < got) mime = magic_buffer (magic, file_data, (size_t) got); else #endif /* MHD_HAVE_LIBMAGIC */ mime = NULL; if (NULL == (response = MHD_create_response_from_fd ((size_t) buf.st_size, fd))) { /* internal error (i.e. out of memory) */ (void) close (fd); return MHD_NO; } /* add mime type if we had one */ if (NULL != mime) (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { /* upload! */ struct UploadContext *uc = *req_cls; if (NULL == uc) { if (NULL == (uc = malloc (sizeof (struct UploadContext)))) return MHD_NO; /* out of memory, close connection */ memset (uc, 0, sizeof (struct UploadContext)); uc->fd = -1; uc->connection = connection; uc->pp = MHD_create_post_processor (connection, 64 * 1024 /* buffer size */, &process_upload_data, uc); if (NULL == uc->pp) { /* out of memory, close connection */ free (uc); return MHD_NO; } *req_cls = uc; return MHD_YES; } if (0 != *upload_data_size) { if (NULL == uc->response) (void) MHD_post_process (uc->pp, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } /* end of upload, finish it! */ MHD_destroy_post_processor (uc->pp); uc->pp = NULL; if (-1 != uc->fd) { close (uc->fd); uc->fd = -1; } if (NULL != uc->response) { return MHD_queue_response (connection, MHD_HTTP_FORBIDDEN, uc->response); } else { update_directory (); return return_directory_response (connection); } } if (0 == strcmp (method, MHD_HTTP_METHOD_GET)) { return return_directory_response (connection); } /* unexpected request, refuse */ return MHD_queue_response (connection, MHD_HTTP_FORBIDDEN, request_refused_response); } #ifndef MINGW /** * Function called if we get a SIGPIPE. Does nothing. * * @param sig will be SIGPIPE (ignored) */ static void catcher (int sig) { (void) sig; /* Unused. Silent compiler warning. */ /* do nothing */ } /** * setup handlers to ignore SIGPIPE. */ static void ignore_sigpipe (void) { struct sigaction oldsig; struct sigaction sig; sig.sa_handler = &catcher; sigemptyset (&sig.sa_mask); #ifdef SA_INTERRUPT sig.sa_flags = SA_INTERRUPT; /* SunOS */ #else sig.sa_flags = SA_RESTART; #endif if (0 != sigaction (SIGPIPE, &sig, &oldsig)) fprintf (stderr, "Failed to install SIGPIPE handler: %s\n", strerror (errno)); } #endif /* test server key */ static const char srv_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n\ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\ rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\ UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\ +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\ HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\ CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\ dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\ +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\ XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\ znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\ pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\ D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\ pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\ zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\ pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\ KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\ OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\ XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\ wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\ ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\ 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\ ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\ QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\ qdJNJ1DkyUc9dN2cliX4R+rG\n\ -----END PRIVATE KEY-----"; /* test server CA signed certificates */ static const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\ NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\ TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\ c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\ psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\ atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\ 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\ n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\ qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\ kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\ AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\ c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\ 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\ IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\ Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\ X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\ aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\ HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\ hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\ 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\ UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\ B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\ SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\ WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\ OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\ /w0gW9EVWzFhsFeGEssi\n\ -----END CERTIFICATE-----"; /** * Entry point to demo. Note: this HTTP server will make all * files in the current directory and its subdirectories available * to anyone. Press ENTER to stop the server once it has started. * * @param argc number of arguments in argv * @param argv first and only argument should be the port number * @return 0 on success */ int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (UINT16_MAX < port) ) { fprintf (stderr, "%s PORT\n", argv[0]); return 1; } #ifndef MINGW ignore_sigpipe (); #endif #ifdef MHD_HAVE_LIBMAGIC magic = magic_open (MAGIC_MIME_TYPE); (void) magic_load (magic, NULL); #endif /* MHD_HAVE_LIBMAGIC */ (void) pthread_mutex_init (&mutex, NULL); file_not_found_response = MHD_create_response_from_buffer_static (strlen (FILE_NOT_FOUND_PAGE), (const void *) FILE_NOT_FOUND_PAGE); mark_as_html (file_not_found_response); request_refused_response = MHD_create_response_from_buffer_static (strlen (REQUEST_REFUSED_PAGE), (const void *) REQUEST_REFUSED_PAGE); mark_as_html (request_refused_response); internal_error_response = MHD_create_response_from_buffer_static (strlen (INTERNAL_ERROR_PAGE), (const void *) INTERNAL_ERROR_PAGE); mark_as_html (internal_error_response); update_directory (); d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_TLS, (uint16_t) port, NULL, NULL, &generate_page, NULL, MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (256 * 1024), #ifdef PRODUCTION MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) (64), #endif MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) (120 /* seconds */) , MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS, MHD_OPTION_NOTIFY_COMPLETED, &response_completed_callback, NULL, /* Optionally, the gnutls_load_file() can be used to load the key and the certificate from file. */ MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (NULL == d) return 1; fprintf (stderr, "HTTP server running. Press ENTER to stop the server.\n"); (void) getc (stdin); MHD_stop_daemon (d); MHD_destroy_response (file_not_found_response); MHD_destroy_response (request_refused_response); MHD_destroy_response (internal_error_response); update_cached_response (NULL); (void) pthread_mutex_destroy (&mutex); #ifdef MHD_HAVE_LIBMAGIC magic_close (magic); #endif /* MHD_HAVE_LIBMAGIC */ return 0; } /* end of demo_https.c */ libmicrohttpd-1.0.10/src/examples/Makefile.in0000664000175000017500000024504315235436270014611 # Makefile.in generated by automake 1.17 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2024 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) am__rm_f = rm -f $(am__rm_f_notfound) am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = --coverage noinst_PROGRAMS = benchmark$(EXEEXT) benchmark_https$(EXEEXT) \ chunked_example$(EXEEXT) minimal_example$(EXEEXT) \ minimal_example_empty$(EXEEXT) dual_stack_example$(EXEEXT) \ minimal_example_comet$(EXEEXT) querystring_example$(EXEEXT) \ timeout$(EXEEXT) fileserver_example$(EXEEXT) \ fileserver_example_dirs$(EXEEXT) \ fileserver_example_external_select$(EXEEXT) \ refuse_post_example$(EXEEXT) $(am__EXEEXT_1) $(am__EXEEXT_2) \ $(am__EXEEXT_3) $(am__EXEEXT_4) $(am__EXEEXT_5) \ $(am__EXEEXT_6) $(am__EXEEXT_7) $(am__EXEEXT_8) \ $(am__EXEEXT_9) $(am__EXEEXT_10) @MHD_HAVE_EPOLL_TRUE@am__append_2 = \ @MHD_HAVE_EPOLL_TRUE@ suspend_resume_epoll @HAVE_FORK_WAITPID_TRUE@@MHD_HAVE_EPOLL_TRUE@@RUN_LIBCURL_TESTS_TRUE@check_PROGRAMS = test_suspend_resume_epoll$(EXEEXT) @HAVE_JANSSON_TRUE@am__append_3 = \ @HAVE_JANSSON_TRUE@ json_echo @ENABLE_HTTPS_TRUE@am__append_4 = \ @ENABLE_HTTPS_TRUE@ https_fileserver_example \ @ENABLE_HTTPS_TRUE@ minimal_example_empty_tls @HAVE_POSTPROCESSOR_TRUE@am__append_5 = \ @HAVE_POSTPROCESSOR_TRUE@ post_example @HAVE_POSIX_THREADS_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__append_6 = demo @ENABLE_HTTPS_TRUE@@HAVE_POSIX_THREADS_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__append_7 = demo_https @ENABLE_DAUTH_TRUE@am__append_8 = \ @ENABLE_DAUTH_TRUE@ digest_auth_example \ @ENABLE_DAUTH_TRUE@ digest_auth_example_adv @ENABLE_BAUTH_TRUE@am__append_9 = \ @ENABLE_BAUTH_TRUE@ authorization_example @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@am__append_10 = \ @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@ upgrade_example @HAVE_ZLIB_TRUE@am__append_11 = \ @HAVE_ZLIB_TRUE@ http_compression \ @HAVE_ZLIB_TRUE@ http_chunked_compression @HAVE_W32_TRUE@am__append_12 = -DWINDOWS @MHD_HAVE_LIBMAGIC_TRUE@am__append_13 = -lmagic @MHD_HAVE_LIBMAGIC_TRUE@am__append_14 = -lmagic @HAVE_ZLIB_TRUE@am__append_15 = -lz @HAVE_ZLIB_TRUE@am__append_16 = -lz subdir = src/examples ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @MHD_HAVE_EPOLL_TRUE@am__EXEEXT_1 = suspend_resume_epoll$(EXEEXT) @HAVE_JANSSON_TRUE@am__EXEEXT_2 = json_echo$(EXEEXT) @ENABLE_HTTPS_TRUE@am__EXEEXT_3 = https_fileserver_example$(EXEEXT) \ @ENABLE_HTTPS_TRUE@ minimal_example_empty_tls$(EXEEXT) @HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_4 = post_example$(EXEEXT) @HAVE_POSIX_THREADS_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_5 = demo$(EXEEXT) @ENABLE_HTTPS_TRUE@@HAVE_POSIX_THREADS_TRUE@@HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_6 = demo_https$(EXEEXT) @ENABLE_DAUTH_TRUE@am__EXEEXT_7 = digest_auth_example$(EXEEXT) \ @ENABLE_DAUTH_TRUE@ digest_auth_example_adv$(EXEEXT) @ENABLE_BAUTH_TRUE@am__EXEEXT_8 = authorization_example$(EXEEXT) @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@am__EXEEXT_9 = upgrade_example$(EXEEXT) @HAVE_ZLIB_TRUE@am__EXEEXT_10 = http_compression$(EXEEXT) \ @HAVE_ZLIB_TRUE@ http_chunked_compression$(EXEEXT) PROGRAMS = $(noinst_PROGRAMS) am_authorization_example_OBJECTS = authorization_example.$(OBJEXT) authorization_example_OBJECTS = $(am_authorization_example_OBJECTS) authorization_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am_benchmark_OBJECTS = benchmark-benchmark.$(OBJEXT) benchmark_OBJECTS = $(am_benchmark_OBJECTS) benchmark_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_benchmark_https_OBJECTS = \ benchmark_https-benchmark_https.$(OBJEXT) benchmark_https_OBJECTS = $(am_benchmark_https_OBJECTS) benchmark_https_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_chunked_example_OBJECTS = chunked_example.$(OBJEXT) chunked_example_OBJECTS = $(am_chunked_example_OBJECTS) chunked_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_demo_OBJECTS = demo-demo.$(OBJEXT) demo_OBJECTS = $(am_demo_OBJECTS) am__DEPENDENCIES_1 = demo_DEPENDENCIES = $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) demo_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(demo_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_demo_https_OBJECTS = demo_https-demo_https.$(OBJEXT) demo_https_OBJECTS = $(am_demo_https_OBJECTS) demo_https_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) demo_https_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(demo_https_CFLAGS) \ $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ am_digest_auth_example_OBJECTS = digest_auth_example.$(OBJEXT) digest_auth_example_OBJECTS = $(am_digest_auth_example_OBJECTS) digest_auth_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_digest_auth_example_adv_OBJECTS = \ digest_auth_example_adv.$(OBJEXT) digest_auth_example_adv_OBJECTS = \ $(am_digest_auth_example_adv_OBJECTS) digest_auth_example_adv_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_dual_stack_example_OBJECTS = dual_stack_example.$(OBJEXT) dual_stack_example_OBJECTS = $(am_dual_stack_example_OBJECTS) dual_stack_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_fileserver_example_OBJECTS = fileserver_example.$(OBJEXT) fileserver_example_OBJECTS = $(am_fileserver_example_OBJECTS) fileserver_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_fileserver_example_dirs_OBJECTS = \ fileserver_example_dirs.$(OBJEXT) fileserver_example_dirs_OBJECTS = \ $(am_fileserver_example_dirs_OBJECTS) fileserver_example_dirs_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_fileserver_example_external_select_OBJECTS = \ fileserver_example_external_select.$(OBJEXT) fileserver_example_external_select_OBJECTS = \ $(am_fileserver_example_external_select_OBJECTS) fileserver_example_external_select_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_http_chunked_compression_OBJECTS = \ http_chunked_compression.$(OBJEXT) http_chunked_compression_OBJECTS = \ $(am_http_chunked_compression_OBJECTS) http_chunked_compression_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) am_http_compression_OBJECTS = http_compression.$(OBJEXT) http_compression_OBJECTS = $(am_http_compression_OBJECTS) http_compression_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) am_https_fileserver_example_OBJECTS = \ https_fileserver_example-https_fileserver_example.$(OBJEXT) https_fileserver_example_OBJECTS = \ $(am_https_fileserver_example_OBJECTS) https_fileserver_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_json_echo_OBJECTS = json_echo.$(OBJEXT) json_echo_OBJECTS = $(am_json_echo_OBJECTS) json_echo_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_minimal_example_OBJECTS = minimal_example.$(OBJEXT) minimal_example_OBJECTS = $(am_minimal_example_OBJECTS) minimal_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_minimal_example_comet_OBJECTS = minimal_example_comet.$(OBJEXT) minimal_example_comet_OBJECTS = $(am_minimal_example_comet_OBJECTS) minimal_example_comet_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_minimal_example_empty_OBJECTS = minimal_example_empty.$(OBJEXT) minimal_example_empty_OBJECTS = $(am_minimal_example_empty_OBJECTS) minimal_example_empty_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_minimal_example_empty_tls_OBJECTS = \ minimal_example_empty_tls.$(OBJEXT) minimal_example_empty_tls_OBJECTS = \ $(am_minimal_example_empty_tls_OBJECTS) minimal_example_empty_tls_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_post_example_OBJECTS = post_example.$(OBJEXT) post_example_OBJECTS = $(am_post_example_OBJECTS) post_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_querystring_example_OBJECTS = querystring_example.$(OBJEXT) querystring_example_OBJECTS = $(am_querystring_example_OBJECTS) querystring_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_refuse_post_example_OBJECTS = refuse_post_example.$(OBJEXT) refuse_post_example_OBJECTS = $(am_refuse_post_example_OBJECTS) refuse_post_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_suspend_resume_epoll_OBJECTS = \ suspend_resume_epoll-suspend_resume_epoll.$(OBJEXT) suspend_resume_epoll_OBJECTS = $(am_suspend_resume_epoll_OBJECTS) suspend_resume_epoll_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_suspend_resume_epoll_OBJECTS = \ test_suspend_resume_epoll.$(OBJEXT) test_suspend_resume_epoll_OBJECTS = \ $(am_test_suspend_resume_epoll_OBJECTS) test_suspend_resume_epoll_DEPENDENCIES = am_timeout_OBJECTS = timeout.$(OBJEXT) timeout_OBJECTS = $(am_timeout_OBJECTS) timeout_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_upgrade_example_OBJECTS = \ upgrade_example-upgrade_example.$(OBJEXT) upgrade_example_OBJECTS = $(am_upgrade_example_OBJECTS) upgrade_example_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__DEPENDENCIES_1) upgrade_example_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(upgrade_example_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) \ -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/authorization_example.Po \ ./$(DEPDIR)/benchmark-benchmark.Po \ ./$(DEPDIR)/benchmark_https-benchmark_https.Po \ ./$(DEPDIR)/chunked_example.Po ./$(DEPDIR)/demo-demo.Po \ ./$(DEPDIR)/demo_https-demo_https.Po \ ./$(DEPDIR)/digest_auth_example.Po \ ./$(DEPDIR)/digest_auth_example_adv.Po \ ./$(DEPDIR)/dual_stack_example.Po \ ./$(DEPDIR)/fileserver_example.Po \ ./$(DEPDIR)/fileserver_example_dirs.Po \ ./$(DEPDIR)/fileserver_example_external_select.Po \ ./$(DEPDIR)/http_chunked_compression.Po \ ./$(DEPDIR)/http_compression.Po \ ./$(DEPDIR)/https_fileserver_example-https_fileserver_example.Po \ ./$(DEPDIR)/json_echo.Po ./$(DEPDIR)/minimal_example.Po \ ./$(DEPDIR)/minimal_example_comet.Po \ ./$(DEPDIR)/minimal_example_empty.Po \ ./$(DEPDIR)/minimal_example_empty_tls.Po \ ./$(DEPDIR)/post_example.Po ./$(DEPDIR)/querystring_example.Po \ ./$(DEPDIR)/refuse_post_example.Po \ ./$(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po \ ./$(DEPDIR)/test_suspend_resume_epoll.Po \ ./$(DEPDIR)/timeout.Po \ ./$(DEPDIR)/upgrade_example-upgrade_example.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(authorization_example_SOURCES) $(benchmark_SOURCES) \ $(benchmark_https_SOURCES) $(chunked_example_SOURCES) \ $(demo_SOURCES) $(demo_https_SOURCES) \ $(digest_auth_example_SOURCES) \ $(digest_auth_example_adv_SOURCES) \ $(dual_stack_example_SOURCES) $(fileserver_example_SOURCES) \ $(fileserver_example_dirs_SOURCES) \ $(fileserver_example_external_select_SOURCES) \ $(http_chunked_compression_SOURCES) \ $(http_compression_SOURCES) \ $(https_fileserver_example_SOURCES) $(json_echo_SOURCES) \ $(minimal_example_SOURCES) $(minimal_example_comet_SOURCES) \ $(minimal_example_empty_SOURCES) \ $(minimal_example_empty_tls_SOURCES) $(post_example_SOURCES) \ $(querystring_example_SOURCES) $(refuse_post_example_SOURCES) \ $(suspend_resume_epoll_SOURCES) \ $(test_suspend_resume_epoll_SOURCES) $(timeout_SOURCES) \ $(upgrade_example_SOURCES) DIST_SOURCES = $(authorization_example_SOURCES) $(benchmark_SOURCES) \ $(benchmark_https_SOURCES) $(chunked_example_SOURCES) \ $(demo_SOURCES) $(demo_https_SOURCES) \ $(digest_auth_example_SOURCES) \ $(digest_auth_example_adv_SOURCES) \ $(dual_stack_example_SOURCES) $(fileserver_example_SOURCES) \ $(fileserver_example_dirs_SOURCES) \ $(fileserver_example_external_select_SOURCES) \ $(http_chunked_compression_SOURCES) \ $(http_compression_SOURCES) \ $(https_fileserver_example_SOURCES) $(json_echo_SOURCES) \ $(minimal_example_SOURCES) $(minimal_example_comet_SOURCES) \ $(minimal_example_empty_SOURCES) \ $(minimal_example_empty_tls_SOURCES) $(post_example_SOURCES) \ $(querystring_example_SOURCES) $(refuse_post_example_SOURCES) \ $(suspend_resume_epoll_SOURCES) \ $(test_suspend_resume_epoll_SOURCES) $(timeout_SOURCES) \ $(upgrade_example_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ check recheck distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ $$am__collect_skipped_logs \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(IGNORE_SKIPPED_LOGS)'; then \ am__collect_skipped_logs='--collect-skipped-logs no'; \ else \ am__collect_skipped_logs=''; \ fi; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ am__xargs_n = @am__xargs_n@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ # This Makefile.am is in the public domain SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) \ -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ $(am__append_1) \ $(am__append_12) AM_LDFLAGS = $(LDFLAGS_ac) MHD_CPU_COUNT_DEF = -DMHD_CPU_COUNT=$(CPU_COUNT) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) @HAVE_FORK_WAITPID_TRUE@@MHD_HAVE_EPOLL_TRUE@@RUN_LIBCURL_TESTS_TRUE@TESTS = $(check_PROGRAMS) EXTRA_DIST = msgs_i18n.c noinst_EXTRA_DIST = msgs_i18n.c minimal_example_SOURCES = \ minimal_example.c minimal_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_empty_SOURCES = \ minimal_example_empty.c minimal_example_empty_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_empty_tls_SOURCES = \ minimal_example_empty_tls.c minimal_example_empty_tls_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la upgrade_example_SOURCES = \ upgrade_example.c upgrade_example_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) upgrade_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) timeout_SOURCES = \ timeout.c timeout_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la chunked_example_SOURCES = \ chunked_example.c chunked_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la json_echo_SOURCES = \ json_echo.c json_echo_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ -ljansson demo_SOURCES = \ demo.c demo_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) demo_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) demo_LDADD = $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) $(am__append_13) demo_https_SOURCES = \ demo_https.c demo_https_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) demo_https_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) demo_https_LDADD = $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) $(am__append_14) benchmark_SOURCES = \ benchmark.c benchmark_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) benchmark_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la suspend_resume_epoll_SOURCES = \ suspend_resume_epoll.c suspend_resume_epoll_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) suspend_resume_epoll_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la test_suspend_resume_epoll_SOURCES = \ test_suspend_resume_epoll.c test_suspend_resume_epoll_LDADD = \ @LIBCURL@ benchmark_https_SOURCES = \ benchmark_https.c benchmark_https_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) benchmark_https_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la dual_stack_example_SOURCES = \ dual_stack_example.c dual_stack_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la post_example_SOURCES = \ post_example.c post_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_comet_SOURCES = \ minimal_example_comet.c minimal_example_comet_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la authorization_example_SOURCES = \ authorization_example.c authorization_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la digest_auth_example_SOURCES = \ digest_auth_example.c digest_auth_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la digest_auth_example_adv_SOURCES = \ digest_auth_example_adv.c digest_auth_example_adv_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la refuse_post_example_SOURCES = \ refuse_post_example.c refuse_post_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la querystring_example_SOURCES = \ querystring_example.c querystring_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_SOURCES = \ fileserver_example.c fileserver_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_dirs_SOURCES = \ fileserver_example_dirs.c fileserver_example_dirs_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_external_select_SOURCES = \ fileserver_example_external_select.c fileserver_example_external_select_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la https_fileserver_example_SOURCES = \ https_fileserver_example.c https_fileserver_example_CPPFLAGS = \ $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS) https_fileserver_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la http_compression_SOURCES = \ http_compression.c http_chunked_compression_SOURCES = \ http_chunked_compression.c http_compression_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__append_15) http_chunked_compression_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(am__append_16) all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/examples/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/examples/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: $(am__rm_f) $(check_PROGRAMS) test -z "$(EXEEXT)" || $(am__rm_f) $(check_PROGRAMS:$(EXEEXT)=) clean-noinstPROGRAMS: $(am__rm_f) $(noinst_PROGRAMS) test -z "$(EXEEXT)" || $(am__rm_f) $(noinst_PROGRAMS:$(EXEEXT)=) authorization_example$(EXEEXT): $(authorization_example_OBJECTS) $(authorization_example_DEPENDENCIES) $(EXTRA_authorization_example_DEPENDENCIES) @rm -f authorization_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(authorization_example_OBJECTS) $(authorization_example_LDADD) $(LIBS) benchmark$(EXEEXT): $(benchmark_OBJECTS) $(benchmark_DEPENDENCIES) $(EXTRA_benchmark_DEPENDENCIES) @rm -f benchmark$(EXEEXT) $(AM_V_CCLD)$(LINK) $(benchmark_OBJECTS) $(benchmark_LDADD) $(LIBS) benchmark_https$(EXEEXT): $(benchmark_https_OBJECTS) $(benchmark_https_DEPENDENCIES) $(EXTRA_benchmark_https_DEPENDENCIES) @rm -f benchmark_https$(EXEEXT) $(AM_V_CCLD)$(LINK) $(benchmark_https_OBJECTS) $(benchmark_https_LDADD) $(LIBS) chunked_example$(EXEEXT): $(chunked_example_OBJECTS) $(chunked_example_DEPENDENCIES) $(EXTRA_chunked_example_DEPENDENCIES) @rm -f chunked_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(chunked_example_OBJECTS) $(chunked_example_LDADD) $(LIBS) demo$(EXEEXT): $(demo_OBJECTS) $(demo_DEPENDENCIES) $(EXTRA_demo_DEPENDENCIES) @rm -f demo$(EXEEXT) $(AM_V_CCLD)$(demo_LINK) $(demo_OBJECTS) $(demo_LDADD) $(LIBS) demo_https$(EXEEXT): $(demo_https_OBJECTS) $(demo_https_DEPENDENCIES) $(EXTRA_demo_https_DEPENDENCIES) @rm -f demo_https$(EXEEXT) $(AM_V_CCLD)$(demo_https_LINK) $(demo_https_OBJECTS) $(demo_https_LDADD) $(LIBS) digest_auth_example$(EXEEXT): $(digest_auth_example_OBJECTS) $(digest_auth_example_DEPENDENCIES) $(EXTRA_digest_auth_example_DEPENDENCIES) @rm -f digest_auth_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(digest_auth_example_OBJECTS) $(digest_auth_example_LDADD) $(LIBS) digest_auth_example_adv$(EXEEXT): $(digest_auth_example_adv_OBJECTS) $(digest_auth_example_adv_DEPENDENCIES) $(EXTRA_digest_auth_example_adv_DEPENDENCIES) @rm -f digest_auth_example_adv$(EXEEXT) $(AM_V_CCLD)$(LINK) $(digest_auth_example_adv_OBJECTS) $(digest_auth_example_adv_LDADD) $(LIBS) dual_stack_example$(EXEEXT): $(dual_stack_example_OBJECTS) $(dual_stack_example_DEPENDENCIES) $(EXTRA_dual_stack_example_DEPENDENCIES) @rm -f dual_stack_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(dual_stack_example_OBJECTS) $(dual_stack_example_LDADD) $(LIBS) fileserver_example$(EXEEXT): $(fileserver_example_OBJECTS) $(fileserver_example_DEPENDENCIES) $(EXTRA_fileserver_example_DEPENDENCIES) @rm -f fileserver_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(fileserver_example_OBJECTS) $(fileserver_example_LDADD) $(LIBS) fileserver_example_dirs$(EXEEXT): $(fileserver_example_dirs_OBJECTS) $(fileserver_example_dirs_DEPENDENCIES) $(EXTRA_fileserver_example_dirs_DEPENDENCIES) @rm -f fileserver_example_dirs$(EXEEXT) $(AM_V_CCLD)$(LINK) $(fileserver_example_dirs_OBJECTS) $(fileserver_example_dirs_LDADD) $(LIBS) fileserver_example_external_select$(EXEEXT): $(fileserver_example_external_select_OBJECTS) $(fileserver_example_external_select_DEPENDENCIES) $(EXTRA_fileserver_example_external_select_DEPENDENCIES) @rm -f fileserver_example_external_select$(EXEEXT) $(AM_V_CCLD)$(LINK) $(fileserver_example_external_select_OBJECTS) $(fileserver_example_external_select_LDADD) $(LIBS) http_chunked_compression$(EXEEXT): $(http_chunked_compression_OBJECTS) $(http_chunked_compression_DEPENDENCIES) $(EXTRA_http_chunked_compression_DEPENDENCIES) @rm -f http_chunked_compression$(EXEEXT) $(AM_V_CCLD)$(LINK) $(http_chunked_compression_OBJECTS) $(http_chunked_compression_LDADD) $(LIBS) http_compression$(EXEEXT): $(http_compression_OBJECTS) $(http_compression_DEPENDENCIES) $(EXTRA_http_compression_DEPENDENCIES) @rm -f http_compression$(EXEEXT) $(AM_V_CCLD)$(LINK) $(http_compression_OBJECTS) $(http_compression_LDADD) $(LIBS) https_fileserver_example$(EXEEXT): $(https_fileserver_example_OBJECTS) $(https_fileserver_example_DEPENDENCIES) $(EXTRA_https_fileserver_example_DEPENDENCIES) @rm -f https_fileserver_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(https_fileserver_example_OBJECTS) $(https_fileserver_example_LDADD) $(LIBS) json_echo$(EXEEXT): $(json_echo_OBJECTS) $(json_echo_DEPENDENCIES) $(EXTRA_json_echo_DEPENDENCIES) @rm -f json_echo$(EXEEXT) $(AM_V_CCLD)$(LINK) $(json_echo_OBJECTS) $(json_echo_LDADD) $(LIBS) minimal_example$(EXEEXT): $(minimal_example_OBJECTS) $(minimal_example_DEPENDENCIES) $(EXTRA_minimal_example_DEPENDENCIES) @rm -f minimal_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(minimal_example_OBJECTS) $(minimal_example_LDADD) $(LIBS) minimal_example_comet$(EXEEXT): $(minimal_example_comet_OBJECTS) $(minimal_example_comet_DEPENDENCIES) $(EXTRA_minimal_example_comet_DEPENDENCIES) @rm -f minimal_example_comet$(EXEEXT) $(AM_V_CCLD)$(LINK) $(minimal_example_comet_OBJECTS) $(minimal_example_comet_LDADD) $(LIBS) minimal_example_empty$(EXEEXT): $(minimal_example_empty_OBJECTS) $(minimal_example_empty_DEPENDENCIES) $(EXTRA_minimal_example_empty_DEPENDENCIES) @rm -f minimal_example_empty$(EXEEXT) $(AM_V_CCLD)$(LINK) $(minimal_example_empty_OBJECTS) $(minimal_example_empty_LDADD) $(LIBS) minimal_example_empty_tls$(EXEEXT): $(minimal_example_empty_tls_OBJECTS) $(minimal_example_empty_tls_DEPENDENCIES) $(EXTRA_minimal_example_empty_tls_DEPENDENCIES) @rm -f minimal_example_empty_tls$(EXEEXT) $(AM_V_CCLD)$(LINK) $(minimal_example_empty_tls_OBJECTS) $(minimal_example_empty_tls_LDADD) $(LIBS) post_example$(EXEEXT): $(post_example_OBJECTS) $(post_example_DEPENDENCIES) $(EXTRA_post_example_DEPENDENCIES) @rm -f post_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(post_example_OBJECTS) $(post_example_LDADD) $(LIBS) querystring_example$(EXEEXT): $(querystring_example_OBJECTS) $(querystring_example_DEPENDENCIES) $(EXTRA_querystring_example_DEPENDENCIES) @rm -f querystring_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(querystring_example_OBJECTS) $(querystring_example_LDADD) $(LIBS) refuse_post_example$(EXEEXT): $(refuse_post_example_OBJECTS) $(refuse_post_example_DEPENDENCIES) $(EXTRA_refuse_post_example_DEPENDENCIES) @rm -f refuse_post_example$(EXEEXT) $(AM_V_CCLD)$(LINK) $(refuse_post_example_OBJECTS) $(refuse_post_example_LDADD) $(LIBS) suspend_resume_epoll$(EXEEXT): $(suspend_resume_epoll_OBJECTS) $(suspend_resume_epoll_DEPENDENCIES) $(EXTRA_suspend_resume_epoll_DEPENDENCIES) @rm -f suspend_resume_epoll$(EXEEXT) $(AM_V_CCLD)$(LINK) $(suspend_resume_epoll_OBJECTS) $(suspend_resume_epoll_LDADD) $(LIBS) test_suspend_resume_epoll$(EXEEXT): $(test_suspend_resume_epoll_OBJECTS) $(test_suspend_resume_epoll_DEPENDENCIES) $(EXTRA_test_suspend_resume_epoll_DEPENDENCIES) @rm -f test_suspend_resume_epoll$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_suspend_resume_epoll_OBJECTS) $(test_suspend_resume_epoll_LDADD) $(LIBS) timeout$(EXEEXT): $(timeout_OBJECTS) $(timeout_DEPENDENCIES) $(EXTRA_timeout_DEPENDENCIES) @rm -f timeout$(EXEEXT) $(AM_V_CCLD)$(LINK) $(timeout_OBJECTS) $(timeout_LDADD) $(LIBS) upgrade_example$(EXEEXT): $(upgrade_example_OBJECTS) $(upgrade_example_DEPENDENCIES) $(EXTRA_upgrade_example_DEPENDENCIES) @rm -f upgrade_example$(EXEEXT) $(AM_V_CCLD)$(upgrade_example_LINK) $(upgrade_example_OBJECTS) $(upgrade_example_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/authorization_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/benchmark-benchmark.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/benchmark_https-benchmark_https.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/chunked_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo-demo.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/demo_https-demo_https.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/digest_auth_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/digest_auth_example_adv.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dual_stack_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileserver_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileserver_example_dirs.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fileserver_example_external_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/http_chunked_compression.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/http_compression.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/https_fileserver_example-https_fileserver_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/json_echo.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minimal_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minimal_example_comet.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minimal_example_empty.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/minimal_example_empty_tls.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/post_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/querystring_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/refuse_post_example.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_suspend_resume_epoll.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/timeout.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/upgrade_example-upgrade_example.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @: >>$@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< benchmark-benchmark.o: benchmark.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark-benchmark.o -MD -MP -MF $(DEPDIR)/benchmark-benchmark.Tpo -c -o benchmark-benchmark.o `test -f 'benchmark.c' || echo '$(srcdir)/'`benchmark.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/benchmark-benchmark.Tpo $(DEPDIR)/benchmark-benchmark.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='benchmark.c' object='benchmark-benchmark.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark-benchmark.o `test -f 'benchmark.c' || echo '$(srcdir)/'`benchmark.c benchmark-benchmark.obj: benchmark.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark-benchmark.obj -MD -MP -MF $(DEPDIR)/benchmark-benchmark.Tpo -c -o benchmark-benchmark.obj `if test -f 'benchmark.c'; then $(CYGPATH_W) 'benchmark.c'; else $(CYGPATH_W) '$(srcdir)/benchmark.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/benchmark-benchmark.Tpo $(DEPDIR)/benchmark-benchmark.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='benchmark.c' object='benchmark-benchmark.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark-benchmark.obj `if test -f 'benchmark.c'; then $(CYGPATH_W) 'benchmark.c'; else $(CYGPATH_W) '$(srcdir)/benchmark.c'; fi` benchmark_https-benchmark_https.o: benchmark_https.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark_https-benchmark_https.o -MD -MP -MF $(DEPDIR)/benchmark_https-benchmark_https.Tpo -c -o benchmark_https-benchmark_https.o `test -f 'benchmark_https.c' || echo '$(srcdir)/'`benchmark_https.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/benchmark_https-benchmark_https.Tpo $(DEPDIR)/benchmark_https-benchmark_https.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='benchmark_https.c' object='benchmark_https-benchmark_https.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark_https-benchmark_https.o `test -f 'benchmark_https.c' || echo '$(srcdir)/'`benchmark_https.c benchmark_https-benchmark_https.obj: benchmark_https.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT benchmark_https-benchmark_https.obj -MD -MP -MF $(DEPDIR)/benchmark_https-benchmark_https.Tpo -c -o benchmark_https-benchmark_https.obj `if test -f 'benchmark_https.c'; then $(CYGPATH_W) 'benchmark_https.c'; else $(CYGPATH_W) '$(srcdir)/benchmark_https.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/benchmark_https-benchmark_https.Tpo $(DEPDIR)/benchmark_https-benchmark_https.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='benchmark_https.c' object='benchmark_https-benchmark_https.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(benchmark_https_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o benchmark_https-benchmark_https.obj `if test -f 'benchmark_https.c'; then $(CYGPATH_W) 'benchmark_https.c'; else $(CYGPATH_W) '$(srcdir)/benchmark_https.c'; fi` demo-demo.o: demo.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -MT demo-demo.o -MD -MP -MF $(DEPDIR)/demo-demo.Tpo -c -o demo-demo.o `test -f 'demo.c' || echo '$(srcdir)/'`demo.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/demo-demo.Tpo $(DEPDIR)/demo-demo.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='demo.c' object='demo-demo.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -c -o demo-demo.o `test -f 'demo.c' || echo '$(srcdir)/'`demo.c demo-demo.obj: demo.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -MT demo-demo.obj -MD -MP -MF $(DEPDIR)/demo-demo.Tpo -c -o demo-demo.obj `if test -f 'demo.c'; then $(CYGPATH_W) 'demo.c'; else $(CYGPATH_W) '$(srcdir)/demo.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/demo-demo.Tpo $(DEPDIR)/demo-demo.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='demo.c' object='demo-demo.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_CPPFLAGS) $(CPPFLAGS) $(demo_CFLAGS) $(CFLAGS) -c -o demo-demo.obj `if test -f 'demo.c'; then $(CYGPATH_W) 'demo.c'; else $(CYGPATH_W) '$(srcdir)/demo.c'; fi` demo_https-demo_https.o: demo_https.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -MT demo_https-demo_https.o -MD -MP -MF $(DEPDIR)/demo_https-demo_https.Tpo -c -o demo_https-demo_https.o `test -f 'demo_https.c' || echo '$(srcdir)/'`demo_https.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/demo_https-demo_https.Tpo $(DEPDIR)/demo_https-demo_https.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='demo_https.c' object='demo_https-demo_https.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -c -o demo_https-demo_https.o `test -f 'demo_https.c' || echo '$(srcdir)/'`demo_https.c demo_https-demo_https.obj: demo_https.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -MT demo_https-demo_https.obj -MD -MP -MF $(DEPDIR)/demo_https-demo_https.Tpo -c -o demo_https-demo_https.obj `if test -f 'demo_https.c'; then $(CYGPATH_W) 'demo_https.c'; else $(CYGPATH_W) '$(srcdir)/demo_https.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/demo_https-demo_https.Tpo $(DEPDIR)/demo_https-demo_https.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='demo_https.c' object='demo_https-demo_https.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(demo_https_CPPFLAGS) $(CPPFLAGS) $(demo_https_CFLAGS) $(CFLAGS) -c -o demo_https-demo_https.obj `if test -f 'demo_https.c'; then $(CYGPATH_W) 'demo_https.c'; else $(CYGPATH_W) '$(srcdir)/demo_https.c'; fi` https_fileserver_example-https_fileserver_example.o: https_fileserver_example.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT https_fileserver_example-https_fileserver_example.o -MD -MP -MF $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo -c -o https_fileserver_example-https_fileserver_example.o `test -f 'https_fileserver_example.c' || echo '$(srcdir)/'`https_fileserver_example.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo $(DEPDIR)/https_fileserver_example-https_fileserver_example.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='https_fileserver_example.c' object='https_fileserver_example-https_fileserver_example.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o https_fileserver_example-https_fileserver_example.o `test -f 'https_fileserver_example.c' || echo '$(srcdir)/'`https_fileserver_example.c https_fileserver_example-https_fileserver_example.obj: https_fileserver_example.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT https_fileserver_example-https_fileserver_example.obj -MD -MP -MF $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo -c -o https_fileserver_example-https_fileserver_example.obj `if test -f 'https_fileserver_example.c'; then $(CYGPATH_W) 'https_fileserver_example.c'; else $(CYGPATH_W) '$(srcdir)/https_fileserver_example.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/https_fileserver_example-https_fileserver_example.Tpo $(DEPDIR)/https_fileserver_example-https_fileserver_example.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='https_fileserver_example.c' object='https_fileserver_example-https_fileserver_example.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(https_fileserver_example_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o https_fileserver_example-https_fileserver_example.obj `if test -f 'https_fileserver_example.c'; then $(CYGPATH_W) 'https_fileserver_example.c'; else $(CYGPATH_W) '$(srcdir)/https_fileserver_example.c'; fi` suspend_resume_epoll-suspend_resume_epoll.o: suspend_resume_epoll.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(suspend_resume_epoll_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT suspend_resume_epoll-suspend_resume_epoll.o -MD -MP -MF $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Tpo -c -o suspend_resume_epoll-suspend_resume_epoll.o `test -f 'suspend_resume_epoll.c' || echo '$(srcdir)/'`suspend_resume_epoll.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Tpo $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='suspend_resume_epoll.c' object='suspend_resume_epoll-suspend_resume_epoll.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(suspend_resume_epoll_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o suspend_resume_epoll-suspend_resume_epoll.o `test -f 'suspend_resume_epoll.c' || echo '$(srcdir)/'`suspend_resume_epoll.c suspend_resume_epoll-suspend_resume_epoll.obj: suspend_resume_epoll.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(suspend_resume_epoll_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT suspend_resume_epoll-suspend_resume_epoll.obj -MD -MP -MF $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Tpo -c -o suspend_resume_epoll-suspend_resume_epoll.obj `if test -f 'suspend_resume_epoll.c'; then $(CYGPATH_W) 'suspend_resume_epoll.c'; else $(CYGPATH_W) '$(srcdir)/suspend_resume_epoll.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Tpo $(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='suspend_resume_epoll.c' object='suspend_resume_epoll-suspend_resume_epoll.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(suspend_resume_epoll_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o suspend_resume_epoll-suspend_resume_epoll.obj `if test -f 'suspend_resume_epoll.c'; then $(CYGPATH_W) 'suspend_resume_epoll.c'; else $(CYGPATH_W) '$(srcdir)/suspend_resume_epoll.c'; fi` upgrade_example-upgrade_example.o: upgrade_example.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(upgrade_example_CFLAGS) $(CFLAGS) -MT upgrade_example-upgrade_example.o -MD -MP -MF $(DEPDIR)/upgrade_example-upgrade_example.Tpo -c -o upgrade_example-upgrade_example.o `test -f 'upgrade_example.c' || echo '$(srcdir)/'`upgrade_example.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/upgrade_example-upgrade_example.Tpo $(DEPDIR)/upgrade_example-upgrade_example.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='upgrade_example.c' object='upgrade_example-upgrade_example.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(upgrade_example_CFLAGS) $(CFLAGS) -c -o upgrade_example-upgrade_example.o `test -f 'upgrade_example.c' || echo '$(srcdir)/'`upgrade_example.c upgrade_example-upgrade_example.obj: upgrade_example.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(upgrade_example_CFLAGS) $(CFLAGS) -MT upgrade_example-upgrade_example.obj -MD -MP -MF $(DEPDIR)/upgrade_example-upgrade_example.Tpo -c -o upgrade_example-upgrade_example.obj `if test -f 'upgrade_example.c'; then $(CYGPATH_W) 'upgrade_example.c'; else $(CYGPATH_W) '$(srcdir)/upgrade_example.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/upgrade_example-upgrade_example.Tpo $(DEPDIR)/upgrade_example-upgrade_example.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='upgrade_example.c' object='upgrade_example-upgrade_example.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(upgrade_example_CFLAGS) $(CFLAGS) -c -o upgrade_example-upgrade_example.obj `if test -f 'upgrade_example.c'; then $(CYGPATH_W) 'upgrade_example.c'; else $(CYGPATH_W) '$(srcdir)/upgrade_example.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ output_system_information () \ { \ echo; \ { uname -a | $(AWK) '{ \ printf "System information (uname -a):"; \ for (i = 1; i < NF; ++i) \ { \ if (i != 2) \ printf " %s", $$i; \ } \ printf "\n"; \ }'; } 2>&1; \ if test -r /etc/os-release; then \ echo "Distribution information (/etc/os-release):"; \ sed 8q /etc/os-release; \ elif test -r /etc/issue; then \ echo "Distribution information (/etc/issue):"; \ cat /etc/issue; \ fi; \ }; \ please_report () \ { \ echo "Some test(s) failed. Please report this to $(PACKAGE_BUGREPORT),"; \ echo "together with the test-suite.log file (gzipped) and your system"; \ echo "information. Thanks."; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ output_system_information; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG) for debugging.$${std}";\ if test -n "$(PACKAGE_BUGREPORT)"; then \ please_report | sed -e "s/^/$${col}/" -e s/'$$'/"$${std}"/; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) @$(am__rm_f) $(RECHECK_LOGS) @$(am__rm_f) $(RECHECK_LOGS:.log=.trs) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_suspend_resume_epoll.log: test_suspend_resume_epoll$(EXEEXT) @p='test_suspend_resume_epoll$(EXEEXT)'; \ b='test_suspend_resume_epoll'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-recursive all-am: Makefile $(PROGRAMS) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -$(am__rm_f) $(TEST_LOGS) -$(am__rm_f) $(TEST_LOGS:.log=.trs) -$(am__rm_f) $(TEST_SUITE_LOG) clean-generic: distclean-generic: -$(am__rm_f) $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ clean-noinstPROGRAMS mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/authorization_example.Po -rm -f ./$(DEPDIR)/benchmark-benchmark.Po -rm -f ./$(DEPDIR)/benchmark_https-benchmark_https.Po -rm -f ./$(DEPDIR)/chunked_example.Po -rm -f ./$(DEPDIR)/demo-demo.Po -rm -f ./$(DEPDIR)/demo_https-demo_https.Po -rm -f ./$(DEPDIR)/digest_auth_example.Po -rm -f ./$(DEPDIR)/digest_auth_example_adv.Po -rm -f ./$(DEPDIR)/dual_stack_example.Po -rm -f ./$(DEPDIR)/fileserver_example.Po -rm -f ./$(DEPDIR)/fileserver_example_dirs.Po -rm -f ./$(DEPDIR)/fileserver_example_external_select.Po -rm -f ./$(DEPDIR)/http_chunked_compression.Po -rm -f ./$(DEPDIR)/http_compression.Po -rm -f ./$(DEPDIR)/https_fileserver_example-https_fileserver_example.Po -rm -f ./$(DEPDIR)/json_echo.Po -rm -f ./$(DEPDIR)/minimal_example.Po -rm -f ./$(DEPDIR)/minimal_example_comet.Po -rm -f ./$(DEPDIR)/minimal_example_empty.Po -rm -f ./$(DEPDIR)/minimal_example_empty_tls.Po -rm -f ./$(DEPDIR)/post_example.Po -rm -f ./$(DEPDIR)/querystring_example.Po -rm -f ./$(DEPDIR)/refuse_post_example.Po -rm -f ./$(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po -rm -f ./$(DEPDIR)/test_suspend_resume_epoll.Po -rm -f ./$(DEPDIR)/timeout.Po -rm -f ./$(DEPDIR)/upgrade_example-upgrade_example.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/authorization_example.Po -rm -f ./$(DEPDIR)/benchmark-benchmark.Po -rm -f ./$(DEPDIR)/benchmark_https-benchmark_https.Po -rm -f ./$(DEPDIR)/chunked_example.Po -rm -f ./$(DEPDIR)/demo-demo.Po -rm -f ./$(DEPDIR)/demo_https-demo_https.Po -rm -f ./$(DEPDIR)/digest_auth_example.Po -rm -f ./$(DEPDIR)/digest_auth_example_adv.Po -rm -f ./$(DEPDIR)/dual_stack_example.Po -rm -f ./$(DEPDIR)/fileserver_example.Po -rm -f ./$(DEPDIR)/fileserver_example_dirs.Po -rm -f ./$(DEPDIR)/fileserver_example_external_select.Po -rm -f ./$(DEPDIR)/http_chunked_compression.Po -rm -f ./$(DEPDIR)/http_compression.Po -rm -f ./$(DEPDIR)/https_fileserver_example-https_fileserver_example.Po -rm -f ./$(DEPDIR)/json_echo.Po -rm -f ./$(DEPDIR)/minimal_example.Po -rm -f ./$(DEPDIR)/minimal_example_comet.Po -rm -f ./$(DEPDIR)/minimal_example_empty.Po -rm -f ./$(DEPDIR)/minimal_example_empty_tls.Po -rm -f ./$(DEPDIR)/post_example.Po -rm -f ./$(DEPDIR)/querystring_example.Po -rm -f ./$(DEPDIR)/refuse_post_example.Po -rm -f ./$(DEPDIR)/suspend_resume_epoll-suspend_resume_epoll.Po -rm -f ./$(DEPDIR)/test_suspend_resume_epoll.Po -rm -f ./$(DEPDIR)/timeout.Po -rm -f ./$(DEPDIR)/upgrade_example-upgrade_example.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) check-am install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool \ clean-noinstPROGRAMS cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am recheck tags tags-am \ uninstall uninstall-am .PRECIOUS: Makefile $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: # Tell GNU make to disable its built-in pattern rules. %:: %,v %:: RCS/%,v %:: RCS/% %:: s.% %:: SCCS/s.% libmicrohttpd-1.0.10/src/examples/minimal_example.c0000644000175000017500000000712414760713574016052 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file minimal_example.c * @brief minimal example for how to use libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #define PAGE \ "libmicrohttpd demo" \ "libmicrohttpd demo" struct handler_param { const char *response_page; }; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct handler_param *param = (struct handler_param *) cls; struct MHD_Response *response; enum MHD_Result ret; (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_buffer_static (strlen (param->response_page), param->response_page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct handler_param data_for_handler; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } data_for_handler.response_page = PAGE; d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ (uint16_t) port, NULL, NULL, &ahc_echo, &data_for_handler, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/dual_stack_example.c0000644000175000017500000000640714760713574016541 /* This file is part of libmicrohttpd Copyright (C) 2007, 2012 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file dual_stack_example.c * @brief how to use MHD with both IPv4 and IPv6 support (dual-stack) * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #define PAGE \ "libmicrohttpd demolibmicrohttpd demo" struct handler_param { const char *response_page; }; static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct handler_param *param = (struct handler_param *) cls; struct MHD_Response *response; enum MHD_Result ret; (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_from_buffer_static (strlen (param->response_page), param->response_page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct handler_param data_for_handler; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } data_for_handler.response_page = PAGE; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_DUAL_STACK, (uint16_t) port, NULL, NULL, &ahc_echo, &data_for_handler, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_END); (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/timeout.c0000644000175000017500000000636414760713574014404 /* This file is part of libmicrohttpd Copyright (C) 2016-2017 Christian Grothoff, Silvio Clecio (silvioprog), Evgeny Grin (Karlson2k) Copyright (C) 2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file timeout.c * @brief example for how to use libmicrohttpd request timeout * @author Christian Grothoff, Silvio Clecio (silvioprog), Karlson2k (Evgeny Grin) */ #include #include #include #define PORT 8080 static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { const char *page = "Hello timeout!"; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) method; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ response = MHD_create_response_from_buffer_static (strlen (page), (const void *) page); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html")) { fprintf (stderr, "Failed to set content type header!\n"); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, /* 3 seconds */ MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 3, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; } libmicrohttpd-1.0.10/src/examples/minimal_example_empty_tls.c0000644000175000017500000001655114760713574020156 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff (and other contributing authors) Copyright (C) 2021-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file minimal_example_empty_tls.c * @brief minimal example for how to use libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ response = MHD_create_response_empty (MHD_RF_NONE); ret = MHD_queue_response (connection, MHD_HTTP_NO_CONTENT, response); MHD_destroy_response (response); return ret; } /* test server key */ static const char srv_signed_key_pem[] = "-----BEGIN PRIVATE KEY-----\n\ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\ rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\ UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\ +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\ HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\ CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\ dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\ +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\ XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\ znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\ pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\ D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\ pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\ zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\ pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\ KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\ OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\ XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\ wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\ ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\ 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\ ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\ QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\ qdJNJ1DkyUc9dN2cliX4R+rG\n\ -----END PRIVATE KEY-----"; /* test server CA signed certificates */ static const char srv_signed_cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\ NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\ TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\ c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\ psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\ atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\ 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\ n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\ qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\ kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\ AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\ c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\ 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\ IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\ Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\ X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\ aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\ HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\ hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\ 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\ UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\ B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\ SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\ WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\ OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\ /w0gW9EVWzFhsFeGEssi\n\ -----END CERTIFICATE-----"; int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (/* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_TLS, /* MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_POLL, */ /* MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, */ (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, MHD_OPTION_CLIENT_DISCIPLINE_LVL, (int) 1, /* Optionally, the gnutls_load_file() can be used to load the key and the certificate from file. */ MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_END); if (d == NULL) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/json_echo.c0000644000175000017500000002406515235436771014662 /* This file is part of libmicrohttpd Copyright (C) 2025 Christian Grothoff (and other contributing authors) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file json_echo.c * @brief example for processing POST requests with JSON uploads, echos the JSON back to the client * @author Christian Grothoff */ #include #include #include #include #include #include #include /** * Bad request page. */ #define BAD_REQUEST_ERROR \ "Illegal requestGo away." /** * Invalid JSON page. */ #define NOT_FOUND_ERROR \ "Not foundGo away." /** * State we keep for each request. */ struct Request { /** * Number of bytes received. */ size_t off; /** * Size of @a buf. */ size_t len; /** * Buffer for POST data. */ void *buf; }; /** * Handler used to generate a 404 reply. * * @param connection connection to use */ static enum MHD_Result not_found_page (struct MHD_Connection *connection) { struct MHD_Response *response; enum MHD_Result ret; response = MHD_create_response_from_buffer_static (strlen (NOT_FOUND_ERROR), (const void *) NOT_FOUND_ERROR); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, "text/html")) { fprintf (stderr, "Failed to set content encoding header!\n"); } MHD_destroy_response (response); return ret; } /** * Handler used to generate a 400 reply. * * @param connection connection to use */ static enum MHD_Result invalid_request (struct MHD_Connection *connection) { enum MHD_Result ret; struct MHD_Response *response; response = MHD_create_response_from_buffer_static ( strlen (BAD_REQUEST_ERROR), (const void *) BAD_REQUEST_ERROR); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_BAD_REQUEST, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, "text/html")) { fprintf (stderr, "Failed to set content encoding header!\n"); } MHD_destroy_response (response); return ret; } /** * Main MHD callback for handling requests. * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param connection handle identifying the incoming connection * @param url the requested url * @param method the HTTP method used ("GET", "PUT", etc.) * @param version the HTTP version string (i.e. "HTTP/1.1") * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of MHD_get_connection_values; very large POST * data *will* be made available incrementally in * upload_data) * @param upload_data_size set initially to the size of the * upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param req_cls pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global "MHD_RequestCompleted" callback (which * can be set with the MHD_OPTION_NOTIFY_COMPLETED). * Initially, *req_cls will be NULL. * @return MHS_YES if the connection was handled successfully, * MHS_NO if the socket must be closed due to a serious * error while handling the request */ static enum MHD_Result create_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct Request *request = *req_cls; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silence compiler warning. */ (void) version; /* Unused. Silence compiler warning. */ if (NULL == request) { const char *clen; char dummy; unsigned int len; request = calloc (1, sizeof (struct Request)); if (NULL == request) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return MHD_NO; } *req_cls = request; if (0 != strcmp (method, MHD_HTTP_METHOD_POST)) { return not_found_page (connection); } clen = MHD_lookup_connection_value ( connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH); if (NULL == clen) return invalid_request (connection); if (1 != sscanf (clen, "%u%c", &len, &dummy)) return invalid_request (connection); request->len = len; request->buf = malloc (request->len); if (NULL == request->buf) return MHD_NO; return MHD_YES; } if (0 != *upload_data_size) { if (request->len < *upload_data_size + request->off) { fprintf (stderr, "Content-length header wrong, aborting\n"); return MHD_NO; } memcpy (request->buf, upload_data, *upload_data_size); request->off += *upload_data_size; *upload_data_size = 0; return MHD_YES; } { json_t *j; json_error_t err; char *s; j = json_loadb (request->buf, request->len, 0, &err); if (NULL == j) return invalid_request (connection); s = json_dumps (j, JSON_INDENT (2)); json_decref (j); response = MHD_create_response_from_buffer (strlen (s), s, MHD_RESPMEM_MUST_FREE); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } } /** * Callback called upon completion of a request. * Decrements session reference counter. * * @param cls not used * @param connection connection that completed * @param req_cls session handle * @param toe status code */ static void request_completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct Request *request = *req_cls; (void) cls; /* Unused. Silence compiler warning. */ (void) connection; /* Unused. Silence compiler warning. */ (void) toe; /* Unused. Silence compiler warning. */ if (NULL == request) return; if (NULL != request->buf) free (request->buf); free (request); } /** * Call with the port number as the only argument. * Never terminates (other than by signals, such as CTRL-C). */ int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct timeval tv; struct timeval *tvp; fd_set rs; fd_set ws; fd_set es; MHD_socket max; uint64_t mhd_timeout; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } /* initialize PRNG */ srand ((unsigned int) time (NULL)); d = MHD_start_daemon (MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &create_response, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15, MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (NULL == d) return 1; while (1) { max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) break; /* fatal internal error */ if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (mhd_timeout / 1000LL); #else /* Native W32 */ tv.tv_sec = (long) (mhd_timeout / 1000LL); #endif /* Native W32 */ tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000; tvp = &tv; } else tvp = NULL; if (-1 == select ((int) max + 1, &rs, &ws, &es, tvp)) { if (EINTR != errno) abort (); } MHD_run (d); } MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/https_fileserver_example.c0000644000175000017500000002243014760713574020011 /* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file https_fileserver_example.c * @brief a simple HTTPS file server using TLS. * * Usage : * * 'http_fileserver_example HTTP-PORT SECONDS-TO-RUN' * * The certificate & key are required by the server to operate, omitting the * path arguments will cause the server to use the hard coded example certificate & key. * * 'certtool' may be used to generate these if required. * * @author Sagie Amir * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #define BUF_SIZE 1024 #define MAX_URL_LEN 255 #define EMPTY_PAGE \ "File not foundFile not found" /* test server key */ static const char key_pem[] = "-----BEGIN PRIVATE KEY-----\n\ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h\n\ rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG\n\ UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g\n\ +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU\n\ HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8\n\ CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7\n\ dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz\n\ +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np\n\ XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp\n\ znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP\n\ pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW\n\ D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ\n\ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx\n\ pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo\n\ zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg\n\ pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM\n\ KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+\n\ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB\n\ OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx\n\ XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2\n\ wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG\n\ ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8\n\ 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB\n\ ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT\n\ QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE\n\ qdJNJ1DkyUc9dN2cliX4R+rG\n\ -----END PRIVATE KEY-----"; /* test server CA signed certificates */ static const char cert_pem[] = "-----BEGIN CERTIFICATE-----\n\ MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx\n\ DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0\n\ LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y\n\ ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4\n\ NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG\n\ TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl\n\ c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2\n\ psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd\n\ atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN\n\ 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM\n\ n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5\n\ qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo\n\ kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E\n\ AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk\n\ c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae\n\ 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk\n\ IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF\n\ Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x\n\ X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N\n\ aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll\n\ HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv\n\ hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb\n\ 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy\n\ UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y\n\ B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC\n\ SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM\n\ WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj\n\ OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27\n\ /w0gW9EVWzFhsFeGEssi\n\ -----END CERTIFICATE-----"; static ssize_t file_reader (void *cls, uint64_t pos, char *buf, size_t max) { FILE *file = (FILE *) cls; size_t bytes_read; /* 'fseek' may not support files larger 2GiB, depending on platform. * For production code, make sure that 'pos' has valid values, supported by * 'fseek', or use 'fseeko' or similar function. */ if (0 != fseek (file, (long) pos, SEEK_SET)) return MHD_CONTENT_READER_END_WITH_ERROR; bytes_read = fread (buf, 1, max, file); if (0 == bytes_read) return (0 != ferror (file)) ? MHD_CONTENT_READER_END_WITH_ERROR : MHD_CONTENT_READER_END_OF_STREAM; return (ssize_t) bytes_read; } static void file_free_callback (void *cls) { FILE *file = cls; fclose (file); } /* HTTP access handler call back */ static enum MHD_Result http_ahc (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; FILE *file; int fd; struct stat buf; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ file = fopen (&url[1], "rb"); if (NULL != file) { fd = fileno (file); if (-1 == fd) { (void) fclose (file); return MHD_NO; /* internal error */ } if ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) { /* not a regular file, refuse to serve */ fclose (file); file = NULL; } } if (NULL == file) { response = MHD_create_response_from_buffer_static (strlen (EMPTY_PAGE), (const void *) EMPTY_PAGE); ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); } else { response = MHD_create_response_from_callback ((size_t) buf.st_size, 32 * 1024, /* 32k page size */ &file_reader, file, &file_free_callback); if (NULL == response) { fclose (file); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *TLS_daemon; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > UINT16_MAX) ) { fprintf (stderr, "Port must be a number between 1 and 65535\n"); return 1; } TLS_daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | MHD_USE_TLS, (uint16_t) port, NULL, NULL, &http_ahc, NULL, MHD_OPTION_CONNECTION_TIMEOUT, 256, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END); if (NULL == TLS_daemon) { fprintf (stderr, "Error: failed to start TLS_daemon.\n"); return 1; } printf ("MHD daemon listening on port %u\n", (unsigned int) port); (void) getc (stdin); MHD_stop_daemon (TLS_daemon); return 0; } libmicrohttpd-1.0.10/src/examples/fileserver_example_dirs.c0000644000175000017500000001474014760713574017615 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file fileserver_example_dirs.c * @brief example for how to use libmicrohttpd to serve files (with directory support) * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #ifdef HAVE_UNISTD_H #include #endif #include static ssize_t file_reader (void *cls, uint64_t pos, char *buf, size_t max) { FILE *file = (FILE *) cls; size_t bytes_read; /* 'fseek' may not support files larger 2GiB, depending on platform. * For production code, make sure that 'pos' has valid values, supported by * 'fseek', or use 'fseeko' or similar function. */ if (0 != fseek (file, (long) pos, SEEK_SET)) return MHD_CONTENT_READER_END_WITH_ERROR; bytes_read = fread (buf, 1, max, file); if (0 == bytes_read) return (0 != ferror (file)) ? MHD_CONTENT_READER_END_WITH_ERROR : MHD_CONTENT_READER_END_OF_STREAM; return (ssize_t) bytes_read; } static void file_free_callback (void *cls) { FILE *file = cls; fclose (file); } static void dir_free_callback (void *cls) { DIR *dir = cls; if (dir != NULL) closedir (dir); } static ssize_t dir_reader (void *cls, uint64_t pos, char *buf, size_t max) { DIR *dir = cls; struct dirent *e; int res; if (max < 512) return 0; (void) pos; /* 'pos' is ignored as function return next one single entry per call. */ do { e = readdir (dir); if (e == NULL) return MHD_CONTENT_READER_END_OF_STREAM; } while (e->d_name[0] == '.'); res = snprintf (buf, max, "%s
    ", e->d_name, e->d_name); if (0 >= res) return MHD_CONTENT_READER_END_WITH_ERROR; if (max < (size_t) res) return MHD_CONTENT_READER_END_WITH_ERROR; return (ssize_t) res; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int aptr; struct MHD_Response *response; enum MHD_Result ret; FILE *file; int fd; DIR *dir; struct stat buf; char emsg[1024]; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */ if (&aptr != *req_cls) { /* do never respond on first call */ *req_cls = &aptr; return MHD_YES; } *req_cls = NULL; /* reset when done */ file = fopen (&url[1], "rb"); if (NULL != file) { fd = fileno (file); if (-1 == fd) { (void) fclose (file); return MHD_NO; /* internal error */ } if ( (0 != fstat (fd, &buf)) || (! S_ISREG (buf.st_mode)) ) { /* not a regular file, refuse to serve */ fclose (file); file = NULL; } } if (NULL == file) { dir = opendir ("."); if (NULL == dir) { /* most likely cause: more concurrent requests than available file descriptors / 2 */ snprintf (emsg, sizeof (emsg), "Failed to open directory `.': %s\n", strerror (errno)); response = MHD_create_response_from_buffer (strlen (emsg), emsg, MHD_RESPMEM_MUST_COPY); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_SERVICE_UNAVAILABLE, response); MHD_destroy_response (response); } else { response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 32 * 1024, &dir_reader, dir, &dir_free_callback); if (NULL == response) { closedir (dir); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } } else { response = MHD_create_response_from_callback ((size_t) buf.st_size, 32 * 1024, /* 32k page size */ &file_reader, file, &file_free_callback); if (NULL == response) { fclose (file); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/msgs_i18n.c0000644000175000017500000000603414760713574014520 /* This file is part of libmicrohttpd Copyright (C) 2017 Christian Grothoff, Silvio Clecio (silvioprog) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file msgs_i18n.c * @brief example for how to use translate libmicrohttpd messages * @author Christian Grothoff * @author Silvio Clecio (silvioprog) */ /* * supposing you are in Brazil: * * # generate the PO file * $ msginit --input=po/libmicrohttpd.pot --locale=pt_BR --output=libmicrohttpd.po * # open the generated .po in any program like Poedit and translate the MHD messages; once done, let's go to the test: * mkdir -p src/examples/locale/pt_BR/LC_MESSAGES * mv libmicrohttpd.mo libmicrohttpd.po src/examples/locale/pt_BR/LC_MESSAGES * cd src/examples/ * gcc -o msgs_i18n msgs_i18n.c -lmicrohttpd * export LANGUAGE=pt_BR * ./msgs_i18n * # it may print: Opção inválida 4196490! (Você terminou a lista com MHD_OPTION_END?) */ #include #include #include #include static int ahc_echo (void *cls, struct MHD_Connection *cnc, const char *url, const char *mt, const char *ver, const char *upd, size_t *upsz, void **req_cls) { return MHD_NO; } static void error_handler (void *cls, const char *fm, va_list ap) { /* Here we do the translation using GNU gettext. As the error message is from libmicrohttpd, we specify "libmicrohttpd" as the translation domain here. */ vprintf (dgettext ("libmicrohttpd", fm), ap); } int main (int argc, char **argv) { setlocale (LC_ALL, ""); /* The example uses PO files in the directory "libmicrohttpd/src/examples/locale". This needs to be adapted to match where the MHD PO files are installed. */ bindtextdomain ("libmicrohttpd", "locale"); MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_FEATURE_MESSAGES | MHD_USE_ERROR_LOG, 8080, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_EXTERNAL_LOGGER, &error_handler, NULL, 99999 /* invalid option, to raise the error "Invalid option ..." which we are going to translate */); return 1; /* This program won't "succeed"... */ } libmicrohttpd-1.0.10/src/examples/Makefile.am0000664000175000017500000001420415232215632014563 # This Makefile.am is in the public domain SUBDIRS = . AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) \ -DDATA_DIR=\"$(top_srcdir)/src/datadir/\" AM_CFLAGS = $(CFLAGS_ac) @LIBGCRYPT_CFLAGS@ AM_LDFLAGS = $(LDFLAGS_ac) MHD_CPU_COUNT_DEF = -DMHD_CPU_COUNT=$(CPU_COUNT) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) if USE_COVERAGE AM_CFLAGS += --coverage endif $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la # example programs noinst_PROGRAMS = \ benchmark \ benchmark_https \ chunked_example \ minimal_example \ minimal_example_empty \ dual_stack_example \ minimal_example_comet \ querystring_example \ timeout \ fileserver_example \ fileserver_example_dirs \ fileserver_example_external_select \ refuse_post_example if MHD_HAVE_EPOLL noinst_PROGRAMS += \ suspend_resume_epoll if HAVE_FORK_WAITPID if RUN_LIBCURL_TESTS check_PROGRAMS = test_suspend_resume_epoll TESTS = $(check_PROGRAMS) endif endif endif if HAVE_JANSSON noinst_PROGRAMS += \ json_echo endif EXTRA_DIST = msgs_i18n.c noinst_EXTRA_DIST = msgs_i18n.c if ENABLE_HTTPS noinst_PROGRAMS += \ https_fileserver_example \ minimal_example_empty_tls endif if HAVE_POSTPROCESSOR noinst_PROGRAMS += \ post_example if HAVE_POSIX_THREADS noinst_PROGRAMS += demo if ENABLE_HTTPS noinst_PROGRAMS += demo_https endif endif endif if ENABLE_DAUTH noinst_PROGRAMS += \ digest_auth_example \ digest_auth_example_adv endif if ENABLE_BAUTH noinst_PROGRAMS += \ authorization_example endif if HAVE_POSIX_THREADS if ENABLE_UPGRADE noinst_PROGRAMS += \ upgrade_example endif endif if HAVE_ZLIB noinst_PROGRAMS += \ http_compression \ http_chunked_compression endif if HAVE_W32 AM_CFLAGS += -DWINDOWS endif minimal_example_SOURCES = \ minimal_example.c minimal_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_empty_SOURCES = \ minimal_example_empty.c minimal_example_empty_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_empty_tls_SOURCES = \ minimal_example_empty_tls.c minimal_example_empty_tls_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la upgrade_example_SOURCES = \ upgrade_example.c upgrade_example_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) upgrade_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) timeout_SOURCES = \ timeout.c timeout_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la chunked_example_SOURCES = \ chunked_example.c chunked_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la json_echo_SOURCES = \ json_echo.c json_echo_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ -ljansson demo_SOURCES = \ demo.c demo_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) demo_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) demo_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) if MHD_HAVE_LIBMAGIC demo_LDADD += -lmagic endif demo_https_SOURCES = \ demo_https.c demo_https_CFLAGS = \ $(PTHREAD_CFLAGS) $(AM_CFLAGS) demo_https_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) demo_https_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ $(PTHREAD_LIBS) if MHD_HAVE_LIBMAGIC demo_https_LDADD += -lmagic endif benchmark_SOURCES = \ benchmark.c benchmark_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) benchmark_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la suspend_resume_epoll_SOURCES = \ suspend_resume_epoll.c suspend_resume_epoll_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) suspend_resume_epoll_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la test_suspend_resume_epoll_SOURCES = \ test_suspend_resume_epoll.c test_suspend_resume_epoll_LDADD = \ @LIBCURL@ benchmark_https_SOURCES = \ benchmark_https.c benchmark_https_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_CPU_COUNT_DEF) benchmark_https_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la dual_stack_example_SOURCES = \ dual_stack_example.c dual_stack_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la post_example_SOURCES = \ post_example.c post_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la minimal_example_comet_SOURCES = \ minimal_example_comet.c minimal_example_comet_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la authorization_example_SOURCES = \ authorization_example.c authorization_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la digest_auth_example_SOURCES = \ digest_auth_example.c digest_auth_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la digest_auth_example_adv_SOURCES = \ digest_auth_example_adv.c digest_auth_example_adv_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la refuse_post_example_SOURCES = \ refuse_post_example.c refuse_post_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la querystring_example_SOURCES = \ querystring_example.c querystring_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_SOURCES = \ fileserver_example.c fileserver_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_dirs_SOURCES = \ fileserver_example_dirs.c fileserver_example_dirs_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la fileserver_example_external_select_SOURCES = \ fileserver_example_external_select.c fileserver_example_external_select_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la https_fileserver_example_SOURCES = \ https_fileserver_example.c https_fileserver_example_CPPFLAGS = \ $(AM_CPPFLAGS) $(GNUTLS_CPPFLAGS) https_fileserver_example_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la http_compression_SOURCES = \ http_compression.c http_chunked_compression_SOURCES = \ http_chunked_compression.c http_compression_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la http_chunked_compression_LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la if HAVE_ZLIB http_compression_LDADD += -lz http_chunked_compression_LDADD += -lz endif libmicrohttpd-1.0.10/src/examples/http_compression.c0000644000175000017500000001222114760713574016303 /* This file is part of libmicrohttpd Copyright (C) 2019 Christian Grothoff (and other contributing authors) Copyright (C) 2019-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file http_compression.c * @brief minimal example for how to compress HTTP response * @author Silvio Clecio (silvioprog) * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #define PAGE \ "HTTP compressionHello, " \ "hello, hello. This is a 'hello world' message for the world, " \ "repeat, for the world." static enum MHD_Result can_compress (struct MHD_Connection *con) { const char *ae; const char *de; ae = MHD_lookup_connection_value (con, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT_ENCODING); if (NULL == ae) return MHD_NO; if (0 == strcmp (ae, "*")) return MHD_YES; de = strstr (ae, "deflate"); if (NULL == de) return MHD_NO; if (((de == ae) || (de[-1] == ',') || (de[-1] == ' ')) && ((de[strlen ("deflate")] == '\0') || (de[strlen ("deflate")] == ',') || (de[strlen ("deflate")] == ';'))) return MHD_YES; return MHD_NO; } static enum MHD_Result body_compress (void **buf, size_t *buf_size) { Bytef *cbuf; uLongf cbuf_size; int ret; cbuf_size = compressBound ((uLong) * buf_size); cbuf = malloc (cbuf_size); if (NULL == cbuf) return MHD_NO; ret = compress (cbuf, &cbuf_size, (const Bytef *) *buf, (uLong) * buf_size); if ((Z_OK != ret) || (cbuf_size >= *buf_size)) { /* compression failed */ free (cbuf); return MHD_NO; } free (*buf); *buf = (void *) cbuf; *buf_size = (size_t) cbuf_size; return MHD_YES; } static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; enum MHD_Result comp; size_t body_len; char *body_str; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; /* unexpected method */ if (! *req_cls) { *req_cls = (void *) 1; return MHD_YES; } *req_cls = NULL; body_str = strdup (PAGE); if (NULL == body_str) { return MHD_NO; } body_len = strlen (body_str); /* try to compress the body */ comp = MHD_NO; if (MHD_YES == can_compress (connection)) comp = body_compress ((void **) &body_str, &body_len); response = MHD_create_response_from_buffer_with_free_callback (body_len, body_str, &free); if (NULL == response) { free (body_str); return MHD_NO; } if (MHD_YES == comp) { /* Need to indicate to client that body is compressed */ if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, "deflate")) { MHD_destroy_response (response); return MHD_NO; } } ret = MHD_queue_response (connection, 200, response); MHD_destroy_response (response); return ret; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; unsigned int port; if ( (argc != 2) || (1 != sscanf (argv[1], "%u", &port)) || (65535 < port) ) { printf ("%s PORT\n", argv[0]); return 1; } d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 1; (void) getc (stdin); MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/post_example.c0000644000175000017500000005436414760713574015421 /* This file is part of libmicrohttpd Copyright (C) 2011 Christian Grothoff (and other contributing authors) Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file post_example.c * @brief example for processing POST requests using libmicrohttpd * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include #include #include #include #include #include /** * Invalid method page. */ #define METHOD_ERROR \ "Illegal requestGo away." /** * Invalid URL page. */ #define NOT_FOUND_ERROR \ "Not foundGo away." /** * Front page. (/) */ #define MAIN_PAGE \ "Welcome
    What is your name?
    " /** * Second page. (/2) */ #define SECOND_PAGE \ "Tell me moreprevious
    %s, what is your job?
    " /** * Second page (/S) */ #define SUBMIT_PAGE \ "Ready to submit?
    previous
    " /** * Last page. */ #define LAST_PAGE \ "Thank youThank you." /** * Name of our cookie. */ #define COOKIE_NAME "session" /** * State we keep for each user/session/browser. */ struct Session { /** * We keep all sessions in a linked list. */ struct Session *next; /** * Unique ID for this session. */ char sid[33]; /** * Reference counter giving the number of connections * currently using this session. */ unsigned int rc; /** * Time when this session was last active. */ time_t start; /** * String submitted via form. */ char value_1[64]; /** * Another value submitted via form. */ char value_2[64]; }; /** * Data kept per request. */ struct Request { /** * Associated session. */ struct Session *session; /** * Post processor handling form data (IF this is * a POST request). */ struct MHD_PostProcessor *pp; /** * URL to serve in response to this POST (if this request * was a 'POST') */ const char *post_url; }; /** * Linked list of all active sessions. Yes, O(n) but a * hash table would be overkill for a simple example... */ static struct Session *sessions; /** * Return the session handle for this connection, or * create one if this is a new user. */ static struct Session * get_session (struct MHD_Connection *connection) { struct Session *ret; const char *cookie; cookie = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, COOKIE_NAME); if (cookie != NULL) { /* find existing session */ ret = sessions; while (NULL != ret) { if (0 == strcmp (cookie, ret->sid)) break; ret = ret->next; } if (NULL != ret) { ret->rc++; return ret; } } /* create fresh session */ ret = calloc (1, sizeof (struct Session)); if (NULL == ret) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return NULL; } /* not a super-secure way to generate a random session ID, but should do for a simple example... */ snprintf (ret->sid, sizeof (ret->sid), "%X%X%X%X", (unsigned int) rand (), (unsigned int) rand (), (unsigned int) rand (), (unsigned int) rand ()); ret->rc++; ret->start = time (NULL); ret->next = sessions; sessions = ret; return ret; } /** * Type of handler that generates a reply. * * @param cls content for the page (handler-specific) * @param mime mime type to use * @param session session information * @param connection connection to process * @param #MHD_YES on success, #MHD_NO on failure */ typedef enum MHD_Result (*PageHandler)(const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection); /** * Entry we generate for each page served. */ struct Page { /** * Acceptable URL for this page. */ const char *url; /** * Mime type to set for the page. */ const char *mime; /** * Handler to call to generate response. */ PageHandler handler; /** * Extra argument to handler. */ const void *handler_cls; }; /** * Add header to response to set a session cookie. * * @param session session to use * @param response response to modify */ static void add_session_cookie (struct Session *session, struct MHD_Response *response) { char cstr[256]; snprintf (cstr, sizeof (cstr), "%s=%s", COOKIE_NAME, session->sid); if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_SET_COOKIE, cstr)) { fprintf (stderr, "Failed to set session cookie header!\n"); } } /** * Handler that returns a simple static HTTP page that * is passed in via 'cls'. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result serve_simple_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; const char *form = cls; struct MHD_Response *response; /* return static form */ response = MHD_create_response_from_buffer_static (strlen (form), (const void *) form); if (NULL == response) return MHD_NO; add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, mime)) { fprintf (stderr, "Failed to set content encoding header!\n"); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Handler that adds the 'v1' value to the given HTML code. * * @param cls unused * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result fill_v1_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; size_t slen; char *reply; struct MHD_Response *response; (void) cls; /* Unused. Silent compiler warning. */ slen = strlen (MAIN_PAGE) + strlen (session->value_1); reply = malloc (slen + 1); if (NULL == reply) return MHD_NO; snprintf (reply, slen + 1, MAIN_PAGE, session->value_1); /* return static form */ response = MHD_create_response_from_buffer_with_free_callback (slen, (void *) reply, &free); if (NULL == response) { free (reply); return MHD_NO; } add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, mime)) { fprintf (stderr, "Failed to set content encoding header!\n"); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Handler that adds the 'v1' and 'v2' values to the given HTML code. * * @param cls unused * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result fill_v1_v2_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; char *reply; struct MHD_Response *response; size_t slen; (void) cls; /* Unused. Silent compiler warning. */ slen = strlen (SECOND_PAGE) + strlen (session->value_1) + strlen (session->value_2); reply = malloc (slen + 1); if (NULL == reply) return MHD_NO; snprintf (reply, slen + 1, SECOND_PAGE, session->value_1, session->value_2); /* return static form */ response = MHD_create_response_from_buffer_with_free_callback (slen, (void *) reply, &free); if (NULL == response) { free (reply); return MHD_NO; } add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, mime)) { fprintf (stderr, "Failed to set content encoding header!\n"); } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Handler used to generate a 404 reply. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result not_found_page (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; struct MHD_Response *response; (void) cls; /* Unused. Silent compiler warning. */ (void) session; /* Unused. Silent compiler warning. */ /* unsupported HTTP method */ response = MHD_create_response_from_buffer_static (strlen (NOT_FOUND_ERROR), (const void *) NOT_FOUND_ERROR); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, mime)) { fprintf (stderr, "Failed to set content encoding header!\n"); } MHD_destroy_response (response); return ret; } /** * List of all pages served by this HTTP server. */ static struct Page pages[] = { { "/", "text/html", &fill_v1_form, NULL }, { "/2", "text/html", &fill_v1_v2_form, NULL }, { "/S", "text/html", &serve_simple_form, SUBMIT_PAGE }, { "/F", "text/html", &serve_simple_form, LAST_PAGE }, { NULL, NULL, ¬_found_page, NULL } /* 404 */ }; /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return MHD_YES to continue iterating, * MHD_NO to abort the iteration */ static enum MHD_Result post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct Request *request = cls; struct Session *session = request->session; (void) kind; /* Unused. Silent compiler warning. */ (void) filename; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ if (0 == strcmp ("DONE", key)) { fprintf (stdout, "Session `%s' submitted `%s', `%s'\n", session->sid, session->value_1, session->value_2); return MHD_YES; } if (0 == strcmp ("v1", key)) { if (off >= sizeof(session->value_1) - 1) return MHD_YES; /* Discard extra data */ if (size + off >= sizeof(session->value_1)) size = (size_t) (sizeof (session->value_1) - off - 1); /* crop extra data */ memcpy (&session->value_1[off], data, size); session->value_1[size + off] = '\0'; return MHD_YES; } if (0 == strcmp ("v2", key)) { if (off >= sizeof(session->value_2) - 1) return MHD_YES; /* Discard extra data */ if (size + off >= sizeof(session->value_2)) size = (size_t) (sizeof (session->value_2) - off - 1); /* crop extra data */ memcpy (&session->value_2[off], data, size); session->value_2[size + off] = '\0'; return MHD_YES; } fprintf (stderr, "Unsupported form value `%s'\n", key); return MHD_YES; } /** * Main MHD callback for handling requests. * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param connection handle identifying the incoming connection * @param url the requested url * @param method the HTTP method used ("GET", "PUT", etc.) * @param version the HTTP version string (i.e. "HTTP/1.1") * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of MHD_get_connection_values; very large POST * data *will* be made available incrementally in * upload_data) * @param upload_data_size set initially to the size of the * upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param req_cls pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global "MHD_RequestCompleted" callback (which * can be set with the MHD_OPTION_NOTIFY_COMPLETED). * Initially, *req_cls will be NULL. * @return MHS_YES if the connection was handled successfully, * MHS_NO if the socket must be closed due to a serious * error while handling the request */ static enum MHD_Result create_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; struct Request *request; struct Session *session; enum MHD_Result ret; unsigned int i; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ request = *req_cls; if (NULL == request) { request = calloc (1, sizeof (struct Request)); if (NULL == request) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return MHD_NO; } *req_cls = request; if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { request->pp = MHD_create_post_processor (connection, 1024, &post_iterator, request); if (NULL == request->pp) { fprintf (stderr, "Failed to setup post processor for `%s'\n", url); return MHD_NO; /* internal error */ } } return MHD_YES; } if (NULL == request->session) { request->session = get_session (connection); if (NULL == request->session) { fprintf (stderr, "Failed to setup session for `%s'\n", url); return MHD_NO; /* internal error */ } } session = request->session; session->start = time (NULL); if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { /* evaluate POST data */ if (MHD_YES != MHD_post_process (request->pp, upload_data, *upload_data_size)) return MHD_NO; if (0 != *upload_data_size) { *upload_data_size = 0; return MHD_YES; } /* done with POST data, serve response */ MHD_destroy_post_processor (request->pp); request->pp = NULL; method = MHD_HTTP_METHOD_GET; /* fake 'GET' */ if (NULL != request->post_url) url = request->post_url; } if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) || (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) ) { /* find out which page to serve */ i = 0; while ( (pages[i].url != NULL) && (0 != strcmp (pages[i].url, url)) ) i++; ret = pages[i].handler (pages[i].handler_cls, pages[i].mime, session, connection); if (ret != MHD_YES) fprintf (stderr, "Failed to create page for `%s'\n", url); return ret; } /* unsupported HTTP method */ response = MHD_create_response_from_buffer_static (strlen (METHOD_ERROR), (const void *) METHOD_ERROR); ret = MHD_queue_response (connection, MHD_HTTP_NOT_ACCEPTABLE, response); MHD_destroy_response (response); return ret; } /** * Callback called upon completion of a request. * Decrements session reference counter. * * @param cls not used * @param connection connection that completed * @param req_cls session handle * @param toe status code */ static void request_completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct Request *request = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == request) return; if (NULL != request->session) request->session->rc--; if (NULL != request->pp) MHD_destroy_post_processor (request->pp); free (request); } /** * Clean up handles of sessions that have been idle for * too long. */ static void expire_sessions (void) { struct Session *pos; struct Session *prev; struct Session *next; time_t now; now = time (NULL); prev = NULL; pos = sessions; while (NULL != pos) { next = pos->next; if (now - pos->start > 60 * 60) { /* expire sessions after 1h */ if (NULL == prev) sessions = pos->next; else prev->next = next; free (pos); } else prev = pos; pos = next; } } /** * Call with the port number as the only argument. * Never terminates (other than by signals, such as CTRL-C). */ int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct timeval tv; struct timeval *tvp; fd_set rs; fd_set ws; fd_set es; MHD_socket max; uint64_t mhd_timeout; int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } port = atoi (argv[1]); if ( (1 > port) || (port > 65535) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } /* initialize PRNG */ srand ((unsigned int) time (NULL)); d = MHD_start_daemon (MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &create_response, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15, MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (NULL == d) return 1; while (1) { expire_sessions (); max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) break; /* fatal internal error */ if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (mhd_timeout / 1000LL); #else /* Native W32 */ tv.tv_sec = (long) (mhd_timeout / 1000LL); #endif /* Native W32 */ tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000; tvp = &tv; } else tvp = NULL; if (-1 == select ((int) max + 1, &rs, &ws, &es, tvp)) { if (EINTR != errno) abort (); } MHD_run (d); } MHD_stop_daemon (d); return 0; } libmicrohttpd-1.0.10/src/examples/digest_auth_example_adv.c0000644000175000017500000010075114760713574017556 /* This file is part of libmicrohttpd Copyright (C) 2010 Christian Grothoff (and other contributing authors) Copyright (C) 2016-2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file digest_auth_example_adv.c * @brief Advanced example for digest auth with libmicrohttpd * @author Karlson2k (Evgeny Grin) */ #include #include #include #include #include #if ! defined(_WIN32) || defined(__CYGWIN__) # include # include # include #else /* Native W32 */ # include #endif /* Native W32 */ #define SEC_AREA1_URL "/secret_page/" #define SEC_AREA2_URL "/super_secret_page/" #define MAIN_PAGE \ "Welcome to the site" \ "

    Restricted Page

    " \ "

    Very Restricted Page

    " #define OPAQUE_DATA "ServerOpaqueData" #define REALM "authenticated_users@thishost" /** * Force select "MD5" algorithm instead of MHD default (currently the same) if non-zero. */ static int force_md5 = 0; /** * Force select "SHA-256" algorithm instead of MHD default (MD5) if non-zero. */ static int force_sha256 = 0; /** * Force select "SHA-512/256" algorithm instead of MHD default (MD5) if non-zero. */ static int force_sha512_256 = 0; /** * Disable fallback to (less secure) RFC2069 if non-zero. */ static int allow_rfc2069 = 0; /** * The daemon's port */ static uint16_t daemon_port = 0; /* *** "Database" of users and "database" functions *** */ /** * User record. * This kind of data (or something similar) should be stored in some database * or file. */ struct UserEntry { /** * The username. * Static data is used in this example. * In real application dynamic buffer or fixed size array could be used. */ const char *username; #if 0 /* Disabled code */ /* The cleartext password is not stored in the database. The more secure "userdigest" is used instead. */ /** * The password. * Static data is used in this example. * In real application dynamic buffer or fixed size array could be used. */ const char *password; #endif /* Disabled code */ /** * The realm for this entry. * Static data is used in this example. * In real application dynamic buffer or fixed size array could be used. */ const char *realm; /** * The MD5 hash of the username together with the realm. * This hash can be used by the client to send the username in encrypted * form. * The purpose of userhash is to hide user identity when transmitting * requests over insecure link. */ uint8_t userhash_md5[MHD_MD5_DIGEST_SIZE]; /** * The MD5 hash of the username with the password and the realm. * It is used to verify that password used by the client matches password * required by the server. * The purpose of userhash is to avoid keeping the password in cleartext * on the server side. */ uint8_t userdigest_md5[MHD_MD5_DIGEST_SIZE]; /** * The SHA-256 hash of the username together with the realm. * This hash can be used by the client to send the username in encrypted * form. * The purpose of userhash is to hide user identity when transmitting * requests over insecure link. */ uint8_t userhash_sha256[MHD_SHA256_DIGEST_SIZE]; /** * The SHA-256 hash of the username with the password and the realm. * It is used to verify that password used by the client matches password * required by the server. * The purpose of userhash is to avoid keeping the password in cleartext * on the server side. */ uint8_t userdigest_sha256[MHD_SHA256_DIGEST_SIZE]; /** * The SHA-512/256 hash of the username together with the realm. * This hash can be used by the client to send the username in encrypted * form. * The purpose of userhash is to hide user identity when transmitting * requests over insecure link. */ uint8_t userhash_sha512_256[MHD_SHA512_256_DIGEST_SIZE]; /** * The SHA-512/256 hash of the username with the password and the realm. * It is used to verify that password used by the client matches password * required by the server. * The purpose of userhash is to avoid keeping the password in cleartext * on the server side. */ uint8_t userdigest_sha512_256[MHD_SHA512_256_DIGEST_SIZE]; /** * User has access to "area 1" if non-zero */ int allow_area_1; /** * User has access to "area 2" if non-zero */ int allow_area_2; }; /** * The array of user entries. * In real application it should be loaded from external sources * at the application startup. */ static struct UserEntry user_ids[2]; /** * The number of entries used in @a user_ids. */ static size_t user_ids_used = 0; /** * Add new user to the users database/array. * * This kind of function must be used only when the new user is introduced. * It must not be used at the every start of the application. The database * of users should be stored somewhere and reloaded when application is * started. * * @param username the username of the new user * @param password the password of the new user * @param realm the realm (the protection space) for which the new user * is added * @param allow_area_1 if non-zero than user has access to the "area 1" * @param allow_area_2 if non-zero than user has access to the "area 2" * @return non-zero on success, * zero on failure (like no more space in the database). */ static int add_new_user_entry (const char *const username, const char *const password, const char *const realm, int allow_area_1, int allow_area_2) { struct UserEntry *entry; enum MHD_Result res; if ((sizeof(user_ids) / sizeof(user_ids[0])) <= user_ids_used) return 0; /* No more space to add new entry */ entry = user_ids + user_ids_used; entry->username = username; entry->realm = realm; res = MHD_YES; if (MHD_NO != res) res = MHD_digest_auth_calc_userhash (MHD_DIGEST_AUTH_ALGO3_MD5, username, realm, entry->userhash_md5, sizeof(entry->userhash_md5)); if (MHD_NO != res) res = MHD_digest_auth_calc_userdigest (MHD_DIGEST_AUTH_ALGO3_MD5, username, realm, password, entry->userdigest_md5, sizeof(entry->userdigest_md5)); if (MHD_NO != res) res = MHD_digest_auth_calc_userhash (MHD_DIGEST_AUTH_ALGO3_SHA256, username, realm, entry->userhash_sha256, sizeof(entry->userhash_sha256)); if (MHD_NO != res) res = MHD_digest_auth_calc_userdigest (MHD_DIGEST_AUTH_ALGO3_SHA256, username, realm, password, entry->userdigest_sha256, sizeof(entry->userdigest_sha256)); if (MHD_NO != res) res = MHD_digest_auth_calc_userhash (MHD_DIGEST_AUTH_ALGO3_SHA512_256, username, realm, entry->userhash_sha512_256, sizeof(entry->userhash_sha512_256)); if (MHD_NO != res) res = MHD_digest_auth_calc_userdigest (MHD_DIGEST_AUTH_ALGO3_SHA512_256, username, realm, password, entry->userdigest_sha512_256, sizeof(entry->userdigest_sha512_256)); if (MHD_NO == res) return 0; /* Failure exit point */ entry->allow_area_1 = allow_area_1; entry->allow_area_2 = allow_area_2; user_ids_used++; return ! 0; } /** * Find the user entry for specified username * @param username the username to find * @return NULL if no entry for specified username is found, * pointer to user entry if found */ static struct UserEntry * find_entry_by_username (const char *const username) { size_t i; for (i = 0; i < (sizeof(user_ids) / sizeof(user_ids[0])); ++i) { struct UserEntry *entry; entry = user_ids + i; if (0 == strcmp (username, entry->username)) return entry; } return NULL; } /** * Find the user entry for specified userhash * @param algo3 the algorithm used for userhash calculation * @param userhash the userhash identifier to find * @param userhash_size the size @a userhash in bytes * @return NULL if no entry for specified userhash is found, * pointer to user entry if found */ static struct UserEntry * find_entry_by_userhash (enum MHD_DigestAuthAlgo3 algo3, const void *userhash, size_t userhash_size) { size_t i; if (MHD_digest_get_hash_size (algo3) != userhash_size) return NULL; /* Wrong length of the userhash */ switch (algo3) { case MHD_DIGEST_AUTH_ALGO3_MD5: case MHD_DIGEST_AUTH_ALGO3_MD5_SESSION: /* An extra case not used currently */ if (sizeof(user_ids[0].userhash_md5) != userhash_size) /* Extra check. The size was checked before */ return NULL; for (i = 0; i < (sizeof(user_ids) / sizeof(user_ids[0])); ++i) { struct UserEntry *entry; entry = user_ids + i; if (0 == memcmp (userhash, entry->userhash_md5, sizeof(entry->userhash_md5))) return entry; } break; case MHD_DIGEST_AUTH_ALGO3_SHA256: case MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION: /* An extra case not used currently */ if (sizeof(user_ids[0].userhash_sha256) != userhash_size) /* Extra check. The size was checked before */ return NULL; for (i = 0; i < (sizeof(user_ids) / sizeof(user_ids[0])); ++i) { struct UserEntry *entry; entry = user_ids + i; if (0 == memcmp (userhash, entry->userhash_sha256, sizeof(entry->userhash_sha256))) return entry; } break; case MHD_DIGEST_AUTH_ALGO3_SHA512_256: case MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION: /* An extra case not used currently */ if (sizeof(user_ids[0].userhash_sha512_256) != userhash_size) /* Extra check. The size was checked before */ return NULL; for (i = 0; i < (sizeof(user_ids) / sizeof(user_ids[0])); ++i) { struct UserEntry *entry; entry = user_ids + i; if (0 == memcmp (userhash, entry->userhash_sha512_256, sizeof(entry->userhash_sha512_256))) return entry; } break; case MHD_DIGEST_AUTH_ALGO3_INVALID: /* Mute compiler warning. Impossible value in this context. */ default: break; } return NULL; } /** * Find the user entry for the user specified by provided username info * @param user_info the pointer to the structure username info returned by MHD * @return NULL if no entry for specified username info is found, * pointer to user entry if found */ static struct UserEntry * find_entry_by_userinfo (const struct MHD_DigestAuthUsernameInfo *username_info) { if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD <= username_info->uname_type) return find_entry_by_username (username_info->username); if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == username_info->uname_type) return find_entry_by_userhash (username_info->algo3, username_info->userhash_bin, username_info->userhash_hex_len / 2); return NULL; /* Should be unreachable as all cases are covered before */ } /* *** End of "database" of users and "database" functions *** */ /* *** Requests handling *** */ /** * Send "Requested HTTP method is not supported" page * @param c the connection structure * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_page_not_found (struct MHD_Connection *c) { static const char page_content[] = "Page Not Found" \ "The requested page not found."; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content); if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_NOT_FOUND, resp); MHD_destroy_response (resp); return ret; } /** * Get enum MHD_DigestAuthMultiAlgo3 value to be used for authentication. * @return the algorithm number/value */ static enum MHD_DigestAuthMultiAlgo3 get_m_algo (void) { if (force_md5) return MHD_DIGEST_AUTH_MULT_ALGO3_MD5; else if (force_sha256) return MHD_DIGEST_AUTH_MULT_ALGO3_SHA256; else if (force_sha512_256) return MHD_DIGEST_AUTH_MULT_ALGO3_SHA512_256; /* No forced algorithm selection, let MHD to use default */ return MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION; } /** * Get enum MHD_DigestAuthMultiQOP value to be used for authentication. * @return the "Quality Of Protection" number/value */ static enum MHD_DigestAuthMultiQOP get_m_QOP (void) { if (allow_rfc2069) return MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT; return MHD_DIGEST_AUTH_MULT_QOP_AUTH; } /** * Send "Authentication required" page * @param c the connection structure * @param stale if non-zero then "nonce stale" is indicated in the reply * @param wrong_cred if non-zero then client is informed the previously * it used wrong credentials * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_auth_required (struct MHD_Connection *c, int stale, int wrong_cred) { static const char auth_required_content[] = "Authentication required" \ "The requested page needs authentication."; static const size_t auth_required_content_len = (sizeof(auth_required_content) / sizeof(char)) - 1; static const char wrong_creds_content[] = "Wrong credentials" \ "The provided credentials are incorrect."; static const size_t wrong_creds_content_len = (sizeof(wrong_creds_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; if (wrong_cred) stale = 0; /* Force client to ask user for username and password */ if (! wrong_cred) resp = MHD_create_response_from_buffer_static (auth_required_content_len, auth_required_content); else resp = MHD_create_response_from_buffer_static (wrong_creds_content_len, wrong_creds_content); if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_auth_required_response3 ( c, REALM, OPAQUE_DATA, /* The "opaque data", not really useful */ SEC_AREA1_URL " " SEC_AREA2_URL, /* Space-separated list of URLs' initial parts */ resp, stale, get_m_QOP (), get_m_algo (), ! 0, /* Userhash support enabled */ ! 0 /* UTF-8 is preferred */); MHD_destroy_response (resp); return ret; } /** * Send "Forbidden" page * @param c the connection structure * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_forbidden (struct MHD_Connection *c) { static const char page_content[] = "Forbidden" \ "You do not have access to this page."; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content) ; if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_FORBIDDEN, resp); MHD_destroy_response (resp); return ret; } /** * Send "Area 1" pages * @param c the connection structure * @param url the requested URL * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_area1_pages (struct MHD_Connection *c, const char *url) { if (0 == strcmp (url, SEC_AREA1_URL "")) { static const char page_content[] = "Restricted secret page" \ "Welcome to the restricted area"; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content); if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_OK, resp); MHD_destroy_response (resp); return ret; } /* If needed: add handlers for other URLs in this area */ #if 0 /* Disabled code */ if (0 == strcmp (url, SEC_AREA1_URL "some_path/some_page")) { /* Add page creation/processing code */ } #endif /* Disabled code */ /* The requested URL is unknown */ return reply_with_page_not_found (c); } /** * Send "Area 2" pages * @param c the connection structure * @param url the requested URL * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_area2_pages (struct MHD_Connection *c, const char *url) { if (0 == strcmp (url, SEC_AREA2_URL "")) { static const char page_content[] = "Very restricted secret page" \ "Welcome to the super restricted area"; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content); if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_OK, resp); MHD_destroy_response (resp); return ret; } /* If needed: add handlers for other URLs in this area */ #if 0 /* Disabled code */ if (0 == strcmp (url, SEC_AREA2_URL "other_path/other_page")) { /* Add page creation/processing code */ } #endif /* Disabled code */ /* The requested URL is unknown */ return reply_with_page_not_found (c); } /** * Handle client's request for secured areas * @param c the connection structure * @param url the URL requested by the client * @param sec_area_num the number of secured area * @return MHD_YES if request was handled (either with "denied" or with * "allowed" result), * MHD_NO if it was an error handling the request. */ static enum MHD_Result handle_sec_areas_req (struct MHD_Connection *c, const char *url, unsigned int sec_area_num) { struct MHD_DigestAuthUsernameInfo *username_info; struct UserEntry *user_entry; void *userdigest; size_t userdigest_size; enum MHD_DigestAuthResult auth_res; username_info = MHD_digest_auth_get_username3 (c); if (NULL == username_info) return reply_with_auth_required (c, 0, 0); user_entry = find_entry_by_userinfo (username_info); if (NULL == user_entry) return reply_with_auth_required (c, 0, 1); switch (username_info->algo3) { case MHD_DIGEST_AUTH_ALGO3_MD5: userdigest = user_entry->userdigest_md5; userdigest_size = sizeof(user_entry->userdigest_md5); break; case MHD_DIGEST_AUTH_ALGO3_SHA256: userdigest = user_entry->userdigest_sha256; userdigest_size = sizeof(user_entry->userdigest_sha256); break; case MHD_DIGEST_AUTH_ALGO3_SHA512_256: userdigest = user_entry->userdigest_sha512_256; userdigest_size = sizeof(user_entry->userdigest_sha512_256); break; case MHD_DIGEST_AUTH_ALGO3_MD5_SESSION: case MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION: case MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION: /* Not supported currently and not used by MHD. The client incorrectly used algorithm not advertised by the server. */ return reply_with_auth_required (c, 0, 1); case MHD_DIGEST_AUTH_ALGO3_INVALID: /* Mute compiler warning */ default: return MHD_NO; /* Should be unreachable */ } auth_res = MHD_digest_auth_check_digest3 ( c, REALM, /* Make sure to use the proper realm, not the realm provided by the client and returned by "user_entry" */ user_entry->username, userdigest, userdigest_size, 0, /* Use daemon's default value for nonce_timeout*/ 0, /* Use daemon's default value for max_nc */ get_m_QOP (), (enum MHD_DigestAuthMultiAlgo3) username_info->algo3 /* Direct cast from "single algorithm" to "multi-algorithm" is allowed */ ); if (MHD_DAUTH_OK != auth_res) { int need_just_refresh_nonce; /* Actually MHD_DAUTH_NONCE_OTHER_COND should not be returned as MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE is not used for the daemon. To keep the code universal the MHD_DAUTH_NONCE_OTHER_COND is still checked here. */ need_just_refresh_nonce = (MHD_DAUTH_NONCE_STALE == auth_res) || (MHD_DAUTH_NONCE_OTHER_COND == auth_res); return reply_with_auth_required (c, need_just_refresh_nonce, ! need_just_refresh_nonce); } /* The user successfully authenticated */ /* Check whether access to the request area is allowed for the user */ if (1 == sec_area_num) { if (user_entry->allow_area_1) return reply_with_area1_pages (c, url); else return reply_with_forbidden (c); } else if (2 == sec_area_num) { if (user_entry->allow_area_2) return reply_with_area2_pages (c, url); else return reply_with_forbidden (c); } return MHD_NO; /* Should be unreachable */ } /** * Send the main page * @param c the connection structure * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_main_page (struct MHD_Connection *c) { static const char page_content[] = MAIN_PAGE; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content) ; if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_OK, resp); MHD_destroy_response (resp); return ret; } /** * Send "Requested HTTP method is not supported" page * @param c the connection structure * @return MHD_YES if response was successfully queued, * MHD_NO otherwise */ static enum MHD_Result reply_with_method_not_supported (struct MHD_Connection *c) { static const char page_content[] = "Requested HTTP Method Is Not Supported" \ "The requested HTTP method is not supported."; static const size_t page_content_len = (sizeof(page_content) / sizeof(char)) - 1; struct MHD_Response *resp; enum MHD_Result ret; resp = MHD_create_response_from_buffer_static (page_content_len, page_content) ; if (NULL == resp) return MHD_NO; /* Ignore possible error when adding the header as the reply will work even without this header. */ (void) MHD_add_response_header (resp, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html"); ret = MHD_queue_response (c, MHD_HTTP_NOT_IMPLEMENTED, resp); MHD_destroy_response (resp); return ret; } static enum MHD_Result ahc_main (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int already_called_marker; size_t url_len; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))) return reply_with_method_not_supported (connection); if (0 != *upload_data_size) return MHD_NO; /* No upload expected for GET or HEAD */ if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } if (0 == strcmp (url, "/")) return reply_with_main_page (connection); url_len = strlen (url); if ((strlen (SEC_AREA1_URL) <= url_len) && (0 == memcmp (url, SEC_AREA1_URL, strlen (SEC_AREA1_URL)))) return handle_sec_areas_req (connection, url, 1); /* The requested URL is within SEC_AREA1_URL */ if ((strlen (SEC_AREA2_URL) <= url_len) && (0 == memcmp (url, SEC_AREA2_URL, strlen (SEC_AREA2_URL)))) return handle_sec_areas_req (connection, url, 2); /* The requested URL is within SEC_AREA2_URL */ return reply_with_page_not_found (connection); } /* *** End of requests handling *** */ /** * Add new users to the users "database". * * In real application this kind of function must NOT be called at * the application startup. Instead similar function should be * called only when new user is introduced. The users "database" * should be stored somewhere and reloaded at the application * startup. * * @return non-zero on success, * zero in case of error. */ static int add_new_users (void) { if (! add_new_user_entry ("joepublic", "password", REALM, ! 0, 0)) return 0; if (! add_new_user_entry ("superadmin", "pA$$w0Rd", REALM, ! 0, ! 0)) return 0; return ! 0; } /** * Check and apply application parameters * @param argc the argc of the @a main function * @param argv the argv of the @a main function * @return non-zero on success, * zero in case of any error (like wrong parameters). */ static int check_params (int argc, char *const *const argv) { size_t i; unsigned int port_value; if (2 > argc) return 0; for (i = 1; i < (unsigned int) argc; ++i) { if (0 == strcmp (argv[i], "--md5")) { /* Force use MD5 */ force_md5 = ! 0; force_sha256 = 0; force_sha512_256 = 0; } else if (0 == strcmp (argv[i], "--sha256")) { /* Force use SHA-256 instead of default MD5 */ force_md5 = 0; force_sha256 = ! 0; force_sha512_256 = 0; } else if (0 == strcmp (argv[i], "--sha512-256")) { /* Force use SHA-512/256 instead of default MD5 */ force_md5 = 0; force_sha256 = 0; force_sha512_256 = ! 0; } else if (0 == strcmp (argv[i], "--allow-rfc2069")) allow_rfc2069 = ! 0; /* Allow fallback to RFC2069. Not recommended! */ else if ((1 == sscanf (argv[i], "%u", &port_value)) && (0 < port_value) && (65535 >= port_value)) daemon_port = (uint16_t) port_value; else { fprintf (stderr, "Unrecognized parameter: %s\n", argv[i]); return 0; } } if (force_sha512_256) printf ( "Note: when testing with curl/libcurl do not be surprised with failures as " "libcurl incorrectly implements SHA-512/256 algorithm.\n"); return ! 0; } /** * The cryptographically secure random data */ static uint8_t rand_data[8]; /** * Initialise the random data * @return non-zero if succeed, * zero if failed */ static int init_rand_data (void) { #if ! defined(_WIN32) || defined(__CYGWIN__) int fd; ssize_t len; size_t off; fd = open ("/dev/urandom", O_RDONLY); if (-1 == fd) { fprintf (stderr, "Failed to open '%s': %s\n", "/dev/urandom", strerror (errno)); return 0; } for (off = 0; off < sizeof(rand_data); off += (size_t) len) { len = read (fd, rand_data, 8); if (0 > len) { fprintf (stderr, "Failed to read '%s': %s\n", "/dev/urandom", strerror (errno)); (void) close (fd); return 0; } } (void) close (fd); #else /* Native W32 */ HCRYPTPROV cc; BOOL b; b = CryptAcquireContext (&cc, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (FALSE == b) { fprintf (stderr, "Failed to acquire crypto provider context: %lu\n", (unsigned long) GetLastError ()); return 0; } b = CryptGenRandom (cc, sizeof(rand_data), (BYTE *) rand_data); if (FALSE == b) { fprintf (stderr, "Failed to generate 8 random bytes: %lu\n", GetLastError ()); } CryptReleaseContext (cc, 0); if (FALSE == b) return 0; #endif /* Native W32 */ return ! 0; } int main (int argc, char *const *argv) { struct MHD_Daemon *d; if (! check_params (argc, argv)) { fprintf (stderr, "Usage: %s [--md5|--sha256|--sha512-256] " "[--allow-rfc2069] PORT\n", argv[0]); return 1; } if (! add_new_users ()) { fprintf (stderr, "Failed to add new users to the users database.\n"); return 2; } if (! init_rand_data ()) { fprintf (stderr, "Failed to initialise random data.\n"); return 2; } d = MHD_start_daemon ( MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_ERROR_LOG, daemon_port, NULL, NULL, &ahc_main, NULL, MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof(rand_data), rand_data, MHD_OPTION_NONCE_NC_SIZE, 500, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 180, MHD_OPTION_END); if (d == NULL) { fprintf (stderr, "Failed to start the server on port %lu.\n", (unsigned long) daemon_port); return 1; } printf ("Running server on port %lu.\nPress ENTER to stop.\n", (unsigned long) daemon_port); (void) getc (stdin); MHD_stop_daemon (d); return 0; } /* End of digest_auth_example_adv.c */ libmicrohttpd-1.0.10/src/datadir/0000775000175000017500000000000015235437005012403 5libmicrohttpd-1.0.10/src/datadir/cert-and-key-for-wireshark.pem0000644000175000017500000000325014674632555020105 -----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8 CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7 dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2 wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE qdJNJ1DkyUc9dN2cliX4R+rG -----END PRIVATE KEY----- libmicrohttpd-1.0.10/src/datadir/cert-and-key.pem0000644000175000017500000000701714674632555015331 -----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCff7amw9zNSE+h rOMhBrzbbsJluUP3gmd8nOKY5MUimoPkxmAXfp2L0il+MPZT/ZEmo11q0k6J2jfG UBQ+oZW9ahNZ9gCDjbYlBblo/mqTai+LdeLO3qk53d0zrZKXvCO6sA3uKpG2WR+g +sNKxfYpIHCpanqBU6O+degIV/+WKy3nQ2Fwp7K5HUNj1u0pg0QQ18yf68LTnKFU HFjZmmaaopWki5wKSBieHivzQy6w+04HSTogHHRK/y/UcoJNSG7xnHmoPPo1vLT8 CMRIYnSSgU3wJ43XBJ80WxrC2dcoZjV2XZz+XdQwCD4ZrC1ihykcAmiQA+sauNm7 dztOMkGzAgMBAAECggEAIbKDzlvXDG/YkxnJqrKXt+yAmak4mNQuNP+YSCEdHSBz +SOILa6MbnvqVETX5grOXdFp7SWdfjZiTj2g6VKOJkSA7iKxHRoVf2DkOTB3J8np XZd8YaRdMGKVV1O2guQ20Dxd1RGdU18k9YfFNsj4Jtw5sTFTzHr1P0n9ybV9xCXp znSxVfRg8U6TcMHoRDJR9EMKQMO4W3OQEmreEPoGt2/+kMuiHjclxLtbwDxKXTLP pD0gdg3ibvlufk/ccKl/yAglDmd0dfW22oS7NgvRKUve7tzDxY1Q6O5v8BCnLFSW D+z4hS1PzooYRXRkM0xYudvPkryPyu+1kEpw3fNsoQKBgQDRfXJo82XQvlX8WPdZ Ts3PfBKKMVu3Wf8J3SYpuvYT816qR3ot6e4Ivv5ZCQkdDwzzBKe2jAv6JddMJIhx pkGHc0KKOodd9HoBewOd8Td++hapJAGaGblhL5beIidLKjXDjLqtgoHRGlv5Cojo zHa7Viel1eOPPcBumhp83oJ+mQKBgQDC6PmdETZdrW3QPm7ZXxRzF1vvpC55wmPg pRfTRM059jzRzAk0QiBgVp3yk2a6Ob3mB2MLfQVDgzGf37h2oO07s5nspSFZTFnM KgSjFy0xVOAVDLe+0VpbmLp1YUTYvdCNowaoTE7++5rpePUDu3BjAifx07/yaSB+ W+YPOfOuKwKBgQCGK6g5G5qcJSuBIaHZ6yTZvIdLRu2M8vDral5k3793a6m3uWvB OFAh/eF9ONJDcD5E7zhTLEMHhXDs7YEN+QODMwjs6yuDu27gv97DK5j1lEsrLUpx XgRjAE3KG2m7NF+WzO1K74khWZaKXHrvTvTEaxudlO3X8h7rN3u7ee9uEQKBgQC2 wI1zeTUZhsiFTlTPWfgppchdHPs6zUqq0wFQ5Zzr8Pa72+zxY+NJkU2NqinTCNsG ePykQ/gQgk2gUrt595AYv2De40IuoYk9BlTMuql0LNniwsbykwd/BOgnsSlFdEy8 0RQn70zOhgmNSg2qDzDklJvxghLi7zE5aV9//V1/ewKBgFRHHZN1a8q/v8AAOeoB ROuXfgDDpxNNUKbzLL5MO5odgZGi61PBZlxffrSOqyZoJkzawXycNtoBP47tcVzT QPq5ZOB3kjHTcN7dRLmPWjji9h4O3eHCX67XaPVMSWiMuNtOZIg2an06+jxGFhLE qdJNJ1DkyUc9dN2cliX4R+rG -----END PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIFSzCCAzOgAwIBAgIBBDANBgkqhkiG9w0BAQsFADCBgTELMAkGA1UEBhMCUlUx DzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwGTW9zY293MRswGQYDVQQKDBJ0ZXN0 LWxpYm1pY3JvaHR0cGQxITAfBgkqhkiG9w0BCQEWEm5vYm9keUBleGFtcGxlLm9y ZzEQMA4GA1UEAwwHdGVzdC1DQTAgFw0yMjA0MjAxODQzMDJaGA8yMTIyMDMyNjE4 NDMwMlowZTELMAkGA1UEBhMCUlUxDzANBgNVBAgMBk1vc2NvdzEPMA0GA1UEBwwG TW9zY293MRswGQYDVQQKDBJ0ZXN0LWxpYm1pY3JvaHR0cGQxFzAVBgNVBAMMDnRl c3QtbWhkc2VydmVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3+2 psPczUhPoazjIQa8227CZblD94JnfJzimOTFIpqD5MZgF36di9IpfjD2U/2RJqNd atJOido3xlAUPqGVvWoTWfYAg422JQW5aP5qk2ovi3Xizt6pOd3dM62Sl7wjurAN 7iqRtlkfoPrDSsX2KSBwqWp6gVOjvnXoCFf/list50NhcKeyuR1DY9btKYNEENfM n+vC05yhVBxY2ZpmmqKVpIucCkgYnh4r80MusPtOB0k6IBx0Sv8v1HKCTUhu8Zx5 qDz6Nby0/AjESGJ0koFN8CeN1wSfNFsawtnXKGY1dl2c/l3UMAg+GawtYocpHAJo kAPrGrjZu3c7TjJBswIDAQABo4HmMIHjMAsGA1UdDwQEAwIFoDAMBgNVHRMBAf8E AjAAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMBMDEGA1UdEQQqMCiCDnRlc3QtbWhk c2VydmVyhwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMB0GA1UdDgQWBBQ57Z06WJae 8fJIHId4QGx/HsRgDDAoBglghkgBhvhCAQ0EGxYZVGVzdCBsaWJtaWNyb2h0dHBk IHNlcnZlcjARBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUWHVDwKVqMcOF Nd0arI3/QB3W6SwwDQYJKoZIhvcNAQELBQADggIBAI7Lggm/XzpugV93H5+KV48x X+Ct8unNmPCSzCaI5hAHGeBBJpvD0KME5oiJ5p2wfCtK5Dt9zzf0S0xYdRKqU8+N aKIvPoU1hFixXLwTte1qOp6TviGvA9Xn2Fc4n36dLt6e9aiqDnqPbJgBwcVO82ll HJxVr3WbrAcQTB3irFUMqgAke/Cva9Bw79VZgX4ghb5EnejDzuyup4pHGzV10Myv hdg+VWZbAxpCe0S4eKmstZC7mWsFCLeoRTf/9Pk1kQ6+azbTuV/9QOBNfFi8QNyb 18jUjmm8sc2HKo8miCGqb2sFqaGD918hfkWmR+fFkzQ3DZQrT+eYbKq2un3k0pMy UySy8SRn1eadfab+GwBVb68I9TrPRMrJsIzysNXMX4iKYl2fFE/RSNnaHtPw0C8y B7memyxPRl+H2xg6UjpoKYh3+8e44/XKm0rNIzXjrwA8f8gnw2TbqmMDkj1YqGnC SCj5A27zUzaf2pT/YsnQXIWOJjVvbEI+YKj34wKWyTrXA093y8YI8T3mal7Kr9YM WiIyPts0/aVeziM0Gunglz+8Rj1VesL52FTurobqusPgM/AME82+qb/qnxuPaCKj OT1qAbIblaRuWqCsid8BzP7ZQiAnAWgMRSUg1gzDwSwRhrYQRRWAyn/Qipzec+27 /w0gW9EVWzFhsFeGEssi -----END CERTIFICATE----- libmicrohttpd-1.0.10/src/Makefile.in0000664000175000017500000005353015235436270012771 # Makefile.in generated by automake 1.17 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2024 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # This Makefile.am is in the public domain VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) am__rm_f = rm -f $(am__rm_f_notfound) am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @RUN_LIBCURL_TESTS_TRUE@am__append_1 = testcurl @RUN_LIBCURL_TESTS_TRUE@@RUN_ZZUF_TESTS_TRUE@am__append_2 = testzzuf @ENABLE_FUZZING_TRUE@am__append_3 = fuzz @BUILD_EXAMPLES_TRUE@am__append_4 = examples @BUILD_TOOLS_TRUE@am__append_5 = tools subdir = src ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` DIST_SUBDIRS = include microhttpd . testcurl testzzuf fuzz examples \ tools am__DIST_COMMON = $(srcdir)/Makefile.in DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ am__xargs_n = @am__xargs_n@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUBDIRS = include microhttpd . $(am__append_1) $(am__append_2) \ $(am__append_3) $(am__append_4) $(am__append_5) EXTRA_DIST = \ datadir/cert-and-key.pem \ datadir/cert-and-key-for-wireshark.pem all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -$(am__rm_f) $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool cscopelist-am ctags \ ctags-am distclean distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am tags tags-am uninstall uninstall-am .PRECIOUS: Makefile .NOTPARALLEL: # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: # Tell GNU make to disable its built-in pattern rules. %:: %,v %:: RCS/%,v %:: RCS/% %:: s.% %:: SCCS/s.% libmicrohttpd-1.0.10/src/testzzuf/0000775000175000017500000000000015235437005012671 5libmicrohttpd-1.0.10/src/testzzuf/test_pipelined.c0000664000175000017500000002065515232103064015765 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testzzuf/test_pipelined.c * @brief Fuzzing testcase for pipelined requests * @author Christian Grothoff * * Several complete requests are written with a single send() call, so that * MHD has to find the request boundaries inside one read buffer. Corrupting * such a stream (or combining it with a connection memory pool that is too * small to hold all pipelined requests at once) is the most direct way to * produce a request boundary de-synchronisation. * * libcurl does not pipeline any more (HTTP/1.1 pipelining support was * removed in libcurl 7.62), therefore the raw socket client is used. The * traffic still goes to the same port and through the same zzuf/socat * corruption layer as the libcurl based tests of this directory. */ #include "platform.h" #include #include #include #include #include "mhd_zzuf_common.h" #define TEST_MAGIC_MARKER 0xFEE1C0DE #define EMPTY_PAGE "Empty page." /** * The port offset used if the port cannot be auto-detected. */ #define TEST_PORT_OFFSET 150 /** * The maximum size of a single pipelined batch. */ #define MAX_BATCH_SIZE 4096 #define HOST_HDR "Host: " ZZUF_MHD_LISTEN_IP "\r\n" /** * The closure of the access handler callback. */ struct ahc_param { /** * Must have #TEST_MAGIC_MARKER value. */ unsigned int magic; /** * Non-zero if any error has been encountered. */ unsigned int err_flag; /** * The number of requests seen so far. */ unsigned int num_requests; }; /** * The request templates that are concatenated into one pipelined batch. * The last request of every batch is added by build_batch(). */ static const char *const req_templates[] = { "GET /pipe/a HTTP/1.1\r\n" HOST_HDR "\r\n", "GET /pipe/b?x=1&y HTTP/1.1\r\n" HOST_HDR "X-Pad: 0123456789\r\n\r\n", "HEAD /pipe/c HTTP/1.1\r\n" HOST_HDR "\r\n", "POST /pipe/d HTTP/1.1\r\n" HOST_HDR "Content-Length: 5\r\n\r\nHELLO", "PUT /pipe/e HTTP/1.1\r\n" HOST_HDR "Transfer-Encoding: chunked\r\n\r\n5\r\nHELLO\r\n0\r\n\r\n", /* An empty line before the request line: allowed to be skipped by MHD */ "\r\nGET /pipe/f HTTP/1.1\r\n" HOST_HDR "\r\n", /* A request with a body that is *not* announced: the following bytes must not be swallowed as a body */ "GET /pipe/g HTTP/1.1\r\n" HOST_HDR "\r\n" }; #define NUM_REQ_TEMPLATES \ (sizeof(req_templates) / sizeof(req_templates[0])) static enum MHD_Result ahc_pipelined (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct ahc_param *param = (struct ahc_param *) cls; struct MHD_Response *response; enum MHD_Result ret; (void) url; (void) method; (void) version; (void) upload_data; if ((NULL == param) || (TEST_MAGIC_MARKER != param->magic)) { fprintf (stderr, "The 'cls' parameter is invalid " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if ((NULL == url) || (NULL == method) || (NULL == version)) { fprintf (stderr, "One of the mandatory string parameters is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; } if (NULL == *req_cls) { *req_cls = ▮ return MHD_YES; } if ((NULL != upload_data_size) && (0 != *upload_data_size)) { *upload_data_size = 0; /* Discard the body */ return MHD_YES; } param->num_requests++; response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (EMPTY_PAGE), EMPTY_PAGE); if (NULL == response) { fprintf (stderr, "MHD_create_response_from_buffer_static() failed " "at line %d.\n", (int) __LINE__); return MHD_NO; /* External error, do not raise the error flag */ } ret = MHD_YES; if (zzuf_use_close) ret = MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); if (MHD_YES == ret) ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Build one pipelined batch of requests. * * @param iteration the number of the current iteration * @param[out] buf the buffer to fill * @param buf_size the size of @a buf * @return the number of bytes written to @a buf */ static size_t build_batch (unsigned int iteration, char *buf, size_t buf_size) { static const char last_req[] = "GET /pipe/last HTTP/1.1\r\n" HOST_HDR "Connection: close\r\n\r\n"; size_t pos = 0; unsigned int i; unsigned int num; num = 2 + (iteration % 4); /* 2 to 5 requests per batch */ for (i = 0; i < num; ++i) { const char *req = req_templates[(iteration + i) % NUM_REQ_TEMPLATES]; const size_t len = strlen (req); if (pos + len + sizeof(last_req) > buf_size) break; memcpy (buf + pos, req, len); pos += len; } if (pos + MHD_STATICSTR_LEN_ (last_req) <= buf_size) { memcpy (buf + pos, last_req, MHD_STATICSTR_LEN_ (last_req)); pos += MHD_STATICSTR_LEN_ (last_req); } return pos; } static unsigned int client_run (struct MHD_Daemon *d_extern, uint16_t port, void *cls) { struct ahc_param *param = (struct ahc_param *) cls; unsigned int i; unsigned int loops; char batch[MAX_BATCH_SIZE]; loops = zzuf_loop_count (); for (i = 0; i < loops; ++i) { struct zzuf_raw_part parts[2]; size_t batch_len; size_t num_parts; fprintf (stderr, "."); batch_len = build_batch (i, batch, sizeof(batch)); parts[0].data = batch; parts[0].size = batch_len; num_parts = 1; if (0 != i % 2) { /* Every other iteration: split the batch in the middle of a request, so that MHD has to keep a partial request in the read buffer while the previous ones are still being answered. */ parts[0].size = batch_len / 2; parts[1].data = batch + parts[0].size; parts[1].size = batch_len - parts[0].size; num_parts = 2; } if (ZZUF_RAW_SETUP_FAILED == zzuf_raw_exchange (d_extern, port, parts, num_parts, (unsigned int) ZZUF_CLIENT_TIMEOUT)) { fprintf (stderr, "The raw client could not be set up " "at line %d.\n", (int) __LINE__); return 99; /* Not an MHD error */ } fflush (stderr); } if (0 != param->err_flag) { fprintf (stderr, "One or more errors have been detected by the access " "handler callback function. At line %d.\n", (int) __LINE__); return 1; } return 0; } int main (int argc, char *const *argv) { struct ahc_param param; struct zzuf_run_params rp; unsigned int res; int use_magic_exit_codes; zzuf_parse_common_args (argc, argv); use_magic_exit_codes = zzuf_run_with_socat || zzuf_dry_run; res = zzuf_check_runnable (); if (0 != res) return use_magic_exit_codes ? (int) res : 0; param.magic = (unsigned int) TEST_MAGIC_MARKER; param.err_flag = 0; param.num_requests = 0; memset (&rp, 0, sizeof(rp)); rp.port = zzuf_pick_port (TEST_PORT_OFFSET); rp.ahc = &ahc_pipelined; rp.ahc_cls = ¶m; rp.rcc = NULL; rp.rcc_cls = NULL; rp.mem_limit_override = 0; rp.sweep_profiles = 1; rp.profile_start = 0; rp.client = &client_run; rp.client_cls = ¶m; res = zzuf_run_polling_modes (&rp); if (99 == res) return use_magic_exit_codes ? 99 : 0; if (77 == res) return use_magic_exit_codes ? 77 : 0; return (0 == res) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testzzuf/zzuf_socat_test_runner.sh0000775000175000017500000001406215232103064017762 #!/bin/sh # # Run one fuzzing test with zzuf fuzzing a socat relay that sits between # the test clients and MHD. This mode is mandatory when MHD is built with # sanitizers (zzuf and the sanitizers cannot both intercept the standard # library calls) or when MHD uses accept4(). # # Recognised environment variables: # ZZUF the zzuf command (set by configure) # ZZUF_SEED the single seed to use (default "0") # ZZUF_SEED_START the first seed of a seed range (overrides ZZUF_SEED) # ZZUF_SEED_STOP the last seed of a seed range # ZZUF_FLAGS additional flags for zzuf # SOCAT the socat command (set by configure) # SOCAT_FLAGS additional flags for socat # # This script is POSIX shell only, do not use any bashism. if set -m ; then : ; else echo "The shell $SHELL does not support background jobs, the test cannot run." 1>&2 exit 77 fi socat_listen_ip='127.0.0.121' socat_listen_port='10121' mhd_listen_port='4010' max_runtime_sec='1800' if test "x${ZZUF}" = "xno" ; then echo "zzuf command missing" 1>&2 exit 77 fi if command -v "${ZZUF}" > /dev/null 2>&1 ; then : ; else echo "zzuf command missing" 1>&2 exit 77 fi if test "x${SOCAT}" = "xno" ; then echo "socat command missing" 1>&2 exit 77 fi if command -v "${SOCAT}" > /dev/null 2>&1 ; then : ; else echo "socat command missing" 1>&2 exit 77 fi # Build the "--seed" parameter for zzuf. zzuf_seed_param='' if test -n "${ZZUF_SEED_START}" ; then if test -n "${ZZUF_SEED_STOP}" ; then zzuf_seed_param="--seed=${ZZUF_SEED_START}:${ZZUF_SEED_STOP}" seed_descr="range ${ZZUF_SEED_START}:${ZZUF_SEED_STOP}" else zzuf_seed_param="--seed=${ZZUF_SEED_START}" seed_descr="${ZZUF_SEED_START}" fi elif test -n "${ZZUF_SEED}" ; then zzuf_seed_param="--seed=${ZZUF_SEED}" seed_descr="${ZZUF_SEED}" else seed_descr="(zzuf default)" fi test_descr="$*" test_name=`echo "$1" | sed 's|^.*/||'` # Print a loud, easy to grep report about a failing run. # In this mode zzuf fuzzes socat, while the test program (and MHD) runs # outside of zzuf, so the exit code below is the exit code (or the signal) # of the *server side* and the seed is the one this run was started with. # $1: the exit code of the test program report_failure () { echo '' 1>&2 echo '###############################################################' 1>&2 echo '## FUZZING TEST FAILED (server side)' 1>&2 echo "## test : ${test_descr}" 1>&2 echo "## exit code : $1" 1>&2 if test "$1" -gt 128 2> /dev/null ; then echo "## (killed by signal `expr $1 - 128`)" 1>&2 fi echo "## FAILING SEED: ${seed_descr}" 1>&2 echo '## Replay with:' 1>&2 if test -n "${ZZUF_SEED_START}" ; then echo "## make ZZUF_SEED_START=${ZZUF_SEED_START} \ ZZUF_SEED_STOP=${ZZUF_SEED_STOP} TESTS=${test_name} check" 1>&2 else echo "## make ZZUF_SEED=${ZZUF_SEED} TESTS=${test_name} check" 1>&2 fi echo '###############################################################' 1>&2 echo '' 1>&2 } socat_test_params="-ls -lu \ -T0.1 -4 \ TCP-LISTEN:${socat_listen_port},bind=${socat_listen_ip},reuseaddr,linger=2,linger2=1,accept-timeout=0.1 \ TCP:127.0.0.1:${mhd_listen_port},reuseaddr" echo "## Trying to run socat to test ports availability..." if "${SOCAT}" ${socat_test_params} ; then echo "Success." else echo "socat test run failed" 1>&2 exit 77 fi # fuzz the input only for IP ${socat_listen_ip}. libcurl and the raw client # use another IP in these tests, therefore the input of the clients is not # fuzzed. zzuf_all_params="--ratio=0.001:0.4 --autoinc --verbose --signal \ --max-usertime=${max_runtime_sec} --check-exit --network --allow=${socat_listen_ip} --exclude=." if test -n "${zzuf_seed_param}" ; then zzuf_all_params="${zzuf_all_params} ${zzuf_seed_param}" fi if test -n "${ZZUF_FLAGS}" ; then zzuf_all_params="${zzuf_all_params} ${ZZUF_FLAGS}" fi # Uncomment the next line to see more zzuf data in logs #zzuf_all_params="${zzuf_all_params} -dd" socat_options="-ls -lu \ -T3 -4" socat_addr1="TCP-LISTEN:${socat_listen_port},bind=${socat_listen_ip},reuseaddr,nodelay,linger=2,linger2=1,accept-timeout=${max_runtime_sec},fork" socat_addr2="TCP:127.0.0.1:${mhd_listen_port},reuseaddr,connect-timeout=3,nodelay,linger=2,linger2=1" if test -n "${SOCAT_FLAGS}" ; then socat_options="${socat_options} ${SOCAT_FLAGS}" fi # Uncomment the next line to see more socat data in logs #socat_options="${socat_options} -dd -D" # Uncomment the next line to see all traffic in logs #socat_options="${socat_options} -v" stop_zzuf_socat () { trap - EXIT if test -n "$zzuf_pid" ; then echo "The test has been interrupted." 1>&2 test "x$zzuf_pid" = "xstarting" && zzuf_pid=$! # Finish zzuf + socat kill -TERM ${zzuf_pid} -${zzuf_pid} # Finish the test kill -INT %2 2> /dev/null || kill -INT %1 2> /dev/null exit 99 fi } echo "## Starting zzuf with socat to reflect fuzzed traffic (seed: ${seed_descr})..." trap 'stop_zzuf_socat' EXIT zzuf_pid="starting" "${ZZUF}" ${zzuf_all_params} "${SOCAT}" ${socat_options} ${socat_addr1} ${socat_addr2} & if test $? -eq 0 ; then zzuf_pid=$! echo "zzuf with socat has been started." else zzuf_pid='' echo "Failed to start zzuf with socat" 1>&2 exit 99 fi echo "## Starting real test of $* with traffic fuzzed by zzuf with socat..." "$@" --with-socat test_result=$? trap - EXIT echo "$* has exited with the return code $test_result" if kill -s 0 -- $$ 2> /dev/null ; then if kill -s 0 -- ${zzuf_pid} -${zzuf_pid} 2> /dev/null ; then : ; else echo "No running zzuf with socat is detected after the test." 1>&2 echo "Looks like zzuf ended prematurely, at least part of the testing has not been performed." 1>&2 if test "x${test_result}" = "x0" ; then test_result=99 else echo "The test itself has already failed with the code ${test_result}," 1>&2 echo "this code is kept as the result of this run." 1>&2 fi fi fi kill -TERM ${zzuf_pid} -${zzuf_pid} 2> /dev/null zzuf_pid='' if test "x${test_result}" != "x0" && test "x${test_result}" != "x77" ; then report_failure "${test_result}" fi exit $test_result libmicrohttpd-1.0.10/src/testzzuf/test_get_chunked_ext.c0000664000175000017500000005000615232103064017145 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testzzuf/test_get_chunked_ext.c * @brief Fuzzing testcase for chunked transfers with chunk extensions * @author Christian Grothoff * * This single source builds two programs: * - test_get_chunked_ext: the request is a GET with a chunked body and * MHD answers with a chunked reply that carries a footer, so that both * the request-side chunk parser and the reply-side chunk writer are * exercised; * - test_put_chunked_ext: the request is a PUT with a chunked body and * MHD answers from a static buffer. * * libcurl cannot generate chunk extensions, so the requests are written * by the raw socket client of mhd_zzuf_common.c. The client still talks * to the very same port (and therefore through the very same zzuf/socat * corruption layer) as the libcurl based tests of this directory. * * In addition to the fuzzed traffic, the test runs a small deterministic * self-check of the chunk-extension parser. The self-check talks to MHD * *directly*, bypassing socat, and is therefore not fuzzed at all; it can * only be run in the socat mode (which is the mode that is mandatory when * MHD is built with sanitizers). The self-check verifies that a chunked * body with chunk extensions is decoded byte-exactly; a parser that fails * to consume the CRLF that terminates a chunk-extension line cannot pass * it. */ #include "platform.h" #include #include #include #include #include "mhd_zzuf_common.h" #define TEST_MAGIC_MARKER 0xFEE1C0DE #define EMPTY_PAGE "Empty page." /** * The port offset used if the port cannot be auto-detected. */ #define TEST_PORT_OFFSET 145 /** * The port offset of the (unfuzzed) self-check daemon. */ #define TEST_SELFCHECK_PORT_OFFSET 160 /** * The maximum size of a request body accepted by this test. */ #define MAX_BODY_SIZE 256 /** * Non-zero for the "put" flavour of this test. */ static int use_put; /** * Non-zero if MHD should answer with a chunked reply. */ static int use_chunked_reply; /** * One chunked request body with (possibly hostile) chunk extensions. */ struct chunk_case { /** * The name of the case; also used as the last path segment of the URI. */ const char *name; /** * The chunked body, exactly as it goes on the wire. */ const char *wire; /** * The body that MHD is expected to decode, or NULL if the request is * not required to be accepted at all (deliberately malformed input). */ const char *expected; }; static const struct chunk_case chunk_cases[] = { { "simple", "5;name=value\r\nHELLO\r\n0\r\n\r\n", "HELLO" }, { "flag", "5;flag\r\nHELLO\r\n0\r\n\r\n", "HELLO" }, { "quoted", "5;n=\"a;b=c\"\r\nHELLO\r\n0\r\n\r\n", "HELLO" }, { "multi", "3;a=b;c=d;e\r\nabc\r\n2;x\r\nde\r\n0\r\n\r\n", "abcde" }, { "lastext", "5;a=b\r\nHELLO\r\n0;final=1\r\n\r\n", "HELLO" }, { "trailers", "5;a=b\r\nHELLO\r\n0\r\nX-Trailer: yes\r\nX-Other: 1\r\n\r\n", "HELLO" }, { "extonly", "5;a\r\nHELLO\r\n0;b\r\n\r\n", "HELLO" }, /* The following cases are deliberately malformed: MHD is free to reject them, it just must not misbehave. */ { "wsbefore", "5 ;n=v\r\nHELLO\r\n0\r\n\r\n", NULL }, { "wsaround", "5; n = v \r\nHELLO\r\n0\r\n\r\n", NULL }, { "barelf", "5;a=b\nHELLO\r\n0\r\n\r\n", NULL }, { "extcr", "5;a=b\rHELLO\r\n0\r\n\r\n", NULL }, { "noext", "5;\r\nHELLO\r\n0\r\n\r\n", NULL } }; #define NUM_CHUNK_CASES \ (sizeof(chunk_cases) / sizeof(chunk_cases[0])) /** * The number of leading entries of #chunk_cases that are well-formed and * therefore usable for the deterministic self-check. */ #define NUM_VALID_CHUNK_CASES 7 /** * A chunk-size line with a very long extension, built at run time. */ static char *long_ext_body; /** * The closure of the access handler callback. */ struct ahc_param { /** * Must have #TEST_MAGIC_MARKER value. */ unsigned int magic; /** * Non-zero if any error has been encountered. */ unsigned int err_flag; /** * Non-zero while the deterministic self-check is running. */ int self_check; /** * The body that is expected during the self-check, may be NULL. */ const char *expect_body; /** * Set to non-zero by the handler when the expected body has been seen. */ int body_matched; }; /** * The per-request state. */ struct req_state { /** * The number of bytes stored in @e body. */ size_t body_len; /** * Set to non-zero if more data has been received than fits into @e body. */ int overflow; /** * The received body. */ char body[MAX_BODY_SIZE]; }; /** * The closure of the content reader callback. */ struct content_cb_param { /** * The response the callback belongs to, needed to add the footer. */ struct MHD_Response *response; }; /** * MHD content reader callback for the chunked reply. * * @param cls the closure * @param pos the position in the reply body * @param[out] buf the buffer to fill * @param max the size of @a buf * @return the number of bytes written, or the end-of-stream marker */ static ssize_t content_cb (void *cls, uint64_t pos, char *buf, size_t max) { struct content_cb_param *ccp = (struct content_cb_param *) cls; if (pos >= 512) { if (MHD_YES != MHD_add_response_footer (ccp->response, "Footer", "working")) { fprintf (stderr, "MHD_add_response_footer() failed " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } return MHD_CONTENT_READER_END_OF_STREAM; } if (max > 128) max = 128; memset (buf, 'A' + (char) (unsigned int) (pos / 128), max); return (ssize_t) max; } /** * Free the closure of the content reader callback. * * @param ptr the closure to free */ static void content_cb_free (void *ptr) { free (ptr); } /** * Iterator over the request footers (trailers). * * @param cls the closure * @param kind the kind of the value * @param key the key * @param value the value * @return #MHD_YES to continue the iteration */ static enum MHD_Result footer_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { unsigned int *sum = (unsigned int *) cls; (void) kind; /* Unused. Mute compiler warning. */ if (NULL != key) *sum += (unsigned int) strlen (key); if (NULL != value) *sum += (unsigned int) strlen (value); return MHD_YES; } static enum MHD_Result ahc_chunked_ext (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct ahc_param *param = (struct ahc_param *) cls; struct req_state *rs; struct MHD_Response *response; enum MHD_Result ret; unsigned int footer_sum = 0; (void) url; (void) method; (void) version; if ((NULL == param) || (TEST_MAGIC_MARKER != param->magic)) { fprintf (stderr, "The 'cls' parameter is invalid " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (NULL == *req_cls) { rs = malloc (sizeof(struct req_state)); if (NULL == rs) return MHD_NO; /* External error */ rs->body_len = 0; rs->overflow = 0; *req_cls = rs; return MHD_YES; } rs = (struct req_state *) *req_cls; if ((NULL != upload_data_size) && (0 != *upload_data_size)) { size_t to_copy = *upload_data_size; if (to_copy > sizeof(rs->body) - rs->body_len) { to_copy = sizeof(rs->body) - rs->body_len; rs->overflow = 1; } if ((0 != to_copy) && (NULL != upload_data)) { memcpy (rs->body + rs->body_len, upload_data, to_copy); rs->body_len += to_copy; } *upload_data_size = 0; /* All data have been processed */ return MHD_YES; } /* The request is complete. */ (void) MHD_get_connection_values (connection, MHD_FOOTER_KIND, &footer_iterator, &footer_sum); if (param->self_check && (NULL != param->expect_body)) { const size_t elen = strlen (param->expect_body); if ((! rs->overflow) && (elen == rs->body_len) && (0 == memcmp (rs->body, param->expect_body, elen))) param->body_matched = 1; else { fprintf (stderr, "Self-check: the decoded request body does not match the " "expected body. Expected %u bytes ('%s'), got %u bytes. " "At line %d.\n", (unsigned int) elen, param->expect_body, (unsigned int) rs->body_len, (int) __LINE__); param->err_flag = 1; } } free (rs); *req_cls = NULL; if (use_chunked_reply) { struct content_cb_param *ccp; ccp = malloc (sizeof(struct content_cb_param)); if (NULL == ccp) return MHD_NO; /* External error */ ccp->response = NULL; response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, &content_cb, ccp, &content_cb_free); if (NULL == response) free (ccp); else ccp->response = response; } else response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (EMPTY_PAGE), EMPTY_PAGE); if (NULL == response) { fprintf (stderr, "Failed to create the response " "at line %d.\n", (int) __LINE__); return MHD_NO; /* External error, do not raise the error flag */ } ret = MHD_YES; if (zzuf_use_close || ! zzuf_oneone) ret = MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); if (MHD_YES == ret) ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static void req_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { (void) cls; (void) connection; (void) toe; if (NULL == *req_cls) return; free (*req_cls); *req_cls = NULL; } /** * Build the request head for a given case. * * @param name the case name (used in the URI) * @param close_conn if non-zero, "Connection: close" is added, so that MHD * closes the connection right after the reply instead of * waiting for the connection timeout * @param[out] buf the buffer to fill * @param buf_size the size of @a buf */ static void build_head (const char *name, int close_conn, char *buf, size_t buf_size) { int len; len = snprintf (buf, buf_size, "%s /chunked_ext/%s HTTP/1.1\r\n" "Host: " ZZUF_MHD_LISTEN_IP "\r\n" "Transfer-Encoding: chunked\r\n" "%s" "\r\n", use_put ? "PUT" : "GET", name, close_conn ? "Connection: close\r\n" : ""); if ((0 > len) || (buf_size <= (size_t) len)) { fprintf (stderr, "snprintf() failed at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } } static unsigned int client_run (struct MHD_Daemon *d_extern, uint16_t port, void *cls) { struct ahc_param *param = (struct ahc_param *) cls; unsigned int i; unsigned int loops; loops = zzuf_loop_count (); for (i = 0; i < loops; ++i) { const struct chunk_case *cc = chunk_cases + (i % NUM_CHUNK_CASES); struct zzuf_raw_part parts[4]; char head[256]; size_t num_parts; const char *wire; size_t wire_len; size_t split; fprintf (stderr, "."); build_head (cc->name, 0, head, sizeof(head)); if ((NULL != long_ext_body) && (0 == i % 5)) wire = long_ext_body; /* Occasionally use the over-long extension */ else wire = cc->wire; wire_len = strlen (wire); /* Split the body so that the chunk-size (and chunk-extension) lines are torn apart between two TCP segments. */ split = wire_len / 2; parts[0].data = head; parts[0].size = strlen (head); parts[1].data = wire; parts[1].size = split; parts[2].data = wire + split; parts[2].size = wire_len - split; /* Always append a pipelined follow-up request: if the chunk-extension line is not consumed correctly, the request boundary is lost and this second request is interpreted as chunk data (or the other way round). Its "Connection: close" also makes MHD close the connection right after the reply instead of waiting for the connection timeout. */ parts[3].data = "GET /chunked_ext/after HTTP/1.1\r\n" "Host: " ZZUF_MHD_LISTEN_IP "\r\n" "Connection: close\r\n\r\n"; parts[3].size = strlen (parts[3].data); num_parts = 4; if (ZZUF_RAW_SETUP_FAILED == zzuf_raw_exchange (d_extern, port, parts, num_parts, (unsigned int) ZZUF_CLIENT_TIMEOUT)) { fprintf (stderr, "The raw client could not be set up " "at line %d.\n", (int) __LINE__); return 99; /* Not an MHD error */ } fflush (stderr); } if (0 != param->err_flag) { fprintf (stderr, "One or more errors have been detected by the access " "handler callback function. At line %d.\n", (int) __LINE__); return 1; } return 0; } /** * Run the deterministic (unfuzzed) self-check of the chunk-extension * parser. Only possible in the socat mode, where MHD's own port is not * touched by zzuf. * * @return zero on success, non-zero on failure */ static unsigned int run_self_check (void) { struct MHD_Daemon *d; struct MHD_Daemon *d_extern; struct ahc_param param; uint16_t port; unsigned int flags; unsigned int i; unsigned int ret = 0; param.magic = (unsigned int) TEST_MAGIC_MARKER; param.err_flag = 0; param.self_check = 1; param.expect_body = NULL; param.body_matched = 0; if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; else port = (uint16_t) (ZZUF_BASE_PORT + TEST_SELFCHECK_PORT_OFFSET); if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) flags = MHD_USE_SELECT_INTERNALLY; else flags = MHD_USE_NO_THREAD_SAFETY; d = zzuf_start_daemon (flags, &port, zzuf_opt_profile (0), 0, &ahc_chunked_ext, ¶m, &req_completed, ¶m, NULL); if (NULL == d) return 99; /* Not an MHD error */ d_extern = (0 == (MHD_USE_INTERNAL_POLLING_THREAD & flags)) ? d : NULL; printf ("Running the deterministic (unfuzzed) chunk-extension " "self-check...\n"); fflush (stdout); for (i = 0; i < NUM_VALID_CHUNK_CASES; ++i) { const struct chunk_case *cc = chunk_cases + i; struct zzuf_raw_part parts[3]; char head[256]; char resp[512]; size_t resp_len = 0; size_t wire_len; size_t split; build_head (cc->name, 1, head, sizeof(head)); wire_len = strlen (cc->wire); split = wire_len / 2; parts[0].data = head; parts[0].size = strlen (head); parts[1].data = cc->wire; parts[1].size = split; parts[2].data = cc->wire + split; parts[2].size = wire_len - split; param.expect_body = cc->expected; param.body_matched = 0; if (ZZUF_RAW_SETUP_FAILED == zzuf_raw_exchange2 (d_extern, port, 1, parts, 3, (unsigned int) ZZUF_CLIENT_TIMEOUT, resp, sizeof(resp), &resp_len)) { fprintf (stderr, "The raw client could not be set up " "at line %d.\n", (int) __LINE__); MHD_stop_daemon (d); return 99; /* Not an MHD error */ } if (! param.body_matched) { fprintf (stderr, "Self-check FAILED for the chunk-extension case '%s': " "MHD did not decode the body as expected. " "At line %d.\n", cc->name, (int) __LINE__); ret = 1; } else if ((12 > resp_len) || (0 != memcmp (resp, "HTTP/1.1 200", 12))) { fprintf (stderr, "Self-check FAILED for the chunk-extension case '%s': " "MHD did not reply with '200'. " "At line %d.\n", cc->name, (int) __LINE__); ret = 1; } } MHD_stop_daemon (d); if (0 != param.err_flag) ret = 1; if (0 == ret) printf ("The chunk-extension self-check succeeded.\n"); fflush (stdout); return ret; } /** * Build the chunked body with a very long chunk extension. * * With a connection memory pool of 256 or 512 bytes the chunk-size line * does not fit into the read buffer, so MHD emits the 413 reply from * handle_req_chunk_size_line_no_space(). Before commit e04eb218 it then * re-entered the error path and discarded that reply, so this is also the * regression test for it. * * @return non-zero on success, zero on failure */ static int init_long_ext_body (void) { static const char head[] = "5;longext="; static const char tail[] = "\r\nHELLO\r\n0\r\n\r\n"; const size_t ext_len = 600; char *buf; buf = malloc (sizeof(head) + ext_len + sizeof(tail)); if (NULL == buf) return 0; memcpy (buf, head, MHD_STATICSTR_LEN_ (head)); memset (buf + MHD_STATICSTR_LEN_ (head), 'E', ext_len); memcpy (buf + MHD_STATICSTR_LEN_ (head) + ext_len, tail, sizeof(tail)); long_ext_body = buf; return ! 0; } int main (int argc, char *const *argv) { struct ahc_param param; struct zzuf_run_params rp; unsigned int res; int use_magic_exit_codes; zzuf_parse_common_args (argc, argv); use_put = zzuf_name_has ("_put"); use_chunked_reply = zzuf_name_has ("_get"); if (1 != ((use_put ? 1 : 0) + (use_chunked_reply ? 1 : 0))) { fprintf (stderr, "Wrong test name '%s': no or multiple indications " "for the test type.\n", (NULL != argv[0]) ? argv[0] : "(NULL)"); return 99; } use_magic_exit_codes = zzuf_run_with_socat || zzuf_dry_run; res = zzuf_check_runnable (); if (0 != res) return use_magic_exit_codes ? (int) res : 0; long_ext_body = NULL; if (! init_long_ext_body ()) { fprintf (stderr, "malloc() failed at line %d.\n", (int) __LINE__); return use_magic_exit_codes ? 99 : 0; } /* The self-check needs an unfuzzed channel to MHD, which only exists when zzuf fuzzes socat instead of this process. */ if (zzuf_run_with_socat && ! zzuf_dry_run) { res = run_self_check (); if (99 == res) { free (long_ext_body); return 99; } if (0 != res) { free (long_ext_body); return 1; } } param.magic = (unsigned int) TEST_MAGIC_MARKER; param.err_flag = 0; param.self_check = 0; param.expect_body = NULL; param.body_matched = 0; memset (&rp, 0, sizeof(rp)); rp.port = zzuf_pick_port (TEST_PORT_OFFSET); rp.ahc = &ahc_chunked_ext; rp.ahc_cls = ¶m; rp.rcc = &req_completed; rp.rcc_cls = ¶m; rp.mem_limit_override = 0; rp.sweep_profiles = 1; rp.profile_start = 0; rp.client = &client_run; rp.client_cls = ¶m; res = zzuf_run_polling_modes (&rp); free (long_ext_body); long_ext_body = NULL; if (99 == res) return use_magic_exit_codes ? 99 : 0; if (77 == res) return use_magic_exit_codes ? 77 : 0; return (0 == res) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testzzuf/README0000664000175000017500000003337515232103064013474 GNU libmicrohttpd -- fuzzing testsuite (src/testzzuf) ===================================================== The testcases in this directory require zzuf, and most of them also require socat. zzuf randomly mangles the TCP byte stream that reaches MHD. The goal is to expose problems in MHD's error handling by introducing random syntax errors into otherwise valid HTTP traffic. There are two modes of operation: * direct mode (zzuf_test_runner.sh) zzuf runs the test binary itself and intercepts the data that MHD reads from its accepted sockets. Only possible when MHD uses accept() (not accept4()) and when no sanitizer is active, because zzuf and the sanitizers both intercept the standard library. * socat mode (zzuf_socat_test_runner.sh) zzuf runs a socat relay that listens on 127.0.0.121:10121 and forwards the mangled stream to MHD on 127.0.0.1:4010. The test binary (and therefore MHD) runs outside of zzuf, so this mode works with sanitizers and with accept4(). configure selects this mode automatically when it is required (FORCE_USE_ZZUF_SOCAT). Because the byte stream is corrupted at random, the testcases do NOT check that whatever the client receives is what was expected. A testcase "fails" when MHD crashes, aborts, hangs, reports an internal inconsistency through its callbacks, or when a sanitizer fires. What is being tested -------------------- Every test starts a series of MHD daemons -- one per polling mode that the current build supports (internal select(), internal select() with thread-per-connection, internal poll(), internal poll() with thread-per-connection, internal epoll, external polling, external polling without thread safety) -- and runs a client against each of them. Clients come in two flavours: * libcurl clients, for everything libcurl can express; * a small raw socket client (mhd_zzuf_common.c), for everything libcurl cannot express: chunk extensions, request pipelining, header-less requests and hand-written "Authorization:" headers. Both flavours use 127.0.0.101 as their source address, while MHD listens on 127.0.0.1 (and socat on 127.0.0.121). zzuf is told to fuzz only the traffic of the server side address, so the data the *clients* read is left alone. The daemon option matrix ------------------------ Historically all fuzzing tests here used essentially one set of daemon options. Several MHD code paths are only reachable with other options, most importantly the read-buffer "shift back" in get_req_headers(), which is only executed when the connection memory pool is smaller than MHD_BUF_INC_SIZE (1500 bytes). mhd_zzuf_common.c therefore defines a matrix of option profiles: name mem_limit conn_limit timeout discipline ---------------- --------- ---------- ------- ------------------ plain - - 2 0 pool-128 128 - 2 0 pool-256-strict 256 - 2 1 pool-512-lax 512 - 2 -1 pool-1024-conn 1024 4 2 2 pool-1400-hard 1400 2 1 3 pool-768-loose 768 - 1 -3 legacy-strict 192 - 2 1 (STRICT_FOR_CLIENT) legacy-lax 320 - 2 -1 (STRICT_FOR_CLIENT) "discipline" is MHD_OPTION_CLIENT_DISCIPLINE_LVL, except for the two "legacy" profiles which use the older MHD_OPTION_STRICT_FOR_CLIENT so that the option translation code is covered as well. Every daemon that a test starts uses the next profile of the matrix, so a single run of one test program sweeps the whole matrix. MHD_OPTION_SERVER_INSANITY is deliberately *not* used: in this version of MHD the only value of "enum MHD_DisableSanityCheck" is MHD_DSC_SANE (0), so the option cannot actually disable any check. The test programs ----------------- All programs decide what to do from their own name (argv[0]). A "10" in the name selects HTTP/1.0, a "_close" suffix makes MHD close the connection after every reply, and a "_hostile" marker enables the option matrix described above. test_get, test_get_chunked, test_post, test_post_form, test_put, test_put_chunked, test_put_large, test_get_long_uri, test_get_long_header (+ "_close" and "10" variants) The original tests: well-formed libcurl traffic, single set of daemon options. test_get_hostile, test_get_chunked_hostile, test_post_hostile, test_put_chunked_hostile, test_put_large_hostile The very same client/server exchanges, but sweeping the daemon option matrix. test_get_args (+ "_close", "10") GET requests with hostile query strings: arguments without '=', empty names, empty values, trailing '&', percent-encoded and invalid percent-encoded names, duplicated names and a very long tail argument. All daemons of this test use a connection memory pool smaller than MHD_BUF_INC_SIZE. In addition to the libcurl requests, the raw client sends *header-less* HTTP/1.0 requests: libcurl always sends at least a "Host:" header, so with libcurl alone the last parsed element of a request header is always a header and never a query argument. test_get_chunked_ext, test_put_chunked_ext (+ "_close") Chunked request bodies whose chunk-size lines carry chunk extensions: "name=value", flags without a value, quoted-string values containing ';', several extensions on one line, extensions on the terminating "0" chunk, extensions after bad whitespace, an extension line longer than the whole memory pool, and trailers (footers) after the last chunk. The body is always split across two send() calls so that MHD sees partial chunk-size lines. Every third iteration appends a pipelined follow-up request, so a chunk-extension line that is not consumed correctly shows up as a request boundary de-synchronisation. test_get_chunked_ext additionally makes MHD answer with a chunked reply that carries a footer. These tests also run a small deterministic *self-check*, see below. test_pipelined (+ "_close") Two to five complete requests written with a single send() call, mixing GET/HEAD/POST/PUT, bodies with Content-Length, chunked bodies, and a leading empty line. Every other iteration the batch is split in the middle of a request. test_digest_auth (+ "_close") [only if ENABLE_DAUTH] libcurl performs a complete Digest handshake, so zzuf's bit flips land inside real "WWW-Authenticate:" and "Authorization:" headers. The raw client additionally sends hand-crafted "Authorization: Digest" headers with an unknown "algorithm" token, an empty "algorithm", a "-sess" algorithm, an over-long "response" (quoted and unquoted), an over-long hex userhash, an over-long username, a missing "response", garbage in "nc", an unterminated quoted string and a bare "Digest" scheme without parameters. The variants that have to survive MHD's nonce check are built from a nonce that the raw client first obtains from MHD's own 401 reply. test_basic_auth (+ "_close") [only if ENABLE_BAUTH] libcurl performs a Basic handshake; the raw client adds truncated Base64, characters outside the Base64 alphabet, payloads without the ':' separator, payloads decoding to binary zeros, padding in the middle, an empty value, a 4 KiB payload, whitespace inside the payload and an unknown authentication scheme. Automake conditionals used by this directory: FORCE_USE_ZZUF_SOCAT, USE_COVERAGE, VHEAVY_TESTS (already used before) ENABLE_DAUTH, ENABLE_BAUTH (new here) All of them are defined in configure.ac. The directory as a whole is only built when RUN_ZZUF_TESTS is true (see src/Makefile.am), which in turn requires --enable-heavy-tests and a usable libcurl. The deterministic self-check ---------------------------- Bit flipping can show that a parser crashes, but it cannot show that a parser produces the *wrong result*. test_get_chunked_ext and test_put_chunked_ext therefore also verify, once per run, that a chunked body with chunk extensions is decoded byte-exactly and answered with "200". That verification obviously must not be fuzzed. In socat mode zzuf only fuzzes the socat relay, so MHD's own port is a clean channel: the self-check connects to MHD directly, bypassing socat. In direct mode every byte that MHD accepts is fuzzed and no clean channel exists, so the self-check is silently skipped there. Since socat mode is mandatory whenever MHD is built with sanitizers, the sanitizer workflow below always includes the self-check. Running under the sanitizers ---------------------------- ./configure --enable-heavy-tests --enable-asserts \ --enable-sanitizers=address,undefined make make -C src/testzzuf check Enabling sanitizers automatically forces the socat mode (see configure.ac), because zzuf and the sanitizers cannot both intercept the standard library calls. The Makefile appends ASAN_OPTIONS=abort_on_error=1:detect_leaks=0 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 to whatever configure has already put into ASAN_OPTIONS / UBSAN_OPTIONS. Aborting on the first error is essential: otherwise the input that produced the error is lost. Leak detection is off because MHD legitimately abandons half-processed requests when the input is broken, and because the test process may be killed by zzuf. The values can be overridden per run: make ZZUF_ASAN_OPTIONS=abort_on_error=1:detect_leaks=1 check Seeds, replaying and sweeping ----------------------------- A single seed (the default is 0): make ZZUF_SEED=1234 check A range of seeds; zzuf starts one child per seed and stops at the first crash: make ZZUF_SEED_START=0 ZZUF_SEED_STOP=500 check ZZUF_SEED_START takes precedence over ZZUF_SEED. A large range takes a correspondingly long time, so for CI it is usually better to sweep a moderate range per job and to give different jobs different ranges. Both runner scripts print a prominent, easy to grep block when a test fails: ############################################################### ## FUZZING TEST FAILED ## test : ./test_get_args ## exit code : 134 ## seed(s) used: 0 ## FAILING SEED(S): 17 ## Replay a single failing seed with: ## make ZZUF_SEED=17 TESTS=test_get_args check ############################################################### In direct mode the failing seeds are extracted from zzuf's own per-child messages ("zzuf[s=17,r=...]: signal 6 (SIGABRT)"). In socat mode the test program runs outside of zzuf, so the runner reports the exit code (or the signal) of the *server side* together with the seed the run was started with. Other useful knobs: make ZZUF_FLAGS='--ratio=0.01:0.1' check extra zzuf flags make SOCAT_FLAGS='-v' check extra socat flags make TESTS='test_get_args test_pipelined' check run a subset ./configure --enable-heavy-tests=full 200 instead of 10 client iterations per daemon What zzuf-style fuzzing fundamentally cannot find ------------------------------------------------- This is important, because three of the four remotely triggerable bugs that were fixed on 2026-07-27 had been sitting in code that this directory nominally "covered". zzuf flips bits in an otherwise valid, libcurl-generated byte stream. That gives a *uniformly random* perturbation of a *structurally valid* input. Consequently: * It cannot invent structure that the generator never produces. libcurl never emits chunk extensions, never pipelines, never sends a request without a "Host:" header, and never sends an "Authorization:" header unless the test asks it to. No amount of bit flipping turns a libcurl request into a request with a chunk extension: the fuzzer would have to insert bytes, not change them, and it would have to keep the surrounding framing intact. * It essentially never produces a *semantically hostile but syntactically valid* token. "algorithm=BOGUS-ALGO" or a "response=" with 128 hex digits are perfectly well-formed HTTP; they are simply values a well-behaved client never sends. Random bit flips overwhelmingly produce inputs that MHD rejects in the first few hundred bytes of parsing, so the deep parsers are never reached with values that are valid enough to get there. Reaching the over-long "response" check even requires a *server generated* nonce, which a random mutation can never produce. * It only explores the option space that the tests configure. The read-buffer shift-back arithmetic simply does not run unless the connection memory pool is below 1500 bytes. * It only detects crashes and hangs. A parser that silently accepts a malformed chunk-extension line, or that mis-frames a request, looks exactly like a healthy parser to this suite unless the resulting memory access happens to be invalid. The additions described above buy back a good deal of this: the raw client provides the structures libcurl cannot express, the option matrix provides the configurations, and the deterministic self-check provides an oracle for "wrong result" instead of only "crash". But they do it by hand-writing interesting inputs, which does not generalise. The complementary approach is a structure-aware harness, which lives in src/fuzz/. There the HTTP request is *generated* from the fuzzer's random bytes (so the fuzzer can produce any header, any chunk extension, any authentication parameter, in any combination) and the fuzzer is coverage-guided, so it can learn its way into the deep parsers instead of stumbling into them. Use src/testzzuf for "does MHD survive a hostile network", and src/fuzz for "does MHD parse hostile HTTP correctly". libmicrohttpd-1.0.10/src/testzzuf/test_digest_auth.c0000664000175000017500000005224115232103064016310 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testzzuf/test_digest_auth.c * @brief Fuzzing testcase for Digest Authentication * @author Christian Grothoff * * The Digest Authentication parser of MHD used to be completely outside of * the reach of the fuzzing tests of this directory: no test ever produced * an "Authorization: Digest" header. * * This test closes that gap from two sides: * - libcurl performs a complete, well-formed digest handshake (two round * trips), so zzuf's bit flips land inside real "WWW-Authenticate:" and * "Authorization:" headers; * - the raw socket client sends hand-crafted "Authorization: Digest" * headers that are *syntactically* well-formed but semantically hostile * (unknown "algorithm" token, over-long "response", over-long userhash, * over-long username, missing parameters, ...). Random bit flipping * essentially never produces such an input; these headers have to be * written on purpose. * * The hostile headers that need a server generated nonce (everything that * is checked *after* the nonce validation) are built from the nonce that * MHD hands out in its own 401 reply, which the raw client parses. */ #include "platform.h" #include #include #include #include #include "mhd_zzuf_common.h" #define TEST_MAGIC_MARKER 0xFEE1C0DE #define DENIED_PAGE "Access denied." #define GRANTED_PAGE "Access granted." /** * The port offset used if the port cannot be auto-detected. */ #define TEST_PORT_OFFSET 155 #define TEST_REALM "TestRealm" #define TEST_OPAQUE "0123456789abcdef" #define TEST_USERNAME "testuser" #define TEST_PASSWORD "testpass" /** * The path that makes MHD issue an MD5 challenge (used by libcurl). */ #define URI_MD5 "/dauth/md5" /** * The path that makes MHD issue a SHA-256 challenge. A SHA-256 nonce is * needed to reach the code that decodes the client's "response" parameter * with a SHA-256 sized digest. */ #define URI_SHA256 "/dauth/sha256" #define HOST_HDR "Host: " ZZUF_MHD_LISTEN_IP "\r\n" /** * The size of the buffer used to build the raw requests. */ #define RAW_BUF_SIZE 2048 /** * The random data for the nonce generation. */ static const char digest_rnd_data[32] = { 'z','z','u','f','_','d','i','g','e','s','t','_','a','u','t','h', '_','r','a','n','d','o','m','_','s','e','e','d','_','0','0','1' }; /** * The closure of the access handler callback. */ struct ahc_param { /** * Must have #TEST_MAGIC_MARKER value. */ unsigned int magic; /** * Non-zero if any error has been encountered. */ unsigned int err_flag; /** * The number of successful authentications. */ unsigned int num_ok; }; static enum MHD_Result ahc_digest (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct ahc_param *param = (struct ahc_param *) cls; struct MHD_Response *response; enum MHD_Result ret; enum MHD_DigestAuthResult check_res; enum MHD_DigestAuthMultiAlgo3 challenge_algo; (void) method; (void) version; (void) upload_data; if ((NULL == param) || (TEST_MAGIC_MARKER != param->magic)) { fprintf (stderr, "The 'cls' parameter is invalid " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (NULL == *req_cls) { *req_cls = ▮ return MHD_YES; } if ((NULL != upload_data_size) && (0 != *upload_data_size)) { *upload_data_size = 0; /* Discard the body */ return MHD_YES; } /* This is the call that parses the (fuzzed or hand-crafted) client's "Authorization: Digest" header. */ check_res = MHD_digest_auth_check3 (connection, TEST_REALM, TEST_USERNAME, TEST_PASSWORD, 0 /* daemon default timeout */, 0 /* daemon default max nc */, MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT, MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION); if (MHD_DAUTH_OK == check_res) { param->num_ok++; response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ ( GRANTED_PAGE), GRANTED_PAGE); if (NULL == response) return MHD_NO; /* External error */ if (zzuf_use_close || ! zzuf_oneone) (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /* Not authenticated (or the header was broken): send a challenge. */ if ((NULL != url) && (0 == strcmp (url, URI_SHA256))) challenge_algo = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256; else challenge_algo = MHD_DIGEST_AUTH_MULT_ALGO3_MD5; response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED_PAGE), DENIED_PAGE); if (NULL == response) return MHD_NO; /* External error */ if (zzuf_use_close || ! zzuf_oneone) (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); ret = MHD_queue_auth_required_response3 (connection, TEST_REALM, TEST_OPAQUE, NULL, response, (MHD_DAUTH_NONCE_STALE == check_res) ? MHD_YES : MHD_NO, MHD_DIGEST_AUTH_MULT_QOP_AUTH, challenge_algo, MHD_YES /* userhash support */, MHD_NO); MHD_destroy_response (response); return ret; } /** * Extract the value of the "nonce" parameter from a reply. * * @param reply the reply, not necessarily zero-terminated * @param reply_len the number of valid bytes in @a reply * @param[out] nonce the buffer for the nonce * @param nonce_size the size of @a nonce * @return non-zero if a nonce has been extracted, zero otherwise */ static int extract_nonce (const char *reply, size_t reply_len, char *nonce, size_t nonce_size) { static const char marker[] = "nonce=\""; size_t i; if (reply_len < MHD_STATICSTR_LEN_ (marker) + 1) return 0; for (i = 0; i <= reply_len - MHD_STATICSTR_LEN_ (marker) - 1; ++i) { size_t k; if (0 != memcmp (reply + i, marker, MHD_STATICSTR_LEN_ (marker))) continue; i += MHD_STATICSTR_LEN_ (marker); for (k = 0; (i + k < reply_len) && (k + 1 < nonce_size); ++k) { if ('"' == reply[i + k]) { nonce[k] = 0; return (0 != k) ? ! 0 : 0; } if (('\r' == reply[i + k]) || ('\n' == reply[i + k])) return 0; nonce[k] = reply[i + k]; } return 0; } return 0; } /** * Fill @a buf with @a len hexadecimal digits and zero-terminate it. * * @param[out] buf the buffer to fill * @param len the number of digits to write */ static void fill_hex (char *buf, size_t len) { static const char hex[] = "0123456789abcdef"; size_t i; for (i = 0; i < len; ++i) buf[i] = hex[i % 16]; buf[len] = 0; } /** * Build one hostile "Authorization: Digest" request. * * @param variant the number of the variant to build * @param nonce the server generated nonce, may be an empty string * @param[out] buf the buffer for the request * @param buf_size the size of @a buf * @return the length of the request, or zero on failure */ static size_t build_hostile_request (unsigned int variant, const char *nonce, char *buf, size_t buf_size) { char big1[512]; char big2[512]; int len; switch (variant % 10) { case 0: /* An "algorithm" token that MHD does not know. Before the fix of 2026-07-27 this made MHD_digest_auth_check3() run into MHD_PANIC("Wrong 'malgo3' value, API violation") and abort(). No valid nonce is needed: the algorithm is checked first. */ len = snprintf (buf, buf_size, "GET " URI_MD5 " HTTP/1.1\r\n" HOST_HDR "Authorization: Digest username=\"" TEST_USERNAME "\", " "realm=\"" TEST_REALM "\", nonce=\"%s\", uri=\"" URI_MD5 "\", algorithm=BOGUS-ALGO, qop=auth, nc=00000001, " "cnonce=\"0a0b0c0d\", response=\"" "0123456789abcdef0123456789abcdef\"\r\n" "Connection: close\r\n\r\n", nonce); break; case 1: /* An empty (quoted) "algorithm" value. */ len = snprintf (buf, buf_size, "GET " URI_MD5 " HTTP/1.1\r\n" HOST_HDR "Authorization: Digest username=\"" TEST_USERNAME "\", " "realm=\"" TEST_REALM "\", nonce=\"%s\", uri=\"" URI_MD5 "\", algorithm=\"\", qop=auth, nc=00000001, " "cnonce=\"0a0b0c0d\", response=\"" "0123456789abcdef0123456789abcdef\"\r\n" "Connection: close\r\n\r\n", nonce); break; case 2: /* A "-sess" algorithm, which MHD does not support. */ len = snprintf (buf, buf_size, "GET " URI_MD5 " HTTP/1.1\r\n" HOST_HDR "Authorization: Digest username=\"" TEST_USERNAME "\", " "realm=\"" TEST_REALM "\", nonce=\"%s\", uri=\"" URI_MD5 "\", algorithm=MD5-sess, qop=auth, nc=00000001, " "cnonce=\"0a0b0c0d\", response=\"" "0123456789abcdef0123456789abcdef\"\r\n" "Connection: close\r\n\r\n", nonce); break; case 3: /* An over-long "response" together with a SHA-256 nonce. Before the fix of 2026-07-27 the hex decoder wrote 64 bytes into a 32 byte stack buffer. This needs a *valid* server nonce, otherwise the nonce check rejects the request before the "response" is decoded. */ fill_hex (big1, 128); len = snprintf (buf, buf_size, "GET " URI_SHA256 " HTTP/1.1\r\n" HOST_HDR "Authorization: Digest username=\"" TEST_USERNAME "\", " "realm=\"" TEST_REALM "\", nonce=\"%s\", uri=\"" URI_SHA256 "\", algorithm=SHA-256, qop=auth, " "nc=00000001, cnonce=\"0a0b0c0d\", response=\"%s\"\r\n" "Connection: close\r\n\r\n", nonce, big1); break; case 4: /* The same, unquoted. */ fill_hex (big1, 128); len = snprintf (buf, buf_size, "GET " URI_SHA256 " HTTP/1.1\r\n" HOST_HDR "Authorization: Digest username=\"" TEST_USERNAME "\", " "realm=\"" TEST_REALM "\", nonce=%s, uri=\"" URI_SHA256 "\", algorithm=SHA-256, qop=auth, " "nc=00000001, cnonce=\"0a0b0c0d\", response=%s\r\n" "Connection: close\r\n\r\n", nonce, big1); break; case 5: /* An over-long hex encoded userhash. */ fill_hex (big1, 256); fill_hex (big2, 64); len = snprintf (buf, buf_size, "GET " URI_SHA256 " HTTP/1.1\r\n" HOST_HDR "Authorization: Digest username=\"%s\", userhash=true, " "realm=\"" TEST_REALM "\", nonce=\"%s\", uri=\"" URI_SHA256 "\", algorithm=SHA-256, qop=auth, " "nc=00000001, cnonce=\"0a0b0c0d\", response=\"%s\"\r\n" "Connection: close\r\n\r\n", big1, nonce, big2); break; case 6: /* A very long username. */ fill_hex (big1, 500); len = snprintf (buf, buf_size, "GET " URI_MD5 " HTTP/1.1\r\n" HOST_HDR "Authorization: Digest username=\"%s\", " "realm=\"" TEST_REALM "\", nonce=\"%s\", uri=\"" URI_MD5 "\", algorithm=MD5, qop=auth, nc=00000001, " "cnonce=\"0a0b0c0d\", response=\"" "0123456789abcdef0123456789abcdef\"\r\n" "Connection: close\r\n\r\n", big1, nonce); break; case 7: /* No "response" parameter at all, plus the extended notation for the username. */ len = snprintf (buf, buf_size, "GET " URI_MD5 " HTTP/1.1\r\n" HOST_HDR "Authorization: Digest username*=UTF-8''%%41%%42, " "realm=\"" TEST_REALM "\", nonce=\"%s\", uri=\"" URI_MD5 "\", algorithm=MD5, qop=auth, nc=00000001, " "cnonce=\"0a0b0c0d\"\r\n" "Connection: close\r\n\r\n", nonce); break; case 8: /* Garbage in "nc" and an unterminated quoted string. */ len = snprintf (buf, buf_size, "GET " URI_MD5 " HTTP/1.1\r\n" HOST_HDR "Authorization: Digest username=\"" TEST_USERNAME "\", " "realm=\"" TEST_REALM "\", nonce=\"%s\", uri=\"" URI_MD5 "\", algorithm=MD5, qop=auth, nc=zzzzzzzz, " "cnonce=\"0a0b0c0d, response=\"" "0123456789abcdef0123456789abcdef\"\r\n" "Connection: close\r\n\r\n", nonce); break; case 9: default: /* A "Digest" scheme without any parameter, and a second, empty "Authorization" header. */ len = snprintf (buf, buf_size, "GET " URI_MD5 " HTTP/1.1\r\n" HOST_HDR "Authorization: Digest\r\n" "Authorization: \r\n" "Connection: close\r\n\r\n"); break; } if ((0 > len) || (buf_size <= (size_t) len)) return 0; return (size_t) len; } /** * Ask MHD for a challenge and extract the nonce from the reply. * * @param d_extern the daemon to drive, or NULL * @param port the port MHD is listening on * @param uri the URI to request * @param[out] nonce the buffer for the nonce * @param nonce_size the size of @a nonce */ static void fetch_nonce (struct MHD_Daemon *d_extern, uint16_t port, const char *uri, char *nonce, size_t nonce_size) { struct zzuf_raw_part part; char req[256]; char reply[2048]; size_t reply_len = 0; int len; nonce[0] = 0; len = snprintf (req, sizeof(req), "GET %s HTTP/1.1\r\n" HOST_HDR "Connection: close\r\n\r\n", uri); if ((0 > len) || (sizeof(req) <= (size_t) len)) return; part.data = req; part.size = (size_t) len; /* Bypass socat (when it is used): a nonce that has been mangled by zzuf is useless for building a request that must survive the nonce check. */ if (ZZUF_RAW_OK != zzuf_raw_exchange2 (d_extern, port, 1, &part, 1, (unsigned int) ZZUF_CLIENT_TIMEOUT, reply, sizeof(reply), &reply_len)) return; (void) extract_nonce (reply, reply_len, nonce, nonce_size); } static unsigned int client_run (struct MHD_Daemon *d_extern, uint16_t port, void *cls) { struct ahc_param *param = (struct ahc_param *) cls; struct zzuf_curl_driver drv; struct zzuf_curl_sink sink; char nonce_md5[256]; char nonce_sha256[256]; char *req; unsigned int i; unsigned int loops; loops = zzuf_loop_count (); if (! zzuf_curl_driver_init (&drv, d_extern)) return 99; /* Not an MHD error */ req = malloc (RAW_BUF_SIZE); if (NULL == req) { zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } nonce_md5[0] = 0; nonce_sha256[0] = 0; for (i = 0; i < loops; ++i) { CURL *c; struct zzuf_raw_part part; size_t req_len; const char *nonce; fprintf (stderr, "."); /* 1. A complete, well-formed digest handshake performed by libcurl. The traffic goes through the fuzzing layer. */ c = zzuf_curl_setup (port, URI_MD5, &sink); if (NULL == c) { free (req); zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, (long) CURLAUTH_DIGEST)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD, TEST_USERNAME ":" TEST_PASSWORD))) { curl_easy_cleanup (c); free (req); zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } zzuf_curl_driver_perform (&drv, c); curl_easy_cleanup (c); /* 2. Refresh the nonces from time to time: MHD only accepts a given nonce/nc combination once. */ if (0 == i % 2) { fetch_nonce (d_extern, port, URI_MD5, nonce_md5, sizeof(nonce_md5)); fetch_nonce (d_extern, port, URI_SHA256, nonce_sha256, sizeof(nonce_sha256)); } /* 3. The hand-crafted hostile headers. */ nonce = ((3 == i % 10) || (4 == i % 10) || (5 == i % 10)) ? nonce_sha256 : nonce_md5; req_len = build_hostile_request (i, nonce, req, RAW_BUF_SIZE); if (0 != req_len) { part.data = req; part.size = req_len; /* Once through the fuzzing layer ... */ if (ZZUF_RAW_SETUP_FAILED == zzuf_raw_exchange (d_extern, port, &part, 1, (unsigned int) ZZUF_CLIENT_TIMEOUT)) { free (req); zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } /* ... and once verbatim, so that the hostile header is guaranteed to reach the parser unmodified at least once. */ if (ZZUF_RAW_SETUP_FAILED == zzuf_raw_exchange2 (d_extern, port, 1, &part, 1, (unsigned int) ZZUF_CLIENT_TIMEOUT, NULL, 0, NULL)) { free (req); zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } } fflush (stderr); } free (req); zzuf_curl_driver_deinit (&drv); if (0 != param->err_flag) { fprintf (stderr, "One or more errors have been detected by the access " "handler callback function. At line %d.\n", (int) __LINE__); return 1; } return 0; } int main (int argc, char *const *argv) { struct ahc_param param; struct zzuf_run_params rp; struct MHD_OptionItem extra_opts[3]; unsigned int res; int use_magic_exit_codes; zzuf_parse_common_args (argc, argv); use_magic_exit_codes = zzuf_run_with_socat || zzuf_dry_run; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH)) { fprintf (stderr, "Digest Authentication is not supported by this " "MHD build.\n"); return use_magic_exit_codes ? 77 : 0; } res = zzuf_check_runnable (); if (0 != res) return use_magic_exit_codes ? (int) res : 0; if (CURLE_OK != curl_global_init (CURL_GLOBAL_WIN32)) { fprintf (stderr, "curl_global_init() failed at line %d.\n", (int) __LINE__); return use_magic_exit_codes ? 99 : 0; } param.magic = (unsigned int) TEST_MAGIC_MARKER; param.err_flag = 0; param.num_ok = 0; extra_opts[0].option = MHD_OPTION_DIGEST_AUTH_RANDOM; extra_opts[0].value = (intptr_t) sizeof(digest_rnd_data); extra_opts[0].ptr_value = (void *) (intptr_t) digest_rnd_data; extra_opts[1].option = MHD_OPTION_NONCE_NC_SIZE; extra_opts[1].value = (intptr_t) 300; extra_opts[1].ptr_value = NULL; extra_opts[2].option = MHD_OPTION_END; extra_opts[2].value = 0; extra_opts[2].ptr_value = NULL; memset (&rp, 0, sizeof(rp)); rp.port = zzuf_pick_port (TEST_PORT_OFFSET); rp.ahc = &ahc_digest; rp.ahc_cls = ¶m; rp.rcc = NULL; rp.rcc_cls = NULL; /* The digest headers are large, use a memory limit that can hold them. */ rp.mem_limit_override = 4096; rp.sweep_profiles = 1; rp.profile_start = 0; rp.client = &client_run; rp.client_cls = ¶m; rp.extra_opts = extra_opts; res = zzuf_run_polling_modes (&rp); curl_global_cleanup (); if (99 == res) return use_magic_exit_codes ? 99 : 0; if (77 == res) return use_magic_exit_codes ? 77 : 0; return (0 == res) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testzzuf/zzuf_test_runner.sh0000775000175000017500000001366615232103064016602 #!/bin/sh # # Run one fuzzing test with zzuf intercepting the network input of the # test process itself. # # Recognised environment variables: # ZZUF the zzuf command (set by configure) # ZZUF_SEED the single seed to use (default "0") # ZZUF_SEED_START the first seed of a seed range (overrides ZZUF_SEED) # ZZUF_SEED_STOP the last seed of a seed range # ZZUF_FLAGS additional flags for zzuf # SOCAT the socat command (set by configure) # SOCAT_FLAGS additional flags for socat # # This script is POSIX shell only, do not use any bashism. mhd_listen_ip='127.0.0.1' max_runtime_sec='1800' if test "x${ZZUF}" = "xno" ; then echo "zzuf command missing" 1>&2 exit 77 fi if command -v "${ZZUF}" > /dev/null 2>&1 ; then : ; else echo "zzuf command missing" 1>&2 exit 77 fi # Build the "--seed" parameter for zzuf. # A seed range makes zzuf start one child per seed, which is what CI uses # to sweep a large number of seeds. zzuf_seed_param='' if test -n "${ZZUF_SEED_START}" ; then if test -n "${ZZUF_SEED_STOP}" ; then zzuf_seed_param="--seed=${ZZUF_SEED_START}:${ZZUF_SEED_STOP}" seed_descr="range ${ZZUF_SEED_START}:${ZZUF_SEED_STOP}" else zzuf_seed_param="--seed=${ZZUF_SEED_START}" seed_descr="${ZZUF_SEED_START}" fi elif test -n "${ZZUF_SEED}" ; then zzuf_seed_param="--seed=${ZZUF_SEED}" seed_descr="${ZZUF_SEED}" else seed_descr="(zzuf default)" fi test_log='' cleanup_log () { if test -n "${test_log}" ; then rm -f "${test_log}" test_log='' fi } # Print a loud, easy to grep report about a failing run, including the # seed(s) that produced the failure. # $1: the exit code of zzuf report_failure () { failed_seeds='' if test -n "${test_log}" && test -r "${test_log}" ; then # zzuf prints one line per child, e.g. # zzuf[s=17,r=0.012345]: signal 6 (SIGABRT) failed_seeds=`grep -E '^zzuf\[s=[0-9]+' "${test_log}" 2> /dev/null | \ grep -E 'signal|exit|crash|abort|too (slow|much|many)' 2> /dev/null | \ sed -e 's/^zzuf\[s=//' -e 's/[^0-9].*$//' | \ sort -n -u | tr '\n' ' '` fi echo '' 1>&2 echo '###############################################################' 1>&2 echo '## FUZZING TEST FAILED' 1>&2 echo "## test : ${test_descr}" 1>&2 echo "## exit code : $1" 1>&2 echo "## seed(s) used: ${seed_descr}" 1>&2 if test -n "${failed_seeds}" ; then echo "## FAILING SEED(S): ${failed_seeds}" 1>&2 echo '## Replay a single failing seed with:' 1>&2 for one_seed in ${failed_seeds} ; do echo "## make ZZUF_SEED=${one_seed} TESTS=${test_name} check" 1>&2 done else echo '## No failing seed could be extracted from the zzuf output.' 1>&2 echo '## Replay the whole run with:' 1>&2 if test -n "${ZZUF_SEED_START}" ; then echo "## make ZZUF_SEED_START=${ZZUF_SEED_START} \ ZZUF_SEED_STOP=${ZZUF_SEED_STOP} TESTS=${test_name} check" 1>&2 else echo "## make ZZUF_SEED=${ZZUF_SEED} TESTS=${test_name} check" 1>&2 fi fi echo '###############################################################' 1>&2 echo '' 1>&2 } run_with_socat () { echo "Trying to run the test with socat..." script_dir="" if command -v dirname > /dev/null 2>&1 ; then test_dir=`dirname /` if test "x${test_dir}" = "x/" ; then if dirname "$1" > /dev/null 2>&1 ; then script_dir=`dirname "$1"` if test -n "${script_dir}" ; then # Assume script is not in the root dir script_dir="${script_dir}/" else script_dir="./" fi fi fi fi if test -z "${script_dir}" ; then if echo "$1" | sed 's|[^/]*$||' > /dev/null 2>&1 ; then script_dir=`echo "$1" | sed 's|[^/]*$||'` if test -z "${script_dir}" ; then script_dir="./" fi fi fi if test -z "${script_dir}" ; then echo "Cannot determine script location, will try current directory." 1>&2 script_dir="./" fi cleanup_log $SHELL "${script_dir}zzuf_socat_test_runner.sh" "$@" exit $? } test_descr="$*" test_name=`echo "$1" | sed 's|^.*/||'` trap 'cleanup_log' EXIT # zzuf cannot pass-through the return value of checked program # so try the direct dry-run first to get possible 77 or 99 codes echo "## Dry-run of the $* ..." if "$@" --dry-run ; then echo "# Dry-run succeeded." else res_code=$? echo "Dry-run failed with exit code $res_code." 1>&2 if test $res_code -ne 99; then run_with_socat "$@" fi echo "$* will not be run with zzuf." 1>&2 exit $res_code fi # fuzz the input only for IP ${mhd_listen_ip}. libcurl and the raw client # use another IP in these tests, therefore the input of the clients is not # fuzzed. zzuf_all_params="--ratio=0.001:0.4 --autoinc --verbose --signal \ --max-usertime=${max_runtime_sec} --check-exit --network \ --allow=${mhd_listen_ip} --exclude=." if test -n "${zzuf_seed_param}" ; then zzuf_all_params="${zzuf_all_params} ${zzuf_seed_param}" fi if test -n "${ZZUF_FLAGS}" ; then zzuf_all_params="${zzuf_all_params} ${ZZUF_FLAGS}" fi # Uncomment the next line to see more data in logs #zzuf_all_params="${zzuf_all_params} -dd" echo "## Dry-run of the $* with zzuf..." if "$ZZUF" ${zzuf_all_params} "$@" --dry-run ; then echo "# Dry-run with zzuf succeeded." else res_code=$? echo "$* cannot be run with zzuf directly." 1>&2 run_with_socat "$@" exit $res_code fi echo "## Real test of $* with zzuf (seed: ${seed_descr})..." if command -v tee > /dev/null 2>&1 ; then test_log="${TMPDIR:-/tmp}/mhd_zzuf_$$.log" rc_file="${test_log}.rc" { "$ZZUF" ${zzuf_all_params} "$@" ; echo $? > "${rc_file}" ; } 2>&1 | \ tee "${test_log}" if test -r "${rc_file}" ; then res_code=`cat "${rc_file}"` else res_code=1 fi rm -f "${rc_file}" else # No 'tee': run without capturing, the failing seed has to be taken # from the test log by hand. "$ZZUF" ${zzuf_all_params} "$@" res_code=$? fi if test "x${res_code}" != "x0" ; then report_failure "${res_code}" fi cleanup_log exit ${res_code} libmicrohttpd-1.0.10/src/testzzuf/mhd_debug_funcs.c0000644000175000017500000000551214760713574016104 /* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file testzzuf/mhd_debug_funcs.c * @brief Implementations of MHD private debug functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_debug_funcs.h" #include "internal.h" #include "mhd_sockets.h" /** * Checks whether MHD can use accept() syscall and * avoid accept4() syscall. * @return non-zero if accept() is possible, * zero if accept4() is always used by MHD */ int MHD_is_avoid_accept4_possible_ (void) { #if ! defined(USE_ACCEPT4) return ! 0; #else /* ! USE_ACCEPT4 */ return (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_DEBUG_BUILD)) ? ! 0 : 0; #endif /* ! USE_ACCEPT4 */ } /** * Switch MHD daemon to use accept() syscalls for new connections. * @param daemon the daemon to operate */ void MHD_avoid_accept4_ (struct MHD_Daemon *daemon) { (void) daemon; /* Mute compiler warning */ #ifdef USE_ACCEPT4 #ifdef _DEBUG daemon->avoid_accept4 = true; #else /* ! _DEBUG */ abort (); #endif /* ! _DEBUG */ #endif /* USE_ACCEPT4 */ } #ifdef MHD_ASAN_ACTIVE #define MHD_ASAN_ENABLED_ 1 #else /* ! MHD_ASAN_ACTIVE */ #ifdef __SANITIZE_ADDRESS__ #define MHD_ASAN_ENABLED_ 1 #else /* ! __SANITIZE_ADDRESS__ */ #if defined(__has_feature) #if __has_feature(address_sanitizer) #define MHD_ASAN_ENABLED_ 1 #endif /* __has_feature(address_sanitizer) */ #endif /* __has_feature */ #endif /* ! __SANITIZE_ADDRESS__ */ #endif /* ! MHD_ASAN_ACTIVE */ /** * Checks whether any know sanitizer is enabled for this build. * zzuf does not work together with sanitizers as both are intercepting * standard library calls. * @return non-zero if any sanitizer is enabled, * zero otherwise */ int MHD_are_sanitizers_enabled_ (void) { int ret = 0; #ifdef MHD_ASAN_ENABLED_ ++ret; #endif /* ! MHD_ASAN_ENABLED_ */ #if defined(__has_feature) #if __has_feature(thread_sanitizer) ++ret; #endif #if __has_feature(memory_sanitizer) ++ret; #endif #if __has_feature(dataflow_sanitizer) ++ret; #endif #else /* ! defined(__has_feature) */ #ifdef __SANITIZE_THREAD__ ++ret; #endif #endif /* ! defined(__has_feature) */ return ret; } libmicrohttpd-1.0.10/src/testzzuf/test_get_args.c0000664000175000017500000003216515232103064015606 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testzzuf/test_get_args.c * @brief Fuzzing testcase for GET requests with hostile query strings * @author Christian Grothoff * * The point of this test is the combination of * - query strings that contain arguments *without* the '=' character, * empty names, empty values, trailing '&', percent-encoded names and * a very long tail argument, and * - a very small connection memory pool (below MHD_BUF_INC_SIZE == 1500). * * Only with a pool that small does MHD try to re-use the tail of the * request header buffer ("shift back", see get_req_headers() in * connection.c), and the position of the end of the *last parsed element* * is used for the pointer arithmetic there. For an argument without '=' * that element has no value at all, so the "end of the value" is not a * valid pointer. * * libcurl always sends at least a "Host:" header, so with libcurl alone * the last parsed element is always a header and never a query argument. * Therefore this test additionally uses the raw socket client to send * header-less HTTP/1.0 requests, for which the last parsed element really * is the trailing query argument. */ #include "platform.h" #include #include #include #include #include "mhd_zzuf_common.h" #define TEST_MAGIC_MARKER 0xFEE1C0DE #define EMPTY_PAGE "Empty page." /** * The port offset used if the port cannot be auto-detected. */ #define TEST_PORT_OFFSET 140 /** * The length of the "very long" trailing argument. * Deliberately larger than the largest memory pool of the option matrix, * so that MHD has to reject some of the requests as "too large" as well. */ #define LONG_ARG_LEN 700 /** * The closure of the access handler callback. */ struct ahc_param { /** * Must have #TEST_MAGIC_MARKER value. */ unsigned int magic; /** * Non-zero if any error has been encountered. */ unsigned int err_flag; /** * The checksum over all seen arguments, only used to make sure that * the compiler cannot optimise the memory accesses away. */ unsigned int arg_sum; }; /** * The query strings used by the libcurl-driven part of the test. * Every one of them ends with an element that has no '=' character. */ static const char *const query_strings[] = { "/test_uri?a=1&b&c=&d", "/test_uri?x&y=&z=%20%41&trail", "/test_uri?%61%62=%63&noeq", "/test_uri?one=1&&two=2&", "/test_uri?=novalue&=&x", "/test_uri?a=1;b=2&c", "/test_uri?%zz=%2&broken%", "/test_uri?dup=1&dup=2&dup" }; /** * The raw (header-less) requests. Filled in by init_raw_requests(). */ static char *raw_requests[6]; /** * Build the raw requests used by this test. * * @return non-zero on success, zero on failure */ static int init_raw_requests (void) { static const char *const tails[] = { /* Last element of the request has no '=': the interesting case. */ "/test_uri?a=1&b HTTP/1.0\r\n\r\n", "/test_uri?trailing_argument_without_equals_sign HTTP/1.0\r\n\r\n", "/test_uri?a=1&b=2& HTTP/1.0\r\n\r\n", "/test_uri?= HTTP/1.0\r\n\r\n" }; size_t i; char *buf; for (i = 0; i < sizeof(tails) / sizeof(tails[0]); ++i) { const size_t len = strlen ("GET ") + strlen (tails[i]); buf = malloc (len + 1); if (NULL == buf) return 0; memcpy (buf, "GET ", strlen ("GET ")); memcpy (buf + strlen ("GET "), tails[i], strlen (tails[i]) + 1); raw_requests[i] = buf; } /* A header-less request with a very long trailing argument without '=' */ buf = malloc (LONG_ARG_LEN + 64); if (NULL == buf) return 0; memcpy (buf, "GET /t?k=v&", strlen ("GET /t?k=v&")); memset (buf + strlen ("GET /t?k=v&"), 'L', LONG_ARG_LEN); memcpy (buf + strlen ("GET /t?k=v&") + LONG_ARG_LEN, " HTTP/1.0\r\n\r\n", strlen (" HTTP/1.0\r\n\r\n") + 1); raw_requests[4] = buf; /* The same, but with a single (minimal) header line, so that the last parsed element is a header and the "normal" branch is taken with the very same (small) memory pool. */ buf = malloc (LONG_ARG_LEN + 96); if (NULL == buf) return 0; memcpy (buf, "GET /t?k=v&", strlen ("GET /t?k=v&")); memset (buf + strlen ("GET /t?k=v&"), 'L', LONG_ARG_LEN); memcpy (buf + strlen ("GET /t?k=v&") + LONG_ARG_LEN, " HTTP/1.1\r\nHost: a\r\n\r\n", strlen (" HTTP/1.1\r\nHost: a\r\n\r\n") + 1); raw_requests[5] = buf; return ! 0; } /** * Free the raw requests. */ static void free_raw_requests (void) { size_t i; for (i = 0; i < sizeof(raw_requests) / sizeof(raw_requests[0]); ++i) { if (NULL != raw_requests[i]) free (raw_requests[i]); raw_requests[i] = NULL; } } /** * Touch every byte of every key and value so that the sanitizers (or * the operating system) notice pointers into unmapped memory. * * @param cls the closure * @param kind the kind of the value * @param key the key, never NULL * @param key_size the size of @a key * @param value the value, may be NULL for arguments without '=' * @param value_size the size of @a value * @return #MHD_YES to continue the iteration */ static enum MHD_Result arg_iterator (void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct ahc_param *param = (struct ahc_param *) cls; size_t i; (void) kind; /* Unused. Mute compiler warning. */ if (TEST_MAGIC_MARKER != param->magic) { fprintf (stderr, "The 'param->magic' has wrong value " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if ((NULL == key) && (0 != key_size)) { fprintf (stderr, "The 'key' is NULL while 'key_size' is not zero " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_YES; } if ((NULL == value) && (0 != value_size)) { fprintf (stderr, "The 'value' is NULL while 'value_size' is not zero " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_YES; } for (i = 0; i < key_size; ++i) param->arg_sum += (unsigned int) (unsigned char) key[i]; for (i = 0; i < value_size; ++i) param->arg_sum += (unsigned int) (unsigned char) value[i]; /* Also touch the zero-termination that MHD guarantees. */ if (NULL != key) param->arg_sum += (unsigned int) (unsigned char) key[key_size]; if (NULL != value) param->arg_sum += (unsigned int) (unsigned char) value[value_size]; return MHD_YES; } static enum MHD_Result ahc_args (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct ahc_param *param = (struct ahc_param *) cls; struct MHD_Response *response; enum MHD_Result ret; const char *val; (void) url; (void) method; (void) version; (void) upload_data; if ((NULL == param) || (TEST_MAGIC_MARKER != param->magic)) { fprintf (stderr, "The 'cls' parameter is invalid " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (NULL == *req_cls) { *req_cls = ▮ return MHD_YES; } if ((NULL != upload_data_size) && (0 != *upload_data_size)) { *upload_data_size = 0; /* Discard any body */ return MHD_YES; } /* Walk over all arguments; this is what dereferences the (possibly broken) pointers stored while the request line was parsed. */ (void) MHD_get_connection_values_n (connection, MHD_GET_ARGUMENT_KIND, &arg_iterator, param); /* Also walk over the headers, so that a corrupted header list is detected as well. */ (void) MHD_get_connection_values_n (connection, MHD_HEADER_KIND, &arg_iterator, param); /* Lookups of both present and absent keys, including a key that is known to be present without a value. */ val = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "b"); if (NULL != val) param->arg_sum += (unsigned int) strlen (val); val = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "a"); if (NULL != val) param->arg_sum += (unsigned int) strlen (val); val = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "no_such_argument"); if (NULL != val) param->arg_sum += (unsigned int) strlen (val); response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (EMPTY_PAGE), EMPTY_PAGE); if (NULL == response) { fprintf (stderr, "MHD_create_response_from_buffer_static() failed " "at line %d.\n", (int) __LINE__); return MHD_NO; /* External error, do not raise the error flag */ } ret = MHD_YES; if (zzuf_use_close || ! zzuf_oneone) ret = MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); if (MHD_YES == ret) ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static unsigned int client_run (struct MHD_Daemon *d_extern, uint16_t port, void *cls) { struct ahc_param *param = (struct ahc_param *) cls; struct zzuf_curl_driver drv; struct zzuf_curl_sink sink; unsigned int i; unsigned int loops; loops = zzuf_loop_count (); if (! zzuf_curl_driver_init (&drv, d_extern)) return 99; /* Not an MHD error */ for (i = 0; i < loops; ++i) { CURL *c; const unsigned int num_q = (unsigned int) (sizeof(query_strings) / sizeof(query_strings[0])); const unsigned int num_r = (unsigned int) (sizeof(raw_requests) / sizeof(raw_requests[0])); fprintf (stderr, "."); c = zzuf_curl_setup (port, query_strings[i % num_q], &sink); if (NULL == c) { zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } zzuf_curl_driver_perform (&drv, c); curl_easy_cleanup (c); /* The raw, header-less requests: only these can make a query argument the last parsed element of the request header. */ if (ZZUF_RAW_SETUP_FAILED == zzuf_raw_request (d_extern, port, raw_requests[i % num_r])) { fprintf (stderr, "The raw client could not be set up " "at line %d.\n", (int) __LINE__); zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } fflush (stderr); } zzuf_curl_driver_deinit (&drv); if (0 != param->err_flag) { fprintf (stderr, "One or more errors have been detected by the access " "handler callback function. At line %d.\n", (int) __LINE__); return 1; } return 0; } int main (int argc, char *const *argv) { struct ahc_param param; struct zzuf_run_params rp; unsigned int res; int use_magic_exit_codes; zzuf_parse_common_args (argc, argv); use_magic_exit_codes = zzuf_run_with_socat || zzuf_dry_run; res = zzuf_check_runnable (); if (0 != res) return use_magic_exit_codes ? (int) res : 0; if (CURLE_OK != curl_global_init (CURL_GLOBAL_WIN32)) { fprintf (stderr, "curl_global_init() failed at line %d.\n", (int) __LINE__); return use_magic_exit_codes ? 99 : 0; } memset (raw_requests, 0, sizeof(raw_requests)); if (! init_raw_requests ()) { fprintf (stderr, "malloc() failed at line %d.\n", (int) __LINE__); free_raw_requests (); curl_global_cleanup (); return use_magic_exit_codes ? 99 : 0; } param.magic = (unsigned int) TEST_MAGIC_MARKER; param.err_flag = 0; param.arg_sum = 0; memset (&rp, 0, sizeof(rp)); rp.port = zzuf_pick_port (TEST_PORT_OFFSET); rp.ahc = &ahc_args; rp.ahc_cls = ¶m; rp.rcc = NULL; rp.rcc_cls = NULL; rp.mem_limit_override = 0; /* Use the small pools of the option matrix */ rp.sweep_profiles = 1; rp.profile_start = 1; /* Skip the "plain" (large pool) profile */ rp.client = &client_run; rp.client_cls = ¶m; res = zzuf_run_polling_modes (&rp); free_raw_requests (); curl_global_cleanup (); if (99 == res) return use_magic_exit_codes ? 99 : 0; if (77 == res) return use_magic_exit_codes ? 77 : 0; return (0 == res) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testzzuf/test_basic_auth.c0000664000175000017500000003062315232103064016112 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testzzuf/test_basic_auth.c * @brief Fuzzing testcase for Basic Authentication * @author Christian Grothoff * * Before this test existed, no fuzzing test of this directory ever sent an * "Authorization:" header, so neither the Base64 decoder nor the username / * password splitting of MHD were reachable by the fuzzer at all. * * libcurl performs a normal Basic Authentication handshake (so that zzuf's * bit flips land inside a real "Authorization: Basic" header) and the raw * socket client adds hand-crafted headers with Base64 payloads that are * truncated, over-long, contain characters outside the Base64 alphabet, * decode to data with binary zeros or lack the ':' separator entirely. */ #include "platform.h" #include #include #include #include #include "mhd_zzuf_common.h" #define TEST_MAGIC_MARKER 0xFEE1C0DE #define DENIED_PAGE "Access denied." #define GRANTED_PAGE "Access granted." /** * The port offset used if the port cannot be auto-detected. */ #define TEST_PORT_OFFSET 165 #define TEST_REALM "TestRealm" #define TEST_USERNAME "testuser" #define TEST_PASSWORD "testpass" #define TEST_URI "/bauth" #define HOST_HDR "Host: " ZZUF_MHD_LISTEN_IP "\r\n" /** * The size of the buffer used to build the raw requests. */ #define RAW_BUF_SIZE 8192 /** * The closure of the access handler callback. */ struct ahc_param { /** * Must have #TEST_MAGIC_MARKER value. */ unsigned int magic; /** * Non-zero if any error has been encountered. */ unsigned int err_flag; /** * The checksum over the decoded credentials, only used so that the * compiler cannot optimise the memory accesses away. */ unsigned int cred_sum; }; static enum MHD_Result ahc_basic (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct ahc_param *param = (struct ahc_param *) cls; struct MHD_BasicAuthInfo *creds; struct MHD_Response *response; enum MHD_Result ret; int authenticated = 0; (void) url; (void) method; (void) version; (void) upload_data; if ((NULL == param) || (TEST_MAGIC_MARKER != param->magic)) { fprintf (stderr, "The 'cls' parameter is invalid " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (NULL == *req_cls) { *req_cls = ▮ return MHD_YES; } if ((NULL != upload_data_size) && (0 != *upload_data_size)) { *upload_data_size = 0; /* Discard the body */ return MHD_YES; } /* This is the call that decodes the (fuzzed or hand-crafted) client's "Authorization: Basic" header. */ creds = MHD_basic_auth_get_username_password3 (connection); if (NULL != creds) { size_t i; if (NULL == creds->username) { fprintf (stderr, "The 'username' member is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } else { /* Touch every byte, including the zero-termination that MHD guarantees. */ for (i = 0; i <= creds->username_len; ++i) param->cred_sum += (unsigned int) (unsigned char) creds->username[i]; } if (NULL == creds->password) { if (0 != creds->password_len) { fprintf (stderr, "The 'password' is NULL while 'password_len' is " "not zero at line %d.\n", (int) __LINE__); param->err_flag = 1; } } else { for (i = 0; i <= creds->password_len; ++i) param->cred_sum += (unsigned int) (unsigned char) creds->password[i]; } if ((NULL != creds->username) && (MHD_STATICSTR_LEN_ (TEST_USERNAME) == creds->username_len) && (0 == memcmp (creds->username, TEST_USERNAME, MHD_STATICSTR_LEN_ (TEST_USERNAME))) && (NULL != creds->password) && (MHD_STATICSTR_LEN_ (TEST_PASSWORD) == creds->password_len) && (0 == memcmp (creds->password, TEST_PASSWORD, MHD_STATICSTR_LEN_ (TEST_PASSWORD)))) authenticated = 1; MHD_free (creds); } if (authenticated) { response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ ( GRANTED_PAGE), GRANTED_PAGE); if (NULL == response) return MHD_NO; /* External error */ if (zzuf_use_close || ! zzuf_oneone) (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (DENIED_PAGE), DENIED_PAGE); if (NULL == response) return MHD_NO; /* External error */ if (zzuf_use_close || ! zzuf_oneone) (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); ret = MHD_queue_basic_auth_required_response3 (connection, TEST_REALM, MHD_NO, response); MHD_destroy_response (response); return ret; } /** * Build one hostile "Authorization: Basic" request. * * @param variant the number of the variant to build * @param[out] buf the buffer for the request * @param buf_size the size of @a buf * @return the length of the request, or zero on failure */ static size_t build_hostile_request (unsigned int variant, char *buf, size_t buf_size) { static const char b64_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; char big[4096]; const char *value; size_t i; int len; switch (variant % 10) { case 0: /* A truncated Base64 payload (not a multiple of four). */ value = "dGVzdHVzZXI"; break; case 1: /* Characters outside the Base64 alphabet. */ value = "!!!!\?\?\?\?===="; /* '?' escaped to avoid a trigraph */ break; case 2: /* Valid Base64 that decodes to a string without ':' separator. */ value = "dGVzdHVzZXI="; break; case 3: /* Valid Base64 that decodes to "\0:\0" (binary zeros). */ value = "ADoA"; break; case 4: /* Valid Base64 that decodes to ":" only (empty username). */ value = "Og=="; break; case 5: /* Padding in the middle of the payload. */ value = "dGVz=dXNlcjpwYXNz"; break; case 6: /* An empty value. */ value = ""; break; case 7: /* A very long, but valid, Base64 payload. */ for (i = 0; i + 1 < sizeof(big); ++i) big[i] = b64_alphabet[i % 64]; big[sizeof(big) - 1] = 0; value = big; break; case 8: /* Whitespace inside the payload. */ value = "dGVz dXNl cjpw YXNz"; break; case 9: default: /* An unknown scheme, and a second "Authorization" header. */ len = snprintf (buf, buf_size, "GET " TEST_URI " HTTP/1.1\r\n" HOST_HDR "Authorization: Bearer dGVzdHVzZXI6dGVzdHBhc3M=\r\n" "Authorization: Basic\r\n" "Connection: close\r\n\r\n"); if ((0 > len) || (buf_size <= (size_t) len)) return 0; return (size_t) len; } len = snprintf (buf, buf_size, "GET " TEST_URI " HTTP/1.1\r\n" HOST_HDR "Authorization: Basic %s\r\n" "Connection: close\r\n\r\n", value); if ((0 > len) || (buf_size <= (size_t) len)) return 0; return (size_t) len; } static unsigned int client_run (struct MHD_Daemon *d_extern, uint16_t port, void *cls) { struct ahc_param *param = (struct ahc_param *) cls; struct zzuf_curl_driver drv; struct zzuf_curl_sink sink; char *req; unsigned int i; unsigned int loops; loops = zzuf_loop_count (); if (! zzuf_curl_driver_init (&drv, d_extern)) return 99; /* Not an MHD error */ req = malloc (RAW_BUF_SIZE); if (NULL == req) { zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } for (i = 0; i < loops; ++i) { CURL *c; struct zzuf_raw_part part; size_t req_len; fprintf (stderr, "."); /* 1. A well-formed Basic Authentication handshake by libcurl, going through the fuzzing layer. */ c = zzuf_curl_setup (port, TEST_URI, &sink); if (NULL == c) { free (req); zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTPAUTH, (long) CURLAUTH_BASIC)) || (CURLE_OK != curl_easy_setopt (c, CURLOPT_USERPWD, TEST_USERNAME ":" TEST_PASSWORD))) { curl_easy_cleanup (c); free (req); zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } zzuf_curl_driver_perform (&drv, c); curl_easy_cleanup (c); /* 2. The hand-crafted hostile headers. */ req_len = build_hostile_request (i, req, RAW_BUF_SIZE); if (0 != req_len) { part.data = req; part.size = req_len; /* Once through the fuzzing layer ... */ if (ZZUF_RAW_SETUP_FAILED == zzuf_raw_exchange (d_extern, port, &part, 1, (unsigned int) ZZUF_CLIENT_TIMEOUT)) { free (req); zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } /* ... and once verbatim. */ if (ZZUF_RAW_SETUP_FAILED == zzuf_raw_exchange2 (d_extern, port, 1, &part, 1, (unsigned int) ZZUF_CLIENT_TIMEOUT, NULL, 0, NULL)) { free (req); zzuf_curl_driver_deinit (&drv); return 99; /* Not an MHD error */ } } fflush (stderr); } free (req); zzuf_curl_driver_deinit (&drv); if (0 != param->err_flag) { fprintf (stderr, "One or more errors have been detected by the access " "handler callback function. At line %d.\n", (int) __LINE__); return 1; } return 0; } int main (int argc, char *const *argv) { struct ahc_param param; struct zzuf_run_params rp; unsigned int res; int use_magic_exit_codes; zzuf_parse_common_args (argc, argv); use_magic_exit_codes = zzuf_run_with_socat || zzuf_dry_run; if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_BASIC_AUTH)) { fprintf (stderr, "Basic Authentication is not supported by this " "MHD build.\n"); return use_magic_exit_codes ? 77 : 0; } res = zzuf_check_runnable (); if (0 != res) return use_magic_exit_codes ? (int) res : 0; if (CURLE_OK != curl_global_init (CURL_GLOBAL_WIN32)) { fprintf (stderr, "curl_global_init() failed at line %d.\n", (int) __LINE__); return use_magic_exit_codes ? 99 : 0; } param.magic = (unsigned int) TEST_MAGIC_MARKER; param.err_flag = 0; param.cred_sum = 0; memset (&rp, 0, sizeof(rp)); rp.port = zzuf_pick_port (TEST_PORT_OFFSET); rp.ahc = &ahc_basic; rp.ahc_cls = ¶m; rp.rcc = NULL; rp.rcc_cls = NULL; /* The hostile headers are large, use a memory limit that can hold them. */ rp.mem_limit_override = 8192; rp.sweep_profiles = 1; rp.profile_start = 0; rp.client = &client_run; rp.client_cls = ¶m; rp.extra_opts = NULL; res = zzuf_run_polling_modes (&rp); curl_global_cleanup (); if (99 == res) return use_magic_exit_codes ? 99 : 0; if (77 == res) return use_magic_exit_codes ? 77 : 0; return (0 == res) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testzzuf/Makefile.in0000664000175000017500000025655115235436271014700 # Makefile.in generated by automake 1.17 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2024 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # This Makefile.am is in the public domain VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) am__rm_f = rm -f $(am__rm_f_notfound) am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @USE_COVERAGE_TRUE@am__append_1 = -fprofile-arcs -ftest-coverage check_PROGRAMS = test_get$(EXEEXT) test_get_chunked$(EXEEXT) \ test_post$(EXEEXT) test_post_form$(EXEEXT) test_put$(EXEEXT) \ test_put_chunked$(EXEEXT) test_put_large$(EXEEXT) \ test_get_long_uri$(EXEEXT) test_get_long_header$(EXEEXT) \ test_get_close$(EXEEXT) test_get_chunked_close$(EXEEXT) \ test_post_close$(EXEEXT) test_post_form_close$(EXEEXT) \ test_put_close$(EXEEXT) test_put_chunked_close$(EXEEXT) \ test_put_large_close$(EXEEXT) test_get_long_uri_close$(EXEEXT) \ test_get_long_header_close$(EXEEXT) test_get10$(EXEEXT) \ test_get_chunked10$(EXEEXT) test_post10$(EXEEXT) \ test_post_form10$(EXEEXT) test_put10$(EXEEXT) \ test_put_large10$(EXEEXT) test_get_long_uri10$(EXEEXT) \ test_get_long_header10$(EXEEXT) test_get_hostile$(EXEEXT) \ test_get_chunked_hostile$(EXEEXT) test_post_hostile$(EXEEXT) \ test_put_chunked_hostile$(EXEEXT) \ test_put_large_hostile$(EXEEXT) test_get_args$(EXEEXT) \ test_get_args_close$(EXEEXT) test_get_args10$(EXEEXT) \ test_get_chunked_ext$(EXEEXT) \ test_get_chunked_ext_close$(EXEEXT) \ test_put_chunked_ext$(EXEEXT) \ test_put_chunked_ext_close$(EXEEXT) test_pipelined$(EXEEXT) \ test_pipelined_close$(EXEEXT) $(am__EXEEXT_1) $(am__EXEEXT_2) @ENABLE_DAUTH_TRUE@am__append_2 = \ @ENABLE_DAUTH_TRUE@ test_digest_auth \ @ENABLE_DAUTH_TRUE@ test_digest_auth_close @ENABLE_BAUTH_TRUE@am__append_3 = \ @ENABLE_BAUTH_TRUE@ test_basic_auth \ @ENABLE_BAUTH_TRUE@ test_basic_auth_close subdir = src/testzzuf ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(dist_check_SCRIPTS) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @ENABLE_DAUTH_TRUE@am__EXEEXT_1 = test_digest_auth$(EXEEXT) \ @ENABLE_DAUTH_TRUE@ test_digest_auth_close$(EXEEXT) @ENABLE_BAUTH_TRUE@am__EXEEXT_2 = test_basic_auth$(EXEEXT) \ @ENABLE_BAUTH_TRUE@ test_basic_auth_close$(EXEEXT) am__objects_1 = mhd_debug_funcs.$(OBJEXT) mhd_zzuf_common.$(OBJEXT) am_test_basic_auth_OBJECTS = test_basic_auth.$(OBJEXT) \ $(am__objects_1) test_basic_auth_OBJECTS = $(am_test_basic_auth_OBJECTS) test_basic_auth_LDADD = $(LDADD) test_basic_auth_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am__objects_2 = test_basic_auth.$(OBJEXT) $(am__objects_1) am_test_basic_auth_close_OBJECTS = $(am__objects_2) test_basic_auth_close_OBJECTS = $(am_test_basic_auth_close_OBJECTS) test_basic_auth_close_LDADD = $(LDADD) test_basic_auth_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_digest_auth_OBJECTS = test_digest_auth.$(OBJEXT) \ $(am__objects_1) test_digest_auth_OBJECTS = $(am_test_digest_auth_OBJECTS) test_digest_auth_LDADD = $(LDADD) test_digest_auth_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_3 = test_digest_auth.$(OBJEXT) $(am__objects_1) am_test_digest_auth_close_OBJECTS = $(am__objects_3) test_digest_auth_close_OBJECTS = $(am_test_digest_auth_close_OBJECTS) test_digest_auth_close_LDADD = $(LDADD) test_digest_auth_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_OBJECTS = test_get.$(OBJEXT) $(am__objects_1) test_get_OBJECTS = $(am_test_get_OBJECTS) test_get_LDADD = $(LDADD) test_get_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_4 = test_get.$(OBJEXT) $(am__objects_1) am_test_get10_OBJECTS = $(am__objects_4) test_get10_OBJECTS = $(am_test_get10_OBJECTS) test_get10_LDADD = $(LDADD) test_get10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_args_OBJECTS = test_get_args.$(OBJEXT) $(am__objects_1) test_get_args_OBJECTS = $(am_test_get_args_OBJECTS) test_get_args_LDADD = $(LDADD) test_get_args_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_5 = test_get_args.$(OBJEXT) $(am__objects_1) am_test_get_args10_OBJECTS = $(am__objects_5) test_get_args10_OBJECTS = $(am_test_get_args10_OBJECTS) test_get_args10_LDADD = $(LDADD) test_get_args10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_args_close_OBJECTS = $(am__objects_5) test_get_args_close_OBJECTS = $(am_test_get_args_close_OBJECTS) test_get_args_close_LDADD = $(LDADD) test_get_args_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_OBJECTS = $(am__objects_4) test_get_chunked_OBJECTS = $(am_test_get_chunked_OBJECTS) test_get_chunked_LDADD = $(LDADD) test_get_chunked_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_6 = $(am__objects_4) am_test_get_chunked10_OBJECTS = $(am__objects_6) test_get_chunked10_OBJECTS = $(am_test_get_chunked10_OBJECTS) test_get_chunked10_LDADD = $(LDADD) test_get_chunked10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_close_OBJECTS = $(am__objects_6) test_get_chunked_close_OBJECTS = $(am_test_get_chunked_close_OBJECTS) test_get_chunked_close_LDADD = $(LDADD) test_get_chunked_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_ext_OBJECTS = test_get_chunked_ext.$(OBJEXT) \ $(am__objects_1) test_get_chunked_ext_OBJECTS = $(am_test_get_chunked_ext_OBJECTS) test_get_chunked_ext_LDADD = $(LDADD) test_get_chunked_ext_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_7 = test_get_chunked_ext.$(OBJEXT) $(am__objects_1) am_test_get_chunked_ext_close_OBJECTS = $(am__objects_7) test_get_chunked_ext_close_OBJECTS = \ $(am_test_get_chunked_ext_close_OBJECTS) test_get_chunked_ext_close_LDADD = $(LDADD) test_get_chunked_ext_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_chunked_hostile_OBJECTS = $(am__objects_6) test_get_chunked_hostile_OBJECTS = \ $(am_test_get_chunked_hostile_OBJECTS) test_get_chunked_hostile_LDADD = $(LDADD) test_get_chunked_hostile_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_close_OBJECTS = $(am__objects_4) test_get_close_OBJECTS = $(am_test_get_close_OBJECTS) test_get_close_LDADD = $(LDADD) test_get_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_hostile_OBJECTS = $(am__objects_4) test_get_hostile_OBJECTS = $(am_test_get_hostile_OBJECTS) test_get_hostile_LDADD = $(LDADD) test_get_hostile_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_header_OBJECTS = $(am__objects_4) test_get_long_header_OBJECTS = $(am_test_get_long_header_OBJECTS) test_get_long_header_LDADD = $(LDADD) test_get_long_header_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_header10_OBJECTS = $(am__objects_6) test_get_long_header10_OBJECTS = $(am_test_get_long_header10_OBJECTS) test_get_long_header10_LDADD = $(LDADD) test_get_long_header10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_header_close_OBJECTS = $(am__objects_6) test_get_long_header_close_OBJECTS = \ $(am_test_get_long_header_close_OBJECTS) test_get_long_header_close_LDADD = $(LDADD) test_get_long_header_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_uri_OBJECTS = $(am__objects_4) test_get_long_uri_OBJECTS = $(am_test_get_long_uri_OBJECTS) test_get_long_uri_LDADD = $(LDADD) test_get_long_uri_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_uri10_OBJECTS = $(am__objects_6) test_get_long_uri10_OBJECTS = $(am_test_get_long_uri10_OBJECTS) test_get_long_uri10_LDADD = $(LDADD) test_get_long_uri10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_get_long_uri_close_OBJECTS = $(am__objects_6) test_get_long_uri_close_OBJECTS = \ $(am_test_get_long_uri_close_OBJECTS) test_get_long_uri_close_LDADD = $(LDADD) test_get_long_uri_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_pipelined_OBJECTS = test_pipelined.$(OBJEXT) $(am__objects_1) test_pipelined_OBJECTS = $(am_test_pipelined_OBJECTS) test_pipelined_LDADD = $(LDADD) test_pipelined_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am__objects_8 = test_pipelined.$(OBJEXT) $(am__objects_1) am_test_pipelined_close_OBJECTS = $(am__objects_8) test_pipelined_close_OBJECTS = $(am_test_pipelined_close_OBJECTS) test_pipelined_close_LDADD = $(LDADD) test_pipelined_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_OBJECTS = $(am__objects_4) test_post_OBJECTS = $(am_test_post_OBJECTS) test_post_LDADD = $(LDADD) test_post_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post10_OBJECTS = $(am__objects_6) test_post10_OBJECTS = $(am_test_post10_OBJECTS) test_post10_LDADD = $(LDADD) test_post10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_close_OBJECTS = $(am__objects_6) test_post_close_OBJECTS = $(am_test_post_close_OBJECTS) test_post_close_LDADD = $(LDADD) test_post_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_form_OBJECTS = $(am__objects_4) test_post_form_OBJECTS = $(am_test_post_form_OBJECTS) test_post_form_LDADD = $(LDADD) test_post_form_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_form10_OBJECTS = $(am__objects_6) test_post_form10_OBJECTS = $(am_test_post_form10_OBJECTS) test_post_form10_LDADD = $(LDADD) test_post_form10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_form_close_OBJECTS = $(am__objects_6) test_post_form_close_OBJECTS = $(am_test_post_form_close_OBJECTS) test_post_form_close_LDADD = $(LDADD) test_post_form_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_post_hostile_OBJECTS = $(am__objects_6) test_post_hostile_OBJECTS = $(am_test_post_hostile_OBJECTS) test_post_hostile_LDADD = $(LDADD) test_post_hostile_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_OBJECTS = $(am__objects_4) test_put_OBJECTS = $(am_test_put_OBJECTS) test_put_LDADD = $(LDADD) test_put_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put10_OBJECTS = $(am__objects_6) test_put10_OBJECTS = $(am_test_put10_OBJECTS) test_put10_LDADD = $(LDADD) test_put10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_chunked_OBJECTS = $(am__objects_4) test_put_chunked_OBJECTS = $(am_test_put_chunked_OBJECTS) test_put_chunked_LDADD = $(LDADD) test_put_chunked_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_chunked_close_OBJECTS = $(am__objects_6) test_put_chunked_close_OBJECTS = $(am_test_put_chunked_close_OBJECTS) test_put_chunked_close_LDADD = $(LDADD) test_put_chunked_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_chunked_ext_OBJECTS = $(am__objects_7) test_put_chunked_ext_OBJECTS = $(am_test_put_chunked_ext_OBJECTS) test_put_chunked_ext_LDADD = $(LDADD) test_put_chunked_ext_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_chunked_ext_close_OBJECTS = $(am__objects_7) test_put_chunked_ext_close_OBJECTS = \ $(am_test_put_chunked_ext_close_OBJECTS) test_put_chunked_ext_close_LDADD = $(LDADD) test_put_chunked_ext_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_chunked_hostile_OBJECTS = $(am__objects_6) test_put_chunked_hostile_OBJECTS = \ $(am_test_put_chunked_hostile_OBJECTS) test_put_chunked_hostile_LDADD = $(LDADD) test_put_chunked_hostile_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_close_OBJECTS = $(am__objects_6) test_put_close_OBJECTS = $(am_test_put_close_OBJECTS) test_put_close_LDADD = $(LDADD) test_put_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large_OBJECTS = $(am__objects_4) test_put_large_OBJECTS = $(am_test_put_large_OBJECTS) test_put_large_LDADD = $(LDADD) test_put_large_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large10_OBJECTS = $(am__objects_6) test_put_large10_OBJECTS = $(am_test_put_large10_OBJECTS) test_put_large10_LDADD = $(LDADD) test_put_large10_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large_close_OBJECTS = $(am__objects_6) test_put_large_close_OBJECTS = $(am_test_put_large_close_OBJECTS) test_put_large_close_LDADD = $(LDADD) test_put_large_close_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la am_test_put_large_hostile_OBJECTS = $(am__objects_6) test_put_large_hostile_OBJECTS = $(am_test_put_large_hostile_OBJECTS) test_put_large_hostile_LDADD = $(LDADD) test_put_large_hostile_DEPENDENCIES = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/mhd_debug_funcs.Po \ ./$(DEPDIR)/mhd_zzuf_common.Po ./$(DEPDIR)/test_basic_auth.Po \ ./$(DEPDIR)/test_digest_auth.Po ./$(DEPDIR)/test_get.Po \ ./$(DEPDIR)/test_get_args.Po \ ./$(DEPDIR)/test_get_chunked_ext.Po \ ./$(DEPDIR)/test_pipelined.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(test_basic_auth_SOURCES) $(test_basic_auth_close_SOURCES) \ $(test_digest_auth_SOURCES) $(test_digest_auth_close_SOURCES) \ $(test_get_SOURCES) $(test_get10_SOURCES) \ $(test_get_args_SOURCES) $(test_get_args10_SOURCES) \ $(test_get_args_close_SOURCES) $(test_get_chunked_SOURCES) \ $(test_get_chunked10_SOURCES) \ $(test_get_chunked_close_SOURCES) \ $(test_get_chunked_ext_SOURCES) \ $(test_get_chunked_ext_close_SOURCES) \ $(test_get_chunked_hostile_SOURCES) $(test_get_close_SOURCES) \ $(test_get_hostile_SOURCES) $(test_get_long_header_SOURCES) \ $(test_get_long_header10_SOURCES) \ $(test_get_long_header_close_SOURCES) \ $(test_get_long_uri_SOURCES) $(test_get_long_uri10_SOURCES) \ $(test_get_long_uri_close_SOURCES) $(test_pipelined_SOURCES) \ $(test_pipelined_close_SOURCES) $(test_post_SOURCES) \ $(test_post10_SOURCES) $(test_post_close_SOURCES) \ $(test_post_form_SOURCES) $(test_post_form10_SOURCES) \ $(test_post_form_close_SOURCES) $(test_post_hostile_SOURCES) \ $(test_put_SOURCES) $(test_put10_SOURCES) \ $(test_put_chunked_SOURCES) $(test_put_chunked_close_SOURCES) \ $(test_put_chunked_ext_SOURCES) \ $(test_put_chunked_ext_close_SOURCES) \ $(test_put_chunked_hostile_SOURCES) $(test_put_close_SOURCES) \ $(test_put_large_SOURCES) $(test_put_large10_SOURCES) \ $(test_put_large_close_SOURCES) \ $(test_put_large_hostile_SOURCES) DIST_SOURCES = $(test_basic_auth_SOURCES) \ $(test_basic_auth_close_SOURCES) $(test_digest_auth_SOURCES) \ $(test_digest_auth_close_SOURCES) $(test_get_SOURCES) \ $(test_get10_SOURCES) $(test_get_args_SOURCES) \ $(test_get_args10_SOURCES) $(test_get_args_close_SOURCES) \ $(test_get_chunked_SOURCES) $(test_get_chunked10_SOURCES) \ $(test_get_chunked_close_SOURCES) \ $(test_get_chunked_ext_SOURCES) \ $(test_get_chunked_ext_close_SOURCES) \ $(test_get_chunked_hostile_SOURCES) $(test_get_close_SOURCES) \ $(test_get_hostile_SOURCES) $(test_get_long_header_SOURCES) \ $(test_get_long_header10_SOURCES) \ $(test_get_long_header_close_SOURCES) \ $(test_get_long_uri_SOURCES) $(test_get_long_uri10_SOURCES) \ $(test_get_long_uri_close_SOURCES) $(test_pipelined_SOURCES) \ $(test_pipelined_close_SOURCES) $(test_post_SOURCES) \ $(test_post10_SOURCES) $(test_post_close_SOURCES) \ $(test_post_form_SOURCES) $(test_post_form10_SOURCES) \ $(test_post_form_close_SOURCES) $(test_post_hostile_SOURCES) \ $(test_put_SOURCES) $(test_put10_SOURCES) \ $(test_put_chunked_SOURCES) $(test_put_chunked_close_SOURCES) \ $(test_put_chunked_ext_SOURCES) \ $(test_put_chunked_ext_close_SOURCES) \ $(test_put_chunked_hostile_SOURCES) $(test_put_close_SOURCES) \ $(test_put_large_SOURCES) $(test_put_large10_SOURCES) \ $(test_put_large_close_SOURCES) \ $(test_put_large_hostile_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ check recheck distdir distdir-am am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ $$am__collect_skipped_logs \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(IGNORE_SKIPPED_LOGS)'; then \ am__collect_skipped_logs='--collect-skipped-logs no'; \ else \ am__collect_skipped_logs=''; \ fi; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver README DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ am__xargs_n = @am__xargs_n@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ SUBDIRS = . # ZZUF_SEED can be redefined to use other initial seeds # for extended testing. E.g., # make ZZUF_SEED=1234 check # When a test fails, the runner scripts print the seed(s) that produced # the failure so that the failure can be replayed with this variable. ZZUF_SEED = 0 # ZZUF_SEED_START / ZZUF_SEED_STOP sweep a whole range of seeds instead of # using a single one; they are mapped onto zzuf's "--seed=start:stop". # Every seed in the range starts one new child, so a large range takes a # correspondingly long time. E.g., # make ZZUF_SEED_START=0 ZZUF_SEED_STOP=500 check # ZZUF_SEED_START takes precedence over ZZUF_SEED. ZZUF_SEED_START = ZZUF_SEED_STOP = # Additional flags for zzuf ZZUF_FLAGS = # Additional flags for socat (if socat is used) SOCAT_FLAGS = # Sanitizer options that are appended to the options set by configure. # The fuzzing tests must abort at the very first error, otherwise the # input that produced the error is lost. # Leak detection is off: under fuzzing MHD legitimately abandons # half-processed requests, and the test itself is killed by zzuf. # To run the fuzzing tests under the sanitizers, configure MHD with # ./configure --enable-sanitizers=address,undefined # (this automatically makes the socat mode mandatory, as zzuf and the # sanitizers cannot both intercept the standard library calls). ZZUF_ASAN_OPTIONS = abort_on_error=1:detect_leaks=0 ZZUF_UBSAN_OPTIONS = print_stacktrace=1:halt_on_error=1 @FORCE_USE_ZZUF_SOCAT_FALSE@TEST_RUNNER_SCRIPT = zzuf_test_runner.sh @FORCE_USE_ZZUF_SOCAT_TRUE@TEST_RUNNER_SCRIPT = zzuf_socat_test_runner.sh AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) $(am__append_1) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) \ ZZUF="$(ZZUF)" ; export ZZUF ; \ ZZUF_SEED="$(ZZUF_SEED)" ; export ZZUF_SEED ; \ ZZUF_SEED_START="$(ZZUF_SEED_START)" ; export ZZUF_SEED_START ; \ ZZUF_SEED_STOP="$(ZZUF_SEED_STOP)" ; export ZZUF_SEED_STOP ; \ ZZUF_FLAGS="$(ZZUF_FLAGS)" ; export ZZUF_FLAGS ; \ SOCAT="$(SOCAT)" ; export SOCAT ; \ SOCAT_FLAGS="$(SOCAT_FLAGS)" ; export SOCAT_FLAGS ; \ ASAN_OPTIONS="$${ASAN_OPTIONS:+$${ASAN_OPTIONS}:}$(ZZUF_ASAN_OPTIONS)" ; \ export ASAN_OPTIONS ; \ UBSAN_OPTIONS="$${UBSAN_OPTIONS:+$${UBSAN_OPTIONS}:}$(ZZUF_UBSAN_OPTIONS)" ; \ export UBSAN_OPTIONS ; LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ @LIBCURL@ TESTS = $(check_PROGRAMS) dist_check_SCRIPTS = zzuf_test_runner.sh zzuf_socat_test_runner.sh LOG_COMPILER = @SHELL@ "$(srcdir)/$(TEST_RUNNER_SCRIPT)" @VHEAVY_TESTS_TRUE@check_SCRIPTS = warn_vheavy_use tests_common_sources = \ mhd_debug_funcs.h mhd_debug_funcs.c \ mhd_zzuf_common.h mhd_zzuf_common.c test_get_SOURCES = \ test_get.c $(tests_common_sources) test_get_chunked_SOURCES = $(test_get_SOURCES) test_post_SOURCES = $(test_get_SOURCES) test_post_form_SOURCES = $(test_get_SOURCES) test_put_SOURCES = $(test_get_SOURCES) test_put_chunked_SOURCES = $(test_get_SOURCES) test_put_large_SOURCES = $(test_get_SOURCES) test_get_long_uri_SOURCES = $(test_get_SOURCES) test_get_long_header_SOURCES = $(test_get_SOURCES) test_get_close_SOURCES = $(test_get_SOURCES) test_get_chunked_close_SOURCES = $(test_get_chunked_SOURCES) test_post_close_SOURCES = $(test_post_SOURCES) test_post_form_close_SOURCES = $(test_post_form_SOURCES) test_put_close_SOURCES = $(test_put_SOURCES) test_put_chunked_close_SOURCES = $(test_put_chunked_SOURCES) test_put_large_close_SOURCES = $(test_put_large_SOURCES) test_get_long_uri_close_SOURCES = $(test_get_long_uri_SOURCES) test_get_long_header_close_SOURCES = $(test_get_long_header_SOURCES) test_get10_SOURCES = $(test_get_SOURCES) test_get_chunked10_SOURCES = $(test_get_chunked_SOURCES) test_post10_SOURCES = $(test_post_SOURCES) test_post_form10_SOURCES = $(test_post_form_SOURCES) test_put10_SOURCES = $(test_put_SOURCES) test_put_large10_SOURCES = $(test_put_large_SOURCES) test_get_long_uri10_SOURCES = $(test_get_long_uri_SOURCES) test_get_long_header10_SOURCES = $(test_get_long_header_SOURCES) # The "_hostile" variants run exactly the same client/server exchange as # the programs above, but every started daemon uses another entry of the # "hostile" daemon option matrix (see mhd_zzuf_common.c): tiny connection # memory pools, small connection limits, short timeouts and the whole # range of MHD_OPTION_CLIENT_DISCIPLINE_LVL / # MHD_OPTION_STRICT_FOR_CLIENT values. test_get_hostile_SOURCES = $(test_get_SOURCES) test_get_chunked_hostile_SOURCES = $(test_get_chunked_SOURCES) test_post_hostile_SOURCES = $(test_post_SOURCES) test_put_chunked_hostile_SOURCES = $(test_put_chunked_SOURCES) test_put_large_hostile_SOURCES = $(test_put_large_SOURCES) # GET requests with hostile query strings (arguments without '=', empty # names and values, trailing '&', percent-encoded names, a very long tail # argument), combined with connection memory pools below MHD_BUF_INC_SIZE. test_get_args_SOURCES = \ test_get_args.c $(tests_common_sources) test_get_args_close_SOURCES = $(test_get_args_SOURCES) test_get_args10_SOURCES = $(test_get_args_SOURCES) # Chunked transfers whose chunk-size lines carry chunk extensions, plus # trailers/footers. libcurl cannot produce chunk extensions, so these # tests use the raw socket client of mhd_zzuf_common.c. test_get_chunked_ext_SOURCES = \ test_get_chunked_ext.c $(tests_common_sources) test_get_chunked_ext_close_SOURCES = $(test_get_chunked_ext_SOURCES) test_put_chunked_ext_SOURCES = $(test_get_chunked_ext_SOURCES) test_put_chunked_ext_close_SOURCES = $(test_get_chunked_ext_SOURCES) # Several complete requests written with a single send() call. test_pipelined_SOURCES = \ test_pipelined.c $(tests_common_sources) test_pipelined_close_SOURCES = $(test_pipelined_SOURCES) # Authentication. Both are built only if the respective support has not # been disabled at configure time (--disable-dauth / --disable-bauth). test_digest_auth_SOURCES = \ test_digest_auth.c $(tests_common_sources) test_digest_auth_close_SOURCES = $(test_digest_auth_SOURCES) test_basic_auth_SOURCES = \ test_basic_auth.c $(tests_common_sources) test_basic_auth_close_SOURCES = $(test_basic_auth_SOURCES) all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/testzzuf/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/testzzuf/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: $(am__rm_f) $(check_PROGRAMS) test -z "$(EXEEXT)" || $(am__rm_f) $(check_PROGRAMS:$(EXEEXT)=) test_basic_auth$(EXEEXT): $(test_basic_auth_OBJECTS) $(test_basic_auth_DEPENDENCIES) $(EXTRA_test_basic_auth_DEPENDENCIES) @rm -f test_basic_auth$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_basic_auth_OBJECTS) $(test_basic_auth_LDADD) $(LIBS) test_basic_auth_close$(EXEEXT): $(test_basic_auth_close_OBJECTS) $(test_basic_auth_close_DEPENDENCIES) $(EXTRA_test_basic_auth_close_DEPENDENCIES) @rm -f test_basic_auth_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_basic_auth_close_OBJECTS) $(test_basic_auth_close_LDADD) $(LIBS) test_digest_auth$(EXEEXT): $(test_digest_auth_OBJECTS) $(test_digest_auth_DEPENDENCIES) $(EXTRA_test_digest_auth_DEPENDENCIES) @rm -f test_digest_auth$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digest_auth_OBJECTS) $(test_digest_auth_LDADD) $(LIBS) test_digest_auth_close$(EXEEXT): $(test_digest_auth_close_OBJECTS) $(test_digest_auth_close_DEPENDENCIES) $(EXTRA_test_digest_auth_close_DEPENDENCIES) @rm -f test_digest_auth_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_digest_auth_close_OBJECTS) $(test_digest_auth_close_LDADD) $(LIBS) test_get$(EXEEXT): $(test_get_OBJECTS) $(test_get_DEPENDENCIES) $(EXTRA_test_get_DEPENDENCIES) @rm -f test_get$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_OBJECTS) $(test_get_LDADD) $(LIBS) test_get10$(EXEEXT): $(test_get10_OBJECTS) $(test_get10_DEPENDENCIES) $(EXTRA_test_get10_DEPENDENCIES) @rm -f test_get10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get10_OBJECTS) $(test_get10_LDADD) $(LIBS) test_get_args$(EXEEXT): $(test_get_args_OBJECTS) $(test_get_args_DEPENDENCIES) $(EXTRA_test_get_args_DEPENDENCIES) @rm -f test_get_args$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_args_OBJECTS) $(test_get_args_LDADD) $(LIBS) test_get_args10$(EXEEXT): $(test_get_args10_OBJECTS) $(test_get_args10_DEPENDENCIES) $(EXTRA_test_get_args10_DEPENDENCIES) @rm -f test_get_args10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_args10_OBJECTS) $(test_get_args10_LDADD) $(LIBS) test_get_args_close$(EXEEXT): $(test_get_args_close_OBJECTS) $(test_get_args_close_DEPENDENCIES) $(EXTRA_test_get_args_close_DEPENDENCIES) @rm -f test_get_args_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_args_close_OBJECTS) $(test_get_args_close_LDADD) $(LIBS) test_get_chunked$(EXEEXT): $(test_get_chunked_OBJECTS) $(test_get_chunked_DEPENDENCIES) $(EXTRA_test_get_chunked_DEPENDENCIES) @rm -f test_get_chunked$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_OBJECTS) $(test_get_chunked_LDADD) $(LIBS) test_get_chunked10$(EXEEXT): $(test_get_chunked10_OBJECTS) $(test_get_chunked10_DEPENDENCIES) $(EXTRA_test_get_chunked10_DEPENDENCIES) @rm -f test_get_chunked10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked10_OBJECTS) $(test_get_chunked10_LDADD) $(LIBS) test_get_chunked_close$(EXEEXT): $(test_get_chunked_close_OBJECTS) $(test_get_chunked_close_DEPENDENCIES) $(EXTRA_test_get_chunked_close_DEPENDENCIES) @rm -f test_get_chunked_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_close_OBJECTS) $(test_get_chunked_close_LDADD) $(LIBS) test_get_chunked_ext$(EXEEXT): $(test_get_chunked_ext_OBJECTS) $(test_get_chunked_ext_DEPENDENCIES) $(EXTRA_test_get_chunked_ext_DEPENDENCIES) @rm -f test_get_chunked_ext$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_ext_OBJECTS) $(test_get_chunked_ext_LDADD) $(LIBS) test_get_chunked_ext_close$(EXEEXT): $(test_get_chunked_ext_close_OBJECTS) $(test_get_chunked_ext_close_DEPENDENCIES) $(EXTRA_test_get_chunked_ext_close_DEPENDENCIES) @rm -f test_get_chunked_ext_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_ext_close_OBJECTS) $(test_get_chunked_ext_close_LDADD) $(LIBS) test_get_chunked_hostile$(EXEEXT): $(test_get_chunked_hostile_OBJECTS) $(test_get_chunked_hostile_DEPENDENCIES) $(EXTRA_test_get_chunked_hostile_DEPENDENCIES) @rm -f test_get_chunked_hostile$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_chunked_hostile_OBJECTS) $(test_get_chunked_hostile_LDADD) $(LIBS) test_get_close$(EXEEXT): $(test_get_close_OBJECTS) $(test_get_close_DEPENDENCIES) $(EXTRA_test_get_close_DEPENDENCIES) @rm -f test_get_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_close_OBJECTS) $(test_get_close_LDADD) $(LIBS) test_get_hostile$(EXEEXT): $(test_get_hostile_OBJECTS) $(test_get_hostile_DEPENDENCIES) $(EXTRA_test_get_hostile_DEPENDENCIES) @rm -f test_get_hostile$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_hostile_OBJECTS) $(test_get_hostile_LDADD) $(LIBS) test_get_long_header$(EXEEXT): $(test_get_long_header_OBJECTS) $(test_get_long_header_DEPENDENCIES) $(EXTRA_test_get_long_header_DEPENDENCIES) @rm -f test_get_long_header$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_header_OBJECTS) $(test_get_long_header_LDADD) $(LIBS) test_get_long_header10$(EXEEXT): $(test_get_long_header10_OBJECTS) $(test_get_long_header10_DEPENDENCIES) $(EXTRA_test_get_long_header10_DEPENDENCIES) @rm -f test_get_long_header10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_header10_OBJECTS) $(test_get_long_header10_LDADD) $(LIBS) test_get_long_header_close$(EXEEXT): $(test_get_long_header_close_OBJECTS) $(test_get_long_header_close_DEPENDENCIES) $(EXTRA_test_get_long_header_close_DEPENDENCIES) @rm -f test_get_long_header_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_header_close_OBJECTS) $(test_get_long_header_close_LDADD) $(LIBS) test_get_long_uri$(EXEEXT): $(test_get_long_uri_OBJECTS) $(test_get_long_uri_DEPENDENCIES) $(EXTRA_test_get_long_uri_DEPENDENCIES) @rm -f test_get_long_uri$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_uri_OBJECTS) $(test_get_long_uri_LDADD) $(LIBS) test_get_long_uri10$(EXEEXT): $(test_get_long_uri10_OBJECTS) $(test_get_long_uri10_DEPENDENCIES) $(EXTRA_test_get_long_uri10_DEPENDENCIES) @rm -f test_get_long_uri10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_uri10_OBJECTS) $(test_get_long_uri10_LDADD) $(LIBS) test_get_long_uri_close$(EXEEXT): $(test_get_long_uri_close_OBJECTS) $(test_get_long_uri_close_DEPENDENCIES) $(EXTRA_test_get_long_uri_close_DEPENDENCIES) @rm -f test_get_long_uri_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_get_long_uri_close_OBJECTS) $(test_get_long_uri_close_LDADD) $(LIBS) test_pipelined$(EXEEXT): $(test_pipelined_OBJECTS) $(test_pipelined_DEPENDENCIES) $(EXTRA_test_pipelined_DEPENDENCIES) @rm -f test_pipelined$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_pipelined_OBJECTS) $(test_pipelined_LDADD) $(LIBS) test_pipelined_close$(EXEEXT): $(test_pipelined_close_OBJECTS) $(test_pipelined_close_DEPENDENCIES) $(EXTRA_test_pipelined_close_DEPENDENCIES) @rm -f test_pipelined_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_pipelined_close_OBJECTS) $(test_pipelined_close_LDADD) $(LIBS) test_post$(EXEEXT): $(test_post_OBJECTS) $(test_post_DEPENDENCIES) $(EXTRA_test_post_DEPENDENCIES) @rm -f test_post$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_OBJECTS) $(test_post_LDADD) $(LIBS) test_post10$(EXEEXT): $(test_post10_OBJECTS) $(test_post10_DEPENDENCIES) $(EXTRA_test_post10_DEPENDENCIES) @rm -f test_post10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post10_OBJECTS) $(test_post10_LDADD) $(LIBS) test_post_close$(EXEEXT): $(test_post_close_OBJECTS) $(test_post_close_DEPENDENCIES) $(EXTRA_test_post_close_DEPENDENCIES) @rm -f test_post_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_close_OBJECTS) $(test_post_close_LDADD) $(LIBS) test_post_form$(EXEEXT): $(test_post_form_OBJECTS) $(test_post_form_DEPENDENCIES) $(EXTRA_test_post_form_DEPENDENCIES) @rm -f test_post_form$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_form_OBJECTS) $(test_post_form_LDADD) $(LIBS) test_post_form10$(EXEEXT): $(test_post_form10_OBJECTS) $(test_post_form10_DEPENDENCIES) $(EXTRA_test_post_form10_DEPENDENCIES) @rm -f test_post_form10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_form10_OBJECTS) $(test_post_form10_LDADD) $(LIBS) test_post_form_close$(EXEEXT): $(test_post_form_close_OBJECTS) $(test_post_form_close_DEPENDENCIES) $(EXTRA_test_post_form_close_DEPENDENCIES) @rm -f test_post_form_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_form_close_OBJECTS) $(test_post_form_close_LDADD) $(LIBS) test_post_hostile$(EXEEXT): $(test_post_hostile_OBJECTS) $(test_post_hostile_DEPENDENCIES) $(EXTRA_test_post_hostile_DEPENDENCIES) @rm -f test_post_hostile$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_post_hostile_OBJECTS) $(test_post_hostile_LDADD) $(LIBS) test_put$(EXEEXT): $(test_put_OBJECTS) $(test_put_DEPENDENCIES) $(EXTRA_test_put_DEPENDENCIES) @rm -f test_put$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_OBJECTS) $(test_put_LDADD) $(LIBS) test_put10$(EXEEXT): $(test_put10_OBJECTS) $(test_put10_DEPENDENCIES) $(EXTRA_test_put10_DEPENDENCIES) @rm -f test_put10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put10_OBJECTS) $(test_put10_LDADD) $(LIBS) test_put_chunked$(EXEEXT): $(test_put_chunked_OBJECTS) $(test_put_chunked_DEPENDENCIES) $(EXTRA_test_put_chunked_DEPENDENCIES) @rm -f test_put_chunked$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_chunked_OBJECTS) $(test_put_chunked_LDADD) $(LIBS) test_put_chunked_close$(EXEEXT): $(test_put_chunked_close_OBJECTS) $(test_put_chunked_close_DEPENDENCIES) $(EXTRA_test_put_chunked_close_DEPENDENCIES) @rm -f test_put_chunked_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_chunked_close_OBJECTS) $(test_put_chunked_close_LDADD) $(LIBS) test_put_chunked_ext$(EXEEXT): $(test_put_chunked_ext_OBJECTS) $(test_put_chunked_ext_DEPENDENCIES) $(EXTRA_test_put_chunked_ext_DEPENDENCIES) @rm -f test_put_chunked_ext$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_chunked_ext_OBJECTS) $(test_put_chunked_ext_LDADD) $(LIBS) test_put_chunked_ext_close$(EXEEXT): $(test_put_chunked_ext_close_OBJECTS) $(test_put_chunked_ext_close_DEPENDENCIES) $(EXTRA_test_put_chunked_ext_close_DEPENDENCIES) @rm -f test_put_chunked_ext_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_chunked_ext_close_OBJECTS) $(test_put_chunked_ext_close_LDADD) $(LIBS) test_put_chunked_hostile$(EXEEXT): $(test_put_chunked_hostile_OBJECTS) $(test_put_chunked_hostile_DEPENDENCIES) $(EXTRA_test_put_chunked_hostile_DEPENDENCIES) @rm -f test_put_chunked_hostile$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_chunked_hostile_OBJECTS) $(test_put_chunked_hostile_LDADD) $(LIBS) test_put_close$(EXEEXT): $(test_put_close_OBJECTS) $(test_put_close_DEPENDENCIES) $(EXTRA_test_put_close_DEPENDENCIES) @rm -f test_put_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_close_OBJECTS) $(test_put_close_LDADD) $(LIBS) test_put_large$(EXEEXT): $(test_put_large_OBJECTS) $(test_put_large_DEPENDENCIES) $(EXTRA_test_put_large_DEPENDENCIES) @rm -f test_put_large$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large_OBJECTS) $(test_put_large_LDADD) $(LIBS) test_put_large10$(EXEEXT): $(test_put_large10_OBJECTS) $(test_put_large10_DEPENDENCIES) $(EXTRA_test_put_large10_DEPENDENCIES) @rm -f test_put_large10$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large10_OBJECTS) $(test_put_large10_LDADD) $(LIBS) test_put_large_close$(EXEEXT): $(test_put_large_close_OBJECTS) $(test_put_large_close_DEPENDENCIES) $(EXTRA_test_put_large_close_DEPENDENCIES) @rm -f test_put_large_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large_close_OBJECTS) $(test_put_large_close_LDADD) $(LIBS) test_put_large_hostile$(EXEEXT): $(test_put_large_hostile_OBJECTS) $(test_put_large_hostile_DEPENDENCIES) $(EXTRA_test_put_large_hostile_DEPENDENCIES) @rm -f test_put_large_hostile$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_put_large_hostile_OBJECTS) $(test_put_large_hostile_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd_debug_funcs.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd_zzuf_common.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_basic_auth.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_digest_auth.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_args.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_get_chunked_ext.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_pipelined.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @: >>$@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ output_system_information () \ { \ echo; \ { uname -a | $(AWK) '{ \ printf "System information (uname -a):"; \ for (i = 1; i < NF; ++i) \ { \ if (i != 2) \ printf " %s", $$i; \ } \ printf "\n"; \ }'; } 2>&1; \ if test -r /etc/os-release; then \ echo "Distribution information (/etc/os-release):"; \ sed 8q /etc/os-release; \ elif test -r /etc/issue; then \ echo "Distribution information (/etc/issue):"; \ cat /etc/issue; \ fi; \ }; \ please_report () \ { \ echo "Some test(s) failed. Please report this to $(PACKAGE_BUGREPORT),"; \ echo "together with the test-suite.log file (gzipped) and your system"; \ echo "information. Thanks."; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ output_system_information; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG) for debugging.$${std}";\ if test -n "$(PACKAGE_BUGREPORT)"; then \ please_report | sed -e "s/^/$${col}/" -e s/'$$'/"$${std}"/; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) $(check_SCRIPTS) $(dist_check_SCRIPTS) @$(am__rm_f) $(RECHECK_LOGS) @$(am__rm_f) $(RECHECK_LOGS:.log=.trs) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) $(check_SCRIPTS) $(dist_check_SCRIPTS) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_get.log: test_get$(EXEEXT) @p='test_get$(EXEEXT)'; \ b='test_get'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked.log: test_get_chunked$(EXEEXT) @p='test_get_chunked$(EXEEXT)'; \ b='test_get_chunked'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post.log: test_post$(EXEEXT) @p='test_post$(EXEEXT)'; \ b='test_post'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_form.log: test_post_form$(EXEEXT) @p='test_post_form$(EXEEXT)'; \ b='test_post_form'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put.log: test_put$(EXEEXT) @p='test_put$(EXEEXT)'; \ b='test_put'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_chunked.log: test_put_chunked$(EXEEXT) @p='test_put_chunked$(EXEEXT)'; \ b='test_put_chunked'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large.log: test_put_large$(EXEEXT) @p='test_put_large$(EXEEXT)'; \ b='test_put_large'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_uri.log: test_get_long_uri$(EXEEXT) @p='test_get_long_uri$(EXEEXT)'; \ b='test_get_long_uri'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_header.log: test_get_long_header$(EXEEXT) @p='test_get_long_header$(EXEEXT)'; \ b='test_get_long_header'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_close.log: test_get_close$(EXEEXT) @p='test_get_close$(EXEEXT)'; \ b='test_get_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_close.log: test_get_chunked_close$(EXEEXT) @p='test_get_chunked_close$(EXEEXT)'; \ b='test_get_chunked_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_close.log: test_post_close$(EXEEXT) @p='test_post_close$(EXEEXT)'; \ b='test_post_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_form_close.log: test_post_form_close$(EXEEXT) @p='test_post_form_close$(EXEEXT)'; \ b='test_post_form_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_close.log: test_put_close$(EXEEXT) @p='test_put_close$(EXEEXT)'; \ b='test_put_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_chunked_close.log: test_put_chunked_close$(EXEEXT) @p='test_put_chunked_close$(EXEEXT)'; \ b='test_put_chunked_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large_close.log: test_put_large_close$(EXEEXT) @p='test_put_large_close$(EXEEXT)'; \ b='test_put_large_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_uri_close.log: test_get_long_uri_close$(EXEEXT) @p='test_get_long_uri_close$(EXEEXT)'; \ b='test_get_long_uri_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_header_close.log: test_get_long_header_close$(EXEEXT) @p='test_get_long_header_close$(EXEEXT)'; \ b='test_get_long_header_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get10.log: test_get10$(EXEEXT) @p='test_get10$(EXEEXT)'; \ b='test_get10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked10.log: test_get_chunked10$(EXEEXT) @p='test_get_chunked10$(EXEEXT)'; \ b='test_get_chunked10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post10.log: test_post10$(EXEEXT) @p='test_post10$(EXEEXT)'; \ b='test_post10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_form10.log: test_post_form10$(EXEEXT) @p='test_post_form10$(EXEEXT)'; \ b='test_post_form10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put10.log: test_put10$(EXEEXT) @p='test_put10$(EXEEXT)'; \ b='test_put10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large10.log: test_put_large10$(EXEEXT) @p='test_put_large10$(EXEEXT)'; \ b='test_put_large10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_uri10.log: test_get_long_uri10$(EXEEXT) @p='test_get_long_uri10$(EXEEXT)'; \ b='test_get_long_uri10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_long_header10.log: test_get_long_header10$(EXEEXT) @p='test_get_long_header10$(EXEEXT)'; \ b='test_get_long_header10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_hostile.log: test_get_hostile$(EXEEXT) @p='test_get_hostile$(EXEEXT)'; \ b='test_get_hostile'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_hostile.log: test_get_chunked_hostile$(EXEEXT) @p='test_get_chunked_hostile$(EXEEXT)'; \ b='test_get_chunked_hostile'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_post_hostile.log: test_post_hostile$(EXEEXT) @p='test_post_hostile$(EXEEXT)'; \ b='test_post_hostile'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_chunked_hostile.log: test_put_chunked_hostile$(EXEEXT) @p='test_put_chunked_hostile$(EXEEXT)'; \ b='test_put_chunked_hostile'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_large_hostile.log: test_put_large_hostile$(EXEEXT) @p='test_put_large_hostile$(EXEEXT)'; \ b='test_put_large_hostile'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_args.log: test_get_args$(EXEEXT) @p='test_get_args$(EXEEXT)'; \ b='test_get_args'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_args_close.log: test_get_args_close$(EXEEXT) @p='test_get_args_close$(EXEEXT)'; \ b='test_get_args_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_args10.log: test_get_args10$(EXEEXT) @p='test_get_args10$(EXEEXT)'; \ b='test_get_args10'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_ext.log: test_get_chunked_ext$(EXEEXT) @p='test_get_chunked_ext$(EXEEXT)'; \ b='test_get_chunked_ext'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_get_chunked_ext_close.log: test_get_chunked_ext_close$(EXEEXT) @p='test_get_chunked_ext_close$(EXEEXT)'; \ b='test_get_chunked_ext_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_chunked_ext.log: test_put_chunked_ext$(EXEEXT) @p='test_put_chunked_ext$(EXEEXT)'; \ b='test_put_chunked_ext'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_put_chunked_ext_close.log: test_put_chunked_ext_close$(EXEEXT) @p='test_put_chunked_ext_close$(EXEEXT)'; \ b='test_put_chunked_ext_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_pipelined.log: test_pipelined$(EXEEXT) @p='test_pipelined$(EXEEXT)'; \ b='test_pipelined'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_pipelined_close.log: test_pipelined_close$(EXEEXT) @p='test_pipelined_close$(EXEEXT)'; \ b='test_pipelined_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digest_auth.log: test_digest_auth$(EXEEXT) @p='test_digest_auth$(EXEEXT)'; \ b='test_digest_auth'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_digest_auth_close.log: test_digest_auth_close$(EXEEXT) @p='test_digest_auth_close$(EXEEXT)'; \ b='test_digest_auth_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_basic_auth.log: test_basic_auth$(EXEEXT) @p='test_basic_auth$(EXEEXT)'; \ b='test_basic_auth'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_basic_auth_close.log: test_basic_auth_close$(EXEEXT) @p='test_basic_auth_close$(EXEEXT)'; \ b='test_basic_auth_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(check_SCRIPTS) \ $(dist_check_SCRIPTS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -$(am__rm_f) $(TEST_LOGS) -$(am__rm_f) $(TEST_LOGS:.log=.trs) -$(am__rm_f) $(TEST_SUITE_LOG) clean-generic: distclean-generic: -$(am__rm_f) $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-recursive -rm -f ./$(DEPDIR)/mhd_debug_funcs.Po -rm -f ./$(DEPDIR)/mhd_zzuf_common.Po -rm -f ./$(DEPDIR)/test_basic_auth.Po -rm -f ./$(DEPDIR)/test_digest_auth.Po -rm -f ./$(DEPDIR)/test_get.Po -rm -f ./$(DEPDIR)/test_get_args.Po -rm -f ./$(DEPDIR)/test_get_chunked_ext.Po -rm -f ./$(DEPDIR)/test_pipelined.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f ./$(DEPDIR)/mhd_debug_funcs.Po -rm -f ./$(DEPDIR)/mhd_zzuf_common.Po -rm -f ./$(DEPDIR)/test_basic_auth.Po -rm -f ./$(DEPDIR)/test_digest_auth.Po -rm -f ./$(DEPDIR)/test_get.Po -rm -f ./$(DEPDIR)/test_get_args.Po -rm -f ./$(DEPDIR)/test_get_chunked_ext.Po -rm -f ./$(DEPDIR)/test_pipelined.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) check-am install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--depfiles check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am .PRECIOUS: Makefile $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la .NOTPARALLEL: @VHEAVY_TESTS_TRUE@.PHONY: warn_vheavy_use warn_vheavy_use: @echo "NOTICE" ; \ echo "NOTICE: Full heavy tests are enabled. Each test may take up to several minutes to complete." ; \ echo "NOTICE" # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: # Tell GNU make to disable its built-in pattern rules. %:: %,v %:: RCS/%,v %:: RCS/% %:: s.% %:: SCCS/s.% libmicrohttpd-1.0.10/src/testzzuf/mhd_zzuf_common.h0000664000175000017500000003702015232103064016152 /* This file is part of GNU libmicrohttpd Copyright (C) 2026 Christian Grothoff GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file testzzuf/mhd_zzuf_common.h * @brief Shared support code for the fuzzing tests in this directory * @author Christian Grothoff * * This header must be included *after* "platform.h" and . * * The helpers here provide: * - the common command line handling ("--dry-run", "--with-socat"), * - the matrix of "hostile" daemon option profiles (small memory pools, * small connection limits, short timeouts, strictness levels), * - a generic driver that runs a client callback against every polling * mode supported by the current MHD build, * - a tiny raw socket HTTP client, needed for all requests that libcurl * is unable to generate (chunk extensions, pipelining, header-less * requests, hand-crafted "Authorization:" headers). */ #ifndef MHD_ZZUF_COMMON_H #define MHD_ZZUF_COMMON_H 1 #include #include #include #include #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /** * The IP address MHD is listening on. * Must match 'mhd_listen_ip' in zzuf_test_runner.sh, as this is the only * address for which zzuf is instructed to fuzz the network traffic. */ #define ZZUF_MHD_LISTEN_IP "127.0.0.1" /** * The IP address used by the test clients as the source address. * Must be different from #ZZUF_MHD_LISTEN_IP so that the traffic * generated by the clients themselves is not fuzzed. */ #define ZZUF_CLIENT_BIND_IP "127.0.0.101" /** * The IP address socat is listening on. * Must match 'socat_listen_ip' in zzuf_socat_test_runner.sh. */ #define ZZUF_SOCAT_IP "127.0.0.121" /** * The port socat is listening on. * Must match 'socat_listen_port' in zzuf_socat_test_runner.sh. */ #define ZZUF_SOCAT_PORT 10121 /** * The port MHD is listening on when the port cannot be auto-detected. * Must match 'mhd_listen_port' in zzuf_socat_test_runner.sh. */ #define ZZUF_BASE_PORT 4010 /** * The default MHD connection timeout (in seconds) used by the tests. */ #define ZZUF_MHD_TIMEOUT 2 /** * The client-side timeout (in seconds). */ #define ZZUF_CLIENT_TIMEOUT 5 /** * A larger loop count runs more random tests, but takes longer. * Can be redefined by CPPFLAGS=-DZZUF_LOOP_COUNT=123 */ #ifndef ZZUF_LOOP_COUNT #ifndef _MHD_VHEAVY_TESTS #define ZZUF_LOOP_COUNT 10 #else /* _MHD_VHEAVY_TESTS */ #define ZZUF_LOOP_COUNT 200 #endif /* _MHD_VHEAVY_TESTS */ #endif /* ! ZZUF_LOOP_COUNT */ /* *** Global test parameters, initialised by zzuf_parse_common_args() *** */ /** * Non-zero if the traffic is relayed (and fuzzed) by socat. */ extern int zzuf_run_with_socat; /** * Non-zero if this is a "dry run", i.e. no real client requests are made. */ extern int zzuf_dry_run; /** * Non-zero if HTTP/1.1 should be used by the clients, zero for HTTP/1.0. */ extern int zzuf_oneone; /** * Non-zero if MHD should close the connection after each reply. */ extern int zzuf_use_close; /** * Parse the common command line parameters and derive the test flavour * from the program name. Also makes SIGPIPE non-fatal (if applicable). * * @param argc as given to main() * @param argv as given to main() */ void zzuf_parse_common_args (int argc, char *const *argv); /** * Check whether the name of the running program contains @a marker. * zzuf_parse_common_args() must have been called before. * * @param marker the marker to look for * @return non-zero if the marker is present, zero otherwise */ int zzuf_name_has (const char *marker); /** * The number of client iterations to perform, zero for "dry runs". */ unsigned int zzuf_loop_count (void); /* *** The matrix of "hostile" daemon option profiles *** */ /** * One set of daemon options used to widen the tested option matrix. */ struct zzuf_opt_profile { /** * Human readable name of the profile, used for logging. */ const char *name; /** * The value for #MHD_OPTION_CONNECTION_MEMORY_LIMIT. * Zero means "keep the MHD default". * Values below MHD_BUF_INC_SIZE (1500) enable the read buffer * "shift back" code path in MHD. */ size_t mem_limit; /** * The value for #MHD_OPTION_CONNECTION_LIMIT. * Zero means "keep the MHD default". */ unsigned int conn_limit; /** * The value for #MHD_OPTION_CONNECTION_TIMEOUT (seconds). * Never zero, as the tests rely on MHD closing idle connections. */ unsigned int timeout; /** * The value for #MHD_OPTION_CLIENT_DISCIPLINE_LVL (or, when * @a use_legacy_strict is set, for #MHD_OPTION_STRICT_FOR_CLIENT). */ int discipline_lvl; /** * If non-zero, the (older) #MHD_OPTION_STRICT_FOR_CLIENT option is used * instead of #MHD_OPTION_CLIENT_DISCIPLINE_LVL, so that the legacy * option translation code is exercised as well. */ int use_legacy_strict; }; /** * The number of available option profiles. */ unsigned int zzuf_num_opt_profiles (void); /** * Get the option profile number @a idx (wrapping around). * * Profile zero is always the "plain" profile, i.e. the set of options * that was used by the fuzzing tests before the option matrix was added. */ const struct zzuf_opt_profile * zzuf_opt_profile (unsigned int idx); /** * The profile that is in use by the currently running daemon. * Never NULL after the first daemon has been started. */ extern const struct zzuf_opt_profile *zzuf_active_profile; /* *** Daemon handling *** */ /** * Select the port to be used by the daemon. * * @param offset the per-test offset added to #ZZUF_BASE_PORT if the port * cannot be auto-detected * @return the port to be given to MHD_start_daemon(), may be zero */ uint16_t zzuf_pick_port (uint16_t offset); /** * Start a daemon for the test. * * @param daemon_flags the flags for MHD_start_daemon() * @param[in,out] pport the port to use, updated with the real port * @param prof the option profile to apply, never NULL * @param mem_limit_override if non-zero, this value is used for * #MHD_OPTION_CONNECTION_MEMORY_LIMIT instead of * the value from @a prof * @param ahc the access handler callback * @param ahc_cls the closure for @a ahc * @param rcc the request completed callback, may be NULL * @param rcc_cls the closure for @a rcc * @param extra_opts additional options, terminated by #MHD_OPTION_END; * may be NULL * @return the daemon, or NULL on error */ struct MHD_Daemon * zzuf_start_daemon (unsigned int daemon_flags, uint16_t *pport, const struct zzuf_opt_profile *prof, size_t mem_limit_override, MHD_AccessHandlerCallback ahc, void *ahc_cls, MHD_RequestCompletedCallback rcc, void *rcc_cls, const struct MHD_OptionItem *extra_opts); /** * The client callback invoked by zzuf_run_polling_modes() once per daemon. * * @param d_extern the daemon that must be driven by MHD_run() while the * client is waiting; NULL if the daemon uses an internal * polling thread * @param port the port the daemon is listening on * @param cls the closure * @return zero on success, 77 to skip the test, 99 for an external * (non-MHD) error, any other non-zero value for a test failure */ typedef unsigned int (*zzuf_client_func)(struct MHD_Daemon *d_extern, uint16_t port, void *cls); /** * Parameters for zzuf_run_polling_modes(). */ struct zzuf_run_params { /** * The port to use, updated in place. */ uint16_t port; /** * The access handler callback. */ MHD_AccessHandlerCallback ahc; /** * The closure for @e ahc. */ void *ahc_cls; /** * The request completed callback, may be NULL. */ MHD_RequestCompletedCallback rcc; /** * The closure for @e rcc. */ void *rcc_cls; /** * If non-zero, this value is always used for the connection memory * limit, overriding the value from the option profile. */ size_t mem_limit_override; /** * If non-zero, a different option profile is used for every started * daemon, sweeping the whole option matrix during a single test run. */ int sweep_profiles; /** * The number of the first option profile to use when @e sweep_profiles * is set. Use 1 to skip the "plain" profile, i.e. to make sure that * every daemon of the test uses a small connection memory pool. */ unsigned int profile_start; /** * The client callback. */ zzuf_client_func client; /** * The closure for @e client. */ void *client_cls; /** * Additional daemon options, terminated by #MHD_OPTION_END. * May be NULL. */ const struct MHD_OptionItem *extra_opts; }; /** * Run the client callback against a daemon in every polling mode * supported by the current MHD build. * * @param[in,out] p the parameters * @return zero if all checks succeeded, 77 to skip, 99 for an external * error, any other non-zero value on failure */ unsigned int zzuf_run_polling_modes (struct zzuf_run_params *p); /** * Check whether the test can be run at all with the current build and * the current invocation mode. * * @return zero if the test may run, 77 if the test must be skipped */ unsigned int zzuf_check_runnable (void); /* *** The raw socket client *** */ /** * One piece of a raw request. Every piece is written with a separate * send() call, so the pieces typically end up in separate TCP segments. * This is used deliberately to feed MHD with partial header, chunk-size * and chunk-extension lines. */ struct zzuf_raw_part { /** * The data to send, not zero-terminated. */ const char *data; /** * The number of bytes to send. */ size_t size; }; /** * The raw exchange has been performed (whatever the result was). */ #define ZZUF_RAW_OK 0 /** * The raw client could not be set up. This is an external error and * must not be reported as a test failure. */ #define ZZUF_RAW_SETUP_FAILED 1 /** * Connect to the daemon (via socat, if used), send @a parts and read the * reply until the peer closes the connection or the timeout expires. * * The reply is discarded: under fuzzing, any reply (including no reply * at all) is a valid outcome. Only crashes and hangs are failures. * * @param d_extern if not NULL, MHD_run() is called while waiting * @param port the port MHD is listening on (ignored if socat is used) * @param parts the pieces of the request * @param num_parts the number of @a parts * @param timeout_sec the maximum number of seconds to spend * @return #ZZUF_RAW_OK or #ZZUF_RAW_SETUP_FAILED */ int zzuf_raw_exchange (struct MHD_Daemon *d_extern, uint16_t port, const struct zzuf_raw_part *parts, size_t num_parts, unsigned int timeout_sec); /** * The same as zzuf_raw_exchange(), but with two extra abilities. * * With @a bypass_relay set, the client connects to MHD directly instead of * going through socat. As zzuf only fuzzes the socat process, such an * exchange is *not* fuzzed at all. This makes it possible to run a small * deterministic self-check of the parser inside the very same test binary. * Note that this only works in the socat mode: when zzuf runs the test * binary itself, all traffic accepted by MHD is fuzzed and there is no * clean channel to MHD. * * @param d_extern if not NULL, MHD_run() is called while waiting * @param port the port MHD is listening on * @param bypass_relay if non-zero, connect to MHD directly * @param parts the pieces of the request * @param num_parts the number of @a parts * @param timeout_sec the maximum number of seconds to spend * @param[out] resp_buf the buffer for the reply, may be NULL * @param resp_buf_size the size of @a resp_buf * @param[out] resp_len set to the number of bytes stored in @a resp_buf, * may be NULL * @return #ZZUF_RAW_OK or #ZZUF_RAW_SETUP_FAILED */ int zzuf_raw_exchange2 (struct MHD_Daemon *d_extern, uint16_t port, int bypass_relay, const struct zzuf_raw_part *parts, size_t num_parts, unsigned int timeout_sec, char *resp_buf, size_t resp_buf_size, size_t *resp_len); /** * Convenience wrapper around zzuf_raw_exchange() for a request that is * sent as a single zero-terminated string. * * @param d_extern if not NULL, MHD_run() is called while waiting * @param port the port MHD is listening on (ignored if socat is used) * @param request the zero-terminated request * @return #ZZUF_RAW_OK or #ZZUF_RAW_SETUP_FAILED */ int zzuf_raw_request (struct MHD_Daemon *d_extern, uint16_t port, const char *request); /* *** libcurl helpers *** */ /** * The sink for the data downloaded by libcurl. */ struct zzuf_curl_sink { /** * The number of bytes received so far. */ size_t dn_pos; /** * The scratch buffer. */ char buf[2048]; }; /** * Create an "easy" handle with the settings that are common to all * fuzzing tests in this directory. * * @param port the port MHD is listening on (ignored if socat is used) * @param uri_tail the path (and query string) of the request-target, * must start with a slash * @param sink the download sink, must stay valid while the handle is used * @return the handle, or NULL on failure */ CURL * zzuf_curl_setup (uint16_t port, const char *uri_tail, struct zzuf_curl_sink *sink); /** * The state needed to run "easy" handles against a daemon that may or * may not have an internal polling thread. */ struct zzuf_curl_driver { /** * The daemon to drive with MHD_run(), NULL for daemons with an internal * polling thread. */ struct MHD_Daemon *d_extern; /** * The "multi" handle, only used when @e d_extern is not NULL. */ CURLM *multi; }; /** * Initialise the driver. * * @param[out] drv the driver to initialise * @param d_extern the daemon to drive, or NULL * @return non-zero on success, zero on failure */ int zzuf_curl_driver_init (struct zzuf_curl_driver *drv, struct MHD_Daemon *d_extern); /** * Release the resources of the driver. * * @param drv the driver to clean up */ void zzuf_curl_driver_deinit (struct zzuf_curl_driver *drv); /** * Run a single transfer to completion (or to the timeout). * * The result of the transfer is deliberately ignored: with the traffic * being fuzzed, libcurl may fail in arbitrary ways. * * @param drv the driver * @param c the "easy" handle to run */ void zzuf_curl_driver_perform (struct zzuf_curl_driver *drv, CURL *c); #endif /* MHD_ZZUF_COMMON_H */ libmicrohttpd-1.0.10/src/testzzuf/mhd_debug_funcs.h0000644000175000017500000000327214760713577016115 /* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file testzzuf/mhd_debug_funcs.h * @brief Declarations of MHD private debug functions * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_DEBUG_FUNCS_H #define MHD_DEBUG_FUNCS_H 1 struct MHD_Daemon; /** * Checks whether MHD can use accept() syscall and * avoid accept4() syscall. * @return non-zero if accept() is possible, * zero if accept4() is always used by MHD */ int MHD_is_avoid_accept4_possible_ (void); /** * Switch MHD daemon to use accept() syscalls for new connections. * @param daemon the daemon to operate */ void MHD_avoid_accept4_ (struct MHD_Daemon *daemon); /** * Checks whether any know sanitizer is enabled for this build. * zzuf does not work together with sanitizers as both are intercepting * standard library calls. * @return non-zero if any sanitizer is enabled, * zero otherwise */ int MHD_are_sanitizers_enabled_ (void); #endif /* MHD_DEBUG_FUNCS_H */ libmicrohttpd-1.0.10/src/testzzuf/Makefile.am0000664000175000017500000001746515232103064014652 # This Makefile.am is in the public domain SUBDIRS = . # ZZUF_SEED can be redefined to use other initial seeds # for extended testing. E.g., # make ZZUF_SEED=1234 check # When a test fails, the runner scripts print the seed(s) that produced # the failure so that the failure can be replayed with this variable. ZZUF_SEED = 0 # ZZUF_SEED_START / ZZUF_SEED_STOP sweep a whole range of seeds instead of # using a single one; they are mapped onto zzuf's "--seed=start:stop". # Every seed in the range starts one new child, so a large range takes a # correspondingly long time. E.g., # make ZZUF_SEED_START=0 ZZUF_SEED_STOP=500 check # ZZUF_SEED_START takes precedence over ZZUF_SEED. ZZUF_SEED_START = ZZUF_SEED_STOP = # Additional flags for zzuf ZZUF_FLAGS = # Additional flags for socat (if socat is used) SOCAT_FLAGS = # Sanitizer options that are appended to the options set by configure. # The fuzzing tests must abort at the very first error, otherwise the # input that produced the error is lost. # Leak detection is off: under fuzzing MHD legitimately abandons # half-processed requests, and the test itself is killed by zzuf. # To run the fuzzing tests under the sanitizers, configure MHD with # ./configure --enable-sanitizers=address,undefined # (this automatically makes the socat mode mandatory, as zzuf and the # sanitizers cannot both intercept the standard library calls). ZZUF_ASAN_OPTIONS = abort_on_error=1:detect_leaks=0 ZZUF_UBSAN_OPTIONS = print_stacktrace=1:halt_on_error=1 if FORCE_USE_ZZUF_SOCAT TEST_RUNNER_SCRIPT = zzuf_socat_test_runner.sh else TEST_RUNNER_SCRIPT = zzuf_test_runner.sh endif AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ -I$(top_srcdir)/src/microhttpd \ -DMHD_CPU_COUNT=$(CPU_COUNT) \ $(CPPFLAGS_ac) $(LIBCURL_CPPFLAGS) AM_CFLAGS = $(CFLAGS_ac) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) \ ZZUF="$(ZZUF)" ; export ZZUF ; \ ZZUF_SEED="$(ZZUF_SEED)" ; export ZZUF_SEED ; \ ZZUF_SEED_START="$(ZZUF_SEED_START)" ; export ZZUF_SEED_START ; \ ZZUF_SEED_STOP="$(ZZUF_SEED_STOP)" ; export ZZUF_SEED_STOP ; \ ZZUF_FLAGS="$(ZZUF_FLAGS)" ; export ZZUF_FLAGS ; \ SOCAT="$(SOCAT)" ; export SOCAT ; \ SOCAT_FLAGS="$(SOCAT_FLAGS)" ; export SOCAT_FLAGS ; \ ASAN_OPTIONS="$${ASAN_OPTIONS:+$${ASAN_OPTIONS}:}$(ZZUF_ASAN_OPTIONS)" ; \ export ASAN_OPTIONS ; \ UBSAN_OPTIONS="$${UBSAN_OPTIONS:+$${UBSAN_OPTIONS}:}$(ZZUF_UBSAN_OPTIONS)" ; \ export UBSAN_OPTIONS ; if USE_COVERAGE AM_CFLAGS += -fprofile-arcs -ftest-coverage endif LDADD = \ $(top_builddir)/src/microhttpd/libmicrohttpd.la \ @LIBCURL@ $(top_builddir)/src/microhttpd/libmicrohttpd.la: $(top_builddir)/src/microhttpd/Makefile @echo ' cd $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la'; \ $(am__cd) $(top_builddir)/src/microhttpd && $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la check_PROGRAMS = \ test_get \ test_get_chunked \ test_post \ test_post_form \ test_put \ test_put_chunked \ test_put_large \ test_get_long_uri \ test_get_long_header \ test_get_close \ test_get_chunked_close \ test_post_close \ test_post_form_close \ test_put_close \ test_put_chunked_close \ test_put_large_close \ test_get_long_uri_close \ test_get_long_header_close \ test_get10 \ test_get_chunked10 \ test_post10 \ test_post_form10 \ test_put10 \ test_put_large10 \ test_get_long_uri10 \ test_get_long_header10 \ test_get_hostile \ test_get_chunked_hostile \ test_post_hostile \ test_put_chunked_hostile \ test_put_large_hostile \ test_get_args \ test_get_args_close \ test_get_args10 \ test_get_chunked_ext \ test_get_chunked_ext_close \ test_put_chunked_ext \ test_put_chunked_ext_close \ test_pipelined \ test_pipelined_close if ENABLE_DAUTH check_PROGRAMS += \ test_digest_auth \ test_digest_auth_close endif if ENABLE_BAUTH check_PROGRAMS += \ test_basic_auth \ test_basic_auth_close endif .NOTPARALLEL: TESTS = $(check_PROGRAMS) dist_check_SCRIPTS = zzuf_test_runner.sh zzuf_socat_test_runner.sh LOG_COMPILER = @SHELL@ "$(srcdir)/$(TEST_RUNNER_SCRIPT)" if VHEAVY_TESTS check_SCRIPTS = warn_vheavy_use .PHONY: warn_vheavy_use endif warn_vheavy_use: @echo "NOTICE" ; \ echo "NOTICE: Full heavy tests are enabled. Each test may take up to several minutes to complete." ; \ echo "NOTICE" tests_common_sources = \ mhd_debug_funcs.h mhd_debug_funcs.c \ mhd_zzuf_common.h mhd_zzuf_common.c test_get_SOURCES = \ test_get.c $(tests_common_sources) test_get_chunked_SOURCES = $(test_get_SOURCES) test_post_SOURCES = $(test_get_SOURCES) test_post_form_SOURCES = $(test_get_SOURCES) test_put_SOURCES = $(test_get_SOURCES) test_put_chunked_SOURCES = $(test_get_SOURCES) test_put_large_SOURCES = $(test_get_SOURCES) test_get_long_uri_SOURCES = $(test_get_SOURCES) test_get_long_header_SOURCES = $(test_get_SOURCES) test_get_close_SOURCES = $(test_get_SOURCES) test_get_chunked_close_SOURCES = $(test_get_chunked_SOURCES) test_post_close_SOURCES = $(test_post_SOURCES) test_post_form_close_SOURCES = $(test_post_form_SOURCES) test_put_close_SOURCES = $(test_put_SOURCES) test_put_chunked_close_SOURCES = $(test_put_chunked_SOURCES) test_put_large_close_SOURCES = $(test_put_large_SOURCES) test_get_long_uri_close_SOURCES = $(test_get_long_uri_SOURCES) test_get_long_header_close_SOURCES = $(test_get_long_header_SOURCES) test_get10_SOURCES = $(test_get_SOURCES) test_get_chunked10_SOURCES = $(test_get_chunked_SOURCES) test_post10_SOURCES = $(test_post_SOURCES) test_post_form10_SOURCES = $(test_post_form_SOURCES) test_put10_SOURCES = $(test_put_SOURCES) test_put_large10_SOURCES = $(test_put_large_SOURCES) test_get_long_uri10_SOURCES = $(test_get_long_uri_SOURCES) test_get_long_header10_SOURCES = $(test_get_long_header_SOURCES) # The "_hostile" variants run exactly the same client/server exchange as # the programs above, but every started daemon uses another entry of the # "hostile" daemon option matrix (see mhd_zzuf_common.c): tiny connection # memory pools, small connection limits, short timeouts and the whole # range of MHD_OPTION_CLIENT_DISCIPLINE_LVL / # MHD_OPTION_STRICT_FOR_CLIENT values. test_get_hostile_SOURCES = $(test_get_SOURCES) test_get_chunked_hostile_SOURCES = $(test_get_chunked_SOURCES) test_post_hostile_SOURCES = $(test_post_SOURCES) test_put_chunked_hostile_SOURCES = $(test_put_chunked_SOURCES) test_put_large_hostile_SOURCES = $(test_put_large_SOURCES) # GET requests with hostile query strings (arguments without '=', empty # names and values, trailing '&', percent-encoded names, a very long tail # argument), combined with connection memory pools below MHD_BUF_INC_SIZE. test_get_args_SOURCES = \ test_get_args.c $(tests_common_sources) test_get_args_close_SOURCES = $(test_get_args_SOURCES) test_get_args10_SOURCES = $(test_get_args_SOURCES) # Chunked transfers whose chunk-size lines carry chunk extensions, plus # trailers/footers. libcurl cannot produce chunk extensions, so these # tests use the raw socket client of mhd_zzuf_common.c. test_get_chunked_ext_SOURCES = \ test_get_chunked_ext.c $(tests_common_sources) test_get_chunked_ext_close_SOURCES = $(test_get_chunked_ext_SOURCES) test_put_chunked_ext_SOURCES = $(test_get_chunked_ext_SOURCES) test_put_chunked_ext_close_SOURCES = $(test_get_chunked_ext_SOURCES) # Several complete requests written with a single send() call. test_pipelined_SOURCES = \ test_pipelined.c $(tests_common_sources) test_pipelined_close_SOURCES = $(test_pipelined_SOURCES) # Authentication. Both are built only if the respective support has not # been disabled at configure time (--disable-dauth / --disable-bauth). test_digest_auth_SOURCES = \ test_digest_auth.c $(tests_common_sources) test_digest_auth_close_SOURCES = $(test_digest_auth_SOURCES) test_basic_auth_SOURCES = \ test_basic_auth.c $(tests_common_sources) test_basic_auth_close_SOURCES = $(test_basic_auth_SOURCES) libmicrohttpd-1.0.10/src/testzzuf/test_get.c0000664000175000017500000015050615232103064014572 /* This file is part of libmicrohttpd Copyright (C) 2007, 2008 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file testzzuf/test_get.c * @brief Several testcases for libmicrohttpd with input fuzzing * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include #include #include #include #include #include #ifndef WINDOWS #include #endif #include "mhd_debug_funcs.h" #include "mhd_zzuf_common.h" #include "test_helpers.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ /** * A larger loop count will run more random tests -- * which would be good, except that it may take too * long for most user's patience. So this small * value is the default. * Can be redefined by CPPFLAGS=-DLOOP_COUNT=123 */ #ifndef LOOP_COUNT #ifndef _MHD_VHEAVY_TESTS #define LOOP_COUNT 10 #else /* ! _MHD_HEAVY_TESTS */ #define LOOP_COUNT 200 #endif /* ! _MHD_HEAVY_TESTS */ #endif /* LOOP_COUNT */ #ifdef _DEBUG /* Uncomment the next line (or use CPPFLAGS) to see all request and response bodies in log */ /* #define TEST_PRINT_BODY */ /* Uncomment the next line (or use CPPFLAGS) to see all request bodies as they are sent by libcurl */ /* #define TEST_PRINT_BODY_RQ 1 */ /* Uncomment the next line (or use CPPFLAGS) to see all request bodies as they are received by libcurl */ /* #define TEST_PRINT_BODY_RP 1 */ #endif /* _DEBUG */ #define MHD_TIMEOUT 2 #define CURL_TIMEOUT 5 /* Global test parameters */ static int oneone; static int dry_run; static int use_get; static int use_get_chunked; static int use_put; static int use_put_large; static int use_put_chunked; static int use_post; static int use_post_form; static int use_long_header; static int use_long_uri; static int use_close; static int run_with_socat; /** * Non-zero if this program sweeps the matrix of "hostile" daemon options * (small connection memory pools, small connection limits, short timeouts * and the various client discipline levels) instead of using the single * "plain" set of daemon options. * Derived from the "_hostile" marker in the program name. */ static int use_hostile_opts; /** * The daemon option profile that is currently in use. */ static const struct zzuf_opt_profile *cur_profile; /** * The connection timeout that the current daemon has been started with. */ static unsigned int expected_conn_timeout = MHD_TIMEOUT; #define TEST_BASE_URI "http:/" "/127.0.0.1/test_uri" #define TEST_BASE_URI_SOCAT "http:/" "/127.0.0.121/test_uri" #define SOCAT_PORT 10121 #define TEST_BASE_PORT 4010 #define EMPTY_PAGE "Empty page." #define EMPTY_PAGE_ALT "Alternative empty page." #define METHOD_NOT_SUPPORTED "HTTP method is not supported." #define POST_DATA_BROKEN "The POST request is ill-formed." #define POST_KEY1 "test" #define POST_VALUE1 "test_post" #define POST_KEY2 "library" #define POST_VALUE2 "GNU libmicrohttpd" #define POST_URLENC_DATA \ POST_KEY1 "=" POST_VALUE1 "&" POST_KEY2 "=" "GNU%20libmicrohttpd" #define PUT_NORMAL_SIZE 11 /* Does not need to be very large as MHD buffer will be made smaller anyway */ #define PUT_LARGE_SIZE (4 * 1024) /* The length of "very long" URI and header strings. MHD uses smaller buffer. */ #define TEST_STRING_VLONG_LEN 8 * 1024 #if ! CURL_AT_LEAST_VERSION (7,56,0) #define TEST_USE_STATIC_POST_DATA 1 static struct curl_httppost *post_first; static struct curl_httppost *post_last; #endif /* ! CURL_AT_LEAST_VERSION(7,56,0) */ static struct curl_slist *libcurl_long_header; /** * Initialise long header for libcurl * * @return non-zero if succeed, * zero if failed */ static int long_header_init (void) { char *buf; buf = malloc (TEST_STRING_VLONG_LEN + 1); if (NULL == buf) { fprintf (stderr, "malloc() failed " "at line %d.\n", (int) __LINE__); return 0; } buf[TEST_STRING_VLONG_LEN] = 0; buf[0] = 'A'; memset (buf + 1, 'a', TEST_STRING_VLONG_LEN / 2 - 2); buf[TEST_STRING_VLONG_LEN / 2 - 1] = ':'; buf[TEST_STRING_VLONG_LEN / 2] = ' '; memset (buf + TEST_STRING_VLONG_LEN / 2 + 1, 'c', TEST_STRING_VLONG_LEN / 2 - 1); libcurl_long_header = curl_slist_append (NULL, buf); free (buf); if (NULL != libcurl_long_header) return ! 0; /* Success exit point */ fprintf (stderr, "curl_slist_append() failed " "at line %d.\n", (int) __LINE__); return 0; /* Failure exit point */ } /** * Globally initialise test environment * @return non-zero if succeed, * zero if failed */ static int test_global_init (void) { libcurl_long_header = NULL; if (CURLE_OK != curl_global_init (CURL_GLOBAL_WIN32)) { fprintf (stderr, "curl_global_init() failed " "at line %d.\n", (int) __LINE__); return 0; } if (long_header_init ()) { #ifndef TEST_USE_STATIC_POST_DATA return 1; /* Success exit point */ #else /* ! TEST_USE_STATIC_POST_DATA */ post_first = NULL; post_last = NULL; if ((CURL_FORMADD_OK != curl_formadd (&post_first, &post_last, CURLFORM_PTRNAME, POST_KEY1, CURLFORM_NAMELENGTH, (long) MHD_STATICSTR_LEN_ (POST_KEY1), CURLFORM_PTRCONTENTS, POST_VALUE1, #if CURL_AT_LEAST_VERSION (7,46,0) CURLFORM_CONTENTLEN, (curl_off_t) MHD_STATICSTR_LEN_ (POST_VALUE1), #else /* ! CURL_AT_LEAST_VERSION(7,46,0) */ CURLFORM_CONTENTSLENGTH, (long) MHD_STATICSTR_LEN_ (POST_VALUE1), #endif /* ! CURL_AT_LEAST_VERSION(7,46,0) */ CURLFORM_END)) || (CURL_FORMADD_OK != curl_formadd (&post_first, &post_last, CURLFORM_PTRNAME, POST_KEY2, CURLFORM_NAMELENGTH, (long) MHD_STATICSTR_LEN_ (POST_KEY2), CURLFORM_PTRCONTENTS, POST_VALUE2, #if CURL_AT_LEAST_VERSION (7,46,0) CURLFORM_CONTENTLEN, (curl_off_t) MHD_STATICSTR_LEN_ (POST_VALUE2), #else /* ! CURL_AT_LEAST_VERSION(7,46,0) */ CURLFORM_CONTENTSLENGTH, (long) MHD_STATICSTR_LEN_ (POST_VALUE2), #endif /* ! CURL_AT_LEAST_VERSION(7,46,0) */ CURLFORM_END))) fprintf (stderr, "curl_formadd() failed " "at line %d.\n", (int) __LINE__); else return 1; /* Success exit point */ if (NULL != post_first) curl_formfree (post_first); curl_slist_free_all (libcurl_long_header); #endif /* ! CURL_AT_LEAST_VERSION(7,56,0) */ } curl_global_cleanup (); return 0; /* Failure exit point */ } /** * Globally de-initialise test environment */ static void test_global_deinit (void) { #ifdef TEST_USE_STATIC_POST_DATA curl_formfree (post_first); #endif /* TEST_USE_STATIC_POST_DATA */ curl_global_cleanup (); if (NULL != libcurl_long_header) curl_slist_free_all (libcurl_long_header); } /** * libcurl callback parameters for uploads, downloads and debug callbacks */ struct CBC { /* Upload members */ size_t up_pos; size_t up_size; /* Download members */ char *dn_buf; size_t dn_pos; size_t dn_buf_size; /* Debug callback members */ unsigned int excess_found; }; static void initCBC (struct CBC *libcurlcbc, char *dn_buf, size_t dn_buf_size) { libcurlcbc->up_pos = 0; if (use_put_large) libcurlcbc->up_size = PUT_LARGE_SIZE; else if (use_put) libcurlcbc->up_size = PUT_NORMAL_SIZE; else libcurlcbc->up_size = 0; libcurlcbc->dn_buf = dn_buf; libcurlcbc->dn_pos = 0; libcurlcbc->dn_buf_size = dn_buf_size; libcurlcbc->excess_found = 0; } static void resetCBC (struct CBC *libcurlcbc) { libcurlcbc->up_pos = 0; libcurlcbc->dn_pos = 0; } static size_t putBuffer (void *stream, size_t item_size, size_t nitems, void *ctx) { size_t to_fill; size_t i; struct CBC *cbc = ctx; to_fill = cbc->up_size - cbc->up_pos; /* Skip overflow check as the return value is valid anyway */ if (use_put_chunked) { /* Send data as several chunks */ if (to_fill > cbc->up_size / 3) to_fill = cbc->up_size / 3; } if (to_fill > item_size * nitems) to_fill = item_size * nitems; /* Avoid libcurl magic numbers */ #ifdef CURL_READFUNC_PAUSE if (CURL_READFUNC_ABORT == to_fill) to_fill -= 2; #endif /* CURL_READFUNC_PAUSE */ #ifdef CURL_READFUNC_ABORT if (CURL_READFUNC_ABORT == to_fill) --to_fill; #endif /* CURL_READFUNC_ABORT */ for (i = 0; i < to_fill; ++i) ((char *) stream)[i] = 'a' + (char) ((cbc->up_pos + i) % (unsigned char) ('z' - 'a' + 1)); cbc->up_pos += to_fill; return to_fill; } static size_t copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->dn_pos + size * nmemb > cbc->dn_buf_size) return 0; /* overflow */ memcpy (&cbc->dn_buf[cbc->dn_pos], ptr, size * nmemb); cbc->dn_pos += size * nmemb; return size * nmemb; } #define TEST_MAGIC_MARKER0 0xFEE1C0DE #define TEST_MAGIC_MARKER1 (TEST_MAGIC_MARKER0 + 1) #define TEST_MAGIC_MARKER2 (TEST_MAGIC_MARKER0 + 2) struct content_cb_param_strct { unsigned int magic0; /**< Must have TEST_MAGIC_MARKER0 value */ struct MHD_Response *response; /**< The pointer to the response structure */ }; /** * MHD content reader callback that returns * data in chunks. */ static ssize_t content_cb (void *cls, uint64_t pos, char *buf, size_t max) { struct content_cb_param_strct *param = (struct content_cb_param_strct *) cls; size_t fill_size; if ((unsigned int) TEST_MAGIC_MARKER0 != param->magic0) { fprintf (stderr, "Wrong cls pointer " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (pos >= 128 * 10) { if (MHD_YES != MHD_add_response_footer (param->response, "Footer", "working")) { fprintf (stderr, "MHD_add_response_footer() failed " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } return MHD_CONTENT_READER_END_OF_STREAM; } if (128 > max) fill_size = 128; else fill_size = max; memset (buf, 'A' + (char) (unsigned int) (pos / 128), fill_size); return (ssize_t) fill_size; } /** * Deallocate memory for callback cls. */ static void crcf (void *ptr) { free (ptr); } struct req_process_strct { unsigned int magic2; /**< Must have TEST_MAGIC_MARKER2 value */ int is_static; /**< Non-zero if statically allocated, zero if malloc()'ed */ struct MHD_PostProcessor *postprocsr; unsigned int post_data_sum; }; static enum MHD_Result post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *value, uint64_t off, size_t size) { struct req_process_strct *param = (struct req_process_strct *) cls; size_t i; (void) filename; (void) content_type; (void) transfer_encoding; (void) off; /* Unused. Mute compiler warnings. */ if (TEST_MAGIC_MARKER2 != param->magic2) { fprintf (stderr, "The 'param->magic2' has wrong value " "at line %d.\n", (int) __LINE__); abort (); } if (MHD_POSTDATA_KIND != kind) { fprintf (stderr, "The 'kind' parameter has wrong value " "at line %d.\n", (int) __LINE__); abort (); } if (NULL != key) param->post_data_sum += (unsigned int) strlen (key); for (i = 0; size > i; ++i) param->post_data_sum += (unsigned int) (unsigned char) value[i]; return MHD_YES; } static void free_req_pr_data (struct req_process_strct *pr_data) { if (NULL == pr_data) return; if (TEST_MAGIC_MARKER2 != pr_data->magic2) { fprintf (stderr, "The 'pr_data->magic2' has wrong value " "at line %d.\n", (int) __LINE__); abort (); } if (pr_data->is_static) { if (NULL != pr_data->postprocsr) { fprintf (stderr, "The 'pr_data->postprocsr' has wrong value " "at line %d.\n", (int) __LINE__); abort (); } return; } if (NULL != pr_data->postprocsr) MHD_destroy_post_processor (pr_data->postprocsr); pr_data->postprocsr = NULL; free (pr_data); } struct ahc_param_strct { unsigned int magic1; /**< Must have TEST_MAGIC_MARKER1 value */ unsigned int err_flag; /**< Non-zero if any error is encountered */ unsigned int num_replies; /**< The number of replies sent for the current request */ }; static enum MHD_Result send_error_response (struct MHD_Connection *connection, struct ahc_param_strct *param, unsigned int status_code, const char *static_text, const size_t static_text_len) { struct MHD_Response *response; response = MHD_create_response_from_buffer_static (static_text_len, static_text); if (NULL != response) { if (MHD_YES == MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close")) { if (MHD_YES == MHD_queue_response (connection, status_code, response)) { MHD_destroy_response (response); return MHD_YES; /* Success exit point */ } else fprintf (stderr, "MHD_queue_response() failed " "at line %d.\n", (int) __LINE__); } else fprintf (stderr, "MHD_add_response_header() failed " "at line %d.\n", (int) __LINE__); MHD_destroy_response (response); } else fprintf (stderr, "MHD_create_response_from_callback() failed " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Failure exit point */ } static enum MHD_Result ahc_check (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static struct req_process_strct static_req_pr_data = { TEST_MAGIC_MARKER2, ! 0, NULL, 0 }; struct req_process_strct *req_pr_data; struct ahc_param_strct *param = (struct ahc_param_strct *) cls; struct MHD_Response *response; enum MHD_Result ret; unsigned char data_sum; int is_post_req; if (NULL == cls) { fprintf (stderr, "The 'cls' parameter is NULL " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if ((unsigned int) TEST_MAGIC_MARKER1 != param->magic1) { fprintf (stderr, "The 'param->magic1' has wrong value " "at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (NULL == connection) { fprintf (stderr, "The 'connection' parameter is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if (1) { /* Simple check for 'connection' parameter validity */ const union MHD_ConnectionInfo *conn_info; conn_info = MHD_get_connection_info (connection, MHD_CONNECTION_INFO_CONNECTION_TIMEOUT); if (NULL == conn_info) { fprintf (stderr, "The 'MHD_get_connection_info' has returned NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } else if (expected_conn_timeout != conn_info->connection_timeout) { fprintf (stderr, "The 'MHD_get_connection_info' has returned " "unexpected timeout value " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } } if (NULL == url) { fprintf (stderr, "The 'url' parameter is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } if (NULL == method) { fprintf (stderr, "The 'method' parameter is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if (NULL == version) { fprintf (stderr, "The 'version' parameter is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if (NULL == upload_data_size) { fprintf (stderr, "The 'upload_data_size' parameter is NULL " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if ((0 != *upload_data_size) && (NULL == upload_data)) { fprintf (stderr, "The 'upload_data' parameter is NULL " "while '*upload_data_size' is not zero " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if ((NULL != upload_data) && (0 == *upload_data_size)) { fprintf (stderr, "The 'upload_data' parameter is NOT NULL " "while '*upload_data_size' is zero " "at line %d.\n", (int) __LINE__); param->err_flag = 1; return MHD_NO; /* Should not reply */ } if (0 != param->num_replies) { /* Phantom "second" request due to the fuzzing of the input. Refuse. */ return MHD_NO; } is_post_req = (0 == strcmp (method, MHD_HTTP_METHOD_POST)); if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD)) && (0 != strcmp (method, MHD_HTTP_METHOD_PUT)) && (! is_post_req)) { /* Unsupported method for this callback */ return send_error_response (connection, param, MHD_HTTP_NOT_IMPLEMENTED, METHOD_NOT_SUPPORTED, MHD_STATICSTR_LEN_ (METHOD_NOT_SUPPORTED)); } if (NULL == *req_cls) { if (! is_post_req) { /* Use static memory */ *req_cls = &static_req_pr_data; } else { /* POST request, use PostProcessor */ req_pr_data = (struct req_process_strct *) malloc (sizeof (struct req_process_strct)); if (NULL == req_pr_data) { fprintf (stderr, "malloc() failed " "at line %d.\n", (int) __LINE__); return MHD_NO; } req_pr_data->magic2 = TEST_MAGIC_MARKER2; req_pr_data->is_static = 0; req_pr_data->post_data_sum = 0; req_pr_data->postprocsr = MHD_create_post_processor (connection, 1024, &post_iterator, req_pr_data); if (NULL == req_pr_data->postprocsr) { free (req_pr_data); if (NULL == upload_data) return send_error_response (connection, param, MHD_HTTP_BAD_REQUEST, POST_DATA_BROKEN, MHD_STATICSTR_LEN_ (POST_DATA_BROKEN)); else return MHD_NO; /* Cannot handle request, broken POST */ } *req_cls = req_pr_data; } if (NULL == upload_data) return MHD_YES; } req_pr_data = (struct req_process_strct *) *req_cls; data_sum = 0; if (NULL != upload_data) { if (is_post_req) { if (MHD_YES != MHD_post_process (req_pr_data->postprocsr, upload_data, *upload_data_size)) { free_req_pr_data (req_pr_data); *req_cls = NULL; /* Processing upload body (context), error reply cannot be queued here */ return MHD_NO; } *upload_data_size = 0; /* All data have been processed */ } else { /* Check that all 'upload_data' is addressable */ size_t pos; for (pos = 0; pos < *upload_data_size; ++pos) data_sum = (unsigned char) (data_sum + (unsigned char) upload_data[pos]); if (0 != *upload_data_size) { if (3 >= *upload_data_size) *upload_data_size = 0; /* Consume all incoming data */ else *upload_data_size = data_sum % *upload_data_size; /* Pseudo-random */ } } return MHD_YES; } if (is_post_req) { if (MHD_YES != MHD_destroy_post_processor (req_pr_data->postprocsr)) { free (req_pr_data); *req_cls = NULL; return send_error_response (connection, param, MHD_HTTP_BAD_REQUEST, POST_DATA_BROKEN, MHD_STATICSTR_LEN_ (POST_DATA_BROKEN)); } req_pr_data->postprocsr = NULL; } data_sum += (unsigned char) req_pr_data->post_data_sum; free_req_pr_data (req_pr_data); *req_cls = NULL; ret = MHD_YES; if (use_get_chunked) { struct content_cb_param_strct *cnt_cb_param; cnt_cb_param = malloc (sizeof (struct content_cb_param_strct)); if (NULL == cnt_cb_param) { fprintf (stderr, "malloc() failed " "at line %d.\n", (int) __LINE__); /* External error, do not rise the error flag */ return MHD_NO; } cnt_cb_param->magic0 = (unsigned int) TEST_MAGIC_MARKER0; response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, 1024, &content_cb, cnt_cb_param, &crcf); if (NULL == response) { fprintf (stderr, "MHD_create_response_from_callback() failed " "at line %d.\n", (int) __LINE__); free (cnt_cb_param); param->err_flag = 1; ret = MHD_NO; } else cnt_cb_param->response = response; } else if (use_get || use_put || use_post) { /* Randomly choose the response page for the POST requests */ if (0 == data_sum % 2) response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (EMPTY_PAGE), EMPTY_PAGE); else response = MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ ( \ EMPTY_PAGE_ALT), EMPTY_PAGE_ALT); if (NULL == response) { fprintf (stderr, "MHD_create_response_from_buffer_static() failed " "at line %d.\n", (int) __LINE__); param->err_flag = 1; ret = MHD_NO; } } else { fprintf (stderr, "Response is not implemented for this test. " "Internal logic is broken. " "At line %d.\n", (int) __LINE__); abort (); } if (NULL != response) { if ((MHD_YES == ret) && (use_close || (! oneone && (0 != strcmp (version, MHD_HTTP_VERSION_1_0))))) { ret = MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); if (MHD_YES != ret) { fprintf (stderr, "MHD_add_response_header() failed " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } } if (MHD_YES == ret) { ret = MHD_queue_response (connection, MHD_HTTP_OK, response); if (MHD_YES != ret) { fprintf (stderr, "MHD_queue_response() failed " "at line %d.\n", (int) __LINE__); param->err_flag = 1; } } else param->num_replies++; MHD_destroy_response (response); } else { fprintf (stderr, "MHD_create_response_from_buffer_static() failed " "at line %d.\n", (int) __LINE__); ret = MHD_NO; } return ret; } static void req_completed_cleanup (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct ahc_param_strct *param = (struct ahc_param_strct *) cls; struct req_process_strct *req_pr_data = (struct req_process_strct *) *req_cls; (void) connection; /* Unused. Mute compiler warning. */ if (NULL == param) { fprintf (stderr, "The 'cls' parameter is NULL at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if ((unsigned int) TEST_MAGIC_MARKER1 != param->magic1) { fprintf (stderr, "The 'param->magic1' has wrong value at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (NULL == req_pr_data) return; /* The data have been freed */ if ((unsigned int) TEST_MAGIC_MARKER2 != req_pr_data->magic2) { fprintf (stderr, "The 'req_pr_data->magic2' has wrong value at line %d.\n", (int) __LINE__); fflush (stderr); abort (); } if (MHD_REQUEST_TERMINATED_COMPLETED_OK == toe) { fprintf (stderr, "The request completed successful, but request cls has" "not been cleared. " "At line %d.\n", (int) __LINE__); param->err_flag = 1; } if (req_pr_data->is_static) return; if (NULL != req_pr_data->postprocsr) MHD_destroy_post_processor (req_pr_data->postprocsr); req_pr_data->postprocsr = NULL; free (req_pr_data); *req_cls = NULL; } /* Un-comment the next line (or use CPPFLAGS) to avoid logging of the traffic with debug builds */ /* #define TEST_NO_PRINT_TRAFFIC 1 */ #ifdef _DEBUG #ifdef TEST_PRINT_BODY #ifndef TEST_PRINT_BODY_RQ #define TEST_PRINT_BODY_RQ 1 #endif /* TEST_PRINT_BODY_RQ */ #ifndef TEST_PRINT_BODY_RP #define TEST_PRINT_BODY_RP 1 #endif /* TEST_PRINT_BODY_RP */ #endif /* TEST_PRINT_BODY */ #endif /* _DEBUG */ static int libcurl_debug_cb (CURL *handle, curl_infotype type, char *data, size_t size, void *ctx) { static const char excess_mark[] = "Excess found"; static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark); struct CBC *cbc = ctx; (void) handle; #if defined(_DEBUG) && ! defined(TEST_NO_PRINT_TRAFFIC) switch (type) { case CURLINFO_TEXT: fprintf (stderr, "* %.*s", (int) size, data); break; case CURLINFO_HEADER_IN: fprintf (stderr, "< %.*s", (int) size, data); break; case CURLINFO_HEADER_OUT: fprintf (stderr, "> %.*s", (int) size, data); break; case CURLINFO_DATA_IN: #ifdef TEST_PRINT_BODY_RP fprintf (stderr, "<| %.*s\n", (int) size, data); #endif /* TEST_PRINT_BODY_RP */ break; case CURLINFO_DATA_OUT: #ifdef TEST_PRINT_BODY_RQ fprintf (stderr, ">| %.*s\n", (int) size, data); #endif /* TEST_PRINT_BODY_RQ */ break; case CURLINFO_SSL_DATA_IN: case CURLINFO_SSL_DATA_OUT: case CURLINFO_END: default: break; } #endif /* _DEBUG && ! TEST_NO_PRINT_TRAFFIC */ if (use_close || ! oneone) { /* Check for extra data only if every connection is terminated by MHD after one request, otherwise MHD may react on garbage after request data. */ if (CURLINFO_TEXT == type) { if ((size >= excess_mark_len) && (0 == memcmp (data, excess_mark, excess_mark_len))) { fprintf (stderr, "Extra data has been detected in MHD reply " "at line %d.\n", (int) __LINE__); cbc->excess_found++; } } } return 0; } static CURL * setupCURL (struct CBC *cbc, uint16_t port #ifndef TEST_USE_STATIC_POST_DATA , curl_mime **mime #endif /* ! TEST_USE_STATIC_POST_DATA */ ) { CURL *c; CURLcode e; char *buf; const char *uri_to_use; const char *base_uri; #ifndef TEST_USE_STATIC_POST_DATA *mime = NULL; #endif /* ! TEST_USE_STATIC_POST_DATA */ base_uri = run_with_socat ? TEST_BASE_URI_SOCAT : TEST_BASE_URI; if (! use_long_uri) { uri_to_use = base_uri; buf = NULL; } else { size_t pos; size_t base_uri_len; base_uri_len = strlen (base_uri); buf = malloc (TEST_STRING_VLONG_LEN + 1); if (NULL == buf) { fprintf (stderr, "malloc() failed " "at line %d.\n", (int) __LINE__); return NULL; } memcpy (buf, base_uri, base_uri_len); for (pos = base_uri_len; pos < TEST_STRING_VLONG_LEN; ++pos) { if (0 == pos % 9) buf[pos] = '/'; else buf[pos] = 'a' + (char) (unsigned char) (pos % ((unsigned char) ('z' - 'a' + 1))); } buf[TEST_STRING_VLONG_LEN] = 0; uri_to_use = buf; } if (run_with_socat) port = SOCAT_PORT; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed " "at line %d.\n", (int) __LINE__); return NULL; } if ((CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_URL, uri_to_use))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, ©Buffer))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) CURL_TIMEOUT)))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) CURL_TIMEOUT)))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L))) && #ifdef _DEBUG (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_VERBOSE, 1L))) && #endif /* _DEBUG */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION, &libcurl_debug_cb))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_DEBUGDATA, cbc))) && #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http"))) && #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http"))) && #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP))) && #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, oneone ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) && #if CURL_AT_LEAST_VERSION (7, 24, 0) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INTERFACE, "host!127.0.0.101"))) && #else /* ! CURL_AT_LEAST_VERSION (7, 24, 0) */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INTERFACE, "127.0.0.101"))) && #endif /* ! CURL_AT_LEAST_VERSION (7, 24, 0) */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_HTTPHEADER, use_long_header ? libcurl_long_header : NULL))) ) { if (NULL != buf) { free (buf); buf = NULL; } if (use_put) { if ((CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_READFUNCTION, &putBuffer))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_READDATA, cbc))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_UPLOAD, (long) 1))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE, use_put_chunked ? ((curl_off_t) -1) : ((curl_off_t) cbc->up_size))))) { return c; /* Success exit point for 'use_put' */ } else fprintf (stderr, "PUT-related curl_easy_setopt() failed at line %d, " "error: %s\n", (int) __LINE__, curl_easy_strerror (e)); } else if (use_post) { if (! use_post_form) { if ((CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_POST, (long) 1))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_POSTFIELDS, POST_URLENC_DATA))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE, MHD_STATICSTR_LEN_ (POST_URLENC_DATA))))) { return c; /* Success exit point for 'use_post' */ } else fprintf (stderr, "POST-related curl_easy_setopt() failed at line %d, " "error: %s\n", (int) __LINE__, curl_easy_strerror (e)); } else { #ifndef TEST_USE_STATIC_POST_DATA *mime = curl_mime_init (c); if (NULL != *mime) { curl_mimepart *part; if ((NULL != (part = curl_mime_addpart (*mime))) && (CURLE_OK == curl_mime_name (part, POST_KEY1)) && (CURLE_OK == curl_mime_data (part, POST_VALUE1, MHD_STATICSTR_LEN_ (POST_VALUE1))) && (NULL != (part = curl_mime_addpart (*mime))) && (CURLE_OK == curl_mime_name (part, POST_KEY2)) && (CURLE_OK == curl_mime_data (part, POST_VALUE2, MHD_STATICSTR_LEN_ (POST_VALUE2)))) { if (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_MIMEPOST, *mime))) return c; /* Success exit point for 'use_post' */ else fprintf (stderr, "curl_easy_setopt(c, CURLOPT_MIMEPOST, mime) " "failed at line %d, error: %s\n", (int) __LINE__, curl_easy_strerror (e)); } else fprintf (stderr, "curl_mime_addpart(), curl_mime_name() or " "curl_mime_data() failed.\n"); } else fprintf (stderr, "curl_mime_init() failed.\n"); #else /* TEST_USE_STATIC_POST_DATA */ if (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_HTTPPOST, post_first))) { return c; /* Success exit point for 'use_post' */ } else fprintf (stderr, "POST form-related curl_easy_setopt() failed, " "error: %s\n", curl_easy_strerror (e)); #endif /* TEST_USE_STATIC_POST_DATA */ } } else return c; /* Success exit point */ } else fprintf (stderr, "curl_easy_setopt() failed at line %d, " "error: %s\n", (int) __LINE__, curl_easy_strerror (e)); curl_easy_cleanup (c); #ifndef TEST_USE_STATIC_POST_DATA if (NULL != *mime) curl_mime_free (*mime); #endif /* ! TEST_USE_STATIC_POST_DATA */ if (NULL != buf) free (buf); return NULL; /* Failure exit point */ } static struct MHD_Daemon * start_daemon_for_test (unsigned int daemon_flags, uint16_t *pport, struct ahc_param_strct *callback_param) { struct MHD_Daemon *d; struct MHD_OptionItem ops[] = { { MHD_OPTION_END, 0, NULL }, { MHD_OPTION_END, 0, NULL }, { MHD_OPTION_END, 0, NULL }, { MHD_OPTION_END, 0, NULL }, { MHD_OPTION_END, 0, NULL }, { MHD_OPTION_END, 0, NULL } }; size_t num_opt; size_t mem_limit; num_opt = 0; callback_param->magic1 = (unsigned int) TEST_MAGIC_MARKER1; callback_param->err_flag = 0; callback_param->num_replies = 0; /* The tests with intentionally huge URIs, headers or bodies need a memory limit that matches the data they send; for all other tests the limit comes from the option profile (which may be "keep the default"). */ if (use_put_large) mem_limit = (size_t) (PUT_LARGE_SIZE / 4); else if (use_long_header || use_long_uri) mem_limit = (size_t) (TEST_STRING_VLONG_LEN / 2); else mem_limit = cur_profile->mem_limit; if (0 != mem_limit) { ops[num_opt].option = MHD_OPTION_CONNECTION_MEMORY_LIMIT; ops[num_opt].value = (intptr_t) mem_limit; ++num_opt; } if (0 != cur_profile->conn_limit) { ops[num_opt].option = MHD_OPTION_CONNECTION_LIMIT; ops[num_opt].value = (intptr_t) cur_profile->conn_limit; ++num_opt; } if (0 != cur_profile->discipline_lvl) { ops[num_opt].option = cur_profile->use_legacy_strict ? MHD_OPTION_STRICT_FOR_CLIENT : MHD_OPTION_CLIENT_DISCIPLINE_LVL; ops[num_opt].value = (intptr_t) cur_profile->discipline_lvl; ++num_opt; } if (0 == (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) { ops[num_opt].option = MHD_OPTION_APP_FD_SETSIZE; ops[num_opt].value = (intptr_t) (FD_SETSIZE); ++num_opt; } expected_conn_timeout = cur_profile->timeout; d = MHD_start_daemon (daemon_flags /* | MHD_USE_ERROR_LOG */, *pport, NULL, NULL, &ahc_check, callback_param, MHD_OPTION_CONNECTION_TIMEOUT, expected_conn_timeout, MHD_OPTION_NOTIFY_COMPLETED, &req_completed_cleanup, callback_param, MHD_OPTION_ARRAY, ops, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "MHD_start_daemon() failed " "at line %d.\n", (int) __LINE__); return NULL; } /* Do not use accept4() as only accept() is intercepted by zzuf */ if (! run_with_socat) MHD_avoid_accept4_ (d); if (0 == *pport) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) { fprintf (stderr, "MHD_get_daemon_info() failed " "at line %d.\n", (int) __LINE__); MHD_stop_daemon (d); return NULL; } *pport = dinfo->port; } return d; } /** * Select the daemon option profile for the next daemon and print * a description of the test that is about to start. * * @param daemon_flags the flags of the daemon that is about to be started */ static void print_test_starting (unsigned int daemon_flags) { static unsigned int profile_num; /* Every started daemon uses the next profile of the matrix, so that a single run of a "_hostile" program sweeps the whole option matrix. */ cur_profile = zzuf_opt_profile (use_hostile_opts ? profile_num++ : 0); fflush (stderr); if (0 != (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) { if (0 != (MHD_USE_THREAD_PER_CONNECTION & daemon_flags)) { if (0 != (MHD_USE_POLL & daemon_flags)) printf ("\nStarting test with internal polling by poll() and " "thread-per-connection.\n"); else printf ("\nStarting test with internal polling by select() and " "thread-per-connection.\n"); } else { if (0 != (MHD_USE_POLL & daemon_flags)) printf ("\nStarting test with internal polling by poll().\n"); else if (0 != (MHD_USE_EPOLL & daemon_flags)) printf ("\nStarting test with internal polling by 'epoll'.\n"); else printf ("\nStarting test with internal polling by select().\n"); } } else { if (0 != (MHD_USE_EPOLL & daemon_flags)) printf ("\nStarting test with%s thread safety with external polling " "and internal 'epoll'.\n", ((0 != (MHD_USE_NO_THREAD_SAFETY & daemon_flags)) ? "out" : "")); else printf ("\nStarting test with%s thread safety with external polling.\n", ((0 != (MHD_USE_NO_THREAD_SAFETY & daemon_flags)) ? "out" : "")); } if (use_hostile_opts) printf ("Daemon options profile '%s' " "(mem_limit=%lu, conn_limit=%u, timeout=%u, %s=%d).\n", cur_profile->name, (unsigned long) cur_profile->mem_limit, cur_profile->conn_limit, cur_profile->timeout, cur_profile->use_legacy_strict ? "strict_for_client" : "discipline_lvl", cur_profile->discipline_lvl); fflush (stdout); } static unsigned int testInternalPolling (uint16_t *pport, unsigned int daemon_flags) { struct MHD_Daemon *d; CURL *c; char buf[2048]; struct CBC cbc; struct ahc_param_strct callback_param; unsigned int ret; #ifndef TEST_USE_STATIC_POST_DATA curl_mime *mime; #endif /* ! TEST_USE_STATIC_POST_DATA */ if (0 == (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) { fprintf (stderr, "Wrong internal flags, the test is broken. " "At line %d.\n", (int) __LINE__); abort (); /* Wrong flags, error in code */ } print_test_starting (daemon_flags); initCBC (&cbc, buf, sizeof(buf)); d = start_daemon_for_test (daemon_flags, pport, &callback_param); if (d == NULL) return 1; ret = 0; c = setupCURL (&cbc, *pport #ifndef TEST_USE_STATIC_POST_DATA , &mime #endif /* ! TEST_USE_STATIC_POST_DATA */ ); if (NULL != c) { int i; for (i = dry_run ? LOOP_COUNT : 0; i < LOOP_COUNT; i++) { fprintf (stderr, "."); callback_param.num_replies = 0; resetCBC (&cbc); /* Run libcurl without checking the result */ curl_easy_perform (c); fflush (stderr); } curl_easy_cleanup (c); #ifndef TEST_USE_STATIC_POST_DATA if (NULL != mime) curl_mime_free (mime); #endif /* ! TEST_USE_STATIC_POST_DATA */ } else ret = 99; /* Not an MHD error */ if ((0 == ret) && callback_param.err_flag) { fprintf (stderr, "One or more errors have been detected by " "access handler callback function. " "At line %d.\n", (int) __LINE__); ret = 1; } else if ((0 == ret) && cbc.excess_found) { fprintf (stderr, "The extra reply data have been detected one " "or more times. " "At line %d.\n", (int) __LINE__); ret = 1; } fprintf (stderr, "\n"); MHD_stop_daemon (d); fflush (stderr); return ret; } static unsigned int testExternalPolling (uint16_t *pport, unsigned int daemon_flags) { struct MHD_Daemon *d; CURLM *multi; char buf[2048]; struct CBC cbc; struct ahc_param_strct callback_param; unsigned int ret; #ifndef TEST_USE_STATIC_POST_DATA curl_mime *mime; #endif /* ! TEST_USE_STATIC_POST_DATA */ if (0 != (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) { fprintf (stderr, "Wrong internal flags, the test is broken. " "At line %d.\n", (int) __LINE__); abort (); /* Wrong flags, error in code */ } print_test_starting (daemon_flags); initCBC (&cbc, buf, sizeof(buf)); d = start_daemon_for_test (daemon_flags, pport, &callback_param); if (d == NULL) return 1; ret = 0; multi = curl_multi_init (); if (multi == NULL) { fprintf (stderr, "curl_multi_init() failed " "at line %d.\n", (int) __LINE__); ret = 99; /* Not an MHD error */ } else { CURL *c; c = setupCURL (&cbc, *pport #ifndef TEST_USE_STATIC_POST_DATA , &mime #endif /* ! TEST_USE_STATIC_POST_DATA */ ); if (NULL == c) ret = 99; /* Not an MHD error */ else { int i; for (i = dry_run ? LOOP_COUNT : 0; (i < LOOP_COUNT) && (0 == ret); i++) { CURLMcode mret; /* The same 'multi' handle will be used in transfers so connection will be reused. The same 'easy' handle is added (and removed later) to (re-)start the same transfer. */ mret = curl_multi_add_handle (multi, c); if (CURLM_OK != mret) { fprintf (stderr, "curl_multi_add_handle() failed at %d, " "error: %s\n", (int) __LINE__, curl_multi_strerror (mret)); ret = 99; /* Not an MHD error */ } else { time_t start; fprintf (stderr, "."); callback_param.num_replies = 0; resetCBC (&cbc); start = time (NULL); do { fd_set rs; fd_set ws; fd_set es; int maxfd_curl; MHD_socket maxfd_mhd; int maxfd; int running; struct timeval tv; maxfd_curl = 0; maxfd_mhd = MHD_INVALID_SOCKET; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (multi, &running); if (0 == running) { int msgs_left; do { (void) curl_multi_info_read (multi, &msgs_left); } while (0 != msgs_left); break; /* The transfer has been finished */ } mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxfd_curl); if (CURLM_OK != mret) { fprintf (stderr, "curl_multi_fdset() failed at line %d, " "error: %s\n", (int) __LINE__, curl_multi_strerror (mret)); ret = 99; /* Not an MHD error */ break; } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxfd_mhd)) { fprintf (stderr, "MHD_get_fdset() failed " "at line %d.\n", (int) __LINE__); ret = 1; break; } #ifndef MHD_WINSOCK_SOCKETS if ((int) maxfd_mhd > maxfd_curl) maxfd = (int) maxfd_mhd; else #endif /* ! MHD_WINSOCK_SOCKETS */ maxfd = maxfd_curl; tv.tv_sec = 0; tv.tv_usec = 100 * 1000; if (0 == MHD_get_timeout64s (d)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } if (-1 == select (maxfd + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) fprintf (stderr, "Unexpected select() error " "at line %d.\n", (int) __LINE__); #else /* ! MHD_POSIX_SOCKETS */ if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count)) fprintf (stderr, "Unexpected select() error " "at line %d.\n", (int) __LINE__); Sleep ((unsigned long) tv.tv_usec / 1000); #endif /* ! MHD_POSIX_SOCKETS */ } MHD_run (d); } while (time (NULL) - start <= MHD_TIMEOUT); /* Remove 'easy' handle from 'multi' handle to * restart the transfer or to finish. */ curl_multi_remove_handle (multi, c); } } curl_easy_cleanup (c); } curl_multi_cleanup (multi); #ifndef TEST_USE_STATIC_POST_DATA if (NULL != mime) curl_mime_free (mime); #endif /* ! TEST_USE_STATIC_POST_DATA */ } if ((0 == ret) && callback_param.err_flag) { fprintf (stderr, "One or more errors have been detected by " "access handler callback function. " "At line %d.\n", (int) __LINE__); ret = 1; } else if ((0 == ret) && cbc.excess_found) { fprintf (stderr, "The extra reply data have been detected one " "or more times. " "At line %d.\n", (int) __LINE__); ret = 1; } fprintf (stderr, "\n"); MHD_stop_daemon (d); return 0; } static unsigned int run_all_checks (void) { uint16_t port; unsigned int testRes; unsigned int ret = 0; if (! run_with_socat) { if (MHD_are_sanitizers_enabled_ ()) { fprintf (stderr, "Direct run with zzuf does not work with sanitizers. " "At line %d.\n", (int) __LINE__); return 77; } if (! MHD_is_avoid_accept4_possible_ ()) { fprintf (stderr, "Non-debug build of MHD on this platform use accept4() function. " "Direct run with zzuf is not possible. " "At line %d.\n", (int) __LINE__); return 77; } if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) port = 0; /* Use system automatic assignment */ else { port = TEST_BASE_PORT; /* Use predefined port, may break parallel testing of another MHD build */ if (oneone) port += 100; if (use_long_uri) port += 30; else if (use_long_header) port += 35; else if (use_get_chunked) port += 0; else if (use_get) port += 5; else if (use_post_form) port += 10; else if (use_post) port += 15; else if (use_put_large) port += 20; else if (use_put_chunked) port += 25; if (use_hostile_opts) port += 40; } } else port = TEST_BASE_PORT; /* Use predefined port, may break parallel testing of another MHD build */ if (! dry_run && (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))) { testRes = testInternalPolling (&port, MHD_USE_SELECT_INTERNALLY); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; testRes = testInternalPolling (&port, MHD_USE_SELECT_INTERNALLY | MHD_USE_THREAD_PER_CONNECTION); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { testRes = testInternalPolling (&port, MHD_USE_POLL_INTERNALLY); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; testRes = testInternalPolling (&port, MHD_USE_POLL_INTERNALLY | MHD_USE_THREAD_PER_CONNECTION); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { testRes = testInternalPolling (&port, MHD_USE_EPOLL_INTERNALLY); if ((77 == testRes) || (99 == testRes)) return testRes; } testRes = testExternalPolling (&port, MHD_NO_FLAG); } testRes = testExternalPolling (&port, MHD_USE_NO_THREAD_SAFETY); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; return ret; } int main (int argc, char *const *argv) { unsigned int res; int use_magic_exit_codes; oneone = ! has_in_name (argv[0], "10"); use_get = has_in_name (argv[0], "_get"); use_get_chunked = has_in_name (argv[0], "_get_chunked"); use_put = has_in_name (argv[0], "_put"); use_put_large = has_in_name (argv[0], "_put_large"); use_put_chunked = has_in_name (argv[0], "_put_chunked"); use_post = has_in_name (argv[0], "_post"); use_post_form = has_in_name (argv[0], "_post_form"); use_long_header = has_in_name (argv[0], "_long_header"); use_long_uri = has_in_name (argv[0], "_long_uri"); use_close = has_in_name (argv[0], "_close"); use_hostile_opts = has_in_name (argv[0], "_hostile"); cur_profile = zzuf_opt_profile (0); run_with_socat = has_param (argc, argv, "--with-socat"); dry_run = has_param (argc, argv, "--dry-run") || has_param (argc, argv, "-n"); if (1 != ((use_get ? 1 : 0) + (use_put ? 1 : 0) + (use_post ? 1 : 0))) { fprintf (stderr, "Wrong test name '%s': no or multiple indications " "for the test type.\n", argv[0] ? argv[0] : "(NULL)"); return 99; } use_magic_exit_codes = run_with_socat || dry_run; /* zzuf cannot bypass exit values. Unless 'dry run' is used, do not return errors for external error conditions (like out-of-memory) as they will be reported as test failures. */ if (! test_global_init ()) return use_magic_exit_codes ? 99 : 0; res = run_all_checks (); test_global_deinit (); if (99 == res) return use_magic_exit_codes ? 99 : 0; if (77 == res) return use_magic_exit_codes ? 77 : 0; return (0 == res) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/testzzuf/mhd_zzuf_common.c0000664000175000017500000006700415232103064016152 /* This file is part of GNU libmicrohttpd Copyright (C) 2026 Christian Grothoff GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file testzzuf/mhd_zzuf_common.c * @brief Shared support code for the fuzzing tests in this directory * @author Christian Grothoff */ #include "platform.h" #include #include #include #include #include #include #ifdef HAVE_NETINET_IN_H #include #endif /* HAVE_NETINET_IN_H */ #ifdef HAVE_ARPA_INET_H #include #endif /* HAVE_ARPA_INET_H */ #ifdef HAVE_NETINET_TCP_H #include #endif /* HAVE_NETINET_TCP_H */ #include "mhd_zzuf_common.h" #include "mhd_debug_funcs.h" #include "test_helpers.h" int zzuf_run_with_socat; int zzuf_dry_run; int zzuf_oneone; int zzuf_use_close; const struct zzuf_opt_profile *zzuf_active_profile; /** * The name of the running program, as given in argv[0]. */ static const char *zzuf_prog_name = ""; /* *** Platform abstraction for the raw socket client *** */ #if defined(MHD_POSIX_SOCKETS) #define ZZUF_CLOSE_SOCKET(s) close (s) #define ZZUF_SOCK_ERR (errno) #define ZZUF_ERR_IS_AGAIN(e) \ ((EAGAIN == (e)) || (EWOULDBLOCK == (e)) || (EINTR == (e))) #define ZZUF_ERR_IS_INPROGRESS(e) \ ((EINPROGRESS == (e)) || (EALREADY == (e)) || ZZUF_ERR_IS_AGAIN (e)) #else /* ! MHD_POSIX_SOCKETS */ #define ZZUF_CLOSE_SOCKET(s) closesocket (s) #define ZZUF_SOCK_ERR ((int) WSAGetLastError ()) #define ZZUF_ERR_IS_AGAIN(e) (WSAEWOULDBLOCK == (e)) #define ZZUF_ERR_IS_INPROGRESS(e) \ ((WSAEWOULDBLOCK == (e)) || (WSAEINPROGRESS == (e)) || \ (WSAEALREADY == (e))) #endif /* ! MHD_POSIX_SOCKETS */ #ifdef MSG_NOSIGNAL #define ZZUF_SEND_FLAGS MSG_NOSIGNAL #else /* ! MSG_NOSIGNAL */ #define ZZUF_SEND_FLAGS 0 #endif /* ! MSG_NOSIGNAL */ void zzuf_parse_common_args (int argc, char *const *argv) { const char *name; name = (NULL != argv[0]) ? argv[0] : ""; zzuf_prog_name = name; zzuf_oneone = ! has_in_name (name, "10"); zzuf_use_close = has_in_name (name, "_close"); zzuf_run_with_socat = has_param (argc, argv, "--with-socat"); zzuf_dry_run = has_param (argc, argv, "--dry-run") || has_param (argc, argv, "-n"); #ifdef SIGPIPE /* The raw client writes to sockets that MHD may close at any moment because of the fuzzed input. Do not die from SIGPIPE. */ (void) signal (SIGPIPE, SIG_IGN); #endif /* SIGPIPE */ } int zzuf_name_has (const char *marker) { return has_in_name (zzuf_prog_name, marker); } unsigned int zzuf_loop_count (void) { return zzuf_dry_run ? 0 : (unsigned int) ZZUF_LOOP_COUNT; } /* *** The option matrix *** */ /** * The matrix of daemon options exercised by the fuzzing tests. * * Entry zero must stay "neutral": it reproduces the configuration that was * used before the option matrix was introduced. * * The memory limits below 1500 (MHD_BUF_INC_SIZE) are the interesting ones: * only with such a small connection pool MHD tries to re-use the tail of the * request header buffer ("shift back"), and only then the buffer arithmetic * around the last parsed header/argument element is reachable at all. * * #MHD_OPTION_SERVER_INSANITY is deliberately *not* used: in this MHD version * the only value of `enum MHD_DisableSanityCheck` is #MHD_DSC_SANE (zero), so * the option cannot disable anything and setting it would be a no-op. * */ static const struct zzuf_opt_profile opt_profiles[] = { /* name mem conn timeout discipline legacy */ { "plain", 0, 0, ZZUF_MHD_TIMEOUT, 0, 0 }, { "pool-128", 128, 0, ZZUF_MHD_TIMEOUT, 0, 0 }, { "pool-256-strict", 256, 0, ZZUF_MHD_TIMEOUT, 1, 0 }, { "pool-512-lax", 512, 0, ZZUF_MHD_TIMEOUT, -1, 0 }, { "pool-1024-conn", 1024, 4, ZZUF_MHD_TIMEOUT, 2, 0 }, { "pool-1400-hard", 1400, 2, 1, 3, 0 }, { "pool-768-loose", 768, 0, 1, -3, 0 }, { "legacy-strict", 192, 0, ZZUF_MHD_TIMEOUT, 1, 1 }, { "legacy-lax", 320, 0, ZZUF_MHD_TIMEOUT, -1, 1 } }; unsigned int zzuf_num_opt_profiles (void) { return (unsigned int) (sizeof(opt_profiles) / sizeof(opt_profiles[0])); } const struct zzuf_opt_profile * zzuf_opt_profile (unsigned int idx) { return opt_profiles + (idx % zzuf_num_opt_profiles ()); } /* *** Daemon handling *** */ uint16_t zzuf_pick_port (uint16_t offset) { if (zzuf_run_with_socat) return (uint16_t) ZZUF_BASE_PORT; /* socat forwards to this fixed port */ if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) return 0; /* Use system automatic assignment */ /* Use a predefined port; may break parallel testing of another MHD build */ return (uint16_t) (ZZUF_BASE_PORT + offset + (zzuf_oneone ? 100 : 0)); } struct MHD_Daemon * zzuf_start_daemon (unsigned int daemon_flags, uint16_t *pport, const struct zzuf_opt_profile *prof, size_t mem_limit_override, MHD_AccessHandlerCallback ahc, void *ahc_cls, MHD_RequestCompletedCallback rcc, void *rcc_cls, const struct MHD_OptionItem *extra_opts) { struct MHD_Daemon *d; struct MHD_OptionItem ops[16]; size_t num_opt; size_t mem_limit; num_opt = 0; mem_limit = (0 != mem_limit_override) ? mem_limit_override : prof->mem_limit; if (0 != mem_limit) { ops[num_opt].option = MHD_OPTION_CONNECTION_MEMORY_LIMIT; ops[num_opt].value = (intptr_t) mem_limit; ops[num_opt].ptr_value = NULL; ++num_opt; } if (0 != prof->conn_limit) { ops[num_opt].option = MHD_OPTION_CONNECTION_LIMIT; ops[num_opt].value = (intptr_t) prof->conn_limit; ops[num_opt].ptr_value = NULL; ++num_opt; } if (0 != prof->discipline_lvl) { ops[num_opt].option = prof->use_legacy_strict ? MHD_OPTION_STRICT_FOR_CLIENT : MHD_OPTION_CLIENT_DISCIPLINE_LVL; ops[num_opt].value = (intptr_t) prof->discipline_lvl; ops[num_opt].ptr_value = NULL; ++num_opt; } if (0 == (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) { ops[num_opt].option = MHD_OPTION_APP_FD_SETSIZE; ops[num_opt].value = (intptr_t) (FD_SETSIZE); ops[num_opt].ptr_value = NULL; ++num_opt; } if (NULL != rcc) { ops[num_opt].option = MHD_OPTION_NOTIFY_COMPLETED; ops[num_opt].value = (intptr_t) rcc; ops[num_opt].ptr_value = rcc_cls; ++num_opt; } if (NULL != extra_opts) { size_t i; for (i = 0; MHD_OPTION_END != extra_opts[i].option; ++i) { if (num_opt + 2 > sizeof(ops) / sizeof(ops[0])) { fprintf (stderr, "Too many daemon options at line %d.\n", (int) __LINE__); fflush (stderr); abort (); /* Broken test code */ } ops[num_opt++] = extra_opts[i]; } } if (num_opt + 1 > sizeof(ops) / sizeof(ops[0])) { fprintf (stderr, "Too many daemon options at line %d.\n", (int) __LINE__); fflush (stderr); abort (); /* Broken test code */ } ops[num_opt].option = MHD_OPTION_END; ops[num_opt].value = 0; ops[num_opt].ptr_value = NULL; ++num_opt; d = MHD_start_daemon (daemon_flags /* | MHD_USE_ERROR_LOG */, *pport, NULL, NULL, ahc, ahc_cls, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) prof->timeout, MHD_OPTION_ARRAY, ops, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "MHD_start_daemon() failed " "at line %d.\n", (int) __LINE__); return NULL; } /* Do not use accept4() as only accept() is intercepted by zzuf */ if (! zzuf_run_with_socat) MHD_avoid_accept4_ (d); if (0 == *pport) { const union MHD_DaemonInfo *dinfo; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port)) { fprintf (stderr, "MHD_get_daemon_info() failed " "at line %d.\n", (int) __LINE__); MHD_stop_daemon (d); return NULL; } *pport = dinfo->port; } return d; } /** * Print a description of the daemon that is about to be tested. * * @param daemon_flags the daemon flags * @param prof the option profile in use */ static void print_test_starting (unsigned int daemon_flags, const struct zzuf_opt_profile *prof) { const char *mode; fflush (stderr); if (0 != (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) { if (0 != (MHD_USE_THREAD_PER_CONNECTION & daemon_flags)) mode = (0 != (MHD_USE_POLL & daemon_flags)) ? "internal poll(), thread-per-connection" : "internal select(), thread-per-connection"; else if (0 != (MHD_USE_POLL & daemon_flags)) mode = "internal poll()"; else if (0 != (MHD_USE_EPOLL & daemon_flags)) mode = "internal 'epoll'"; else mode = "internal select()"; } else { if (0 != (MHD_USE_NO_THREAD_SAFETY & daemon_flags)) mode = "external polling, no thread safety"; else mode = "external polling"; } printf ("\nStarting test with %s; options profile '%s' " "(mem_limit=%lu, conn_limit=%u, timeout=%u, %s=%d).\n", mode, prof->name, (unsigned long) prof->mem_limit, prof->conn_limit, prof->timeout, prof->use_legacy_strict ? "strict_for_client" : "discipline_lvl", prof->discipline_lvl); fflush (stdout); } /** * Run a single check: start a daemon, run the client, stop the daemon. * * @param[in,out] p the parameters * @param daemon_flags the flags for the daemon * @param[in,out] pprofile_num the number of the next profile to use * @return the result of the client callback, or 1 if the daemon could not * be started */ static unsigned int run_one_mode (struct zzuf_run_params *p, unsigned int daemon_flags, unsigned int *pprofile_num) { struct MHD_Daemon *d; const struct zzuf_opt_profile *prof; unsigned int ret; if (p->sweep_profiles) prof = zzuf_opt_profile ((*pprofile_num)++); else prof = zzuf_opt_profile (0); zzuf_active_profile = prof; print_test_starting (daemon_flags, prof); d = zzuf_start_daemon (daemon_flags, &p->port, prof, p->mem_limit_override, p->ahc, p->ahc_cls, p->rcc, p->rcc_cls, p->extra_opts); if (NULL == d) return 1; ret = p->client ((0 == (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags)) ? d : NULL, p->port, p->client_cls); fprintf (stderr, "\n"); MHD_stop_daemon (d); fflush (stderr); return ret; } unsigned int zzuf_check_runnable (void) { if (zzuf_run_with_socat) return 0; if (MHD_are_sanitizers_enabled_ ()) { fprintf (stderr, "Direct run with zzuf does not work with sanitizers. " "At line %d.\n", (int) __LINE__); return 77; } if (! MHD_is_avoid_accept4_possible_ ()) { fprintf (stderr, "Non-debug build of MHD on this platform use accept4() function. " "Direct run with zzuf is not possible. " "At line %d.\n", (int) __LINE__); return 77; } return 0; } unsigned int zzuf_run_polling_modes (struct zzuf_run_params *p) { unsigned int profile_num = p->profile_start; unsigned int testRes; unsigned int ret = 0; if (! zzuf_dry_run && (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))) { testRes = run_one_mode (p, MHD_USE_SELECT_INTERNALLY, &profile_num); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; testRes = run_one_mode (p, MHD_USE_SELECT_INTERNALLY | MHD_USE_THREAD_PER_CONNECTION, &profile_num); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { testRes = run_one_mode (p, MHD_USE_POLL_INTERNALLY, &profile_num); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; testRes = run_one_mode (p, MHD_USE_POLL_INTERNALLY | MHD_USE_THREAD_PER_CONNECTION, &profile_num); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { testRes = run_one_mode (p, MHD_USE_EPOLL_INTERNALLY, &profile_num); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; } testRes = run_one_mode (p, MHD_NO_FLAG, &profile_num); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; } testRes = run_one_mode (p, MHD_USE_NO_THREAD_SAFETY, &profile_num); if ((77 == testRes) || (99 == testRes)) return testRes; ret += testRes; return ret; } /* *** The raw socket client *** */ /** * Switch the socket to the non-blocking mode. * * @param fd the socket to modify * @return non-zero on success, zero on failure */ static int set_nonblocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) return 0; if (0 != (flags & O_NONBLOCK)) return ! 0; return (-1 != fcntl (fd, F_SETFL, flags | O_NONBLOCK)) ? ! 0 : 0; #else /* ! MHD_POSIX_SOCKETS */ unsigned long mode = 1; return (0 == ioctlsocket (fd, FIONBIO, &mode)) ? ! 0 : 0; #endif /* ! MHD_POSIX_SOCKETS */ } /** * Create the client socket and start connecting to the daemon. * * @param port the port MHD is listening on (ignored if socat is used) * @return the socket, or #MHD_INVALID_SOCKET on failure */ static MHD_socket raw_connect (uint16_t port, int bypass_relay) { MHD_socket fd; struct sockaddr_in sa; const char *dst_ip; uint16_t dst_port; int on = 1; if (zzuf_run_with_socat && ! bypass_relay) { dst_ip = ZZUF_SOCAT_IP; dst_port = (uint16_t) ZZUF_SOCAT_PORT; } else { dst_ip = ZZUF_MHD_LISTEN_IP; dst_port = port; } fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == fd) return MHD_INVALID_SOCKET; (void) setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (const void *) &on, (socklen_t) sizeof(on)); /* Use the same source address as libcurl does in the other tests, so that zzuf treats the traffic of this client exactly like libcurl's traffic. */ memset (&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = 0; sa.sin_addr.s_addr = inet_addr (ZZUF_CLIENT_BIND_IP); /* Best effort only: some platforms do not have the whole 127.0.0.0/8 range available. */ (void) bind (fd, (const struct sockaddr *) &sa, (socklen_t) sizeof(sa)); if (! set_nonblocking (fd)) { (void) ZZUF_CLOSE_SOCKET (fd); return MHD_INVALID_SOCKET; } memset (&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons (dst_port); sa.sin_addr.s_addr = inet_addr (dst_ip); if (0 != connect (fd, (const struct sockaddr *) &sa, (socklen_t) sizeof(sa))) { const int err = ZZUF_SOCK_ERR; if (! ZZUF_ERR_IS_INPROGRESS (err)) { (void) ZZUF_CLOSE_SOCKET (fd); return MHD_INVALID_SOCKET; } } return fd; } int zzuf_raw_exchange2 (struct MHD_Daemon *d_extern, uint16_t port, int bypass_relay, const struct zzuf_raw_part *parts, size_t num_parts, unsigned int timeout_sec, char *resp_buf, size_t resp_buf_size, size_t *resp_len) { MHD_socket fd; size_t cur_part = 0; size_t cur_off = 0; size_t resp_pos = 0; int send_done = 0; int peer_closed = 0; time_t start; char rbuf[1024]; if (NULL != resp_len) *resp_len = 0; fd = raw_connect (port, bypass_relay); if (MHD_INVALID_SOCKET == fd) return ZZUF_RAW_SETUP_FAILED; if (0 == num_parts) send_done = 1; start = time (NULL); while (1) { fd_set rs; fd_set ws; fd_set es; struct timeval tv; int maxfd; MHD_socket maxfd_mhd = MHD_INVALID_SOCKET; if (send_done && peer_closed) break; if (((time_t) timeout_sec) < (time (NULL) - start)) break; /* The peer did not close the connection in time */ FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); #if defined(MHD_POSIX_SOCKETS) if (FD_SETSIZE <= (int) fd) { (void) ZZUF_CLOSE_SOCKET (fd); return ZZUF_RAW_SETUP_FAILED; } #endif /* MHD_POSIX_SOCKETS */ if (! peer_closed) FD_SET (fd, &rs); if (! send_done) FD_SET (fd, &ws); maxfd = (int) fd; if (NULL != d_extern) { if (MHD_YES != MHD_get_fdset (d_extern, &rs, &ws, &es, &maxfd_mhd)) { fprintf (stderr, "MHD_get_fdset() failed " "at line %d.\n", (int) __LINE__); (void) ZZUF_CLOSE_SOCKET (fd); return ZZUF_RAW_SETUP_FAILED; } #ifndef MHD_WINSOCK_SOCKETS if ((int) maxfd_mhd > maxfd) maxfd = (int) maxfd_mhd; #endif /* ! MHD_WINSOCK_SOCKETS */ } tv.tv_sec = 0; tv.tv_usec = 25 * 1000; if (-1 == select (maxfd + 1, &rs, &ws, &es, &tv)) { #if defined(MHD_POSIX_SOCKETS) if (EINTR != errno) fprintf (stderr, "Unexpected select() error " "at line %d.\n", (int) __LINE__); #endif /* MHD_POSIX_SOCKETS */ } if (NULL != d_extern) MHD_run (d_extern); if (! send_done) { ssize_t res; res = (ssize_t) send (fd, (const void *) (parts[cur_part].data + cur_off), parts[cur_part].size - cur_off, ZZUF_SEND_FLAGS); if (0 > res) { const int err = ZZUF_SOCK_ERR; if (! ZZUF_ERR_IS_AGAIN (err)) { /* MHD (or socat) closed the connection: a perfectly normal outcome when the traffic is being fuzzed. */ send_done = 1; peer_closed = 1; } } else { cur_off += (size_t) res; if (cur_off >= parts[cur_part].size) { cur_off = 0; if (++cur_part >= num_parts) send_done = 1; } } } if (! peer_closed) { ssize_t res; res = (ssize_t) recv (fd, rbuf, sizeof(rbuf), 0); if (0 == res) peer_closed = 1; else if (0 > res) { const int err = ZZUF_SOCK_ERR; if (! ZZUF_ERR_IS_AGAIN (err)) peer_closed = 1; } else if ((NULL != resp_buf) && (resp_pos < resp_buf_size)) { size_t to_copy = (size_t) res; if (to_copy > resp_buf_size - resp_pos) to_copy = resp_buf_size - resp_pos; memcpy (resp_buf + resp_pos, rbuf, to_copy); resp_pos += to_copy; if (NULL != resp_len) *resp_len = resp_pos; } } } (void) ZZUF_CLOSE_SOCKET (fd); if (NULL != d_extern) { /* Give MHD a chance to notice the closed connection and to clean up. */ unsigned int i; for (i = 0; i < 10; ++i) MHD_run (d_extern); } return ZZUF_RAW_OK; } int zzuf_raw_exchange (struct MHD_Daemon *d_extern, uint16_t port, const struct zzuf_raw_part *parts, size_t num_parts, unsigned int timeout_sec) { return zzuf_raw_exchange2 (d_extern, port, 0, parts, num_parts, timeout_sec, NULL, 0, NULL); } int zzuf_raw_request (struct MHD_Daemon *d_extern, uint16_t port, const char *request) { struct zzuf_raw_part part; part.data = request; part.size = strlen (request); return zzuf_raw_exchange (d_extern, port, &part, 1, (unsigned int) ZZUF_CLIENT_TIMEOUT); } /* *** libcurl helpers *** */ #ifndef CURL_VERSION_BITS #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z)) #endif /* ! CURL_VERSION_BITS */ #ifndef CURL_AT_LEAST_VERSION #define CURL_AT_LEAST_VERSION(x,y,z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z)) #endif /* ! CURL_AT_LEAST_VERSION */ #define ZZUF_CURL_HOST "http:/" "/" ZZUF_MHD_LISTEN_IP #define ZZUF_CURL_HOST_SOCAT "http:/" "/" ZZUF_SOCAT_IP /** * The libcurl write callback: discards the data. * * @param ptr the received data * @param size the size of the item * @param nmemb the number of items * @param ctx the sink * @return the number of processed bytes */ static size_t curl_sink_cb (void *ptr, size_t size, size_t nmemb, void *ctx) { struct zzuf_curl_sink *sink = (struct zzuf_curl_sink *) ctx; (void) ptr; /* Unused. Mute compiler warning. */ if (sink->dn_pos + size * nmemb > sizeof(sink->buf)) return 0; /* Overflow, abort the transfer */ memcpy (sink->buf + sink->dn_pos, ptr, size * nmemb); sink->dn_pos += size * nmemb; return size * nmemb; } CURL * zzuf_curl_setup (uint16_t port, const char *uri_tail, struct zzuf_curl_sink *sink) { CURL *c; CURLcode e; char *uri; size_t host_len; size_t tail_len; const char *host; host = zzuf_run_with_socat ? ZZUF_CURL_HOST_SOCAT : ZZUF_CURL_HOST; if (zzuf_run_with_socat) port = (uint16_t) ZZUF_SOCAT_PORT; host_len = strlen (host); tail_len = strlen (uri_tail); uri = malloc (host_len + tail_len + 1); if (NULL == uri) { fprintf (stderr, "malloc() failed at line %d.\n", (int) __LINE__); return NULL; } memcpy (uri, host, host_len); memcpy (uri + host_len, uri_tail, tail_len + 1); sink->dn_pos = 0; c = curl_easy_init (); if (NULL == c) { fprintf (stderr, "curl_easy_init() failed at line %d.\n", (int) __LINE__); free (uri); return NULL; } if ((CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_URL, uri))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, &curl_sink_cb))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_WRITEDATA, sink))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, ((long) ZZUF_CLIENT_TIMEOUT)))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_TIMEOUT, ((long) ZZUF_CLIENT_TIMEOUT)))) && (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L))) && #if CURL_AT_LEAST_VERSION (7, 45, 0) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL, "http"))) && #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */ #if CURL_AT_LEAST_VERSION (7, 85, 0) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR, "http"))) && #elif CURL_AT_LEAST_VERSION (7, 19, 4) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP))) && #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_HTTP_VERSION, zzuf_oneone ? CURL_HTTP_VERSION_1_1 : CURL_HTTP_VERSION_1_0))) && #if CURL_AT_LEAST_VERSION (7, 24, 0) (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INTERFACE, "host!" ZZUF_CLIENT_BIND_IP))) && #else /* ! CURL_AT_LEAST_VERSION (7, 24, 0) */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INTERFACE, ZZUF_CLIENT_BIND_IP))) && #endif /* ! CURL_AT_LEAST_VERSION (7, 24, 0) */ (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PORT, ((long) port))))) { free (uri); return c; /* Success exit point */ } fprintf (stderr, "curl_easy_setopt() failed at line %d, error: %s\n", (int) __LINE__, curl_easy_strerror (e)); curl_easy_cleanup (c); free (uri); return NULL; /* Failure exit point */ } int zzuf_curl_driver_init (struct zzuf_curl_driver *drv, struct MHD_Daemon *d_extern) { drv->d_extern = d_extern; drv->multi = NULL; if (NULL == d_extern) return ! 0; drv->multi = curl_multi_init (); if (NULL == drv->multi) { fprintf (stderr, "curl_multi_init() failed at line %d.\n", (int) __LINE__); return 0; } return ! 0; } void zzuf_curl_driver_deinit (struct zzuf_curl_driver *drv) { if (NULL != drv->multi) curl_multi_cleanup (drv->multi); drv->multi = NULL; drv->d_extern = NULL; } void zzuf_curl_driver_perform (struct zzuf_curl_driver *drv, CURL *c) { CURLMcode mret; time_t start; if (NULL == drv->d_extern) { /* The daemon has an internal polling thread, just run the transfer. */ (void) curl_easy_perform (c); return; } mret = curl_multi_add_handle (drv->multi, c); if (CURLM_OK != mret) { fprintf (stderr, "curl_multi_add_handle() failed at line %d, error: %s\n", (int) __LINE__, curl_multi_strerror (mret)); return; } start = time (NULL); do { fd_set rs; fd_set ws; fd_set es; int maxfd_curl; MHD_socket maxfd_mhd; int maxfd; int running; struct timeval tv; maxfd_curl = 0; maxfd_mhd = MHD_INVALID_SOCKET; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); curl_multi_perform (drv->multi, &running); if (0 == running) { int msgs_left; do { (void) curl_multi_info_read (drv->multi, &msgs_left); } while (0 != msgs_left); break; /* The transfer has been finished */ } mret = curl_multi_fdset (drv->multi, &rs, &ws, &es, &maxfd_curl); if (CURLM_OK != mret) { fprintf (stderr, "curl_multi_fdset() failed at line %d, error: %s\n", (int) __LINE__, curl_multi_strerror (mret)); break; } if (MHD_YES != MHD_get_fdset (drv->d_extern, &rs, &ws, &es, &maxfd_mhd)) { fprintf (stderr, "MHD_get_fdset() failed at line %d.\n", (int) __LINE__); break; } #ifndef MHD_WINSOCK_SOCKETS if ((int) maxfd_mhd > maxfd_curl) maxfd = (int) maxfd_mhd; else #endif /* ! MHD_WINSOCK_SOCKETS */ maxfd = maxfd_curl; tv.tv_sec = 0; tv.tv_usec = 25 * 1000; if (0 == MHD_get_timeout64s (drv->d_extern)) tv.tv_usec = 0; else { long curl_to = -1; curl_multi_timeout (drv->multi, &curl_to); if (0 == curl_to) tv.tv_usec = 0; } if (-1 == select (maxfd + 1, &rs, &ws, &es, &tv)) { #if defined(MHD_POSIX_SOCKETS) if (EINTR != errno) fprintf (stderr, "Unexpected select() error at line %d.\n", (int) __LINE__); #else /* ! MHD_POSIX_SOCKETS */ if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count)) fprintf (stderr, "Unexpected select() error at line %d.\n", (int) __LINE__); Sleep ((unsigned long) tv.tv_usec / 1000); #endif /* ! MHD_POSIX_SOCKETS */ } MHD_run (drv->d_extern); } while (time (NULL) - start <= (time_t) ZZUF_CLIENT_TIMEOUT); curl_multi_remove_handle (drv->multi, c); } libmicrohttpd-1.0.10/src/microhttpd/0000775000175000017500000000000015235437005013150 5libmicrohttpd-1.0.10/src/microhttpd/basicauth.h0000644000175000017500000000256614760713577015230 /* This file is part of libmicrohttpd Copyright (C) 2010, 2011, 2012 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file basicauth.c * @brief Implements HTTP basic authentication methods * @author Amr Ali * @author Matthieu Speder * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_BASICAUTH_H #define MHD_BASICAUTH_H 1 #include "mhd_str.h" /** * Beginning string for any valid Basic authentication header. */ #define _MHD_AUTH_BASIC_BASE "Basic" struct MHD_RqBAuth { struct _MHD_str_w_len token68; }; #endif /* ! MHD_BASICAUTH_H */ /* end of basicauth.h */ libmicrohttpd-1.0.10/src/microhttpd/sha512_256.c0000644000175000017500000007027715035214301014634 /* This file is part of GNU libmicrohttpd Copyright (C) 2022-2023 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha512_256.c * @brief Calculation of SHA-512/256 digest as defined in FIPS PUB 180-4 (2015) * @author Karlson2k (Evgeny Grin) */ #include "sha512_256.h" #include #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #include "mhd_bithelpers.h" #include "mhd_assert.h" /** * Initialise structure for SHA-512/256 calculation. * * @param ctx the calculation context */ void MHD_SHA512_256_init (struct Sha512_256Ctx *ctx) { /* Initial hash values, see FIPS PUB 180-4 clause 5.3.6.2 */ /* Values generated by "IV Generation Function" as described in * clause 5.3.6 */ ctx->H[0] = UINT64_C (0x22312194FC2BF72C); ctx->H[1] = UINT64_C (0x9F555FA3C84C64C2); ctx->H[2] = UINT64_C (0x2393B86B6F53B151); ctx->H[3] = UINT64_C (0x963877195940EABD); ctx->H[4] = UINT64_C (0x96283EE2A88EFFE3); ctx->H[5] = UINT64_C (0xBE5E1E2553863992); ctx->H[6] = UINT64_C (0x2B0199FC2C85B8AA); ctx->H[7] = UINT64_C (0x0EB72DDC81C52CA2); /* Initialise number of bytes and high part of number of bits. */ ctx->count = 0; ctx->count_bits_hi = 0; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /** * Base of SHA-512/256 transformation. * Gets full 128 bytes block of data and updates hash values; * @param H hash values * @param data the data buffer with #SHA512_256_BLOCK_SIZE bytes block */ static void sha512_256_transform (uint64_t H[SHA512_256_HASH_SIZE_WORDS], const void *data) { /* Working variables, see FIPS PUB 180-4 clause 6.7, 6.4. */ uint64_t a = H[0]; uint64_t b = H[1]; uint64_t c = H[2]; uint64_t d = H[3]; uint64_t e = H[4]; uint64_t f = H[5]; uint64_t g = H[6]; uint64_t h = H[7]; /* Data buffer, used as a cyclic buffer. See FIPS PUB 180-4 clause 5.2.2, 6.7, 6.4. */ uint64_t W[16]; #ifndef _MHD_GET_64BIT_BE_ALLOW_UNALIGNED if (0 != (((uintptr_t) data) % _MHD_UINT64_ALIGN)) { /* The input data is unaligned */ /* Copy the unaligned input data to the aligned buffer */ memcpy (W, data, sizeof(W)); /* The W[] buffer itself will be used as the source of the data, * but the data will be reloaded in correct bytes order on * the next steps */ data = (const void *) W; } #endif /* _MHD_GET_64BIT_BE_ALLOW_UNALIGNED */ /* 'Ch' and 'Maj' macro functions are defined with widely-used optimisation. See FIPS PUB 180-4 formulae 4.8, 4.9. */ #define Ch(x,y,z) ( (z) ^ ((x) & ((y) ^ (z))) ) #define Maj(x,y,z) ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) ) /* Unoptimized (original) versions: */ /* #define Ch(x,y,z) ( ( (x) & (y) ) ^ ( ~(x) & (z) ) ) */ /* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */ /* Four 'Sigma' macro functions. See FIPS PUB 180-4 formulae 4.10, 4.11, 4.12, 4.13. */ #define SIG0(x) \ ( _MHD_ROTR64 ((x), 28) ^ _MHD_ROTR64 ((x), 34) ^ _MHD_ROTR64 ((x), 39) ) #define SIG1(x) \ ( _MHD_ROTR64 ((x), 14) ^ _MHD_ROTR64 ((x), 18) ^ _MHD_ROTR64 ((x), 41) ) #define sig0(x) \ ( _MHD_ROTR64 ((x), 1) ^ _MHD_ROTR64 ((x), 8) ^ ((x) >> 7) ) #define sig1(x) \ ( _MHD_ROTR64 ((x), 19) ^ _MHD_ROTR64 ((x), 61) ^ ((x) >> 6) ) /* One step of SHA-512/256 computation, see FIPS PUB 180-4 clause 6.4.2 step 3. * Note: this macro updates working variables in-place, without rotation. * Note: the first (vH += SIG1(vE) + Ch(vE,vF,vG) + kt + wt) equals T1 in FIPS PUB 180-4 clause 6.4.2 step 3. the second (vH += SIG0(vA) + Maj(vE,vF,vC) equals T1 + T2 in FIPS PUB 180-4 clause 6.4.2 step 3. * Note: 'wt' must be used exactly one time in this macro as it change other data as well every time when used. */ #define SHA2STEP64(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do { \ (vD) += ((vH) += SIG1 ((vE)) + Ch ((vE),(vF),(vG)) + (kt) + (wt)); \ (vH) += SIG0 ((vA)) + Maj ((vA),(vB),(vC)); } while (0) /* Get value of W(t) from input data buffer for 0 <= t <= 15, See FIPS PUB 180-4 clause 6.2. Input data must be read in big-endian bytes order, see FIPS PUB 180-4 clause 3.1.2. */ #define GET_W_FROM_DATA(buf,t) \ _MHD_GET_64BIT_BE (((const uint64_t*) (buf)) + (t)) /* 'W' generation and assignment for 16 <= t <= 79. See FIPS PUB 180-4 clause 6.4.2. As only last 16 'W' are used in calculations, it is possible to use 16 elements array of W as a cyclic buffer. * Note: ((t-16) & 15) have same value as (t & 15) */ #define Wgen(w,t) ( (w)[(t - 16) & 15] + sig1 ((w)[((t) - 2) & 15]) \ + (w)[((t) - 7) & 15] + sig0 ((w)[((t) - 15) & 15]) ) #ifndef MHD_FAVOR_SMALL_CODE /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 clause 4.2.3 for K values. */ /* Note: instead of reassigning all working variables on each step, variables are rotated for each step: SHA2STEP64(a, b, c, d, e, f, g, h, K[0], data[0]); SHA2STEP64(h, a, b, c, d, e, f, g, K[1], data[1]); so current 'vD' will be used as 'vE' on next step, current 'vH' will be used as 'vA' on next step. */ #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN if ((const void *) W == data) { /* The input data is already in the cyclic data buffer W[] in correct bytes order. */ SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x428a2f98d728ae22), W[0]); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x7137449123ef65cd), W[1]); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xb5c0fbcfec4d3b2f), W[2]); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xe9b5dba58189dbbc), W[3]); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x3956c25bf348b538), W[4]); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x59f111f1b605d019), W[5]); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x923f82a4af194f9b), W[6]); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xab1c5ed5da6d8118), W[7]); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xd807aa98a3030242), W[8]); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x12835b0145706fbe), W[9]); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x243185be4ee4b28c), W[10]); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x550c7dc3d5ffb4e2), W[11]); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x72be5d74f27b896f), W[12]); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x80deb1fe3b1696b1), W[13]); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x9bdc06a725c71235), W[14]); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xc19bf174cf692694), W[15]); } else /* Combined with the next 'if' */ #endif /* _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */ if (1) { /* During first 16 steps, before making any calculations on each step, the W element is read from the input data buffer as big-endian value and stored in the array of W elements. */ SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x428a2f98d728ae22), \ W[0] = GET_W_FROM_DATA (data, 0)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x7137449123ef65cd), \ W[1] = GET_W_FROM_DATA (data, 1)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xb5c0fbcfec4d3b2f), \ W[2] = GET_W_FROM_DATA (data, 2)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xe9b5dba58189dbbc), \ W[3] = GET_W_FROM_DATA (data, 3)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x3956c25bf348b538), \ W[4] = GET_W_FROM_DATA (data, 4)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x59f111f1b605d019), \ W[5] = GET_W_FROM_DATA (data, 5)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x923f82a4af194f9b), \ W[6] = GET_W_FROM_DATA (data, 6)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xab1c5ed5da6d8118), \ W[7] = GET_W_FROM_DATA (data, 7)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xd807aa98a3030242), \ W[8] = GET_W_FROM_DATA (data, 8)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x12835b0145706fbe), \ W[9] = GET_W_FROM_DATA (data, 9)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x243185be4ee4b28c), \ W[10] = GET_W_FROM_DATA (data, 10)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x550c7dc3d5ffb4e2), \ W[11] = GET_W_FROM_DATA (data, 11)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x72be5d74f27b896f), \ W[12] = GET_W_FROM_DATA (data, 12)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x80deb1fe3b1696b1), \ W[13] = GET_W_FROM_DATA (data, 13)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x9bdc06a725c71235), \ W[14] = GET_W_FROM_DATA (data, 14)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xc19bf174cf692694), \ W[15] = GET_W_FROM_DATA (data, 15)); } /* During last 64 steps, before making any calculations on each step, current W element is generated from other W elements of the cyclic buffer and the generated value is stored back in the cyclic buffer. */ /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 clause 4.2.3 for K values. */ SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xe49b69c19ef14ad2), \ W[16 & 15] = Wgen (W,16)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xefbe4786384f25e3), \ W[17 & 15] = Wgen (W,17)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x0fc19dc68b8cd5b5), \ W[18 & 15] = Wgen (W,18)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x240ca1cc77ac9c65), \ W[19 & 15] = Wgen (W,19)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x2de92c6f592b0275), \ W[20 & 15] = Wgen (W,20)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x4a7484aa6ea6e483), \ W[21 & 15] = Wgen (W,21)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x5cb0a9dcbd41fbd4), \ W[22 & 15] = Wgen (W,22)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x76f988da831153b5), \ W[23 & 15] = Wgen (W,23)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x983e5152ee66dfab), \ W[24 & 15] = Wgen (W,24)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xa831c66d2db43210), \ W[25 & 15] = Wgen (W,25)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xb00327c898fb213f), \ W[26 & 15] = Wgen (W,26)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xbf597fc7beef0ee4), \ W[27 & 15] = Wgen (W,27)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0xc6e00bf33da88fc2), \ W[28 & 15] = Wgen (W,28)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0xd5a79147930aa725), \ W[29 & 15] = Wgen (W,29)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x06ca6351e003826f), \ W[30 & 15] = Wgen (W,30)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x142929670a0e6e70), \ W[31 & 15] = Wgen (W,31)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x27b70a8546d22ffc), \ W[32 & 15] = Wgen (W,32)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x2e1b21385c26c926), \ W[33 & 15] = Wgen (W,33)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x4d2c6dfc5ac42aed), \ W[34 & 15] = Wgen (W,34)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x53380d139d95b3df), \ W[35 & 15] = Wgen (W,35)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x650a73548baf63de), \ W[36 & 15] = Wgen (W,36)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x766a0abb3c77b2a8), \ W[37 & 15] = Wgen (W,37)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x81c2c92e47edaee6), \ W[38 & 15] = Wgen (W,38)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x92722c851482353b), \ W[39 & 15] = Wgen (W,39)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xa2bfe8a14cf10364), \ W[40 & 15] = Wgen (W,40)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xa81a664bbc423001), \ W[41 & 15] = Wgen (W,41)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xc24b8b70d0f89791), \ W[42 & 15] = Wgen (W,42)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xc76c51a30654be30), \ W[43 & 15] = Wgen (W,43)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0xd192e819d6ef5218), \ W[44 & 15] = Wgen (W,44)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0xd69906245565a910), \ W[45 & 15] = Wgen (W,45)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0xf40e35855771202a), \ W[46 & 15] = Wgen (W,46)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x106aa07032bbd1b8), \ W[47 & 15] = Wgen (W,47)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x19a4c116b8d2d0c8), \ W[48 & 15] = Wgen (W,48)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x1e376c085141ab53), \ W[49 & 15] = Wgen (W,49)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x2748774cdf8eeb99), \ W[50 & 15] = Wgen (W,50)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x34b0bcb5e19b48a8), \ W[51 & 15] = Wgen (W,51)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x391c0cb3c5c95a63), \ W[52 & 15] = Wgen (W,52)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x4ed8aa4ae3418acb), \ W[53 & 15] = Wgen (W,53)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x5b9cca4f7763e373), \ W[54 & 15] = Wgen (W,54)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x682e6ff3d6b2b8a3), \ W[55 & 15] = Wgen (W,55)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x748f82ee5defb2fc), \ W[56 & 15] = Wgen (W,56)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x78a5636f43172f60), \ W[57 & 15] = Wgen (W,57)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x84c87814a1f0ab72), \ W[58 & 15] = Wgen (W,58)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x8cc702081a6439ec), \ W[59 & 15] = Wgen (W,59)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x90befffa23631e28), \ W[60 & 15] = Wgen (W,60)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0xa4506cebde82bde9), \ W[61 & 15] = Wgen (W,61)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0xbef9a3f7b2c67915), \ W[62 & 15] = Wgen (W,62)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0xc67178f2e372532b), \ W[63 & 15] = Wgen (W,63)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0xca273eceea26619c), \ W[64 & 15] = Wgen (W,64)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0xd186b8c721c0c207), \ W[65 & 15] = Wgen (W,65)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0xeada7dd6cde0eb1e), \ W[66 & 15] = Wgen (W,66)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0xf57d4f7fee6ed178), \ W[67 & 15] = Wgen (W,67)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x06f067aa72176fba), \ W[68 & 15] = Wgen (W,68)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x0a637dc5a2c898a6), \ W[69 & 15] = Wgen (W,69)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x113f9804bef90dae), \ W[70 & 15] = Wgen (W,70)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x1b710b35131c471b), \ W[71 & 15] = Wgen (W,71)); SHA2STEP64 (a, b, c, d, e, f, g, h, UINT64_C (0x28db77f523047d84), \ W[72 & 15] = Wgen (W,72)); SHA2STEP64 (h, a, b, c, d, e, f, g, UINT64_C (0x32caab7b40c72493), \ W[73 & 15] = Wgen (W,73)); SHA2STEP64 (g, h, a, b, c, d, e, f, UINT64_C (0x3c9ebe0a15c9bebc), \ W[74 & 15] = Wgen (W,74)); SHA2STEP64 (f, g, h, a, b, c, d, e, UINT64_C (0x431d67c49c100d4c), \ W[75 & 15] = Wgen (W,75)); SHA2STEP64 (e, f, g, h, a, b, c, d, UINT64_C (0x4cc5d4becb3e42b6), \ W[76 & 15] = Wgen (W,76)); SHA2STEP64 (d, e, f, g, h, a, b, c, UINT64_C (0x597f299cfc657e2a), \ W[77 & 15] = Wgen (W,77)); SHA2STEP64 (c, d, e, f, g, h, a, b, UINT64_C (0x5fcb6fab3ad6faec), \ W[78 & 15] = Wgen (W,78)); SHA2STEP64 (b, c, d, e, f, g, h, a, UINT64_C (0x6c44198c4a475817), \ W[79 & 15] = Wgen (W,79)); #else /* MHD_FAVOR_SMALL_CODE */ if (1) { unsigned int t; /* K constants array. See FIPS PUB 180-4 clause 4.2.3 for K values. */ static const uint64_t K[80] = { UINT64_C (0x428a2f98d728ae22), UINT64_C (0x7137449123ef65cd), UINT64_C (0xb5c0fbcfec4d3b2f), UINT64_C (0xe9b5dba58189dbbc), UINT64_C (0x3956c25bf348b538), UINT64_C (0x59f111f1b605d019), UINT64_C (0x923f82a4af194f9b), UINT64_C (0xab1c5ed5da6d8118), UINT64_C (0xd807aa98a3030242), UINT64_C (0x12835b0145706fbe), UINT64_C (0x243185be4ee4b28c), UINT64_C (0x550c7dc3d5ffb4e2), UINT64_C (0x72be5d74f27b896f), UINT64_C (0x80deb1fe3b1696b1), UINT64_C (0x9bdc06a725c71235), UINT64_C (0xc19bf174cf692694), UINT64_C (0xe49b69c19ef14ad2), UINT64_C (0xefbe4786384f25e3), UINT64_C (0x0fc19dc68b8cd5b5), UINT64_C (0x240ca1cc77ac9c65), UINT64_C (0x2de92c6f592b0275), UINT64_C (0x4a7484aa6ea6e483), UINT64_C (0x5cb0a9dcbd41fbd4), UINT64_C (0x76f988da831153b5), UINT64_C (0x983e5152ee66dfab), UINT64_C (0xa831c66d2db43210), UINT64_C (0xb00327c898fb213f), UINT64_C (0xbf597fc7beef0ee4), UINT64_C (0xc6e00bf33da88fc2), UINT64_C (0xd5a79147930aa725), UINT64_C (0x06ca6351e003826f), UINT64_C (0x142929670a0e6e70), UINT64_C (0x27b70a8546d22ffc), UINT64_C (0x2e1b21385c26c926), UINT64_C (0x4d2c6dfc5ac42aed), UINT64_C (0x53380d139d95b3df), UINT64_C (0x650a73548baf63de), UINT64_C (0x766a0abb3c77b2a8), UINT64_C (0x81c2c92e47edaee6), UINT64_C (0x92722c851482353b), UINT64_C (0xa2bfe8a14cf10364), UINT64_C (0xa81a664bbc423001), UINT64_C (0xc24b8b70d0f89791), UINT64_C (0xc76c51a30654be30), UINT64_C (0xd192e819d6ef5218), UINT64_C (0xd69906245565a910), UINT64_C (0xf40e35855771202a), UINT64_C (0x106aa07032bbd1b8), UINT64_C (0x19a4c116b8d2d0c8), UINT64_C (0x1e376c085141ab53), UINT64_C (0x2748774cdf8eeb99), UINT64_C (0x34b0bcb5e19b48a8), UINT64_C (0x391c0cb3c5c95a63), UINT64_C (0x4ed8aa4ae3418acb), UINT64_C (0x5b9cca4f7763e373), UINT64_C (0x682e6ff3d6b2b8a3), UINT64_C (0x748f82ee5defb2fc), UINT64_C (0x78a5636f43172f60), UINT64_C (0x84c87814a1f0ab72), UINT64_C (0x8cc702081a6439ec), UINT64_C (0x90befffa23631e28), UINT64_C (0xa4506cebde82bde9), UINT64_C (0xbef9a3f7b2c67915), UINT64_C (0xc67178f2e372532b), UINT64_C (0xca273eceea26619c), UINT64_C (0xd186b8c721c0c207), UINT64_C (0xeada7dd6cde0eb1e), UINT64_C (0xf57d4f7fee6ed178), UINT64_C (0x06f067aa72176fba), UINT64_C (0x0a637dc5a2c898a6), UINT64_C (0x113f9804bef90dae), UINT64_C (0x1b710b35131c471b), UINT64_C (0x28db77f523047d84), UINT64_C (0x32caab7b40c72493), UINT64_C (0x3c9ebe0a15c9bebc), UINT64_C (0x431d67c49c100d4c), UINT64_C (0x4cc5d4becb3e42b6), UINT64_C (0x597f299cfc657e2a), UINT64_C (0x5fcb6fab3ad6faec), UINT64_C (0x6c44198c4a475817)}; /* One step of SHA-512/256 computation with working variables rotation, see FIPS PUB 180-4 clause 6.4.2 step 3. * Note: this version of macro reassign all working variable on each step. */ #define SHA2STEP64RV(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do { \ uint64_t tmp_h_ = (vH); \ SHA2STEP64((vA),(vB),(vC),(vD),(vE),(vF),(vG),tmp_h_,(kt),(wt)); \ (vH) = (vG); \ (vG) = (vF); \ (vF) = (vE); \ (vE) = (vD); \ (vD) = (vC); \ (vC) = (vB); \ (vB) = (vA); \ (vA) = tmp_h_; } while (0) /* During first 16 steps, before making any calculations on each step, the W element is read from the input data buffer as big-endian value and stored in the array of W elements. */ for (t = 0; t < 16; ++t) { SHA2STEP64RV (a, b, c, d, e, f, g, h, K[t], \ W[t] = GET_W_FROM_DATA (data, t)); } /* During last 64 steps, before making any calculations on each step, current W element is generated from other W elements of the cyclic buffer and the generated value is stored back in the cyclic buffer. */ for (t = 16; t < 80; ++t) { SHA2STEP64RV (a, b, c, d, e, f, g, h, K[t], \ W[t & 15] = Wgen (W,t)); } } #endif /* MHD_FAVOR_SMALL_CODE */ /* Compute and store the intermediate hash. See FIPS PUB 180-4 clause 6.4.2 step 4. */ H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h; } /** * Process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA512_256_update (struct Sha512_256Ctx *ctx, const uint8_t *data, size_t length) { unsigned int bytes_have; /**< Number of bytes in the context buffer */ uint64_t count_hi; /**< The high part to be moved to another variable */ mhd_assert ((data != NULL) || (length == 0)); #ifndef MHD_FAVOR_SMALL_CODE if (0 == length) return; /* Shortcut, do nothing */ #endif /* ! MHD_FAVOR_SMALL_CODE */ /* Note: (count & (SHA512_256_BLOCK_SIZE-1)) equals (count % SHA512_256_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned int) (ctx->count & (SHA512_256_BLOCK_SIZE - 1)); ctx->count += length; #if SIZEOF_SIZE_T > 7 if (length > ctx->count) ctx->count_bits_hi += 1U << 3; /* Value wrap */ #endif /* SIZEOF_SIZE_T > 7 */ count_hi = ctx->count >> 61; if (0 != count_hi) { ctx->count_bits_hi += count_hi; ctx->count &= UINT64_C (0x1FFFFFFFFFFFFFFF); } if (0 != bytes_have) { unsigned int bytes_left = SHA512_256_BLOCK_SIZE - bytes_have; if (length >= bytes_left) { /* Combine new data with data in the buffer and process the full block. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, bytes_left); data += bytes_left; length -= bytes_left; sha512_256_transform (ctx->H, ctx->buffer); bytes_have = 0; } } while (SHA512_256_BLOCK_SIZE <= length) { /* Process any full blocks of new data directly, without copying to the buffer. */ sha512_256_transform (ctx->H, data); data += SHA512_256_BLOCK_SIZE; length -= SHA512_256_BLOCK_SIZE; } if (0 != length) { /* Copy incomplete block of new data (if any) to the buffer. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, length); } } /** * Size of "length" insertion in bits. * See FIPS PUB 180-4 clause 5.1.2. */ #define SHA512_256_SIZE_OF_LEN_ADD_BITS 128 /** * Size of "length" insertion in bytes. */ #define SHA512_256_SIZE_OF_LEN_ADD (SHA512_256_SIZE_OF_LEN_ADD_BITS / 8) /** * Finalise SHA-512/256 calculation, return digest. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #SHA512_256_DIGEST_SIZE bytes */ void MHD_SHA512_256_finish (struct Sha512_256Ctx *ctx, uint8_t digest[SHA512_256_DIGEST_SIZE]) { uint64_t num_bits; /**< Number of processed bits */ unsigned int bytes_have; /**< Number of bytes in the context buffer */ /* Memorise the number of processed bits. The padding and other data added here during the postprocessing must not change the amount of hashed data. */ num_bits = ctx->count << 3; /* Note: (count & (SHA512_256_BLOCK_SIZE-1)) equals (count % SHA512_256_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned int) (ctx->count & (SHA512_256_BLOCK_SIZE - 1)); /* Input data must be padded with a single bit "1", then with zeros and the finally the length of data in bits must be added as the final bytes of the last block. See FIPS PUB 180-4 clause 5.1.2. */ /* Data is always processed in form of bytes (not by individual bits), therefore position of the first padding bit in byte is always predefined (0x80). */ /* Buffer always have space for one byte at least (as full buffers are processed immediately). */ ((uint8_t *) ctx->buffer)[bytes_have++] = 0x80; if (SHA512_256_BLOCK_SIZE - bytes_have < SHA512_256_SIZE_OF_LEN_ADD) { /* No space in the current block to put the total length of message. Pad the current block with zeros and process it. */ if (bytes_have < SHA512_256_BLOCK_SIZE) memset (((uint8_t *) ctx->buffer) + bytes_have, 0, SHA512_256_BLOCK_SIZE - bytes_have); /* Process the full block. */ sha512_256_transform (ctx->H, ctx->buffer); /* Start the new block. */ bytes_have = 0; } /* Pad the rest of the buffer with zeros. */ memset (((uint8_t *) ctx->buffer) + bytes_have, 0, SHA512_256_BLOCK_SIZE - SHA512_256_SIZE_OF_LEN_ADD - bytes_have); /* Put high part of number of bits in processed message and then lower part of number of bits as big-endian values. See FIPS PUB 180-4 clause 5.1.2. */ /* Note: the target location is predefined and buffer is always aligned */ _MHD_PUT_64BIT_BE (ctx->buffer + SHA512_256_BLOCK_SIZE_WORDS - 2, ctx->count_bits_hi); _MHD_PUT_64BIT_BE (ctx->buffer + SHA512_256_BLOCK_SIZE_WORDS - 1, num_bits); /* Process the full final block. */ sha512_256_transform (ctx->H, ctx->buffer); /* Put in BE mode the leftmost part of the hash as the final digest. See FIPS PUB 180-4 clause 6.7. */ #ifndef _MHD_PUT_64BIT_BE_UNALIGNED if (1 #ifndef MHD_FAVOR_SMALL_CODE && (0 != ((uintptr_t) digest) % _MHD_UINT64_ALIGN) #endif /* MHD_FAVOR_SMALL_CODE */ ) { /* If storing of the final result requires aligned address and the destination address is not aligned or compact code is used, store the final digest in aligned temporary buffer first, then copy it to the destination. */ uint64_t alig_dgst[SHA512_256_DIGEST_SIZE_WORDS]; _MHD_PUT_64BIT_BE (alig_dgst + 0, ctx->H[0]); _MHD_PUT_64BIT_BE (alig_dgst + 1, ctx->H[1]); _MHD_PUT_64BIT_BE (alig_dgst + 2, ctx->H[2]); _MHD_PUT_64BIT_BE (alig_dgst + 3, ctx->H[3]); /* Copy result to the unaligned destination address */ memcpy (digest, alig_dgst, SHA512_256_DIGEST_SIZE); } #ifndef MHD_FAVOR_SMALL_CODE else /* Combined with the next 'if' */ #endif /* MHD_FAVOR_SMALL_CODE */ #endif /* ! _MHD_PUT_64BIT_BE_UNALIGNED */ #if ! defined(MHD_FAVOR_SMALL_CODE) || defined(_MHD_PUT_64BIT_BE_UNALIGNED) if (1) { /* Use cast to (void*) here to mute compiler alignment warnings. * Compilers are not smart enough to see that alignment has been checked. */ _MHD_PUT_64BIT_BE ((void *) (digest + 0 * SHA512_256_BYTES_IN_WORD), \ ctx->H[0]); _MHD_PUT_64BIT_BE ((void *) (digest + 1 * SHA512_256_BYTES_IN_WORD), \ ctx->H[1]); _MHD_PUT_64BIT_BE ((void *) (digest + 2 * SHA512_256_BYTES_IN_WORD), \ ctx->H[2]); _MHD_PUT_64BIT_BE ((void *) (digest + 3 * SHA512_256_BYTES_IN_WORD), \ ctx->H[3]); } #endif /* ! MHD_FAVOR_SMALL_CODE || _MHD_PUT_64BIT_BE_UNALIGNED */ /* Erase potentially sensitive data. */ memset (ctx, 0, sizeof(struct Sha512_256Ctx)); } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ libmicrohttpd-1.0.10/src/microhttpd/test_str_token.c0000664000175000017500000001147415232103064016302 /* This file is part of libmicrohttpd Copyright (C) 2017 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_token.c * @brief Unit tests for some mhd_str functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include "mhd_str.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static int expect_found_n (const char *str, const char *token, size_t token_len) { if (! MHD_str_has_token_caseless_ (str, token, token_len)) { fprintf (stderr, "MHD_str_has_token_caseless_() FAILED:\n\tMHD_str_has_token_caseless_(%s, %s, %lu) return false\n", str, token, (unsigned long) token_len); return 1; } return 0; } #define expect_found(s,t) expect_found_n ((s),(t),MHD_STATICSTR_LEN_ (t)) static int expect_not_found_n (const char *str, const char *token, size_t token_len) { if (MHD_str_has_token_caseless_ (str, token, token_len)) { fprintf (stderr, "MHD_str_has_token_caseless_() FAILED:\n\tMHD_str_has_token_caseless_(%s, %s, %lu) return true\n", str, token, (unsigned long) token_len); return 1; } return 0; } #define expect_not_found(s,t) expect_not_found_n ((s),(t),MHD_STATICSTR_LEN_ ( \ t)) static int check_match (void) { int errcount = 0; errcount += expect_found ("string", "string"); errcount += expect_found ("String", "string"); errcount += expect_found ("string", "String"); errcount += expect_found ("strinG", "String"); errcount += expect_found ("\t strinG", "String"); errcount += expect_found ("strinG\t ", "String"); errcount += expect_found (" \t tOkEn ", "toKEN"); errcount += expect_found ("not token\t, tOkEn ", "toKEN"); errcount += expect_found ("not token,\t tOkEn, more token", "toKEN"); errcount += expect_found ("not token,\t tOkEn\t, more token", "toKEN"); errcount += expect_found (",,,,,,test,,,,", "TESt"); errcount += expect_found (",,,,,\t,test,,,,", "TESt"); errcount += expect_found (",,,,,,test, ,,,", "TESt"); errcount += expect_found (",,,,,, test,,,,", "TESt"); errcount += expect_found (",,,,,, test not,test,,", "TESt"); errcount += expect_found (",,,,,, test not,,test,,", "TESt"); errcount += expect_found (",,,,,, test not ,test,,", "TESt"); errcount += expect_found (",,,,,, test", "TESt"); errcount += expect_found (",,,,,, test ", "TESt"); errcount += expect_found ("no test,,,,,, test ", "TESt"); return errcount; } static int check_not_match (void) { int errcount = 0; errcount += expect_not_found ("strin", "string"); errcount += expect_not_found ("Stringer", "string"); errcount += expect_not_found ("sstring", "String"); errcount += expect_not_found ("string", "Strin"); errcount += expect_not_found ("\t( strinG", "String"); errcount += expect_not_found (")strinG\t ", "String"); errcount += expect_not_found (" \t tOkEn t ", "toKEN"); errcount += expect_not_found ("not token\t, tOkEner ", "toKEN"); errcount += expect_not_found ("not token,\t tOkEns, more token", "toKEN"); errcount += expect_not_found ("not token,\t tOkEns\t, more token", "toKEN"); errcount += expect_not_found (",,,,,,testing,,,,", "TESt"); errcount += expect_not_found (",,,,,\t,test,,,,", "TESting"); errcount += expect_not_found ("tests,,,,,,quest, ,,,", "TESt"); errcount += expect_not_found (",,,,,, testы,,,,", "TESt"); errcount += expect_not_found (",,,,,, test not,хtest,,", "TESt"); errcount += expect_not_found ("testing,,,,,, test not,,test2,,", "TESt"); errcount += expect_not_found (",testi,,,,, test not ,test,,", "TESting"); errcount += expect_not_found (",,,,,,2 test", "TESt"); errcount += expect_not_found (",,,,,,test test ", "test"); errcount += expect_not_found ("no test,,,,,, test test", "test"); return errcount; } int main (int argc, char *argv[]) { int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_match (); errcount += check_not_match (); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.10/src/microhttpd/test_dauth_userhash.c0000664000175000017500000006075015232103064017302 /* This file is part of libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_dauth_userhash.c * @brief Tests for Digest Auth calculations of userhash * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include "microhttpd.h" #include "test_helpers.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ static int verbose = 1; /* verbose level (0-1)*/ /* Declarations and data */ struct data_md5 { unsigned int line_num; const char *const username; const char *const realm; const uint8_t hash[MHD_MD5_DIGEST_SIZE]; }; static const struct data_md5 md5_tests[] = { {__LINE__, "u", "r", {0xba, 0x84, 0xbe, 0x20, 0x3f, 0xdf, 0xc7, 0xd3, 0x4e, 0x05, 0x4a, 0x76, 0xd2, 0x85, 0xd0, 0xc9}}, {__LINE__, "testuser", "testrealm", {0xab, 0xae, 0x15, 0x95, 0x24, 0xe5, 0x17, 0xbf, 0x48, 0xf4, 0x4a, 0xab, 0xfe, 0xb9, 0x37, 0x40}}, {__LINE__, "test_user", "TestRealm", /* Values from testcurl/test_digestauth2.c */ {0xc5, 0x3c, 0x60, 0x15, 0x03, 0xff, 0x17, 0x6f, 0x18, 0xf6, 0x23, 0x72, 0x5f, 0xba, 0x42, 0x81}}, {__LINE__, "Mufasa", "myhost@testrealm.com", {0x26, 0x45, 0xae, 0x13, 0xd1, 0xa2, 0xa6, 0x9e, 0xd2, 0x6d, 0xd2, 0x1a, 0xa5, 0x52, 0x86, 0xe3}}, {__LINE__, "Mufasa", "myhost@example.com", {0x4f, 0xc8, 0x64, 0x02, 0xd7, 0x18, 0x5d, 0x7b, 0x38, 0xd4, 0x38, 0xad, 0xd5, 0x5a, 0x35, 0x84}}, {__LINE__, "Mufasa", "http-auth@example.org", {0x42, 0x38, 0xf3, 0xa1, 0x61, 0x67, 0x37, 0x3f, 0xeb, 0xb9, 0xbc, 0x4d, 0x43, 0xdb, 0x9c, 0xc4}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", {0x2e, 0x06, 0x3f, 0xa2, 0xc5, 0x4d, 0xea, 0x1c, 0x36, 0x80, 0x8b, 0x7a, 0x6e, 0x3b, 0x14, 0xc9}} }; struct data_sha256 { unsigned int line_num; const char *const username; const char *const realm; const uint8_t hash[MHD_SHA256_DIGEST_SIZE]; }; static const struct data_sha256 sha256_tests[] = { {__LINE__, "u", "r", {0x1d, 0x8a, 0x03, 0xa6, 0xe2, 0x1a, 0x4c, 0xe7, 0x75, 0x06, 0x0e, 0xa5, 0x73, 0x60, 0x32, 0x9a, 0xc7, 0x50, 0xde, 0xa5, 0xd8, 0x47, 0x29, 0x7b, 0x42, 0xf0, 0xd4, 0x65, 0x39, 0xaf, 0x8a, 0xb2}}, {__LINE__, "testuser", "testrealm", {0x75, 0xaf, 0x8a, 0x35, 0x00, 0xf7, 0x71, 0xe5, 0x8a, 0x52, 0x09, 0x3a, 0x25, 0xe7, 0x90, 0x5d, 0x6e, 0x42, 0x8a, 0x51, 0x12, 0x85, 0xc1, 0x2e, 0xa1, 0x42, 0x0c, 0x73, 0x07, 0x8d, 0xfd, 0x61}}, {__LINE__, "test_user", "TestRealm", /* Values from testcurl/test_digestauth2.c */ {0x09, 0x0c, 0x7e, 0x06, 0xb7, 0x7d, 0x66, 0x14, 0xcf, 0x5f, 0xe6, 0xca, 0xfa, 0x00, 0x4d, 0x2e, 0x5f, 0x8f, 0xb3, 0x6b, 0xa4, 0x5a, 0x0e, 0x35, 0xea, 0xcb, 0x2e, 0xb7, 0x72, 0x8f, 0x34, 0xde}}, {__LINE__, "Mufasa", "myhost@testrealm.com", {0x92, 0x9f, 0xac, 0x9e, 0x6c, 0x8b, 0x76, 0xcc, 0xab, 0xa9, 0xe0, 0x6f, 0xf6, 0x4d, 0xf2, 0x6f, 0xcb, 0x40, 0x56, 0x4c, 0x19, 0x9c, 0x32, 0xd9, 0xea, 0xd9, 0x12, 0x4b, 0x25, 0x34, 0xe1, 0xf9}}, {__LINE__, "Mufasa", "myhost@example.com", {0x97, 0x06, 0xf0, 0x07, 0x1c, 0xec, 0x05, 0x3f, 0x88, 0x22, 0xb6, 0x63, 0x69, 0xc4, 0xa4, 0x00, 0x39, 0x79, 0xb7, 0xe7, 0x42, 0xb7, 0x4e, 0x42, 0x59, 0x63, 0x57, 0xf4, 0xd3, 0x02, 0xae, 0x16}}, {__LINE__, "Mufasa", "http-auth@example.org", {0xa9, 0x47, 0xaa, 0xd2, 0x05, 0xe8, 0x0e, 0x42, 0x99, 0x58, 0xa3, 0x87, 0x39, 0x49, 0x44, 0xc6, 0xb4, 0x96, 0x30, 0x1e, 0x79, 0xf8, 0x9d, 0x35, 0xa4, 0xcc, 0x23, 0xb6, 0xee, 0x12, 0xb5, 0xb6}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", {0x5a, 0x1a, 0x8a, 0x47, 0xdf, 0x5c, 0x29, 0x85, 0x51, 0xb9, 0xb4, 0x2b, 0xa9, 0xb0, 0x58, 0x35, 0x17, 0x4a, 0x5b, 0xd7, 0xd5, 0x11, 0xff, 0x7f, 0xe9, 0x19, 0x1d, 0x8e, 0x94, 0x6f, 0xc4, 0xe7}} }; struct data_sha512_256 { unsigned int line_num; const char *const username; const char *const realm; const uint8_t hash[MHD_SHA512_256_DIGEST_SIZE]; }; static const struct data_sha512_256 sha512_256_tests[] = { {__LINE__, "u", "r", {0xc7, 0x38, 0xf2, 0xad, 0x40, 0x1b, 0xc8, 0x7a, 0x71, 0xfe, 0x78, 0x09, 0x60, 0x15, 0xc9, 0x7b, 0x9a, 0x26, 0xd5, 0x5f, 0x15, 0xe9, 0xf5, 0x0a, 0xc3, 0xa6, 0xde, 0x73, 0xdd, 0xcd, 0x3d, 0x08}}, {__LINE__, "testuser", "testrealm", {0x4f, 0x69, 0x1e, 0xe9, 0x50, 0x8a, 0xe4, 0x55, 0x21, 0x32, 0x9e, 0xcf, 0xd4, 0x91, 0xf7, 0xe2, 0x77, 0x4b, 0x6f, 0xb8, 0x60, 0x2c, 0x14, 0x86, 0xad, 0x94, 0x9d, 0x1c, 0x23, 0xd8, 0xa1, 0xf5}}, {__LINE__, "test_user", "TestRealm", /* Values from testcurl/test_digestauth2.c */ {0x62, 0xe1, 0xac, 0x9f, 0x6c, 0xb1, 0xeb, 0x26, 0xaa, 0x75, 0xeb, 0x5d, 0x46, 0xef, 0xcd, 0xc8, 0x9c, 0xcb, 0xa7, 0x81, 0xf0, 0xf9, 0xf7, 0x2f, 0x6a, 0xfd, 0xb9, 0x42, 0x65, 0xd9, 0xa7, 0x9a}}, {__LINE__, "Mufasa", "myhost@testrealm.com", {0xbd, 0x3e, 0xbc, 0x30, 0x10, 0x0b, 0x7c, 0xf1, 0x61, 0x45, 0x6c, 0xfe, 0x64, 0x1c, 0x4c, 0xd2, 0x82, 0xe0, 0x62, 0x6e, 0x2c, 0x5e, 0x09, 0xc2, 0x4c, 0x90, 0xb1, 0x60, 0x8a, 0xec, 0x28, 0x64}}, {__LINE__, "Mufasa", "myhost@example.com", {0xea, 0x4b, 0x59, 0x37, 0xde, 0x2c, 0x4e, 0x9f, 0x16, 0xf9, 0x9c, 0x31, 0x01, 0xb6, 0xdd, 0xf8, 0x8c, 0x85, 0xd7, 0xe8, 0xf1, 0x75, 0x90, 0xd0, 0x63, 0x2a, 0x75, 0x75, 0xe4, 0x80, 0x13, 0x69}}, {__LINE__, "Mufasa", "http-auth@example.org", {0xe2, 0xdf, 0xab, 0xd1, 0xa9, 0x6d, 0xdf, 0x86, 0x77, 0x10, 0xb6, 0x53, 0xb6, 0xe6, 0x85, 0x7d, 0x1f, 0x14, 0x70, 0x86, 0xde, 0x7d, 0x7e, 0xf7, 0x9d, 0xcd, 0x24, 0x98, 0x59, 0x87, 0x25, 0x70}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", {0x79, 0x32, 0x63, 0xca, 0xab, 0xb7, 0x07, 0xa5, 0x62, 0x11, 0x94, 0x0d, 0x90, 0x41, 0x1e, 0xa4, 0xa5, 0x75, 0xad, 0xec, 0xcb, 0x7e, 0x36, 0x0a, 0xeb, 0x62, 0x4e, 0xd0, 0x6e, 0xce, 0x9b, 0x0b}} }; /* * Helper functions */ /** * Print bin as lower case hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'a' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'a' - 10) : (b2 + '0')); } *hex = 0; } /* Tests */ static unsigned int check_md5 (const struct data_md5 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5; uint8_t hash_bin[MHD_MD5_DIGEST_SIZE]; char hash_hex[MHD_MD5_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_MD5_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_YES != MHD_digest_auth_calc_userhash (algo3, data->username, data->realm, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_YES != MHD_digest_auth_calc_userhash_hex (algo3, data->username, data->realm, hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (sizeof(hash_hex) - 1 != strlen (hash_hex)) { failed++; fprintf (stderr, "FAILED: %s produced hash with wrong length. " "Calculated length %u, expected digest %u.\n", func_name, (unsigned) strlen (hash_hex), (unsigned) (sizeof(hash_hex) - 1)); } else { bin2hex (data->hash, sizeof(data->hash), expected_hex); if (0 != memcmp (hash_hex, expected_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_md5 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(md5_tests) / sizeof(md5_tests[0]); i++) num_failed += check_md5 (md5_tests + i); return num_failed; } static unsigned int test_md5_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5; uint8_t hash_bin[MHD_MD5_DIGEST_SIZE]; char hash_hex[MHD_MD5_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5)) { if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5)) { if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } static unsigned int check_sha256 (const struct data_sha256 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256; uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE]; char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_YES != MHD_digest_auth_calc_userhash (algo3, data->username, data->realm, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_YES != MHD_digest_auth_calc_userhash_hex (algo3, data->username, data->realm, hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (sizeof(hash_hex) - 1 != strlen (hash_hex)) { failed++; fprintf (stderr, "FAILED: %s produced hash with wrong length. " "Calculated length %u, expected digest %u.\n", func_name, (unsigned) strlen (hash_hex), (unsigned) (sizeof(hash_hex) - 1)); } else { bin2hex (data->hash, sizeof(data->hash), expected_hex); if (0 != memcmp (hash_hex, expected_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_sha256 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(sha256_tests) / sizeof(sha256_tests[0]); i++) num_failed += check_sha256 (sha256_tests + i); return num_failed; } static unsigned int test_sha256_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256; uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE]; char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) { if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) { if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } static unsigned int check_sha512_256 (const struct data_sha512_256 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA512_256; uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE]; char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_YES != MHD_digest_auth_calc_userhash (algo3, data->username, data->realm, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_YES != MHD_digest_auth_calc_userhash_hex (algo3, data->username, data->realm, hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (sizeof(hash_hex) - 1 != strlen (hash_hex)) { failed++; fprintf (stderr, "FAILED: %s produced hash with wrong length. " "Calculated length %u, expected digest %u.\n", func_name, (unsigned) strlen (hash_hex), (unsigned) (sizeof(hash_hex) - 1)); } else { bin2hex (data->hash, sizeof(data->hash), expected_hex); if (0 != memcmp (hash_hex, expected_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_sha512_256 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(sha512_256_tests) / sizeof(sha512_256_tests[0]); i++) num_failed += check_sha512_256 (sha512_256_tests + i); return num_failed; } static unsigned int test_sha512_256_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA512_256; static const enum MHD_FEATURE feature = MHD_FEATURE_DIGEST_AUTH_SHA512_256; uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE]; char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (feature)) { if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (feature)) { if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } int main (int argc, char *argv[]) { unsigned int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")) verbose = 0; #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5)) num_failed += test_md5 (); num_failed += test_md5_failure (); if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) num_failed += test_sha256 (); num_failed += test_sha256_failure (); if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA512_256)) num_failed += test_sha512_256 (); num_failed += test_sha512_256_failure (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.10/src/microhttpd/digestauth.h0000644000175000017500000000437215035214301015374 /* This file is part of libmicrohttpd Copyright (C) 2010, 2011, 2012, 2015, 2018 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file digestauth.c * @brief Implements HTTP digest authentication * @author Amr Ali * @author Matthieu Speder * @author Christian Grothoff (RFC 7616 support) * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_DIGESTAUTH_H #define MHD_DIGESTAUTH_H 1 #include "mhd_options.h" #include "mhd_str.h" #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ /** * The maximum supported size for Digest Auth parameters, like "real", * "username" etc. This limitation is used only for quoted parameters. * Parameters without quoted backslash character will be processed as long * as they fit connection pool (buffer) size. */ #define _MHD_AUTH_DIGEST_MAX_PARAM_SIZE (65535) /** * Beginning string for any valid Digest Authentication header. */ #define _MHD_AUTH_DIGEST_BASE "Digest" /** * The token for MD5 algorithm. */ #define _MHD_MD5_TOKEN "MD5" /** * The token for SHA-256 algorithm. */ #define _MHD_SHA256_TOKEN "SHA-256" /** * The token for SHA-512/256 algorithm. */ #define _MHD_SHA512_256_TOKEN "SHA-512-256" /** * The suffix token for "session" algorithms. */ #define _MHD_SESS_TOKEN "-sess" /** * The "auth" token for QOP */ #define MHD_TOKEN_AUTH_ "auth" /** * The "auth-int" token for QOP */ #define MHD_TOKEN_AUTH_INT_ "auth-int" #endif /* ! MHD_DIGESTAUTH_H */ /* end of digestauth.h */ libmicrohttpd-1.0.10/src/microhttpd/mhd_panic.h0000644000175000017500000000465714760713577015212 /* This file is part of libmicrohttpd Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_panic.h * @brief Declaration and macros for MHD_panic() * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_PANIC_H #define MHD_PANIC_H 1 #include "mhd_options.h" #ifdef MHD_PANIC /* Override any possible defined MHD_PANIC macro with proper one */ #undef MHD_PANIC #endif /* MHD_PANIC */ /* If we have Clang or gcc >= 4.5, use __builtin_unreachable() */ #if defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 4) || \ (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 5) #define BUILTIN_NOT_REACHED __builtin_unreachable () #elif defined(_MSC_FULL_VER) #define BUILTIN_NOT_REACHED __assume (0) #else #define BUILTIN_NOT_REACHED #endif /* The MHD_PanicCallback type, but without main header. */ /** * Handler for fatal errors. */ extern void (*mhd_panic) (void *cls, const char *file, unsigned int line, const char *reason); /** * Closure argument for "mhd_panic". */ extern void *mhd_panic_cls; #ifdef HAVE_MESSAGES /** * Trigger 'panic' action based on fatal errors. * * @param msg error message (const char *) */ #define MHD_PANIC(msg) do { mhd_panic (mhd_panic_cls, __FILE__, __LINE__, msg); \ BUILTIN_NOT_REACHED; } while (0) #else /** * Trigger 'panic' action based on fatal errors. * * @param msg error message (const char *) */ #define MHD_PANIC(msg) do { mhd_panic (mhd_panic_cls, NULL, __LINE__, NULL); \ BUILTIN_NOT_REACHED; } while (0) #endif #endif /* MHD_PANIC_H */ libmicrohttpd-1.0.10/src/microhttpd/mhd_compat.h0000644000175000017500000000545514760713577015400 /* This file is part of libmicrohttpd Copyright (C) 2014-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_compat.h * @brief Header for platform missing functions. * @author Karlson2k (Evgeny Grin) * * Provides compatibility for platforms with some missing * functionality. * Any functions can be implemented as macro on some platforms * unless explicitly marked otherwise. * Any function argument can be skipped in macro, so avoid * variable modification in function parameters. */ #ifndef MHD_COMPAT_H #define MHD_COMPAT_H 1 #include "mhd_options.h" #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #ifdef HAVE_STRING_H /* for strerror() */ #include #endif /* HAVE_STRING_H */ /* MHD_strerror_ is strerror */ #define MHD_strerror_(errnum) strerror ((errnum)) /* Platform-independent snprintf name */ #if defined(HAVE_SNPRINTF) #define MHD_snprintf_ snprintf #else /* ! HAVE_SNPRINTF */ #if defined(_WIN32) && ! defined(__CYGWIN__) /* Emulate snprintf function on W32 */ int W32_snprintf (char *__restrict s, size_t n, const char *__restrict format, ...); #define MHD_snprintf_ W32_snprintf #else /* ! _WIN32 || __CYGWIN__ */ #error \ Your platform does not support snprintf() and MHD does not know how to emulate it on your platform. #endif /* ! _WIN32 || __CYGWIN__ */ #endif /* ! HAVE_SNPRINTF */ #ifdef HAVE_RANDOM /** * Generate pseudo random number at least 30-bit wide. * @return pseudo random number at least 30-bit wide. */ #define MHD_random_() random () #else /* HAVE_RANDOM */ #ifdef HAVE_RAND /** * Generate pseudo random number at least 30-bit wide. * @return pseudo random number at least 30-bit wide. */ #define MHD_random_() ( (((long) rand ()) << 15) + (long) rand () ) #endif /* HAVE_RAND */ #endif /* HAVE_RANDOM */ #ifdef HAVE_CALLOC /** * MHD_calloc_ is platform-independent calloc() */ #define MHD_calloc_(n,s) calloc ((n),(s)) #else /* ! HAVE_CALLOC */ /** * MHD_calloc_ is platform-independent calloc() */ void *MHD_calloc_ (size_t nelem, size_t elsize); #endif /* ! HAVE_CALLOC */ #endif /* MHD_COMPAT_H */ libmicrohttpd-1.0.10/src/microhttpd/test_sha512_256.c0000664000175000017500000007311315232103064015667 /* This file is part of libmicrohttpd Copyright (C) 2019-2022 Evgeny Grin (Karlson2k) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_sha512_256.h * @brief Unit tests for SHA-512/256 functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "sha512_256.h" #include "test_helpers.h" #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static int verbose = 0; /* verbose level (0-1)*/ struct str_with_len { const char *const str; const size_t len; }; #define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1} struct data_unit1 { const struct str_with_len str_l; const uint8_t digest[SHA512_256_DIGEST_SIZE]; }; static const struct data_unit1 data_units1[] = { {D_STR_W_LEN ("abc"), {0x53, 0x04, 0x8E, 0x26, 0x81, 0x94, 0x1E, 0xF9, 0x9B, 0x2E, 0x29, 0xB7, 0x6B, 0x4C, 0x7D, 0xAB, 0xE4, 0xC2, 0xD0, 0xC6, 0x34, 0xFC, 0x6D, 0x46, 0xE0, 0xE2, 0xF1, 0x31, 0x07, 0xE7, 0xAF, 0x23}}, {D_STR_W_LEN ("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhi" \ "jklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"), {0x39, 0x28, 0xE1, 0x84, 0xFB, 0x86, 0x90, 0xF8, 0x40, 0xDA, 0x39, 0x88, 0x12, 0x1D, 0x31, 0xBE, 0x65, 0xCB, 0x9D, 0x3E, 0xF8, 0x3E, 0xE6, 0x14, 0x6F, 0xEA, 0xC8, 0x61, 0xE1, 0x9B, 0x56, 0x3A}}, {D_STR_W_LEN (""), /* The empty zero-size input */ {0xc6, 0x72, 0xb8, 0xd1, 0xef, 0x56, 0xed, 0x28, 0xab, 0x87, 0xc3, 0x62, 0x2c, 0x51, 0x14, 0x06, 0x9b, 0xdd, 0x3a, 0xd7, 0xb8, 0xf9, 0x73, 0x74, 0x98, 0xd0, 0xc0, 0x1e, 0xce, 0xf0, 0x96, 0x7a}}, {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), {0xc8, 0x7c, 0x5a, 0x55, 0x27, 0x77, 0x1b, 0xe7, 0x69, 0x3c, 0x50, 0x79, 0x32, 0xad, 0x7c, 0x79, 0xe9, 0x60, 0xa0, 0x18, 0xb7, 0x78, 0x2b, 0x6f, 0xa9, 0x7b, 0xa3, 0xa0, 0xb5, 0x18, 0x17, 0xa5}}, {D_STR_W_LEN ("Simple string."), {0xde, 0xcb, 0x3c, 0x81, 0x65, 0x4b, 0xa0, 0xf5, 0xf0, 0x45, 0x6b, 0x7e, 0x61, 0xf5, 0x0d, 0xf5, 0x38, 0xa4, 0xfc, 0xb1, 0x8a, 0x95, 0xff, 0x59, 0xbc, 0x04, 0x82, 0xcf, 0x23, 0xb2, 0x32, 0x56}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), {0xfc, 0x31, 0x89, 0x44, 0x3f, 0x9c, 0x26, 0x8f, 0x62, 0x6a, 0xea, 0x08, 0xa7, 0x56, 0xab, 0xe7, 0xb7, 0x26, 0xb0, 0x5f, 0x70, 0x1c, 0xb0, 0x82, 0x22, 0x31, 0x2c, 0xcf, 0xd6, 0x71, 0x0a, 0x26, }}, {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"), {0xd2, 0x6d, 0x24, 0x81, 0xa4, 0xf9, 0x0a, 0x72, 0xd2, 0x7f, 0xc1, 0xac, 0xac, 0xe1, 0xc0, 0x6b, 0x39, 0x94, 0xac, 0x73, 0x50, 0x2e, 0x27, 0x97, 0xa3, 0x65, 0x37, 0x4e, 0xbb, 0x5c, 0x27, 0xe9}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" \ "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"), {0xad, 0xe9, 0x5d, 0x55, 0x3b, 0x9e, 0x45, 0x69, 0xdb, 0x53, 0xa4, 0x04, 0x92, 0xe7, 0x87, 0x94, 0xff, 0xc9, 0x98, 0x5f, 0x93, 0x03, 0x86, 0x45, 0xe1, 0x97, 0x17, 0x72, 0x7c, 0xbc, 0x31, 0x15}}, {D_STR_W_LEN ("/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/path?with%20some=parameters"), {0xbc, 0xab, 0xc6, 0x2c, 0x0a, 0x22, 0xd5, 0xcb, 0xac, 0xac, 0xe9, 0x25, 0xcf, 0xce, 0xaa, 0xaf, 0x0e, 0xa1, 0xed, 0x42, 0x46, 0x8a, 0xe2, 0x01, 0xee, 0x2f, 0xdb, 0x39, 0x75, 0x47, 0x73, 0xf1}} }; static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]); struct bin_with_len { const uint8_t bin[512]; const size_t len; }; struct data_unit2 { const struct bin_with_len bin_l; const uint8_t digest[SHA512_256_DIGEST_SIZE]; }; /* Size must be less than 512 bytes! */ static const struct data_unit2 data_units2[] = { { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */ {0xfc, 0x31, 0x89, 0x44, 0x3f, 0x9c, 0x26, 0x8f, 0x62, 0x6a, 0xea, 0x08, 0xa7, 0x56, 0xab, 0xe7, 0xb7, 0x26, 0xb0, 0x5f, 0x70, 0x1c, 0xb0, 0x82, 0x22, 0x31, 0x2c, 0xcf, 0xd6, 0x71, 0x0a, 0x26}}, { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65}, 72 }, /* 'A' x 72 times */ {0x36, 0x5d, 0x41, 0x0e, 0x55, 0xd1, 0xfd, 0xe6, 0xc3, 0xb8, 0x68, 0xcc, 0xed, 0xeb, 0xcd, 0x0d, 0x2e, 0x34, 0xb2, 0x5c, 0xdf, 0xe7, 0x79, 0xe2, 0xe9, 0x65, 0x07, 0x33, 0x78, 0x0d, 0x01, 0x89}}, { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73}, 55}, /* 19..73 sequence */ {0xb9, 0xe5, 0x74, 0x11, 0xbf, 0xa2, 0x0e, 0x98, 0xbe, 0x08, 0x69, 0x2e, 0x17, 0x9e, 0xc3, 0xfe, 0x61, 0xe3, 0x7a, 0x80, 0x2e, 0x25, 0x8c, 0xf3, 0x76, 0xda, 0x9f, 0x5f, 0xcd, 0x87, 0x48, 0x0d}}, { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */ {0x80, 0x15, 0x83, 0xed, 0x7d, 0xef, 0x9f, 0xdf, 0xfb, 0x83, 0x1f, 0xc5, 0x8b, 0x50, 0x37, 0x81, 0x00, 0xc3, 0x4f, 0xfd, 0xfe, 0xc2, 0x9b, 0xaf, 0xfe, 0x15, 0x66, 0xe5, 0x08, 0x42, 0x5e, 0xae}}, { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92}, 55}, /* 38..92 sequence */ {0x76, 0x2f, 0x27, 0x4d, 0xfa, 0xd5, 0xa9, 0x21, 0x4e, 0xe9, 0x56, 0x22, 0x54, 0x38, 0x71, 0x3e, 0xef, 0x14, 0xa9, 0x22, 0x37, 0xf3, 0xb0, 0x50, 0x3d, 0x95, 0x40, 0xb7, 0x08, 0x64, 0xa9, 0xfd}}, { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72}, 72}, /* 1..72 sequence */ {0x3f, 0x5c, 0xd3, 0xec, 0x40, 0xc4, 0xb9, 0x78, 0x35, 0x57, 0xc6, 0x4f, 0x3e, 0x46, 0x82, 0xdc, 0xd4, 0x46, 0x11, 0xd0, 0xb3, 0x0a, 0xbb, 0x89, 0xf1, 0x1d, 0x34, 0xb5, 0xf9, 0xd5, 0x10, 0x35}}, { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}, 256}, /* 0..255 sequence */ {0x08, 0x37, 0xa1, 0x1d, 0x99, 0x4d, 0x5a, 0xa8, 0x60, 0xd0, 0x69, 0x17, 0xa8, 0xa0, 0xf6, 0x3e, 0x31, 0x11, 0xb9, 0x56, 0x33, 0xde, 0xeb, 0x15, 0xee, 0xd9, 0x94, 0x93, 0x76, 0xf3, 0x7d, 0x36, }}, { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139}, 61}, /* 199..139 sequence */ {0xcf, 0x21, 0x4b, 0xb2, 0xdd, 0x40, 0x98, 0xdf, 0x3a, 0xb7, 0x21, 0xb4, 0x69, 0x0e, 0x19, 0x36, 0x24, 0xa9, 0xbe, 0x30, 0xf7, 0xd0, 0x75, 0xb0, 0x39, 0x94, 0x82, 0xda, 0x55, 0x97, 0xe4, 0x79}}, { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255}, /* 255..1 sequence */ {0x22, 0x31, 0xf2, 0xa1, 0xb4, 0x89, 0xb2, 0x44, 0xf7, 0x66, 0xa0, 0xb8, 0x31, 0xed, 0xb7, 0x73, 0x8a, 0x34, 0xdc, 0x11, 0xc8, 0x2c, 0xf2, 0xb5, 0x88, 0x60, 0x39, 0x6b, 0x5c, 0x06, 0x70, 0x37}}, { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233, 235, 179, 166, 219, 60, 135, 12, 62, 153, 36, 94, 13, 28, 6, 183, 71, 222, 179, 18, 77, 200, 67, 187, 139, 166, 31, 3, 90, 125, 9, 56, 37, 31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28, 219, 174, 50, 32, 154, 80, 238, 64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220, 173, 79, 20, 242, 68, 64, 102, 208, 107, 196, 48, 183, 50, 59, 161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202, 153, 2, 185, 114, 157, 73, 44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191, 103, 214, 191, 20, 214, 126, 45, 220, 142, 102, 131, 239, 87, 73, 97, 255, 105, 143, 97, 205, 209, 30, 157, 156, 22, 114, 114, 230, 29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51, 116, 158, 12, 244, 213, 212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244, 204, 207, 211, 144, 45, 72, 211, 143, 117, 230, 217, 29, 42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212, 97, 141, 190, 123, 5, 21, 7, 59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62, 105, 21, 248, 70, 106, 4, 150, 115, 14, 217, 22, 47, 103, 104, 212, 247, 74, 74, 208, 87, 104}, 255}, /* pseudo-random data */ {0xb8, 0xdb, 0x2c, 0x2e, 0xf3, 0x12, 0x77, 0x14, 0xf9, 0x34, 0x2d, 0xfa, 0xda, 0x42, 0xbe, 0xfe, 0x67, 0x3a, 0x8a, 0xf6, 0x71, 0x36, 0x00, 0xff, 0x77, 0xa5, 0x83, 0x14, 0x55, 0x2a, 0x05, 0xaf}}, { { {66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66}, 110}, /* 'B' x 110 times */ {0xc8, 0x9e, 0x0d, 0x8f, 0x7b, 0x35, 0xfd, 0x3e, 0xdc, 0x90, 0x87, 0x64, 0x45, 0x94, 0x94, 0x21, 0xb3, 0x8e, 0xb5, 0xc7, 0x54, 0xc8, 0xee, 0xde, 0xfc, 0x77, 0xd6, 0xe3, 0x9f, 0x81, 0x8e, 0x78}}, { { {67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67}, 111}, /* 'C' x 111 times */ {0x86, 0xca, 0x6d, 0x2a, 0x72, 0xe2, 0x8c, 0x17, 0x89, 0x86, 0x89, 0x1b, 0x36, 0xf9, 0x6d, 0xda, 0x8c, 0xd6, 0x30, 0xb2, 0xd3, 0x60, 0x39, 0xfb, 0xc9, 0x04, 0xc5, 0x11, 0xcd, 0x2d, 0xe3, 0x62}}, { { {68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68}, 112}, /* 'D' x 112 times */ {0xdf, 0x9d, 0x4a, 0xcf, 0x81, 0x0d, 0x3a, 0xd4, 0x8e, 0xa4, 0x65, 0x9e, 0x1e, 0x15, 0xe4, 0x15, 0x1b, 0x37, 0xb6, 0xeb, 0x17, 0xab, 0xf6, 0xb1, 0xbc, 0x30, 0x46, 0x34, 0x24, 0x56, 0x1c, 0x06}}, { { {69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69}, 113}, /* 'E' x 113 times */ {0xa5, 0xf1, 0x47, 0x74, 0xf8, 0x2b, 0xed, 0x23, 0xe4, 0x10, 0x59, 0x8f, 0x7e, 0xb1, 0x30, 0xe5, 0x7e, 0xd1, 0x4b, 0xbc, 0x72, 0x58, 0x58, 0x81, 0xbb, 0xa0, 0xa5, 0xb6, 0x15, 0x39, 0x49, 0xa1}}, { { {70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70}, 114}, /* 'F' x 114 times */ {0xe6, 0xa3, 0xc9, 0x63, 0xd5, 0x28, 0x6e, 0x2d, 0xfb, 0x71, 0xdf, 0xd4, 0xff, 0xc2, 0xd4, 0x2b, 0x5d, 0x9b, 0x76, 0x28, 0xd2, 0xcb, 0x15, 0xc8, 0x81, 0x57, 0x14, 0x09, 0xc3, 0x8e, 0x92, 0xce}}, { { {76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76, 76}, 127}, /* 'L' x 127 times */ {0x5d, 0x18, 0xff, 0xd7, 0xbe, 0x23, 0xb2, 0xb2, 0xbd, 0xe3, 0x13, 0x12, 0x1c, 0x16, 0x89, 0x14, 0x4a, 0x42, 0xb4, 0x3f, 0xab, 0xc8, 0x41, 0x14, 0x62, 0x00, 0xb5, 0x53, 0xa7, 0xd6, 0xd5, 0x35}}, { { {77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77}, 128}, /* 'M' x 128 times */ {0x6e, 0xf0, 0xda, 0x81, 0x3d, 0x50, 0x1d, 0x31, 0xf1, 0x4a, 0xf8, 0xd9, 0x7d, 0xd2, 0x13, 0xdd, 0xa4, 0x46, 0x15, 0x0b, 0xb8, 0x5a, 0x8a, 0xc6, 0x1e, 0x3a, 0x1f, 0x21, 0x35, 0xa2, 0xbb, 0x4f}}, { { {78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78, 78}, 129}, /* 'N' x 129 times */ {0xee, 0xce, 0xd5, 0x34, 0xab, 0x14, 0x13, 0x9e, 0x8f, 0x5c, 0xb4, 0xef, 0xac, 0xaf, 0xc5, 0xeb, 0x1d, 0x2f, 0xe3, 0xc5, 0xca, 0x09, 0x29, 0x96, 0xfa, 0x84, 0xff, 0x12, 0x26, 0x6a, 0x50, 0x49}}, { { {97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97}, 238}, /* 'a' x 238 times */ {0xb4, 0x24, 0xe5, 0x7b, 0xa7, 0x37, 0xe3, 0xc4, 0xac, 0x35, 0x21, 0x17, 0x98, 0xec, 0xb9, 0xae, 0x45, 0x13, 0x24, 0xa4, 0x2c, 0x76, 0xae, 0x7d, 0x17, 0x75, 0x27, 0x8a, 0xaa, 0x4a, 0x48, 0x60}}, { { {98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98}, 239}, /* 'b' x 239 times */ {0xcd, 0x93, 0xb8, 0xab, 0x6a, 0x74, 0xbd, 0x34, 0x8c, 0x43, 0x76, 0x0c, 0x2a, 0xd0, 0x6e, 0xd8, 0x76, 0xcf, 0xdf, 0x2a, 0x21, 0x04, 0xfb, 0xf6, 0x16, 0x53, 0x68, 0xf6, 0x10, 0xc3, 0xa1, 0xac}}, { { {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}, 240}, /* 'c' x 240 times */ {0x5f, 0x60, 0xea, 0x44, 0xb6, 0xc6, 0x9e, 0xfe, 0xfc, 0x0e, 0x6a, 0x0a, 0x99, 0x40, 0x1b, 0x61, 0x43, 0x58, 0xba, 0x4a, 0x0a, 0xee, 0x6b, 0x52, 0x10, 0xdb, 0x32, 0xd9, 0x7f, 0x12, 0xba, 0x70}}, { { {48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48}, 241}, /* '0' x 241 times */ {0x3c, 0xcb, 0xcf, 0x50, 0x79, 0xd5, 0xb6, 0xf5, 0xbf, 0x25, 0x07, 0xfb, 0x4d, 0x1f, 0xa3, 0x77, 0xc3, 0x6f, 0xe8, 0xe3, 0xc4, 0x4b, 0xf8, 0xcd, 0x90, 0x93, 0xf1, 0x3e, 0x08, 0x09, 0xa7, 0x69}} }; static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]); /* * Helper functions */ /** * Print bin as hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0')); } *hex = 0; } static int check_result (const char *test_name, unsigned int check_num, const uint8_t calculated[SHA512_256_DIGEST_SIZE], const uint8_t expected[SHA512_256_DIGEST_SIZE]) { int failed = memcmp (calculated, expected, SHA512_256_DIGEST_SIZE); check_num++; /* Print 1-based numbers */ if (failed) { char calc_str[SHA512_256_DIGEST_SIZE * 2 + 1]; char expc_str[SHA512_256_DIGEST_SIZE * 2 + 1]; bin2hex (calculated, SHA512_256_DIGEST_SIZE, calc_str); bin2hex (expected, SHA512_256_DIGEST_SIZE, expc_str); fprintf (stderr, "FAILED: %s check %u: calculated digest %s, expected digest %s.\n", test_name, check_num, calc_str, expc_str); fflush (stderr); } else if (verbose) { char calc_str[SHA512_256_DIGEST_SIZE * 2 + 1]; bin2hex (calculated, SHA512_256_DIGEST_SIZE, calc_str); printf ("PASSED: %s check %u: calculated digest %s matches " \ "expected digest.\n", test_name, check_num, calc_str); fflush (stdout); } return failed ? 1 : 0; } /* * Tests */ /* Calculated SHA-512/256 as one pass for whole data */ static int test1_str (void) { int num_failed = 0; unsigned int i; struct Sha512_256Ctx ctx; for (i = 0; i < units1_num; i++) { uint8_t digest[SHA512_256_DIGEST_SIZE]; MHD_SHA512_256_init (&ctx); MHD_SHA512_256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, data_units1[i].str_l.len); MHD_SHA512_256_finish (&ctx, digest); num_failed += check_result (__FUNCTION__, i, digest, data_units1[i].digest); } return num_failed; } static int test1_bin (void) { int num_failed = 0; unsigned int i; struct Sha512_256Ctx ctx; for (i = 0; i < units2_num; i++) { uint8_t digest[SHA512_256_DIGEST_SIZE]; MHD_SHA512_256_init (&ctx); MHD_SHA512_256_update (&ctx, data_units2[i].bin_l.bin, data_units2[i].bin_l.len); MHD_SHA512_256_finish (&ctx, digest); num_failed += check_result (__FUNCTION__, i, digest, data_units2[i].digest); } return num_failed; } /* Calculated SHA-512/256 as two iterations for whole data */ static int test2_str (void) { int num_failed = 0; unsigned int i; struct Sha512_256Ctx ctx; for (i = 0; i < units1_num; i++) { uint8_t digest[SHA512_256_DIGEST_SIZE]; size_t part_s = data_units1[i].str_l.len / 4; MHD_SHA512_256_init (&ctx); MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA512_256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, part_s); MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA512_256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str + part_s, data_units1[i].str_l.len - part_s); MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA512_256_finish (&ctx, digest); num_failed += check_result (__FUNCTION__, i, digest, data_units1[i].digest); } return num_failed; } static int test2_bin (void) { int num_failed = 0; unsigned int i; struct Sha512_256Ctx ctx; for (i = 0; i < units2_num; i++) { uint8_t digest[SHA512_256_DIGEST_SIZE]; size_t part_s = data_units2[i].bin_l.len * 2 / 3; MHD_SHA512_256_init (&ctx); MHD_SHA512_256_update (&ctx, data_units2[i].bin_l.bin, part_s); MHD_SHA512_256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA512_256_update (&ctx, data_units2[i].bin_l.bin + part_s, data_units2[i].bin_l.len - part_s); MHD_SHA512_256_finish (&ctx, digest); num_failed += check_result (__FUNCTION__, i, digest, data_units2[i].digest); } return num_failed; } /* Use data set number 7 as it has the longest sequence */ #define DATA_POS 6 #define MAX_OFFSET 63 static int test_unaligned (void) { int num_failed = 0; unsigned int offset; uint8_t *buf; uint8_t *digest_buf; struct Sha512_256Ctx ctx; const struct data_unit2 *const tdata = data_units2 + DATA_POS; buf = malloc (tdata->bin_l.len + MAX_OFFSET); digest_buf = malloc (SHA512_256_DIGEST_SIZE + MAX_OFFSET); if ((NULL == buf) || (NULL == digest_buf)) exit (99); for (offset = MAX_OFFSET; offset >= 1; --offset) { uint8_t *unaligned_digest; uint8_t *unaligned_buf; unaligned_buf = buf + offset; memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len); unaligned_digest = digest_buf + MAX_OFFSET - offset; memset (unaligned_digest, 0, SHA512_256_DIGEST_SIZE); MHD_SHA512_256_init (&ctx); MHD_SHA512_256_update (&ctx, unaligned_buf, tdata->bin_l.len); MHD_SHA512_256_finish (&ctx, unaligned_digest); num_failed += check_result (__FUNCTION__, MAX_OFFSET - offset, unaligned_digest, tdata->digest); } free (digest_buf); free (buf); return num_failed; } int main (int argc, char *argv[]) { int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose")) verbose = 1; num_failed += test1_str (); num_failed += test1_bin (); num_failed += test2_str (); num_failed += test2_bin (); num_failed += test_unaligned (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.10/src/microhttpd/test_response_entries.c0000664000175000017500000006402715232103064017663 /* This file is part of libmicrohttpd Copyright (C) 2021 Karlson2k (Evgeny Grin) This test_response_entries.c file is in the public domain */ /** * @file test_response_entries.c * @brief Test adding and removing response headers * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "platform.h" #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static int expect_str (const char *actual, const char *expected) { if (expected == actual) return ! 0; if (NULL == actual) { fprintf (stderr, "FAILED: result: NULL\n" \ " expected: \"%s\"\n", expected); return 0; } if (NULL == expected) { fprintf (stderr, "FAILED: result: \"%s\"\n" \ " expected: NULL\n", actual); return 0; } if (0 != strcmp (actual, expected)) { fprintf (stderr, "FAILED: result: \"%s\"\n" \ " expected: \"%s\"\n", actual, expected); return 0; } return ! 0; } int main (int argc, char *const *argv) { struct MHD_Response *r; (void) argc; (void) argv; /* Unused. Silence compiler warning. */ r = MHD_create_response_empty (MHD_RF_NONE); if (NULL == r) { fprintf (stderr, "Cannot create a response.\n"); return 1; } /* ** Test basic header functions ** */ /* Add first header */ if (MHD_YES != MHD_add_response_header (r, "Header-Type-A", "value-a1")) { fprintf (stderr, "Cannot add header A1.\n"); MHD_destroy_response (r); return 2; } if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a1")) { MHD_destroy_response (r); return 2; } /* Add second header with the same name */ if (MHD_YES != MHD_add_response_header (r, "Header-Type-A", "value-a2")) { fprintf (stderr, "Cannot add header A2.\n"); MHD_destroy_response (r); return 2; } /* Value of the first header must be returned */ if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a1")) { MHD_destroy_response (r); return 2; } /* Remove the first header */ if (MHD_YES != MHD_del_response_header (r, "Header-Type-A", "value-a1")) { fprintf (stderr, "Cannot remove header A1.\n"); MHD_destroy_response (r); return 2; } /* Value of the ex-second header must be returned */ if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a2")) { MHD_destroy_response (r); return 2; } if (MHD_YES != MHD_add_response_header (r, "Header-Type-A", "value-a3")) { fprintf (stderr, "Cannot add header A2.\n"); MHD_destroy_response (r); return 2; } /* Value of the ex-second header must be returned */ if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a2")) { MHD_destroy_response (r); return 2; } /* Remove the last header */ if (MHD_YES != MHD_del_response_header (r, "Header-Type-A", "value-a3")) { fprintf (stderr, "Cannot add header A2.\n"); MHD_destroy_response (r); return 2; } if (! expect_str (MHD_get_response_header (r, "Header-Type-A"), "value-a2")) { MHD_destroy_response (r); return 2; } if (! expect_str (MHD_get_response_header (r, "Header-Type-B"), NULL)) { MHD_destroy_response (r); return 2; } if (MHD_NO != MHD_del_response_header (r, "Header-Type-C", "value-a3")) { fprintf (stderr, "Removed non-existing header.\n"); MHD_destroy_response (r); return 2; } if (MHD_NO != MHD_del_response_header (r, "Header-Type-A", "value-c")) { fprintf (stderr, "Removed non-existing header value.\n"); MHD_destroy_response (r); return 2; } /* ** Test "Connection:" header ** */ if (MHD_YES != MHD_add_response_header (r, "Connection", "a,b,c,d,e")) { fprintf (stderr, "Cannot add \"Connection\" header with simple values.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "a, b, c, d, e")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "e,b,c,d,a")) { fprintf (stderr, "Cannot remove \"Connection\" header with simple values.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "i,k,l,m,n,o,p,close")) { fprintf (stderr, "Cannot add \"Connection\" header with simple values and \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, i, k, l, m, n, o, p")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "i,k,l,m,n,o,p,close")) { fprintf (stderr, "Cannot remove \"Connection\" header with simple values and \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "1,2,3,4,5,6,7,close")) { fprintf (stderr, "Cannot add \"Connection\" header with simple values and \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 1, 2, 3, 4, 5, 6, 7")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "8,9,close")) { fprintf (stderr, "Cannot add second \"Connection\" header with simple values and \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 1, 2, 3, 4, 5, 6, 7, 8, 9")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "1,3,5,7,9")) { fprintf (stderr, "Cannot remove part of \"Connection\" header with simple values.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2, 4, 6, 8")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "10,12")) { fprintf (stderr, "Cannot add third \"Connection\" header with simple values.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2, 4, 6, 8, 10, 12")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "12 ,10 ,8 ,close")) { fprintf (stderr, "Cannot remove part of \"Connection\" header with simple values and \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "2, 4, 6")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\" only.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2, 4, 6")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "4 ,5,6,7 8,")) { fprintf (stderr, "Cannot remove part of \"Connection\" header with simple values and non-existing tokens.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\" only.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, 2")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close, 10, 12, 22, nothing")) { fprintf (stderr, "Cannot remove part of \"Connection\" header with \"close\" and non-existing tokens.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "2")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "2")) { fprintf (stderr, "Cannot remove part of \"Connection\" header with simple values and non-existing tokens.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot remove \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close,other-token")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, other-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, new-token")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, other-token, new-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close, new-token")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "other-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "other-token")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, one-long-token")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, one-long-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, one-long-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "one-long-token,close")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, additional-token")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, additional-token")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "additional-token,close")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "token-1,token-2")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1, token-2")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "token-3")) { fprintf (stderr, "Cannot add \"Connection\" header.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1, token-2, token-3")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, token-4")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3, token-4")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1, token-2, token-3, token-4")) { MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, token-5")) { fprintf (stderr, "Cannot add \"Connection\" header with \"close\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3, token-4, token-5")) { MHD_destroy_response (r); return 3; } if (MHD_NO != MHD_del_response_header (r, "Connection", "non-existing, token-9")) { fprintf (stderr, "Non-existing tokens successfully removed from \"Connection\" header.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3, token-4, token-5")) { MHD_destroy_response (r); return 3; } if (MHD_NO != MHD_add_response_header (r, "Connection", ",,,,,,,,,,,, ,\t\t\t, , , ")) { fprintf (stderr, "Empty token was added successfully to \"Connection\" header.\n"); MHD_destroy_response (r); return 3; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close, token-1, token-2, token-3, token-4, token-5")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_NO != MHD_add_response_header (r, "Connection", ",,,,,,,,,,,, ,\t\t\t, , , ")) { fprintf (stderr, "Empty token was added successfully to \"Connection\" header.\n"); MHD_destroy_response (r); return 3; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 3; } if (MHD_NO != MHD_add_response_header (r, "Connection", "keep-Alive")) { fprintf (stderr, "Successfully added \"Connection\" header with \"keep-Alive\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "keep-Alive, Close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"keep-Alive, Close\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close")) { MHD_destroy_response (r); return 4; } if (MHD_NO != MHD_add_response_header (r, "Connection", "keep-Alive")) { fprintf (stderr, "Successfully added \"Connection\" header with \"keep-Alive\".\n"); MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "keep-Alive, Close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"keep-Alive, Close\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "close, additional-token")) { fprintf (stderr, "Cannot add \"Connection\" header with " "\"close, additional-token\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, additional-token")) { MHD_destroy_response (r); return 4; } if (MHD_NO != MHD_add_response_header (r, "Connection", "keep-Alive")) { fprintf (stderr, "Successfully added \"Connection\" header with \"keep-Alive\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, additional-token")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_del_response_header (r, "Connection", "additional-token,close")) { fprintf (stderr, "Cannot remove tokens from \"Connection\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "Keep-aLive, token-1")) { fprintf (stderr, "Cannot add \"Connection\" header with \"Keep-aLive, token-1\".\n") ; MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "Keep-aLive, token-2")) { fprintf (stderr, "Cannot add \"Connection\" header with \"Keep-aLive, token-2\".\n") ; MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1, token-2")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "Keep-aLive, token-3, close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"Keep-aLive, token-3, close\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close")) { fprintf (stderr, "Cannot remove \"close\" tokens from \"Connection\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "token-1, token-2, token-3")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Connection", "Keep-aLive, close")) { fprintf (stderr, "Cannot add \"Connection\" header with \"Keep-aLive, token-3, close\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), "close, token-1, token-2, token-3")) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_del_response_header (r, "Connection", "close, token-1, Keep-Alive, token-2, token-3")) { fprintf (stderr, "Cannot remove \"close\" tokens from \"Connection\".\n"); MHD_destroy_response (r); return 4; } if (! expect_str (MHD_get_response_header (r, "Connection"), NULL)) { MHD_destroy_response (r); return 4; } if (MHD_YES != MHD_add_response_header (r, "Date", "Wed, 01 Apr 2015 00:00:00 GMT")) { fprintf (stderr, "Cannot add \"Date\" header with \"Wed, 01 Apr 2015 00:00:00 GMT\".\n"); MHD_destroy_response (r); return 5; } if (! expect_str (MHD_get_response_header (r, "Date"), "Wed, 01 Apr 2015 00:00:00 GMT")) { MHD_destroy_response (r); return 5; } if (MHD_YES != MHD_add_response_header (r, "Date", "Thu, 01 Apr 2021 00:00:00 GMT")) { fprintf (stderr, "Cannot add \"Date\" header with \"Thu, 01 Apr 2021 00:00:00 GMT\".\n"); MHD_destroy_response (r); return 5; } if (! expect_str (MHD_get_response_header (r, "Date"), "Thu, 01 Apr 2021 00:00:00 GMT")) { MHD_destroy_response (r); return 5; } if (MHD_YES != MHD_del_response_header (r, "Date", "Thu, 01 Apr 2021 00:00:00 GMT")) { fprintf (stderr, "Cannot remove \"Date\" header.\n"); MHD_destroy_response (r); return 5; } if (! expect_str (MHD_get_response_header (r, "Date"), NULL)) { MHD_destroy_response (r); return 5; } if (MHD_YES != MHD_add_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked")) { fprintf (stderr, "Cannot add \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \ "\" header with \"chunked\".\n"); MHD_destroy_response (r); return 6; } if (! expect_str (MHD_get_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING), "chunked")) { MHD_destroy_response (r); return 6; } if (MHD_YES != MHD_add_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked")) { fprintf (stderr, "Cannot add \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \ "\" second header with \"chunked\".\n"); MHD_destroy_response (r); return 6; } if (! expect_str (MHD_get_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING), "chunked")) { MHD_destroy_response (r); return 6; } if (MHD_NO != MHD_add_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING, "identity")) { fprintf (stderr, "Successfully added \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \ "\" header with \"identity\".\n"); MHD_destroy_response (r); return 6; } if (! expect_str (MHD_get_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING), "chunked")) { MHD_destroy_response (r); return 6; } if (MHD_YES != MHD_del_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked")) { fprintf (stderr, "Cannot remove \"" MHD_HTTP_HEADER_TRANSFER_ENCODING \ "\" header.\n"); MHD_destroy_response (r); return 6; } if (! expect_str (MHD_get_response_header (r, MHD_HTTP_HEADER_TRANSFER_ENCODING), NULL)) { MHD_destroy_response (r); return 6; } MHD_destroy_response (r); printf ("All tests has been successfully passed.\n"); return 0; } libmicrohttpd-1.0.10/src/microhttpd/test_dauth_malformed.c0000664000175000017500000012072015232103064017420 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_dauth_malformed.c * @brief Testcase for malformed Digest "Authorization:" request headers * @author Christian Grothoff * * The malformed headers used by this test cannot be produced with libcurl, * therefore all the requests are sent over a raw socket. * * The test is a regression test for two remotely triggerable defects: * * - An unrecognised "algorithm=" token is parsed to * #MHD_DIGEST_AUTH_ALGO3_INVALID, the numeric value of which is zero. The * "is the client's algorithm allowed by the application" bit-mask test is * passed trivially by a zero value, so an invalid algorithm used to reach * digest_init_one_time(), which aborts the process with MHD_PANIC(). * * - The "response=" value was hex-decoded into a #MAX_DIGEST bytes long * buffer on the stack, while the only length check allowed four times as * many characters as the digest size, resulting in an out-of-bounds stack * write of up to #MAX_DIGEST bytes. Reaching the decoder requires an * otherwise complete and valid Digest handshake, hence the two-step * exchange performed by this test. * * A number of adjacent malformed, empty, over-long and duplicated parameters * is checked as well. Every sub-case must leave the daemons alive and must * be answered with a regular HTTP error reply. * * Two daemons are used: one that issues SHA-256 challenges and one that * issues the challenges with the default "any non-session" algorithm. This * keeps the length of the nonces recorded by a single daemon uniform, which * is what a real-world application does as well. * * The test honours the daemon option matrix of mhd_opt_matrix.h: when one of * the MHD_TEST_* environment variables selects a profile, its connection * memory limit, client discipline level, threading mode and polling backend * are applied to both daemons. Without those variables nothing changes. A * Digest handshake needs room for a 76 character nonce plus the realm, the * username and the response, so a profile asking for less than * #MIN_POOL_FOR_TEST bytes is raised to that value and the adjustment is * reported. */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifndef WINDOWS #include #include #endif #include "mhd_sockets.h" /* only macros used */ #include "mhd_opt_matrix.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" /** * The smallest connection memory pool this test can work with: a complete * Digest "Authorization:" header plus the "WWW-Authenticate:" challenge of * the reply do not fit into a smaller pool. */ #define MIN_POOL_FOR_TEST 4096 #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #if defined(DAUTH_SUPPORT) && defined(MHD_SHA256_SUPPORT) /** * The realm used by the test daemons. */ #define TEST_REALM "TestRealm" /** * The username known to the test daemons. */ #define TEST_USERNAME "testuser" /** * The password known to the test daemons. */ #define TEST_PASSWORD "testpass" /** * The URL used by all the requests. */ #define TEST_URL "/auth" /** * The size of the buffer used to build a request. */ #define REQ_BUF_SIZE 32768 /** * The size of the buffer used to receive a reply. */ #define RPLY_BUF_SIZE 8192 /** * The length of the over-long parameter values. */ #define LONG_PARAM_LEN 4000 /** * Socket send/receive timeout in seconds. */ #define SOCK_TIMEOUT_SEC 5 /** * The number of the "nonce"/"nc" pairs recorded by a daemon. */ #define NONCE_NC_SIZE 100 /** * The port of the daemon issuing SHA-256 challenges. */ static uint16_t port_sha256; /** * The port of the daemon issuing "any non-session" (MD5) challenges. */ static uint16_t port_any; /** * The port used by the sub-case being executed. */ static uint16_t test_port; /** * The number of the sub-case being executed. */ static unsigned int case_num; /** * The number of the failed sub-cases. */ static unsigned int failures; /** * The 'nc' value for the next request, incremented for every request so that * a "nonce"/"nc" combination is never re-used. */ static unsigned int nc_counter; /** * Run only the sub-cases with a name containing this string, NULL for all. */ static const char *case_filter; /** * Set to non-zero by the daemon if a malformed request was authenticated. */ static volatile int wrongly_authenticated; /** * The profile selected by the environment, NULL if the built-in daemon * configuration is used (which is the case for a stock "make check"). */ static const struct MHD_OptMatrixProfile *test_prof; /** * The (possibly adjusted) copy of the profile @a test_prof points to. */ static struct MHD_OptMatrixProfile test_prof_copy; _MHD_NORETURN static void hard_error (const char *msg) { fprintf (stderr, "Hard error: %s\n", msg); fflush (stderr); exit (99); } /** * Fill @a buf with @a len hexadecimal digits and zero-terminate it. * * @param[out] buf the buffer to fill, must be at least @a len + 1 bytes long * @param len the number of the hexadecimal digits to generate * @return the @a buf pointer */ static char * fill_hex (char *buf, size_t len) { static const char hex_chars[] = "0123456789abcdef"; size_t i; for (i = 0; i < len; ++i) buf[i] = hex_chars[i % (MHD_STATICSTR_LEN_ (hex_chars))]; buf[len] = 0; return buf; } /** * Fill @a buf with @a len copies of @a chr and zero-terminate it. * * @param[out] buf the buffer to fill, must be at least @a len + 1 bytes long * @param chr the character to repeat * @param len the number of the characters to generate * @return the @a buf pointer */ static char * fill_chr (char *buf, char chr, size_t len) { memset (buf, chr, len); buf[len] = 0; return buf; } /* * * * * * * * * * * * The daemon side * * * * * * * * * * * */ static enum MHD_Result ahc_check (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; const enum MHD_DigestAuthMultiAlgo3 *const challenge_algo = cls; struct MHD_Response *response; enum MHD_DigestAuthResult check_res; enum MHD_Result ret; (void) url; (void) method; (void) version; (void) upload_data; (void) upload_data_size; if (&marker != *req_cls) { /* The first call for the request */ *req_cls = ▮ return MHD_YES; } check_res = MHD_digest_auth_check3 (connection, TEST_REALM, TEST_USERNAME, TEST_PASSWORD, 300, 0, MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT, MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION); if (MHD_DAUTH_OK == check_res) { /* None of the sub-cases must be authenticated */ static const char page[] = "Authenticated"; wrongly_authenticated = 1; response = MHD_create_response_from_buffer (MHD_STATICSTR_LEN_ (page), (void *) page, MHD_RESPMEM_PERSISTENT); if (NULL == response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } if (1) { static const char page[] = "Access denied"; response = MHD_create_response_from_buffer (MHD_STATICSTR_LEN_ (page), (void *) page, MHD_RESPMEM_PERSISTENT); if (NULL == response) return MHD_NO; ret = MHD_queue_auth_required_response3 (connection, TEST_REALM, "test-opaque", NULL, response, (MHD_DAUTH_NONCE_STALE == check_res) ? MHD_YES : MHD_NO, MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT, *challenge_algo, MHD_YES, MHD_NO); MHD_destroy_response (response); } return ret; } /* * * * * * * * * * * * The raw client side * * * * * * * * * * * */ /** * Send @a req to the daemon at #test_port and receive the complete reply. * * @param req the request to send, zero-terminated * @param[out] rply the buffer for the reply * @param rply_size the size of the @a rply buffer * @return the number of the received bytes, * -1 if no reply has been received */ static ssize_t exchange (const char *req, char *rply, size_t rply_size) { MHD_socket sckt; struct sockaddr_in sa; struct timeval tmo; size_t req_len; size_t sent; size_t received; sckt = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == sckt) hard_error ("socket() failed"); tmo.tv_sec = SOCK_TIMEOUT_SEC; tmo.tv_usec = 0; if ( (0 != setsockopt (sckt, SOL_SOCKET, SO_RCVTIMEO, (const void *) &tmo, sizeof (tmo))) || (0 != setsockopt (sckt, SOL_SOCKET, SO_SNDTIMEO, (const void *) &tmo, sizeof (tmo))) ) hard_error ("setsockopt() failed"); memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (test_port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != connect (sckt, (const struct sockaddr *) &sa, sizeof (sa))) { MHD_socket_close_chk_ (sckt); return -1; } req_len = strlen (req); sent = 0; while (sent < req_len) { ssize_t res; res = send (sckt, req + sent, req_len - sent, 0); if (0 >= res) break; sent += (size_t) res; } if (sent != req_len) { MHD_socket_close_chk_ (sckt); return -1; } received = 0; while (received + 1 < rply_size) { ssize_t res; res = recv (sckt, rply + received, rply_size - received - 1, 0); if (0 >= res) break; received += (size_t) res; } rply[received] = 0; MHD_socket_close_chk_ (sckt); if (0 == received) return -1; return (ssize_t) received; } /** * Extract the HTTP status code from a raw reply. * * @param rply the reply, zero-terminated * @return the status code, zero if the reply is not a valid HTTP reply */ static unsigned int get_status (const char *rply) { unsigned int status; if (MHD_STATICSTR_LEN_ ("HTTP/1.1 000") > strlen (rply)) return 0; if (0 != memcmp (rply, "HTTP/1.", MHD_STATICSTR_LEN_ ("HTTP/1."))) return 0; status = 0; if (1 != sscanf (rply + MHD_STATICSTR_LEN_ ("HTTP/1.1 "), "%3u", &status)) return 0; return status; } /** * Request a challenge from the daemon at #test_port and extract the "nonce" * value from it. * * @param[out] nonce the buffer for the "nonce" value * @param nonce_size the size of the @a nonce buffer * @return non-zero on success, zero on failure */ static int get_nonce (char *nonce, size_t nonce_size) { static const char nonce_tk[] = "nonce=\""; static const char req[] = "GET " TEST_URL " HTTP/1.1\r\n" "Host: 127.0.0.1\r\n" "Connection: close\r\n" "\r\n"; char rply[RPLY_BUF_SIZE]; const char *start; const char *end; size_t len; if (0 >= exchange (req, rply, sizeof (rply))) return 0; if (MHD_HTTP_UNAUTHORIZED != get_status (rply)) return 0; start = strstr (rply, nonce_tk); if (NULL == start) return 0; start += MHD_STATICSTR_LEN_ (nonce_tk); end = strchr (start, '"'); if (NULL == end) return 0; len = (size_t) (end - start); if (len + 1 > nonce_size) return 0; memcpy (nonce, start, len); nonce[len] = 0; return 0 != len; } /** * Obtain a "nonce" or fail the whole test. * * @param[out] nonce the buffer for the "nonce" value * @param nonce_size the size of the @a nonce buffer */ static void need_nonce (char *nonce, size_t nonce_size) { if (! get_nonce (nonce, nonce_size)) hard_error ("cannot obtain a 'nonce' from the daemon"); } /** * Run a single sub-case: send a request with the given "Authorization:" * header value and check that the daemon replies with a regular HTTP error. * * @param name the name of the sub-case, used for reporting * @param auth_fmt the printf-style format of the "Authorization:" header * value, NULL to send no "Authorization:" header * @param ... the arguments for the @a auth_fmt */ static void run_case (const char *name, const char *auth_fmt, ...) { static char req[REQ_BUF_SIZE]; static char auth[REQ_BUF_SIZE - 512]; char rply[RPLY_BUF_SIZE]; unsigned int status; ++case_num; if ( (NULL != case_filter) && (NULL == strstr (name, case_filter)) ) return; /* Report the sub-case before it is executed: if the daemon aborts the process, the last reported sub-case is the failing one. */ fprintf (stderr, "[%02u] %s\n", case_num, name); fflush (stderr); if (NULL != auth_fmt) { va_list ap; va_start (ap, auth_fmt); vsnprintf (auth, sizeof (auth), auth_fmt, ap); va_end (ap); snprintf (req, sizeof (req), "GET " TEST_URL " HTTP/1.1\r\n" "Host: 127.0.0.1\r\n" "Connection: close\r\n" "Authorization: %s\r\n" "\r\n", auth); } else snprintf (req, sizeof (req), "GET " TEST_URL " HTTP/1.1\r\n" "Host: 127.0.0.1\r\n" "Connection: close\r\n" "\r\n"); if (0 >= exchange (req, rply, sizeof (rply))) { fprintf (stderr, "FAILED sub-case '%s': no reply received.\n", name); fflush (stderr); ++failures; return; } status = get_status (rply); /* Any regular HTTP error reply is fine: the point of the test is that the daemon neither crashes nor accepts the malformed credentials. */ if ( (MHD_HTTP_UNAUTHORIZED != status) && (MHD_HTTP_BAD_REQUEST != status) && (MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE != status) ) { fprintf (stderr, "FAILED sub-case '%s': unexpected HTTP status %u.\n", name, status); fflush (stderr); ++failures; return; } if (0 != wrongly_authenticated) { fprintf (stderr, "FAILED sub-case '%s': the malformed request was " "authenticated.\n", name); fflush (stderr); wrongly_authenticated = 0; ++failures; } } /** * Build the common part of an otherwise valid Digest "Authorization:" header. * * @param[out] buf the buffer to fill * @param buf_size the size of the @a buf * @param nonce the "nonce" value received from the daemon */ static void make_valid_params (char *buf, size_t buf_size, const char *nonce) { snprintf (buf, buf_size, "username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"" TEST_URL "\", qop=auth, nc=%08x, " "cnonce=\"0123456789abcdef\"", nonce, ++nc_counter); } /* * * * * * * * * * * * The sub-cases * * * * * * * * * * * */ /** * Sub-cases for the missing #MHD_DIGEST_AUTH_ALGO3_INVALID check. * * An unknown "algorithm=" token is parsed to * #MHD_DIGEST_AUTH_ALGO3_INVALID, which has the numeric value of zero and * therefore satisfies the "allowed algorithms" bit-mask test. Without the * explicit check for the invalid value the request reaches * digest_init_one_time() and aborts the process with MHD_PANIC(). * * The algorithm is checked before anything else, so most of the sub-cases * need no other parameter at all. */ static void test_invalid_algorithm (void) { char nonce[256]; char params[512]; char resp[128]; fill_hex (resp, 64); test_port = port_any; run_case ("bug-c/algo-bogus-alone", "Digest algorithm=BOGUS"); run_case ("bug-c/algo-md5-x", "Digest algorithm=MD5-x"); run_case ("bug-c/algo-sha512", "Digest algorithm=SHA-512"); run_case ("bug-c/algo-sha1", "Digest algorithm=SHA1"); run_case ("bug-c/algo-sha256-typo", "Digest algorithm=SHA256"); run_case ("bug-c/algo-empty-quotes", "Digest algorithm=\"\""); run_case ("bug-c/algo-empty-token", "Digest algorithm="); run_case ("bug-c/algo-empty-token-comma", "Digest algorithm=, nonce=\"deadbeef\""); run_case ("bug-c/algo-quoted-bogus", "Digest algorithm=\"BOGUS\""); run_case ("bug-c/algo-space", "Digest algorithm = BOGUS"); /* A backslash inside the value marks the parameter as "quoted", which selects the second, separate branch of the algorithm token parser. */ run_case ("bug-c/algo-escaped-bogus", "Digest algorithm=\"\\BOGUS\""); run_case ("bug-c/algo-escaped-md5-x", "Digest algorithm=\"MD5\\-x\""); /* The "-sess" variants are valid tokens, but they are rejected by the bit-mask test as they are not allowed by the application. */ run_case ("bug-c/algo-md5-sess", "Digest algorithm=MD5-sess"); run_case ("bug-c/algo-sha256-sess", "Digest algorithm=SHA-256-sess"); run_case ("bug-c/algo-sha512-256-sess", "Digest algorithm=SHA-512-256-sess"); run_case ("bug-c/algo-escaped-md5-sess", "Digest algorithm=\"MD5\\-sess\""); run_case ("bug-c/algo-escaped-sha512-256", "Digest algorithm=\"SHA\\-512-256\""); /* The last occurrence of a duplicated parameter is the effective one. */ run_case ("bug-c/algo-duplicated", "Digest algorithm=MD5, algorithm=BOGUS"); run_case ("bug-c/algo-duplicated-rev", "Digest algorithm=BOGUS, algorithm=MD5"); /* The same, but with all the other parameters present and valid, so that nothing else can short-circuit the check. */ test_port = port_sha256; need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); run_case ("bug-c/algo-bogus-full", "Digest %s, algorithm=BOGUS, response=\"%s\"", params, resp); need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); run_case ("bug-c/algo-empty-full", "Digest %s, algorithm=\"\", response=\"%s\"", params, resp); need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); run_case ("bug-c/algo-escaped-bogus-full", "Digest %s, algorithm=\"\\BOGUS\", response=\"%s\"", params, resp); } /** * Sub-cases for the out-of-bounds stack write in the "response=" hex decoder. * * The decoder writes (len + 1) / 2 bytes into a #MAX_DIGEST (32) bytes long * stack buffer, while the length sanity check accepts up to digest_size * 4 * (128) characters. All the other parameters must be valid to reach the * decoder, therefore a fresh "nonce" is obtained for every sub-case. */ static void test_overlong_response (void) { /* 128 and 127 characters produce the maximum overflow of 32 bytes, 66 and 65 characters produce the minimum overflow of a single byte, 64 characters fit exactly and must not overflow. */ static const size_t resp_lengths[] = { 128, 127, 100, 66, 65, 64 }; char nonce[256]; char params[512]; char resp[512]; char name[128]; size_t i; test_port = port_sha256; for (i = 0; i < sizeof (resp_lengths) / sizeof (resp_lengths[0]); ++i) { const size_t len = resp_lengths[i]; /* The value without the quotation marks */ need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); snprintf (name, sizeof (name), "bug-d/sha256-response-%u-bare", (unsigned) len); run_case (name, "Digest %s, algorithm=SHA-256, response=%s", params, fill_hex (resp, len)); /* The same value in the quotation marks */ need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); snprintf (name, sizeof (name), "bug-d/sha256-response-%u-quoted", (unsigned) len); run_case (name, "Digest %s, algorithm=SHA-256, response=\"%s\"", params, fill_hex (resp, len)); } /* A backslash marks the value as "quoted", so it is unquoted into the temporal buffer first and only then decoded. */ need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); run_case ("bug-d/sha256-response-127-escaped", "Digest %s, algorithm=SHA-256, response=\"\\%s\"", params, fill_hex (resp, 127)); /* The SHA-512/256 algorithm uses the same digest size as SHA-256 and the same nonce length, so it reaches the decoder as well. */ #ifdef MHD_SHA512_256_SUPPORT need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); run_case ("bug-d/sha512-256-response-128-bare", "Digest %s, algorithm=SHA-512-256, response=%s", params, fill_hex (resp, 128)); #endif /* MHD_SHA512_256_SUPPORT */ /* The RFC2069 mode: no "qop", no "nc" and no "cnonce". */ need_nonce (nonce, sizeof (nonce)); run_case ("bug-d/sha256-response-128-rfc2069", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"" TEST_URL "\", algorithm=SHA-256, " "response=%s", nonce, fill_hex (resp, 128)); /* The value is not a valid hexadecimal string, the decoder must bail out before writing anything. */ need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); run_case ("bug-d/sha256-response-128-non-hex", "Digest %s, algorithm=SHA-256, response=%s", params, fill_chr (resp, 'z', 128)); /* Only the last character is not a hexadecimal digit, so the decoder writes 63 bytes before it detects the error. */ need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); fill_hex (resp, 128); resp[127] = 'z'; run_case ("bug-d/sha256-response-128-tail-non-hex", "Digest %s, algorithm=SHA-256, response=%s", params, resp); /* Duplicated parameter: the last (over-long) value is the effective one. */ need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); run_case ("bug-d/sha256-response-duplicated", "Digest %s, algorithm=SHA-256, response=\"00112233\", response=%s", params, fill_hex (resp, 128)); #ifdef MHD_MD5_SUPPORT /* The MD5 variant: the decoder writes 32 bytes, which overflows the buffer only in an MD5-only build, where MAX_DIGEST is 16. */ test_port = port_any; need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); run_case ("bug-d/md5-response-64-bare", "Digest %s, algorithm=MD5, response=%s", params, fill_hex (resp, 64)); need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); run_case ("bug-d/md5-response-63-bare", "Digest %s, algorithm=MD5, response=%s", params, fill_hex (resp, 63)); need_nonce (nonce, sizeof (nonce)); make_valid_params (params, sizeof (params), nonce); run_case ("bug-d/md5-response-34-quoted", "Digest %s, algorithm=MD5, response=\"%s\"", params, fill_hex (resp, 34)); #endif /* MHD_MD5_SUPPORT */ } /** * Sub-cases for the adjacent malformed, empty, over-long and duplicated * parameters. */ static void test_adjacent (void) { static char big[LONG_PARAM_LEN + 1]; char nonce[256]; char resp[128]; fill_hex (resp, 64); /* No or unusable "Authorization:" header. These never reach the "nonce" handling, the daemon used does not matter. */ test_port = port_any; run_case ("adj/no-auth-header", NULL); run_case ("adj/scheme-only", "Digest"); run_case ("adj/scheme-and-space", "Digest "); run_case ("adj/only-commas", "Digest ,,,,"); run_case ("adj/basic-scheme", "Basic dGVzdHVzZXI6dGVzdHBhc3M="); run_case ("adj/unknown-scheme", "Bogus xyz"); run_case ("adj/unterminated-quote", "Digest username=\"" TEST_USERNAME); run_case ("adj/unterminated-quote-escape", "Digest username=\"" TEST_USERNAME "\\\""); run_case ("adj/no-equal-sign", "Digest username"); run_case ("adj/leading-equal-sign", "Digest =value"); run_case ("adj/semicolon-in-value", "Digest username=a;b"); run_case ("adj/garbage-after-value", "Digest username=\"a\" garbage"); run_case ("adj/unknown-parameter", "Digest bogus=\"x\", username=\"" TEST_USERNAME "\""); /* Over-long parameter values */ run_case ("adj/username-too-long", "Digest username=\"%s\", realm=\"" TEST_REALM "\"", fill_chr (big, 'u', LONG_PARAM_LEN)); run_case ("adj/realm-too-long", "Digest username=\"" TEST_USERNAME "\", realm=\"%s\"", fill_chr (big, 'r', LONG_PARAM_LEN)); run_case ("adj/uri-too-long", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "uri=\"%s\"", fill_chr (big, 'p', LONG_PARAM_LEN)); run_case ("adj/cnonce-too-long", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "qop=auth, nc=00000001, cnonce=\"%s\"", fill_chr (big, 'c', LONG_PARAM_LEN)); run_case ("adj/nc-too-long", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "qop=auth, nc=%s, cnonce=\"abc\"", fill_hex (big, LONG_PARAM_LEN)); run_case ("adj/opaque-too-long", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "opaque=\"%s\"", fill_chr (big, 'o', LONG_PARAM_LEN)); run_case ("adj/nonce-too-long", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\"", fill_hex (big, LONG_PARAM_LEN)); run_case ("adj/response-too-long", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "response=\"%s\"", fill_hex (big, LONG_PARAM_LEN)); run_case ("adj/username-ext-too-long", "Digest username*=UTF-8''%s, realm=\"" TEST_REALM "\"", fill_chr (big, 'e', LONG_PARAM_LEN)); /* The extended ("username*") notation */ run_case ("adj/username-ext-truncated", "Digest username*=U, realm=\"" TEST_REALM "\""); run_case ("adj/username-ext-no-lang", "Digest username*=UTF-8', realm=\"" TEST_REALM "\""); run_case ("adj/username-ext-empty", "Digest username*=UTF-8'', realm=\"" TEST_REALM "\""); run_case ("adj/username-ext-broken-pct", "Digest username*=UTF-8''%%, realm=\"" TEST_REALM "\""); run_case ("adj/username-ext-broken-pct2", "Digest username*=UTF-8''%%z, realm=\"" TEST_REALM "\""); run_case ("adj/username-ext-broken-pct3", "Digest username*=UTF-8''%%zz, realm=\"" TEST_REALM "\""); run_case ("adj/username-ext-trailing-pct", "Digest username*=UTF-8''abc%%, realm=\"" TEST_REALM "\""); run_case ("adj/username-ext-bad-charset", "Digest username*=ISO-8859-1''abc, realm=\"" TEST_REALM "\""); run_case ("adj/username-ext-quoted", "Digest username*=\"UTF-8''\\abc\", realm=\"" TEST_REALM "\""); run_case ("adj/username-ext-and-plain", "Digest username=\"" TEST_USERNAME "\", " "username*=UTF-8''" TEST_USERNAME ", realm=\"" TEST_REALM "\""); /* The "userhash" handling */ run_case ("adj/userhash-username-too-short", "Digest userhash=true, username=\"abcd\", " "realm=\"" TEST_REALM "\""); run_case ("adj/userhash-username-empty", "Digest userhash=true, username=\"\", " "realm=\"" TEST_REALM "\""); run_case ("adj/userhash-username-too-long", "Digest userhash=true, username=\"%s\", " "realm=\"" TEST_REALM "\"", fill_hex (big, 200)); run_case ("adj/userhash-username-ext", "Digest userhash=true, username*=UTF-8''abc, " "realm=\"" TEST_REALM "\""); run_case ("adj/userhash-no-username", "Digest userhash=true, realm=\"" TEST_REALM "\""); /* The "nc" handling */ run_case ("adj/nc-zero", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "qop=auth, nc=00000000, cnonce=\"abc\""); run_case ("adj/nc-non-hex", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "qop=auth, nc=zzzzzzzz, cnonce=\"abc\""); run_case ("adj/nc-empty", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "qop=auth, nc=, cnonce=\"abc\""); run_case ("adj/nc-overflow", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "qop=auth, nc=ffffffffffffffffffffffff, cnonce=\"abc\""); run_case ("adj/qop-auth-no-nc", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "qop=auth, cnonce=\"abc\""); run_case ("adj/qop-auth-no-cnonce", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "qop=auth, nc=00000001"); run_case ("adj/cnonce-empty", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "qop=auth, nc=00000001, cnonce=\"\""); /* Malformed "nonce" values. These are rejected by the length check before the "nonce"/"nc" map is consulted. */ run_case ("adj/nonce-short", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"deadbeef\", uri=\"" TEST_URL "\", qop=auth, " "nc=00000001, cnonce=\"abc\", response=\"00112233\""); run_case ("adj/nonce-empty", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"\", uri=\"" TEST_URL "\", qop=auth, " "nc=00000001, cnonce=\"abc\", response=\"00112233\""); /* Duplicated parameters */ run_case ("adj/duplicated-username", "Digest username=\"a\", username=\"" TEST_USERNAME "\", " "realm=\"" TEST_REALM "\""); run_case ("adj/duplicated-realm", "Digest username=\"" TEST_USERNAME "\", realm=\"x\", " "realm=\"" TEST_REALM "\""); run_case ("adj/duplicated-userhash", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "userhash=false, userhash=true"); /* The sub-cases below use the SHA-256 algorithm and therefore need the daemon that issues the SHA-256 (76 characters long) nonces. */ test_port = port_sha256; run_case ("adj/nonce-not-generated-by-mhd", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"" TEST_URL "\", algorithm=SHA-256, " "qop=auth, nc=00000001, cnonce=\"abc\", response=\"%s\"", fill_hex (big, 76), resp); need_nonce (nonce, sizeof (nonce)); run_case ("adj/uri-mismatch", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"/other\", algorithm=SHA-256, qop=auth, " "nc=%08x, cnonce=\"abc\", response=\"%s\"", nonce, ++nc_counter, resp); need_nonce (nonce, sizeof (nonce)); run_case ("adj/uri-empty", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"\", algorithm=SHA-256, qop=auth, " "nc=%08x, cnonce=\"abc\", response=\"%s\"", nonce, ++nc_counter, resp); need_nonce (nonce, sizeof (nonce)); run_case ("adj/uri-with-args", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"" TEST_URL "?a=b\", algorithm=SHA-256, " "qop=auth, nc=%08x, cnonce=\"abc\", response=\"%s\"", nonce, ++nc_counter, resp); need_nonce (nonce, sizeof (nonce)); run_case ("adj/duplicated-nonce", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"deadbeef\", nonce=\"%s\", uri=\"" TEST_URL "\", " "algorithm=SHA-256, qop=auth, nc=%08x, cnonce=\"abc\", " "response=\"%s\"", nonce, ++nc_counter, resp); need_nonce (nonce, sizeof (nonce)); run_case ("adj/qop-auth-int", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"" TEST_URL "\", algorithm=SHA-256, " "qop=auth-int, nc=%08x, cnonce=\"abc\", response=\"%s\"", nonce, ++nc_counter, resp); need_nonce (nonce, sizeof (nonce)); run_case ("adj/qop-bogus", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"" TEST_URL "\", algorithm=SHA-256, " "qop=BOGUS, nc=%08x, cnonce=\"abc\", response=\"%s\"", nonce, ++nc_counter, resp); need_nonce (nonce, sizeof (nonce)); run_case ("adj/userhash-64-non-hex", "Digest userhash=true, username=\"%s\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"" TEST_URL "\", algorithm=SHA-256, qop=auth, " "nc=%08x, cnonce=\"abc\", response=\"%s\"", fill_chr (big, 'z', 64), nonce, ++nc_counter, resp); need_nonce (nonce, sizeof (nonce)); run_case ("adj/userhash-128-hex", "Digest userhash=true, username=\"%s\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"" TEST_URL "\", algorithm=SHA-256, qop=auth, " "nc=%08x, cnonce=\"abc\", response=\"%s\"", fill_hex (big, 128), nonce, ++nc_counter, resp); /* An empty "qop" value ("qop=" or "qop=\"\"") is parsed to #MHD_DIGEST_AUTH_QOP_INVALID, whose numeric value is zero, so it used to pass the "allowed QOP" bit-mask test in exactly the same way an unknown "algorithm" token did before commit bd49ce93, and the empty value then reached get_unquoted_param(), which asserts that the value is not empty. Fixed in commit 3b898eae; these two sub-cases are its regression test. */ need_nonce (nonce, sizeof (nonce)); run_case ("adj/qop-empty", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"" TEST_URL "\", algorithm=SHA-256, qop=, " "nc=%08x, cnonce=\"abc\", response=\"%s\"", nonce, ++nc_counter, resp); need_nonce (nonce, sizeof (nonce)); run_case ("adj/qop-empty-quotes", "Digest username=\"" TEST_USERNAME "\", realm=\"" TEST_REALM "\", " "nonce=\"%s\", uri=\"" TEST_URL "\", algorithm=SHA-256, qop=\"\", " "nc=%08x, cnonce=\"abc\", response=\"%s\"", nonce, ++nc_counter, resp); } /** * Start a test daemon. * * @param challenge_algo the pointer to the algorithm used for the challenges * @param[out] pport the pointer to store the port the daemon listens on * @return the daemon */ static struct MHD_Daemon * start_test_daemon (const enum MHD_DigestAuthMultiAlgo3 *challenge_algo, uint16_t *pport) { struct MHD_Daemon *daemon; const union MHD_DaemonInfo *dinfo; struct MHD_OptMatrixProfile prof; struct MHD_OptionItem ops[8]; unsigned int flags; if (NULL != test_prof) prof = *test_prof; else { memset (&prof, 0, sizeof (prof)); prof.name = "built-in"; prof.threading = MHD_OPT_MATRIX_THR_INTERNAL; prof.poll_backend = MHD_OPT_MATRIX_POLL_SELECT; } if (0 == mhd_opt_matrix_fill_options (&prof, ops, (unsigned int) (sizeof (ops) / sizeof (ops[0])))) hard_error ("The daemon option array is too small"); /* The client of this test is a plain blocking socket client, so external polling is served with an internal polling thread instead. */ flags = mhd_opt_matrix_daemon_flags (&prof, MHD_USE_ERROR_LOG, 0); daemon = MHD_start_daemon (flags, 0, NULL, NULL, &ahc_check, (void *) challenge_algo, MHD_OPTION_ARRAY, ops, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 10, MHD_OPTION_NONCE_NC_SIZE, (unsigned int) NONCE_NC_SIZE, MHD_OPTION_END); if (NULL == daemon) hard_error ("MHD_start_daemon() failed"); dinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) { MHD_stop_daemon (daemon); hard_error ("MHD_get_daemon_info() failed"); } *pport = dinfo->port; return daemon; } int main (int argc, char *const *argv) { static const enum MHD_DigestAuthMultiAlgo3 algo_sha256 = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256; static const enum MHD_DigestAuthMultiAlgo3 algo_any = MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION; struct MHD_Daemon *daemon_sha256; struct MHD_Daemon *daemon_any; char nonce[256]; if (1 < argc) case_filter = argv[1]; mhd_opt_matrix_print_notice ("test_dauth_malformed"); test_prof = mhd_opt_matrix_from_env (); if (NULL != test_prof) { char desc[256]; test_prof_copy = *test_prof; test_prof = &test_prof_copy; if (! mhd_opt_matrix_profile_supported (test_prof)) { printf ("test_dauth_malformed: the selected profile %s is not " "supported by this build, the test is skipped.\n", mhd_opt_matrix_describe (test_prof, desc, sizeof (desc))); return 77; } if (mhd_opt_matrix_raise_mem_limit (&test_prof_copy, MIN_POOL_FOR_TEST)) printf ("test_dauth_malformed: the connection memory limit of the " "profile was raised to %u, the smallest pool this test can " "work with.\n", (unsigned) MIN_POOL_FOR_TEST); } daemon_sha256 = start_test_daemon (&algo_sha256, &port_sha256); daemon_any = start_test_daemon (&algo_any, &port_any); test_invalid_algorithm (); test_overlong_response (); test_adjacent (); /* Both daemons must still be alive and functional. */ test_port = port_sha256; if (! get_nonce (nonce, sizeof (nonce))) { fprintf (stderr, "FAILED: the SHA-256 daemon does not respond after the test.\n"); ++failures; } test_port = port_any; if (! get_nonce (nonce, sizeof (nonce))) { fprintf (stderr, "FAILED: the default daemon does not respond after the test.\n"); ++failures; } MHD_stop_daemon (daemon_any); MHD_stop_daemon (daemon_sha256); if (0 != failures) { fprintf (stderr, "Test FAILED: %u of %u sub-cases failed.\n", failures, case_num); return 1; } printf ("Test PASSED: %u sub-cases.\n", case_num); return 0; } #else /* ! DAUTH_SUPPORT || ! MHD_SHA256_SUPPORT */ int main (void) { fprintf (stderr, "Digest Auth or SHA-256 support is not enabled in this MHD build, " "the test is skipped.\n"); return 77; } #endif /* ! DAUTH_SUPPORT || ! MHD_SHA256_SUPPORT */ libmicrohttpd-1.0.10/src/microhttpd/mhd_str.c0000664000175000017500000020037115232103064014667 /* This file is part of libmicrohttpd Copyright (C) 2015-2024 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_str.c * @brief Functions implementations for string manipulating * @author Karlson2k (Evgeny Grin) */ #include "mhd_str.h" #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ #include #include "mhd_assert.h" #include "mhd_check.h" #include "mhd_limits.h" #include "mhd_assert.h" #ifdef MHD_FAVOR_SMALL_CODE #ifdef _MHD_static_inline #undef _MHD_static_inline #endif /* _MHD_static_inline */ /* Do not force inlining and do not use macro functions, use normal static functions instead. This may give more flexibility for size optimizations. */ #define _MHD_static_inline static #ifndef HAVE_INLINE_FUNCS #define HAVE_INLINE_FUNCS 1 #endif /* !INLINE_FUNC */ #endif /* MHD_FAVOR_SMALL_CODE */ /* * Block of functions/macros that use US-ASCII charset as required by HTTP * standards. Not affected by current locale settings. */ #ifdef HAVE_INLINE_FUNCS #if 0 /* Disable unused functions. */ /** * Check whether character is lower case letter in US-ASCII * * @param c character to check * @return non-zero if character is lower case letter, zero otherwise */ _MHD_static_inline bool isasciilower (char c) { return (c >= 'a') && (c <= 'z'); } #endif /* Disable unused functions. */ /** * Check whether character is upper case letter in US-ASCII * * @param c character to check * @return non-zero if character is upper case letter, zero otherwise */ _MHD_static_inline bool isasciiupper (char c) { return (c >= 'A') && (c <= 'Z'); } #if 0 /* Disable unused functions. */ /** * Check whether character is letter in US-ASCII * * @param c character to check * @return non-zero if character is letter in US-ASCII, zero otherwise */ _MHD_static_inline bool isasciialpha (char c) { return isasciilower (c) || isasciiupper (c); } #endif /* Disable unused functions. */ /** * Check whether character is decimal digit in US-ASCII * * @param c character to check * @return non-zero if character is decimal digit, zero otherwise */ _MHD_static_inline bool isasciidigit (char c) { return (c >= '0') && (c <= '9'); } #if 0 /* Disable unused functions. */ /** * Check whether character is hexadecimal digit in US-ASCII * * @param c character to check * @return non-zero if character is decimal digit, zero otherwise */ _MHD_static_inline bool isasciixdigit (char c) { return isasciidigit (c) || ( (c >= 'A') && (c <= 'F') ) || ( (c >= 'a') && (c <= 'f') ); } /** * Check whether character is decimal digit or letter in US-ASCII * * @param c character to check * @return non-zero if character is decimal digit or letter, zero otherwise */ _MHD_static_inline bool isasciialnum (char c) { return isasciialpha (c) || isasciidigit (c); } #endif /* Disable unused functions. */ #if 0 /* Disable unused functions. */ /** * Convert US-ASCII character to lower case. * If character is upper case letter in US-ASCII than it's converted to lower * case analog. If character is NOT upper case letter than it's returned * unmodified. * * @param c character to convert * @return converted to lower case character */ _MHD_static_inline char toasciilower (char c) { return isasciiupper (c) ? (c - 'A' + 'a') : c; } /** * Convert US-ASCII character to upper case. * If character is lower case letter in US-ASCII than it's converted to upper * case analog. If character is NOT lower case letter than it's returned * unmodified. * * @param c character to convert * @return converted to upper case character */ _MHD_static_inline char toasciiupper (char c) { return isasciilower (c) ? (c - 'a' + 'A') : c; } #endif /* Disable unused functions. */ #if defined(MHD_FAVOR_SMALL_CODE) /* Used only in MHD_str_to_uvalue_n_() */ /** * Convert US-ASCII decimal digit to its value. * * @param c character to convert * @return value of decimal digit or -1 if @ c is not decimal digit */ _MHD_static_inline int todigitvalue (char c) { if (isasciidigit (c)) return (unsigned char) (c - '0'); return -1; } #endif /* MHD_FAVOR_SMALL_CODE */ /** * Convert US-ASCII hexadecimal digit to its value. * * @param c character to convert * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit */ _MHD_static_inline int toxdigitvalue (char c) { #if ! defined(MHD_FAVOR_SMALL_CODE) switch ((unsigned char) c) { #if 0 /* Disabled to give the compiler a hint about low probability */ case 0x00U: /* NUL */ case 0x01U: /* SOH */ case 0x02U: /* STX */ case 0x03U: /* ETX */ case 0x04U: /* EOT */ case 0x05U: /* ENQ */ case 0x06U: /* ACK */ case 0x07U: /* BEL */ case 0x08U: /* BS */ case 0x09U: /* HT */ case 0x0AU: /* LF */ case 0x0BU: /* VT */ case 0x0CU: /* FF */ case 0x0DU: /* CR */ case 0x0EU: /* SO */ case 0x0FU: /* SI */ case 0x10U: /* DLE */ case 0x11U: /* DC1 */ case 0x12U: /* DC2 */ case 0x13U: /* DC3 */ case 0x14U: /* DC4 */ case 0x15U: /* NAK */ case 0x16U: /* SYN */ case 0x17U: /* ETB */ case 0x18U: /* CAN */ case 0x19U: /* EM */ case 0x1AU: /* SUB */ case 0x1BU: /* ESC */ case 0x1CU: /* FS */ case 0x1DU: /* GS */ case 0x1EU: /* RS */ case 0x1FU: /* US */ case 0x20U: /* ' ' */ case 0x21U: /* '!' */ case 0x22U: /* '"' */ case 0x23U: /* '#' */ case 0x24U: /* '$' */ case 0x25U: /* '%' */ case 0x26U: /* '&' */ case 0x27U: /* '\'' */ case 0x28U: /* '(' */ case 0x29U: /* ')' */ case 0x2AU: /* '*' */ case 0x2BU: /* '+' */ case 0x2CU: /* ',' */ case 0x2DU: /* '-' */ case 0x2EU: /* '.' */ case 0x2FU: /* '/' */ return -1; #endif case 0x30U: /* '0' */ return 0; case 0x31U: /* '1' */ return 1; case 0x32U: /* '2' */ return 2; case 0x33U: /* '3' */ return 3; case 0x34U: /* '4' */ return 4; case 0x35U: /* '5' */ return 5; case 0x36U: /* '6' */ return 6; case 0x37U: /* '7' */ return 7; case 0x38U: /* '8' */ return 8; case 0x39U: /* '9' */ return 9; #if 0 /* Disabled to give the compiler a hint about low probability */ case 0x3AU: /* ':' */ case 0x3BU: /* ';' */ case 0x3CU: /* '<' */ case 0x3DU: /* '=' */ case 0x3EU: /* '>' */ case 0x3FU: /* '?' */ case 0x40U: /* '@' */ return -1; #endif case 0x41U: /* 'A' */ return 0xAU; case 0x42U: /* 'B' */ return 0xBU; case 0x43U: /* 'C' */ return 0xCU; case 0x44U: /* 'D' */ return 0xDU; case 0x45U: /* 'E' */ return 0xEU; case 0x46U: /* 'F' */ return 0xFU; #if 0 /* Disabled to give the compiler a hint about low probability */ case 0x47U: /* 'G' */ case 0x48U: /* 'H' */ case 0x49U: /* 'I' */ case 0x4AU: /* 'J' */ case 0x4BU: /* 'K' */ case 0x4CU: /* 'L' */ case 0x4DU: /* 'M' */ case 0x4EU: /* 'N' */ case 0x4FU: /* 'O' */ case 0x50U: /* 'P' */ case 0x51U: /* 'Q' */ case 0x52U: /* 'R' */ case 0x53U: /* 'S' */ case 0x54U: /* 'T' */ case 0x55U: /* 'U' */ case 0x56U: /* 'V' */ case 0x57U: /* 'W' */ case 0x58U: /* 'X' */ case 0x59U: /* 'Y' */ case 0x5AU: /* 'Z' */ case 0x5BU: /* '[' */ case 0x5CU: /* '\' */ case 0x5DU: /* ']' */ case 0x5EU: /* '^' */ case 0x5FU: /* '_' */ case 0x60U: /* '`' */ return -1; #endif case 0x61U: /* 'a' */ return 0xAU; case 0x62U: /* 'b' */ return 0xBU; case 0x63U: /* 'c' */ return 0xCU; case 0x64U: /* 'd' */ return 0xDU; case 0x65U: /* 'e' */ return 0xEU; case 0x66U: /* 'f' */ return 0xFU; #if 0 /* Disabled to give the compiler a hint about low probability */ case 0x67U: /* 'g' */ case 0x68U: /* 'h' */ case 0x69U: /* 'i' */ case 0x6AU: /* 'j' */ case 0x6BU: /* 'k' */ case 0x6CU: /* 'l' */ case 0x6DU: /* 'm' */ case 0x6EU: /* 'n' */ case 0x6FU: /* 'o' */ case 0x70U: /* 'p' */ case 0x71U: /* 'q' */ case 0x72U: /* 'r' */ case 0x73U: /* 's' */ case 0x74U: /* 't' */ case 0x75U: /* 'u' */ case 0x76U: /* 'v' */ case 0x77U: /* 'w' */ case 0x78U: /* 'x' */ case 0x79U: /* 'y' */ case 0x7AU: /* 'z' */ case 0x7BU: /* '{' */ case 0x7CU: /* '|' */ case 0x7DU: /* '}' */ case 0x7EU: /* '~' */ case 0x7FU: /* DEL */ case 0x80U: /* EXT */ case 0x81U: /* EXT */ case 0x82U: /* EXT */ case 0x83U: /* EXT */ case 0x84U: /* EXT */ case 0x85U: /* EXT */ case 0x86U: /* EXT */ case 0x87U: /* EXT */ case 0x88U: /* EXT */ case 0x89U: /* EXT */ case 0x8AU: /* EXT */ case 0x8BU: /* EXT */ case 0x8CU: /* EXT */ case 0x8DU: /* EXT */ case 0x8EU: /* EXT */ case 0x8FU: /* EXT */ case 0x90U: /* EXT */ case 0x91U: /* EXT */ case 0x92U: /* EXT */ case 0x93U: /* EXT */ case 0x94U: /* EXT */ case 0x95U: /* EXT */ case 0x96U: /* EXT */ case 0x97U: /* EXT */ case 0x98U: /* EXT */ case 0x99U: /* EXT */ case 0x9AU: /* EXT */ case 0x9BU: /* EXT */ case 0x9CU: /* EXT */ case 0x9DU: /* EXT */ case 0x9EU: /* EXT */ case 0x9FU: /* EXT */ case 0xA0U: /* EXT */ case 0xA1U: /* EXT */ case 0xA2U: /* EXT */ case 0xA3U: /* EXT */ case 0xA4U: /* EXT */ case 0xA5U: /* EXT */ case 0xA6U: /* EXT */ case 0xA7U: /* EXT */ case 0xA8U: /* EXT */ case 0xA9U: /* EXT */ case 0xAAU: /* EXT */ case 0xABU: /* EXT */ case 0xACU: /* EXT */ case 0xADU: /* EXT */ case 0xAEU: /* EXT */ case 0xAFU: /* EXT */ case 0xB0U: /* EXT */ case 0xB1U: /* EXT */ case 0xB2U: /* EXT */ case 0xB3U: /* EXT */ case 0xB4U: /* EXT */ case 0xB5U: /* EXT */ case 0xB6U: /* EXT */ case 0xB7U: /* EXT */ case 0xB8U: /* EXT */ case 0xB9U: /* EXT */ case 0xBAU: /* EXT */ case 0xBBU: /* EXT */ case 0xBCU: /* EXT */ case 0xBDU: /* EXT */ case 0xBEU: /* EXT */ case 0xBFU: /* EXT */ case 0xC0U: /* EXT */ case 0xC1U: /* EXT */ case 0xC2U: /* EXT */ case 0xC3U: /* EXT */ case 0xC4U: /* EXT */ case 0xC5U: /* EXT */ case 0xC6U: /* EXT */ case 0xC7U: /* EXT */ case 0xC8U: /* EXT */ case 0xC9U: /* EXT */ case 0xCAU: /* EXT */ case 0xCBU: /* EXT */ case 0xCCU: /* EXT */ case 0xCDU: /* EXT */ case 0xCEU: /* EXT */ case 0xCFU: /* EXT */ case 0xD0U: /* EXT */ case 0xD1U: /* EXT */ case 0xD2U: /* EXT */ case 0xD3U: /* EXT */ case 0xD4U: /* EXT */ case 0xD5U: /* EXT */ case 0xD6U: /* EXT */ case 0xD7U: /* EXT */ case 0xD8U: /* EXT */ case 0xD9U: /* EXT */ case 0xDAU: /* EXT */ case 0xDBU: /* EXT */ case 0xDCU: /* EXT */ case 0xDDU: /* EXT */ case 0xDEU: /* EXT */ case 0xDFU: /* EXT */ case 0xE0U: /* EXT */ case 0xE1U: /* EXT */ case 0xE2U: /* EXT */ case 0xE3U: /* EXT */ case 0xE4U: /* EXT */ case 0xE5U: /* EXT */ case 0xE6U: /* EXT */ case 0xE7U: /* EXT */ case 0xE8U: /* EXT */ case 0xE9U: /* EXT */ case 0xEAU: /* EXT */ case 0xEBU: /* EXT */ case 0xECU: /* EXT */ case 0xEDU: /* EXT */ case 0xEEU: /* EXT */ case 0xEFU: /* EXT */ case 0xF0U: /* EXT */ case 0xF1U: /* EXT */ case 0xF2U: /* EXT */ case 0xF3U: /* EXT */ case 0xF4U: /* EXT */ case 0xF5U: /* EXT */ case 0xF6U: /* EXT */ case 0xF7U: /* EXT */ case 0xF8U: /* EXT */ case 0xF9U: /* EXT */ case 0xFAU: /* EXT */ case 0xFBU: /* EXT */ case 0xFCU: /* EXT */ case 0xFDU: /* EXT */ case 0xFEU: /* EXT */ case 0xFFU: /* EXT */ return -1; default: mhd_assert (0); break; /* Should be unreachable */ #else default: break; #endif } return -1; #else /* MHD_FAVOR_SMALL_CODE */ if (isasciidigit (c)) return (unsigned char) (c - '0'); if ( (c >= 'A') && (c <= 'F') ) return (unsigned char) (c - 'A' + 10); if ( (c >= 'a') && (c <= 'f') ) return (unsigned char) (c - 'a' + 10); return -1; #endif /* MHD_FAVOR_SMALL_CODE */ } /** * Caseless compare two characters. * * @param c1 the first char to compare * @param c2 the second char to compare * @return boolean 'true' if chars are caseless equal, false otherwise */ _MHD_static_inline bool charsequalcaseless (const char c1, const char c2) { return ( (c1 == c2) || (isasciiupper (c1) ? ((c1 - 'A' + 'a') == c2) : ((c1 == (c2 - 'A' + 'a')) && isasciiupper (c2))) ); } #else /* !INLINE_FUNC */ /** * Checks whether character is lower case letter in US-ASCII * * @param c character to check * @return boolean true if character is lower case letter, * boolean false otherwise */ #define isasciilower(c) (((char) (c)) >= 'a' && ((char) (c)) <= 'z') /** * Checks whether character is upper case letter in US-ASCII * * @param c character to check * @return boolean true if character is upper case letter, * boolean false otherwise */ #define isasciiupper(c) (((char) (c)) >= 'A' && ((char) (c)) <= 'Z') /** * Checks whether character is letter in US-ASCII * * @param c character to check * @return boolean true if character is letter, boolean false * otherwise */ #define isasciialpha(c) (isasciilower (c) || isasciiupper (c)) /** * Check whether character is decimal digit in US-ASCII * * @param c character to check * @return boolean true if character is decimal digit, boolean false * otherwise */ #define isasciidigit(c) (((char) (c)) >= '0' && ((char) (c)) <= '9') /** * Check whether character is hexadecimal digit in US-ASCII * * @param c character to check * @return boolean true if character is hexadecimal digit, * boolean false otherwise */ #define isasciixdigit(c) (isasciidigit ((c)) || \ (((char) (c)) >= 'A' && ((char) (c)) <= 'F') || \ (((char) (c)) >= 'a' && ((char) (c)) <= 'f') ) /** * Check whether character is decimal digit or letter in US-ASCII * * @param c character to check * @return boolean true if character is decimal digit or letter, * boolean false otherwise */ #define isasciialnum(c) (isasciialpha (c) || isasciidigit (c)) /** * Convert US-ASCII character to lower case. * If character is upper case letter in US-ASCII than it's converted to lower * case analog. If character is NOT upper case letter than it's returned * unmodified. * * @param c character to convert * @return converted to lower case character */ #define toasciilower(c) ((isasciiupper (c)) ? (((char) (c)) - 'A' + 'a') : \ ((char) (c))) /** * Convert US-ASCII character to upper case. * If character is lower case letter in US-ASCII than it's converted to upper * case analog. If character is NOT lower case letter than it's returned * unmodified. * * @param c character to convert * @return converted to upper case character */ #define toasciiupper(c) ((isasciilower (c)) ? (((char) (c)) - 'a' + 'A') : \ ((char) (c))) /** * Convert US-ASCII decimal digit to its value. * * @param c character to convert * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit */ #define todigitvalue(c) (isasciidigit (c) ? (int) (((char) (c)) - '0') : \ (int) (-1)) /** * Convert US-ASCII hexadecimal digit to its value. * @param c character to convert * @return value of hexadecimal digit or -1 if @ c is not hexadecimal digit */ #define toxdigitvalue(c) (isasciidigit (c) ? (int) (((char) (c)) - '0') : \ ( (((char) (c)) >= 'A' && ((char) (c)) <= 'F') ? \ (int) (((unsigned char) (c)) - 'A' + 10) : \ ( (((char) (c)) >= 'a' && ((char) (c)) <= 'f') ? \ (int) (((unsigned char) (c)) - 'a' + 10) : \ (int) (-1) ))) /** * Caseless compare two characters. * * @param c1 the first char to compare * @param c2 the second char to compare * @return boolean 'true' if chars are caseless equal, false otherwise */ #define charsequalcaseless(c1, c2) \ ( ((c1) == (c2)) || \ (isasciiupper (c1) ? \ (((c1) - 'A' + 'a') == (c2)) : \ (((c1) == ((c2) - 'A' + 'a')) && isasciiupper (c2))) ) #endif /* !HAVE_INLINE_FUNCS */ #ifndef MHD_FAVOR_SMALL_CODE /** * Check two strings for equality, ignoring case of US-ASCII letters. * * @param str1 first string to compare * @param str2 second string to compare * @return non-zero if two strings are equal, zero otherwise. */ int MHD_str_equal_caseless_ (const char *str1, const char *str2) { while (0 != (*str1)) { const char c1 = *str1; const char c2 = *str2; if (charsequalcaseless (c1, c2)) { str1++; str2++; } else return 0; } return 0 == (*str2); } #endif /* ! MHD_FAVOR_SMALL_CODE */ /** * Check two string for equality, ignoring case of US-ASCII letters and * checking not more than @a maxlen characters. * Compares up to first terminating null character, but not more than * first @a maxlen characters. * * @param str1 first string to compare * @param str2 second string to compare * @param maxlen maximum number of characters to compare * @return non-zero if two strings are equal, zero otherwise. */ int MHD_str_equal_caseless_n_ (const char *const str1, const char *const str2, size_t maxlen) { size_t i; for (i = 0; i < maxlen; ++i) { const char c1 = str1[i]; const char c2 = str2[i]; if (0 == c2) return 0 == c1; if (charsequalcaseless (c1, c2)) continue; else return 0; } return ! 0; } /** * Check two string for equality, ignoring case of US-ASCII letters and * checking not more than @a len bytes. * Compares not more first than @a len bytes, including binary zero characters. * Comparison stops at first unmatched byte. * @param str1 first string to compare * @param str2 second string to compare * @param len number of characters to compare * @return non-zero if @a len bytes are equal, zero otherwise. */ bool MHD_str_equal_caseless_bin_n_ (const char *const str1, const char *const str2, size_t len) { size_t i; for (i = 0; i < len; ++i) { const char c1 = str1[i]; const char c2 = str2[i]; if (charsequalcaseless (c1, c2)) continue; else return 0; } return ! 0; } /** * Check whether @a str has case-insensitive @a token. * Token could be surrounded by spaces and tabs and delimited by comma. * Match succeed if substring between start, end (of string) or comma * contains only case-insensitive token and optional spaces and tabs. * @warning token must not contain null-characters except optional * terminating null-character. * @param str the string to check * @param token the token to find * @param token_len length of token, not including optional terminating * null-character. * @return non-zero if two strings are equal, zero otherwise. */ bool MHD_str_has_token_caseless_ (const char *str, const char *const token, size_t token_len) { if (0 == token_len) return false; while (0 != *str) { size_t i; /* Skip all whitespaces and empty tokens. */ while (' ' == *str || '\t' == *str || ',' == *str) str++; /* Check for token match. */ i = 0; while (1) { const char sc = *(str++); const char tc = token[i++]; if (0 == sc) return false; if (! charsequalcaseless (sc, tc)) break; if (i >= token_len) { /* Check whether substring match token fully or * has additional unmatched chars at tail. */ while (' ' == *str || '\t' == *str) str++; /* End of (sub)string? */ if ((0 == *str) || (',' == *str) ) return true; /* Unmatched chars at end of substring. */ break; } } /* Find next substring. */ while (0 != *str && ',' != *str) str++; } return false; } /** * Remove case-insensitive @a token from the @a str and put result * to the output @a buf. * * Tokens in @a str could be surrounded by spaces and tabs and delimited by * comma. The token match succeed if substring between start, end (of string) * or comma contains only case-insensitive token and optional spaces and tabs. * The quoted strings and comments are not supported by this function. * * The output string is normalised: empty tokens and repeated whitespaces * are removed, no whitespaces before commas, exactly one space is used after * each comma. * * @param str the string to process * @param str_len the length of the @a str, not including optional * terminating null-character. * @param token the token to find * @param token_len the length of @a token, not including optional * terminating null-character. * @param[out] buf the output buffer, not null-terminated. * @param[in,out] buf_size pointer to the size variable, at input it * is the size of allocated buffer, at output * it is the size of the resulting string (can * be up to 50% larger than input) or negative value * if there is not enough space for the result * @return 'true' if token has been removed, * 'false' otherwise. */ bool MHD_str_remove_token_caseless_ (const char *str, size_t str_len, const char *const token, const size_t token_len, char *buf, ssize_t *buf_size) { const char *s1; /**< the "input" string / character */ char *s2; /**< the "output" string / character */ size_t t_pos; /**< position of matched character in the token */ bool token_removed; mhd_assert (NULL == memchr (token, 0, token_len)); mhd_assert (NULL == memchr (token, ' ', token_len)); mhd_assert (NULL == memchr (token, '\t', token_len)); mhd_assert (NULL == memchr (token, ',', token_len)); mhd_assert (0 <= *buf_size); if ((str_len / 2) >= (((size_t) SSIZE_MAX - 1) / 3)) { /* The return value may overflow, refuse */ *buf_size = (ssize_t) -1; return false; } s1 = str; s2 = buf; token_removed = false; while ((size_t) (s1 - str) < str_len) { const char *cur_token; /**< the first char of current token */ size_t copy_size; /* Skip any initial whitespaces and empty tokens */ while ( ((size_t) (s1 - str) < str_len) && ((' ' == *s1) || ('\t' == *s1) || (',' == *s1)) ) s1++; /* 's1' points to the first char of token in the input string or * points just beyond the end of the input string */ if ((size_t) (s1 - str) >= str_len) break; /* Nothing to copy, end of the input string */ /* 's1' points to the first char of token in the input string */ cur_token = s1; /* the first char of input token */ /* Check the token with case-insensitive match */ t_pos = 0; while ( ((size_t) (s1 - str) < str_len) && (token_len > t_pos) && (charsequalcaseless (*s1, token[t_pos])) ) { s1++; t_pos++; } /* s1 may point just beyond the end of the input string */ if ( (token_len == t_pos) && (0 != token_len) ) { /* 'token' matched, check that current input token does not have * any suffixes */ while ( ((size_t) (s1 - str) < str_len) && ((' ' == *s1) || ('\t' == *s1)) ) s1++; /* 's1' points to the first non-whitespace char after the token matched * requested token or points just beyond the end of the input string after * the requested token */ if (((size_t) (s1 - str) == str_len) || (',' == *s1)) {/* full token match, do not copy current token to the output */ token_removed = true; continue; } } /* 's1' points to first non-whitespace char, to some char after * first non-whitespace char in the token in the input string, to * the ',', or just beyond the end of the input string */ /* The current token in the input string does not match the token * to exclude, it must be copied to the output string */ /* the current token size excluding leading whitespaces and current char */ copy_size = (size_t) (s1 - cur_token); if (buf == s2) { /* The first token to copy to the output */ if ((size_t) *buf_size < copy_size) { /* Not enough space in the output buffer */ *buf_size = (ssize_t) -1; return false; } } else { /* Some token was already copied to the output buffer */ mhd_assert (s2 > buf); if ((size_t) *buf_size < ((size_t) (s2 - buf)) + copy_size + 2) { /* Not enough space in the output buffer */ *buf_size = (ssize_t) -1; return false; } *(s2++) = ','; *(s2++) = ' '; } /* Copy non-matched token to the output */ if (0 != copy_size) { memcpy (s2, cur_token, copy_size); s2 += copy_size; } while ( ((size_t) (s1 - str) < str_len) && (',' != *s1)) { /* 's1' points to first non-whitespace char, to some char after * first non-whitespace char in the token in the input string */ /* Copy all non-whitespace chars from the current token in * the input string */ while ( ((size_t) (s1 - str) < str_len) && (',' != *s1) && (' ' != *s1) && ('\t' != *s1) ) { mhd_assert (s2 >= buf); if ((size_t) *buf_size <= (size_t) (s2 - buf)) /* '<= s2' equals '< s2 + 1' */ { /* Not enough space in the output buffer */ *buf_size = (ssize_t) -1; return false; } *(s2++) = *(s1++); } /* 's1' points to some whitespace char in the token in the input * string, to the ',', or just beyond the end of the input string */ /* Skip all whitespaces */ while ( ((size_t) (s1 - str) < str_len) && ((' ' == *s1) || ('\t' == *s1)) ) s1++; /* 's1' points to the first non-whitespace char in the input string * after whitespace chars, to the ',', or just beyond the end of * the input string */ if (((size_t) (s1 - str) < str_len) && (',' != *s1)) { /* Not the end of the current token */ mhd_assert (s2 >= buf); if ((size_t) *buf_size <= (size_t) (s2 - buf)) /* '<= s2' equals '< s2 + 1' */ { /* Not enough space in the output buffer */ *buf_size = (ssize_t) -1; return false; } *(s2++) = ' '; } } } mhd_assert (((ssize_t) (s2 - buf)) <= *buf_size); *buf_size = (ssize_t) (s2 - buf); return token_removed; } /** * Perform in-place case-insensitive removal of @a tokens from the @a str. * * Token could be surrounded by spaces and tabs and delimited by comma. * The token match succeed if substring between start, end (of the string), or * comma contains only case-insensitive token and optional spaces and tabs. * The quoted strings and comments are not supported by this function. * * The input string must be normalised: empty tokens and repeated whitespaces * are removed, no whitespaces before commas, exactly one space is used after * each comma. The string is updated in-place. * * Behavior is undefined is the input string in not normalised. * * @param[in,out] str the string to update * @param[in,out] str_len the length of the @a str, not including optional * terminating null-character, not null-terminated * @param tokens the token to find * @param tokens_len the length of @a tokens, not including optional * terminating null-character. * @return 'true' if any token has been removed, * 'false' otherwise. */ bool MHD_str_remove_tokens_caseless_ (char *str, size_t *str_len, const char *const tokens, const size_t tokens_len) { const char *const t = tokens; /**< a short alias for @a tokens */ size_t pt; /**< position in @a tokens */ bool token_removed; mhd_assert (NULL == memchr (tokens, 0, tokens_len)); token_removed = false; pt = 0; while (pt < tokens_len && *str_len != 0) { const char *tkn; /**< the current token */ size_t tkn_len; /* Skip any initial whitespaces and empty tokens in 'tokens' */ while ( (pt < tokens_len) && ((' ' == t[pt]) || ('\t' == t[pt]) || (',' == t[pt])) ) pt++; if (pt >= tokens_len) break; /* No more tokens, nothing to remove */ /* Found non-whitespace char which is not a comma */ tkn = t + pt; do { do { pt++; } while (pt < tokens_len && (' ' != t[pt] && '\t' != t[pt] && ',' != t[pt])); /* Found end of the token string, space, tab, or comma */ tkn_len = pt - (size_t) (tkn - t); /* Skip all spaces and tabs */ while (pt < tokens_len && (' ' == t[pt] || '\t' == t[pt])) pt++; /* Found end of the token string or non-whitespace char */ } while (pt < tokens_len && ',' != t[pt]); /* 'tkn' is the input token with 'tkn_len' chars */ mhd_assert (0 != tkn_len); if (*str_len == tkn_len) { if (MHD_str_equal_caseless_bin_n_ (str, tkn, tkn_len)) { *str_len = 0; token_removed = true; } continue; } /* 'tkn' cannot match part of 'str' if length of 'tkn' is larger * than length of 'str'. * It's know that 'tkn' is not equal to the 'str' (was checked previously). * As 'str' is normalized when 'tkn' is not equal to the 'str' * it is required that 'str' to be at least 3 chars larger then 'tkn' * (the comma, the space and at least one additional character for the next * token) to remove 'tkn' from the 'str'. */ if (*str_len > tkn_len + 2) { /* Remove 'tkn' from the input string */ size_t pr; /**< the 'read' position in the @a str */ size_t pw; /**< the 'write' position in the @a str */ pr = 0; pw = 0; do { mhd_assert (pr >= pw); mhd_assert ((*str_len) >= (pr + tkn_len)); if ( ( ((*str_len) == (pr + tkn_len)) || (',' == str[pr + tkn_len]) ) && MHD_str_equal_caseless_bin_n_ (str + pr, tkn, tkn_len) ) { /* current token in the input string matches the 'tkn', skip it */ mhd_assert ((*str_len == pr + tkn_len) || \ (' ' == str[pr + tkn_len + 1])); /* 'str' must be normalized */ token_removed = true; /* Advance to the next token in the input string or beyond * the end of the input string. */ pr += tkn_len + 2; } else { /* current token in the input string does not match the 'tkn', * copy to the output */ if (0 != pw) { /* not the first output token, add ", " to separate */ if (pr != pw + 2) { str[pw++] = ','; str[pw++] = ' '; } else pw += 2; /* 'str' is not yet modified in this round */ } do { if (pr != pw) str[pw] = str[pr]; pr++; pw++; } while (pr < *str_len && ',' != str[pr]); /* Advance to the next token in the input string or beyond * the end of the input string. */ pr += 2; } /* 'pr' should point to the next token in the input string or beyond * the end of the input string */ if ((*str_len) < (pr + tkn_len)) { /* The rest of the 'str + pr' is too small to match 'tkn' */ if ((*str_len) > pr) { /* Copy the rest of the string */ size_t copy_size; copy_size = *str_len - pr; if (0 != pw) { /* not the first output token, add ", " to separate */ if (pr != pw + 2) { str[pw++] = ','; str[pw++] = ' '; } else pw += 2; /* 'str' is not yet modified in this round */ } if (pr != pw) memmove (str + pw, str + pr, copy_size); pw += copy_size; } *str_len = pw; break; } mhd_assert ((' ' != str[0]) && ('\t' != str[0])); mhd_assert ((0 == pr) || (3 <= pr)); mhd_assert ((0 == pr) || (' ' == str[pr - 1])); mhd_assert ((0 == pr) || (',' == str[pr - 2])); } while (1); } } return token_removed; } #ifndef MHD_FAVOR_SMALL_CODE /* Use individual function for each case */ /** * Convert decimal US-ASCII digits in string to number in uint64_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_str_to_uint64_ (const char *str, uint64_t *out_val) { const char *const start = str; uint64_t res; if (! str || ! out_val || ! isasciidigit (str[0])) return 0; res = 0; do { const int digit = (unsigned char) (*str) - '0'; if ( (res > (UINT64_MAX / 10)) || ( (res == (UINT64_MAX / 10)) && ((uint64_t) digit > (UINT64_MAX % 10)) ) ) return 0; res *= 10; res += (unsigned int) digit; str++; } while (isasciidigit (*str)); *out_val = res; return (size_t) (str - start); } /** * Convert not more then @a maxlen decimal US-ASCII digits in string to * number in uint64_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_str_to_uint64_n_ (const char *str, size_t maxlen, uint64_t *out_val) { uint64_t res; size_t i; if (! str || ! maxlen || ! out_val || ! isasciidigit (str[0])) return 0; res = 0; i = 0; do { const int digit = (unsigned char) str[i] - '0'; if ( (res > (UINT64_MAX / 10)) || ( (res == (UINT64_MAX / 10)) && ((uint64_t) digit > (UINT64_MAX % 10)) ) ) return 0; res *= 10; res += (unsigned int) digit; i++; } while ( (i < maxlen) && isasciidigit (str[i]) ); *out_val = res; return i; } /** * Convert hexadecimal US-ASCII digits in string to number in uint32_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint32_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint32_t or @a out_val is NULL */ size_t MHD_strx_to_uint32_ (const char *str, uint32_t *out_val) { const char *const start = str; uint32_t res; int digit; if (! str || ! out_val) return 0; res = 0; digit = toxdigitvalue (*str); while (digit >= 0) { if ( (res < (UINT32_MAX / 16)) || ((res == (UINT32_MAX / 16)) && ( (uint32_t) digit <= (UINT32_MAX % 16)) ) ) { res *= 16; res += (unsigned int) digit; } else return 0; str++; digit = toxdigitvalue (*str); } if (str - start > 0) *out_val = res; return (size_t) (str - start); } /** * Convert not more then @a maxlen hexadecimal US-ASCII digits in string * to number in uint32_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint32_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint32_t or @a out_val is NULL */ size_t MHD_strx_to_uint32_n_ (const char *str, size_t maxlen, uint32_t *out_val) { size_t i; uint32_t res; int digit; if (! str || ! out_val) return 0; res = 0; i = 0; while (i < maxlen && (digit = toxdigitvalue (str[i])) >= 0) { if ( (res > (UINT32_MAX / 16)) || ((res == (UINT32_MAX / 16)) && ( (uint32_t) digit > (UINT32_MAX % 16)) ) ) return 0; res *= 16; res += (unsigned int) digit; i++; } if (i) *out_val = res; return i; } /** * Convert hexadecimal US-ASCII digits in string to number in uint64_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_strx_to_uint64_ (const char *str, uint64_t *out_val) { const char *const start = str; uint64_t res; int digit; if (! str || ! out_val) return 0; res = 0; digit = toxdigitvalue (*str); while (digit >= 0) { if ( (res < (UINT64_MAX / 16)) || ((res == (UINT64_MAX / 16)) && ( (uint64_t) digit <= (UINT64_MAX % 16)) ) ) { res *= 16; res += (unsigned int) digit; } else return 0; str++; digit = toxdigitvalue (*str); } if (str - start > 0) *out_val = res; return (size_t) (str - start); } /** * Convert not more then @a maxlen hexadecimal US-ASCII digits in string * to number in uint64_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_strx_to_uint64_n_ (const char *str, size_t maxlen, uint64_t *out_val) { size_t i; uint64_t res; int digit; if (! str || ! out_val) return 0; res = 0; i = 0; while (i < maxlen && (digit = toxdigitvalue (str[i])) >= 0) { if ( (res > (UINT64_MAX / 16)) || ((res == (UINT64_MAX / 16)) && ( (uint64_t) digit > (UINT64_MAX % 16)) ) ) return 0; res *= 16; res += (unsigned int) digit; i++; } if (i) *out_val = res; return i; } #else /* MHD_FAVOR_SMALL_CODE */ /** * Generic function for converting not more then @a maxlen * hexadecimal or decimal US-ASCII digits in string to number. * Conversion stopped at first non-digit character or after @a maxlen * digits. * To be used only within macro. * * @param str the string to convert * @param maxlen the maximum number of characters to process * @param out_val the pointer to variable to store result of conversion * @param val_size the size of variable pointed by @a out_val, in bytes, 4 or 8 * @param max_val the maximum decoded number * @param base the numeric base, 10 or 16 * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then @a max_val, @a val_size is not 4/8 or @a out_val is NULL */ size_t MHD_str_to_uvalue_n_ (const char *str, size_t maxlen, void *out_val, size_t val_size, uint64_t max_val, unsigned int base) { size_t i; uint64_t res; const uint64_t max_v_div_b = max_val / base; const uint64_t max_v_mod_b = max_val % base; if (! str || ! out_val || ((base != 16) && (base != 10)) ) return 0; res = 0; i = 0; while (maxlen > i) { const int digit = (base == 16) ? toxdigitvalue (str[i]) : todigitvalue (str[i]); if (0 > digit) break; if ( ((max_v_div_b) < res) || (( (max_v_div_b) == res) && ( (max_v_mod_b) < (uint64_t) digit) ) ) return 0; res *= base; res += (unsigned int) digit; i++; } if (i) { if (8 == val_size) *(uint64_t *) out_val = res; else if (4 == val_size) *(uint32_t *) out_val = (uint32_t) res; else return 0; } return i; } #endif /* MHD_FAVOR_SMALL_CODE */ size_t MHD_uint32_to_strx (uint32_t val, char *buf, size_t buf_size) { size_t o_pos = 0; /**< position of the output character */ int digit_pos = 8; /** zero-based, digit position in @a 'val' */ int digit; /* Skip leading zeros */ do { digit_pos--; digit = (int) (val >> 28); val <<= 4; } while ((0 == digit) && (0 != digit_pos)); while (o_pos < buf_size) { buf[o_pos++] = (char) ((digit <= 9) ? ('0' + (char) digit) : ('A' + (char) digit - 10)); if (0 == digit_pos) return o_pos; digit_pos--; digit = (int) (val >> 28); val <<= 4; } return 0; /* The buffer is too small */ } #ifndef MHD_FAVOR_SMALL_CODE size_t MHD_uint16_to_str (uint16_t val, char *buf, size_t buf_size) { char *chr; /**< pointer to the current printed digit */ /* The biggest printable number is 65535 */ uint16_t divisor = UINT16_C (10000); int digit; chr = buf; digit = (int) (val / divisor); mhd_assert (digit < 10); /* Do not print leading zeros */ while ((0 == digit) && (1 < divisor)) { divisor /= 10; digit = (int) (val / divisor); mhd_assert (digit < 10); } while (0 != buf_size) { *chr = (char) ((char) digit + '0'); chr++; buf_size--; if (1 == divisor) return (size_t) (chr - buf); val = (uint16_t) (val % divisor); divisor /= 10; digit = (int) (val / divisor); mhd_assert (digit < 10); } return 0; /* The buffer is too small */ } #endif /* !MHD_FAVOR_SMALL_CODE */ size_t MHD_uint64_to_str (uint64_t val, char *buf, size_t buf_size) { char *chr; /**< pointer to the current printed digit */ /* The biggest printable number is 18446744073709551615 */ uint64_t divisor = UINT64_C (10000000000000000000); int digit; chr = buf; digit = (int) (val / divisor); mhd_assert (digit < 10); /* Do not print leading zeros */ while ((0 == digit) && (1 < divisor)) { divisor /= 10; digit = (int) (val / divisor); mhd_assert (digit < 10); } while (0 != buf_size) { *chr = (char) ((char) digit + '0'); chr++; buf_size--; if (1 == divisor) return (size_t) (chr - buf); val %= divisor; divisor /= 10; digit = (int) (val / divisor); mhd_assert (digit < 10); } return 0; /* The buffer is too small */ } size_t MHD_uint8_to_str_pad (uint8_t val, uint8_t min_digits, char *buf, size_t buf_size) { size_t pos; /**< the position of the current printed digit */ int digit; mhd_assert (3 >= min_digits); if (0 == buf_size) return 0; pos = 0; digit = val / 100; if (0 == digit) { if (3 <= min_digits) buf[pos++] = '0'; } else { buf[pos++] = (char) ('0' + (char) digit); val %= 100; min_digits = 2; } if (buf_size <= pos) return 0; digit = val / 10; if (0 == digit) { if (2 <= min_digits) buf[pos++] = '0'; } else { buf[pos++] = (char) ('0' + (char) digit); val %= 10; } if (buf_size <= pos) return 0; buf[pos++] = (char) ('0' + (char) val); return pos; } size_t MHD_bin_to_hex (const void *bin, size_t size, char *hex) { size_t i; for (i = 0; i < size; ++i) { uint8_t j; const uint8_t b = ((const uint8_t *) bin)[i]; j = b >> 4; hex[i * 2] = (char) ((j < 10) ? (j + '0') : (j - 10 + 'a')); j = b & 0x0f; hex[i * 2 + 1] = (char) ((j < 10) ? (j + '0') : (j - 10 + 'a')); } return i * 2; } size_t MHD_bin_to_hex_z (const void *bin, size_t size, char *hex) { size_t res; res = MHD_bin_to_hex (bin, size, hex); hex[res] = 0; return res; } size_t MHD_hex_to_bin (const char *hex, size_t len, void *bin) { uint8_t *const out = (uint8_t *) bin; size_t r; size_t w; if (0 == len) return 0; r = 0; w = 0; if (0 != len % 2) { /* Assume the first byte is encoded with single digit */ const char c2 = hex[r++]; const int l = toxdigitvalue (c2); if (0 > l) return 0; out[w++] = (uint8_t) ((unsigned int) l); } while (r < len) { const char c1 = hex[r++]; const char c2 = hex[r++]; const int h = toxdigitvalue (c1); const int l = toxdigitvalue (c2); if ((0 > h) || (0 > l)) return 0; out[w++] = (uint8_t) ( ((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l)) ); } mhd_assert (len == r); mhd_assert ((len + 1) / 2 == w); return w; } size_t MHD_str_pct_decode_strict_n_ (const char *pct_encoded, size_t pct_encoded_len, char *decoded, size_t buf_size) { #ifdef MHD_FAVOR_SMALL_CODE bool broken; size_t res; res = MHD_str_pct_decode_lenient_n_ (pct_encoded, pct_encoded_len, decoded, buf_size, &broken); if (broken) return 0; return res; #else /* ! MHD_FAVOR_SMALL_CODE */ size_t r; size_t w; r = 0; w = 0; if (buf_size >= pct_encoded_len) { while (r < pct_encoded_len) { const char chr = pct_encoded[r]; if ('%' == chr) { if (3 > pct_encoded_len - r) return 0; { const char c1 = pct_encoded[++r]; const char c2 = pct_encoded[++r]; const int h = toxdigitvalue (c1); const int l = toxdigitvalue (c2); unsigned char out; if ((0 > h) || (0 > l)) return 0; out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); decoded[w] = (char) out; } } else decoded[w] = chr; ++r; ++w; } return w; } while (r < pct_encoded_len) { const char chr = pct_encoded[r]; if (w >= buf_size) return 0; if ('%' == chr) { if (3 > pct_encoded_len - r) return 0; { const char c1 = pct_encoded[++r]; const char c2 = pct_encoded[++r]; const int h = toxdigitvalue (c1); const int l = toxdigitvalue (c2); unsigned char out; if ((0 > h) || (0 > l)) return 0; out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); decoded[w] = (char) out; } } else decoded[w] = chr; ++r; ++w; } return w; #endif /* ! MHD_FAVOR_SMALL_CODE */ } size_t MHD_str_pct_decode_lenient_n_ (const char *pct_encoded, size_t pct_encoded_len, char *decoded, size_t buf_size, bool *broken_encoding) { size_t r; size_t w; r = 0; w = 0; if (NULL != broken_encoding) *broken_encoding = false; #ifndef MHD_FAVOR_SMALL_CODE if (buf_size >= pct_encoded_len) { while (r < pct_encoded_len) { const char chr = pct_encoded[r]; if ('%' == chr) { if (3 > pct_encoded_len - r) { if (NULL != broken_encoding) *broken_encoding = true; decoded[w] = chr; /* Copy "as is" */ } else { const char c1 = pct_encoded[++r]; const char c2 = pct_encoded[++r]; const int h = toxdigitvalue (c1); const int l = toxdigitvalue (c2); unsigned char out; if ((0 > h) || (0 > l)) { r -= 2; if (NULL != broken_encoding) *broken_encoding = true; decoded[w] = chr; /* Copy "as is" */ } else { out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); decoded[w] = (char) out; } } } else decoded[w] = chr; ++r; ++w; } return w; } #endif /* ! MHD_FAVOR_SMALL_CODE */ while (r < pct_encoded_len) { const char chr = pct_encoded[r]; if (w >= buf_size) return 0; if ('%' == chr) { if (3 > pct_encoded_len - r) { if (NULL != broken_encoding) *broken_encoding = true; decoded[w] = chr; /* Copy "as is" */ } else { const char c1 = pct_encoded[++r]; const char c2 = pct_encoded[++r]; const int h = toxdigitvalue (c1); const int l = toxdigitvalue (c2); if ((0 > h) || (0 > l)) { r -= 2; if (NULL != broken_encoding) *broken_encoding = true; decoded[w] = chr; /* Copy "as is" */ } else { unsigned char out; out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); decoded[w] = (char) out; } } } else decoded[w] = chr; ++r; ++w; } return w; } size_t MHD_str_pct_decode_in_place_strict_ (char *str) { #ifdef MHD_FAVOR_SMALL_CODE size_t res; bool broken; res = MHD_str_pct_decode_in_place_lenient_ (str, &broken); if (broken) { res = 0; str[0] = 0; } return res; #else /* ! MHD_FAVOR_SMALL_CODE */ size_t r; size_t w; r = 0; w = 0; while (0 != str[r]) { const char chr = str[r++]; if ('%' == chr) { const char d1 = str[r++]; if (0 == d1) return 0; else { const char d2 = str[r++]; if (0 == d2) return 0; else { const int h = toxdigitvalue (d1); const int l = toxdigitvalue (d2); unsigned char out; if ((0 > h) || (0 > l)) return 0; out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); str[w++] = (char) out; } } } else str[w++] = chr; } str[w] = 0; return w; #endif /* ! MHD_FAVOR_SMALL_CODE */ } size_t MHD_str_pct_decode_in_place_lenient_ (char *str, bool *broken_encoding) { #ifdef MHD_FAVOR_SMALL_CODE size_t len; size_t res; len = strlen (str); res = MHD_str_pct_decode_lenient_n_ (str, len, str, len, broken_encoding); str[res] = 0; return res; #else /* ! MHD_FAVOR_SMALL_CODE */ size_t r; size_t w; if (NULL != broken_encoding) *broken_encoding = false; r = 0; w = 0; while (0 != str[r]) { const char chr = str[r++]; if ('%' == chr) { const char d1 = str[r++]; if (0 == d1) { if (NULL != broken_encoding) *broken_encoding = true; str[w++] = chr; /* Copy "as is" */ str[w] = 0; return w; } else { const char d2 = str[r++]; if (0 == d2) { if (NULL != broken_encoding) *broken_encoding = true; str[w++] = chr; /* Copy "as is" */ str[w++] = d1; /* Copy "as is" */ str[w] = 0; return w; } else { const int h = toxdigitvalue (d1); const int l = toxdigitvalue (d2); unsigned char out; if ((0 > h) || (0 > l)) { if (NULL != broken_encoding) *broken_encoding = true; str[w++] = chr; /* Copy "as is" */ str[w++] = d1; str[w++] = d2; continue; } out = (unsigned char) (((uint8_t) (((uint8_t) ((unsigned int) h)) << 4)) | ((uint8_t) ((unsigned int) l))); str[w++] = (char) out; continue; } } } str[w++] = chr; } str[w] = 0; return w; #endif /* ! MHD_FAVOR_SMALL_CODE */ } #ifdef DAUTH_SUPPORT bool MHD_str_equal_quoted_bin_n (const char *quoted, size_t quoted_len, const char *unquoted, size_t unquoted_len) { size_t i; size_t j; if (unquoted_len < quoted_len / 2) return false; j = 0; for (i = 0; quoted_len > i && unquoted_len > j; ++i, ++j) { if ('\\' == quoted[i]) { i++; /* Advance to the next character */ if (quoted_len == i) return false; /* No character after escaping backslash */ } if (quoted[i] != unquoted[j]) return false; /* Different characters */ } if ((quoted_len != i) || (unquoted_len != j)) return false; /* The strings have different length */ return true; } bool MHD_str_equal_caseless_quoted_bin_n (const char *quoted, size_t quoted_len, const char *unquoted, size_t unquoted_len) { size_t i; size_t j; if (unquoted_len < quoted_len / 2) return false; j = 0; for (i = 0; quoted_len > i && unquoted_len > j; ++i, ++j) { if ('\\' == quoted[i]) { i++; /* Advance to the next character */ if (quoted_len == i) return false; /* No character after escaping backslash */ } if (! charsequalcaseless (quoted[i], unquoted[j])) return false; /* Different characters */ } if ((quoted_len != i) || (unquoted_len != j)) return false; /* The strings have different length */ return true; } size_t MHD_str_unquote (const char *quoted, size_t quoted_len, char *result) { size_t r; size_t w; r = 0; w = 0; while (quoted_len > r) { if ('\\' == quoted[r]) { ++r; if (quoted_len == r) return 0; /* Last backslash is not followed by char to unescape */ } result[w++] = quoted[r++]; } return w; } #endif /* DAUTH_SUPPORT */ #if defined(DAUTH_SUPPORT) || defined(BAUTH_SUPPORT) size_t MHD_str_quote (const char *unquoted, size_t unquoted_len, char *result, size_t buf_size) { size_t r; size_t w; r = 0; w = 0; #ifndef MHD_FAVOR_SMALL_CODE if (unquoted_len * 2 <= buf_size) { /* Fast loop: the output will fit the buffer with any input string content */ while (unquoted_len > r) { const char chr = unquoted[r++]; if (('\\' == chr) || ('\"' == chr)) result[w++] = '\\'; /* Escape current char */ result[w++] = chr; } } else { if (unquoted_len > buf_size) return 0; /* Quick fail: the output buffer is too small */ #else /* MHD_FAVOR_SMALL_CODE */ if (1) { #endif /* MHD_FAVOR_SMALL_CODE */ while (unquoted_len > r) { if (buf_size <= w) return 0; /* The output buffer is too small */ else { const char chr = unquoted[r++]; if (('\\' == chr) || ('\"' == chr)) { result[w++] = '\\'; /* Escape current char */ if (buf_size <= w) return 0; /* The output buffer is too small */ } result[w++] = chr; } } } mhd_assert (w >= r); mhd_assert (w <= r * 2); return w; } #endif /* DAUTH_SUPPORT || BAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT /* * MHD_BASE64_FUNC_VERSION * 1 = smallest, * 2 = medium, * 3 = fastest */ #ifndef MHD_BASE64_FUNC_VERSION #ifdef MHD_FAVOR_SMALL_CODE #define MHD_BASE64_FUNC_VERSION 1 #else /* ! MHD_FAVOR_SMALL_CODE */ #define MHD_BASE64_FUNC_VERSION 3 #endif /* ! MHD_FAVOR_SMALL_CODE */ #endif /* ! MHD_BASE64_FUNC_VERSION */ #if MHD_BASE64_FUNC_VERSION < 1 || MHD_BASE64_FUNC_VERSION > 3 #error Wrong MHD_BASE64_FUNC_VERSION value #endif /* MHD_BASE64_FUNC_VERSION < 1 || MHD_BASE64_FUNC_VERSION > 3 */ #if MHD_BASE64_FUNC_VERSION == 3 #define MHD_base64_map_type_ int #else /* MHD_BASE64_FUNC_VERSION < 3 */ #define MHD_base64_map_type_ int8_t #endif /* MHD_BASE64_FUNC_VERSION < 3 */ #if MHD_BASE64_FUNC_VERSION == 1 static MHD_base64_map_type_ base64_char_to_value_ (uint8_t c) { if ('Z' >= c) { if ('A' <= c) return (MHD_base64_map_type_) ((c - 'A') + 0); if ('0' <= c) { if ('9' >= c) return (MHD_base64_map_type_) ((c - '0') + 52); if ('=' == c) return -2; return -1; } if ('+' == c) return 62; if ('/' == c) return 63; return -1; } if (('z' >= c) && ('a' <= c)) return (MHD_base64_map_type_) ((c - 'a') + 26); return -1; } #endif /* MHD_BASE64_FUNC_VERSION == 1 */ MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ size_t MHD_base64_to_bin_n (const char *base64, size_t base64_len, void *bin, size_t bin_size) { #if MHD_BASE64_FUNC_VERSION >= 2 static const MHD_base64_map_type_ map[] = { /* -1 = invalid char, -2 = padding 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, NUL, SOH, STX, ETX, EOT, ENQ, ACK, BEL, */ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, BS, HT, LF, VT, FF, CR, SO, SI, */ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB, */ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, CAN, EM, SUB, ESC, FS, GS, RS, US, */ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, ' ', '!', '"', '#', '$', '%', '&', '\'', */ -1, -1, -1, -1, -1, -1, -1, -1, /* 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, '(', ')', '*', '+', ',', '-', '.', '/', */ -1, -1, -1, 62, -1, -1, -1, 63, /* 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, '0', '1', '2', '3', '4', '5', '6', '7', */ 52, 53, 54, 55, 56, 57, 58, 59, /* 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, '8', '9', ':', ';', '<', '=', '>', '?', */ 60, 61, -1, -1, -1, -2, -1, -1, /* 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', */ -1, 0, 1, 2, 3, 4, 5, 6, /* 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', */ 7, 8, 9, 10, 11, 12, 13, 14, /* 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', */ 15, 16, 17, 18, 19, 20, 21, 22, /* 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 'X', 'Y', 'Z', '[', '\', ']', '^', '_', */ 23, 24, 25, -1, -1, -1, -1, -1, /* 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', */ -1, 26, 27, 28, 29, 30, 31, 32, /* 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', */ 33, 34, 35, 36, 37, 38, 39, 40, /* 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', */ 41, 42, 43, 44, 45, 46, 47, 48, /* 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 'x', 'y', 'z', '{', '|', '}', '~', DEL, */ 49, 50, 51, -1, -1, -1, -1, -1 #if MHD_BASE64_FUNC_VERSION == 3 , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 80..8F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 90..9F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* A0..AF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* B0..BF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* C0..CF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* D0..DF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* E0..EF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* F0..FF */ #endif /* ! MHD_BASE64_FUNC_VERSION == 3 */ }; #define base64_char_to_value_(c) map[(c)] #endif /* MHD_BASE64_FUNC_VERSION >= 2 */ const uint8_t *const in = (const uint8_t *) base64; uint8_t *const out = (uint8_t *) bin; size_t i; size_t j; if (0 == base64_len) return 0; /* Nothing to decode */ if (0 != base64_len % 4) return 0; /* Wrong input length */ if (base64_len / 4 * 3 - 2 > bin_size) return 0; j = 0; for (i = 0; i < (base64_len - 4); i += 4) { #if MHD_BASE64_FUNC_VERSION == 2 if (0 != (0x80 & (in[i] | in[i + 1] | in[i + 2] | in[i + 3]))) return 0; #endif /* MHD_BASE64_FUNC_VERSION == 2 */ if (1) { const MHD_base64_map_type_ v1 = base64_char_to_value_ (in[i + 0]); const MHD_base64_map_type_ v2 = base64_char_to_value_ (in[i + 1]); const MHD_base64_map_type_ v3 = base64_char_to_value_ (in[i + 2]); const MHD_base64_map_type_ v4 = base64_char_to_value_ (in[i + 3]); if ((0 > v1) || (0 > v2) || (0 > v3) || (0 > v4)) return 0; out[j + 0] = (uint8_t) (((uint8_t) (((uint8_t) v1) << 2)) | ((uint8_t) (((uint8_t) v2) >> 4))); out[j + 1] = (uint8_t) (((uint8_t) (((uint8_t) v2) << 4)) | ((uint8_t) (((uint8_t) v3) >> 2))); out[j + 2] = (uint8_t) (((uint8_t) (((uint8_t) v3) << 6)) | ((uint8_t) v4)); } j += 3; } #if MHD_BASE64_FUNC_VERSION == 2 if (0 != (0x80 & (in[i] | in[i + 1] | in[i + 2] | in[i + 3]))) return 0; #endif /* MHD_BASE64_FUNC_VERSION == 2 */ if (1) { /* The last four chars block */ const MHD_base64_map_type_ v1 = base64_char_to_value_ (in[i + 0]); const MHD_base64_map_type_ v2 = base64_char_to_value_ (in[i + 1]); const MHD_base64_map_type_ v3 = base64_char_to_value_ (in[i + 2]); const MHD_base64_map_type_ v4 = base64_char_to_value_ (in[i + 3]); if ((0 > v1) || (0 > v2)) return 0; /* Invalid char or padding at first two positions */ MHD_CHECK_RET_ (j < bin_size, 0); out[j++] = (uint8_t) (((uint8_t) (((uint8_t) v1) << 2)) | ((uint8_t) (((uint8_t) v2) >> 4))); if (0 > v3) { /* Third char is either padding or invalid */ if ((-2 != v3) || (-2 != v4)) return 0; /* Both two last chars must be padding */ if (0 != (uint8_t) (((uint8_t) v2) << 4)) return 0; /* Wrong last char */ return j; } if (j >= bin_size) return 0; /* Not enough space */ out[j++] = (uint8_t) (((uint8_t) (((uint8_t) v2) << 4)) | ((uint8_t) (((uint8_t) v3) >> 2))); if (0 > v4) { /* Fourth char is either padding or invalid */ if (-2 != v4) return 0; /* The char must be padding */ if (0 != (uint8_t) (((uint8_t) v3) << 6)) return 0; /* Wrong last char */ return j; } if (j >= bin_size) return 0; /* Not enough space */ out[j++] = (uint8_t) (((uint8_t) (((uint8_t) v3) << 6)) | ((uint8_t) v4)); } return j; #if MHD_BASE64_FUNC_VERSION >= 2 #undef base64_char_to_value_ #endif /* MHD_BASE64_FUNC_VERSION >= 2 */ } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ #undef MHD_base64_map_type_ #endif /* BAUTH_SUPPORT */ libmicrohttpd-1.0.10/src/microhttpd/mhd_send.c0000644000175000017500000015225415035214301015012 /* This file is part of libmicrohttpd Copyright (C) 2017-2023 Karlson2k (Evgeny Grin), Full re-write of buffering and pushing, many bugs fixes, optimisations, sendfile() porting Copyright (C) 2019 ng0 , Initial version of send() wrappers This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_send.c * @brief Implementation of send() wrappers and helper functions. * @author Karlson2k (Evgeny Grin) * @author ng0 (N. Gillmann) * @author Christian Grothoff */ /* Worth considering for future improvements and additions: * NetBSD has no sendfile or sendfile64. The way to work * with this seems to be to mmap the file and write(2) as * large a chunk as possible to the socket. Alternatively, * use madvise(..., MADV_SEQUENTIAL). */ #include "mhd_send.h" #ifdef MHD_LINUX_SOLARIS_SENDFILE #include #endif /* MHD_LINUX_SOLARIS_SENDFILE */ #if defined(HAVE_FREEBSD_SENDFILE) || defined(HAVE_DARWIN_SENDFILE) #include #include #include #endif /* HAVE_FREEBSD_SENDFILE || HAVE_DARWIN_SENDFILE */ #ifdef HAVE_SYS_PARAM_H /* For FreeBSD version identification */ #include #endif /* HAVE_SYS_PARAM_H */ #ifdef HAVE_SYSCONF #include #endif /* HAVE_SYSCONF */ #include "mhd_assert.h" #include "mhd_limits.h" #ifdef MHD_VECT_SEND #if (! defined(HAVE_SENDMSG) || ! defined(MSG_NOSIGNAL)) && \ defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) && \ defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) #define _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED 1 #endif /* (!HAVE_SENDMSG || !MSG_NOSIGNAL) && MHD_SEND_SPIPE_SUPPRESS_POSSIBLE && MHD_SEND_SPIPE_SUPPRESS_NEEDED */ #endif /* MHD_VECT_SEND */ /** * sendfile() chuck size */ #define MHD_SENFILE_CHUNK_ (0x20000) /** * sendfile() chuck size for thread-per-connection */ #define MHD_SENFILE_CHUNK_THR_P_C_ (0x200000) #ifdef HAVE_FREEBSD_SENDFILE #ifdef SF_FLAGS /** * FreeBSD sendfile() flags */ static int freebsd_sendfile_flags_; /** * FreeBSD sendfile() flags for thread-per-connection */ static int freebsd_sendfile_flags_thd_p_c_; /** * Initialises variables for FreeBSD's sendfile() */ static void freebsd_sendfile_init_ (void) { long sys_page_size = sysconf (_SC_PAGESIZE); if (0 >= sys_page_size) { /* Failed to get page size. */ freebsd_sendfile_flags_ = SF_NODISKIO; freebsd_sendfile_flags_thd_p_c_ = SF_NODISKIO; } else { freebsd_sendfile_flags_ = SF_FLAGS ((uint16_t) ((MHD_SENFILE_CHUNK_ + sys_page_size - 1) / sys_page_size), SF_NODISKIO); freebsd_sendfile_flags_thd_p_c_ = SF_FLAGS ((uint16_t) ((MHD_SENFILE_CHUNK_THR_P_C_ + sys_page_size - 1) / sys_page_size), SF_NODISKIO); } } #endif /* SF_FLAGS */ #endif /* HAVE_FREEBSD_SENDFILE */ #if defined(HAVE_SYSCONF) && defined(_SC_IOV_MAX) /** * Current IOV_MAX system value */ static unsigned long mhd_iov_max_ = 0; static void iov_max_init_ (void) { long res = sysconf (_SC_IOV_MAX); if (res >= 0) mhd_iov_max_ = (unsigned long) res; else { #if defined(IOV_MAX) mhd_iov_max_ = IOV_MAX; #else /* ! IOV_MAX */ mhd_iov_max_ = 8; /* Should be the safe limit */ #endif /* ! IOV_MAX */ } } /** * IOV_MAX (run-time) value */ #define _MHD_IOV_MAX mhd_iov_max_ #elif defined(IOV_MAX) /** * IOV_MAX (static) value */ #define _MHD_IOV_MAX IOV_MAX #endif /* HAVE_SYSCONF && _SC_IOV_MAX */ /** * Initialises static variables */ void MHD_send_init_static_vars_ (void) { #ifdef HAVE_FREEBSD_SENDFILE /* FreeBSD 11 and later allow to specify read-ahead size * and handles SF_NODISKIO differently. * SF_FLAGS defined only on FreeBSD 11 and later. */ #ifdef SF_FLAGS freebsd_sendfile_init_ (); #endif /* SF_FLAGS */ #endif /* HAVE_FREEBSD_SENDFILE */ #if defined(HAVE_SYSCONF) && defined(_SC_IOV_MAX) iov_max_init_ (); #endif /* HAVE_SYSCONF && _SC_IOV_MAX */ } bool MHD_connection_set_nodelay_state_ (struct MHD_Connection *connection, bool nodelay_state) { #ifdef TCP_NODELAY const MHD_SCKT_OPT_BOOL_ off_val = 0; const MHD_SCKT_OPT_BOOL_ on_val = 1; int err_code; if (_MHD_YES == connection->is_nonip) return false; if (0 == setsockopt (connection->socket_fd, IPPROTO_TCP, TCP_NODELAY, (const void *) (nodelay_state ? &on_val : &off_val), sizeof (off_val))) { connection->sk_nodelay = nodelay_state; return true; } err_code = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_EINVAL_) || MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOPROTOOPT_) || MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOTSOCK_)) { if (_MHD_UNKNOWN == connection->is_nonip) connection->is_nonip = _MHD_YES; #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Setting %s option to %s state failed " "for TCP/IP socket %d: %s\n"), "TCP_NODELAY", nodelay_state ? _ ("ON") : _ ("OFF"), (int) connection->socket_fd, MHD_socket_strerr_ (err_code)); } #endif /* HAVE_MESSAGES */ } #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Setting %s option to %s state failed: %s\n"), "TCP_NODELAY", nodelay_state ? _ ("ON") : _ ("OFF"), MHD_socket_strerr_ (err_code)); } #endif /* HAVE_MESSAGES */ #else /* ! TCP_NODELAY */ (void) connection; (void) nodelay_state; /* Mute compiler warnings */ #endif /* ! TCP_NODELAY */ return false; } /** * Set required cork state for connection socket * * The function automatically updates sk_corked state. * * @param connection the connection to manipulate * @param cork_state the requested new state of socket * @return true if succeed, false if failed or not supported * by the current platform / kernel. */ bool MHD_connection_set_cork_state_ (struct MHD_Connection *connection, bool cork_state) { #if defined(MHD_TCP_CORK_NOPUSH) const MHD_SCKT_OPT_BOOL_ off_val = 0; const MHD_SCKT_OPT_BOOL_ on_val = 1; int err_code; if (_MHD_YES == connection->is_nonip) return false; if (0 == setsockopt (connection->socket_fd, IPPROTO_TCP, MHD_TCP_CORK_NOPUSH, (const void *) (cork_state ? &on_val : &off_val), sizeof (off_val))) { connection->sk_corked = cork_state; return true; } err_code = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_EINVAL_) || MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOPROTOOPT_) || MHD_SCKT_ERR_IS_ (err_code, MHD_SCKT_ENOTSOCK_)) { if (_MHD_UNKNOWN == connection->is_nonip) connection->is_nonip = _MHD_YES; #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Setting %s option to %s state failed " "for TCP/IP socket %d: %s\n"), #ifdef TCP_CORK "TCP_CORK", #else /* ! TCP_CORK */ "TCP_NOPUSH", #endif /* ! TCP_CORK */ cork_state ? _ ("ON") : _ ("OFF"), (int) connection->socket_fd, MHD_socket_strerr_ (err_code)); } #endif /* HAVE_MESSAGES */ } #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Setting %s option to %s state failed: %s\n"), #ifdef TCP_CORK "TCP_CORK", #else /* ! TCP_CORK */ "TCP_NOPUSH", #endif /* ! TCP_CORK */ cork_state ? _ ("ON") : _ ("OFF"), MHD_socket_strerr_ (err_code)); } #endif /* HAVE_MESSAGES */ #else /* ! MHD_TCP_CORK_NOPUSH */ (void) connection; (void) cork_state; /* Mute compiler warnings. */ #endif /* ! MHD_TCP_CORK_NOPUSH */ return false; } /** * Handle pre-send setsockopt calls. * * @param connection the MHD_Connection structure * @param plain_send set to true if plain send() or sendmsg() will be called, * set to false if TLS socket send(), sendfile() or * writev() will be called. * @param push_data whether to push data to the network from buffers after * the next call of send function. */ static void pre_send_setopt (struct MHD_Connection *connection, bool plain_send, bool push_data) { /* Try to buffer data if not sending the final piece. * Final piece is indicated by push_data == true. */ const bool buffer_data = (! push_data); if (_MHD_YES == connection->is_nonip) return; /* The goal is to minimise the total number of additional sys-calls * before and after send(). * The following tricky (over-)complicated algorithm typically use zero, * one or two additional sys-calls (depending on OS) for each response. */ if (buffer_data) { /* Need to buffer data if possible. */ #ifdef MHD_USE_MSG_MORE if (plain_send) return; /* Data is buffered by send() with MSG_MORE flag. * No need to check or change anything. */ #else /* ! MHD_USE_MSG_MORE */ (void) plain_send; /* Mute compiler warning. */ #endif /* ! MHD_USE_MSG_MORE */ #ifdef MHD_TCP_CORK_NOPUSH if (_MHD_ON == connection->sk_corked) return; /* The connection was already corked. */ if (MHD_connection_set_cork_state_ (connection, true)) return; /* The connection has been corked. */ /* Failed to cork the connection. * Really unlikely to happen on TCP connections. */ #endif /* MHD_TCP_CORK_NOPUSH */ if (_MHD_OFF == connection->sk_nodelay) return; /* TCP_NODELAY was not set for the socket. * Nagle's algorithm will buffer some data. */ /* Try to reset TCP_NODELAY state for the socket. * Ignore possible error as no other options exist to * buffer data. */ MHD_connection_set_nodelay_state_ (connection, false); /* TCP_NODELAY has been (hopefully) reset for the socket. * Nagle's algorithm will buffer some data. */ return; } /* Need to push data after send() */ /* If additional sys-call is required prefer to make it after the send() * as the next send() may consume only part of the prepared data and * more send() calls will be used. */ #ifdef MHD_TCP_CORK_NOPUSH #ifdef _MHD_CORK_RESET_PUSH_DATA #ifdef _MHD_CORK_RESET_PUSH_DATA_ALWAYS /* Data can be pushed immediately by uncorking socket regardless of * cork state before. */ /* This is typical for Linux, no other kernel with * such behavior are known so far. */ /* No need to check the current state of TCP_CORK / TCP_NOPUSH * as reset of cork will push the data anyway. */ return; /* Data may be pushed by resetting of * TCP_CORK / TCP_NOPUSH after send() */ #else /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */ /* Reset of TCP_CORK / TCP_NOPUSH will push the data * only if socket is corked. */ #ifdef _MHD_NODELAY_SET_PUSH_DATA_ALWAYS /* Data can be pushed immediately by setting TCP_NODELAY regardless * of TCP_NODDELAY or corking state before. */ /* Dead code currently, no known kernels with such behavior. */ return; /* Data may be pushed by setting of TCP_NODELAY after send(). No need to make extra sys-calls before send().*/ #else /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */ #ifdef _MHD_NODELAY_SET_PUSH_DATA /* Setting of TCP_NODELAY will push the data only if * both TCP_NODELAY and TCP_CORK / TCP_NOPUSH were not set. */ /* Data can be pushed immediately by uncorking socket if * socket was corked before or by setting TCP_NODELAY if * socket was not corked and TCP_NODELAY was not set before. */ /* Dead code currently as Linux is the only kernel that push * data by setting of TCP_NODELAY and Linux push data always. */ #else /* ! _MHD_NODELAY_SET_PUSH_DATA */ /* Data can be pushed immediately by uncorking socket or * can be pushed by send() on uncorked socket if * TCP_NODELAY was set *before*. */ /* This is typical FreeBSD behavior. */ #endif /* ! _MHD_NODELAY_SET_PUSH_DATA */ if (_MHD_ON == connection->sk_corked) return; /* Socket is corked. Data can be pushed by resetting of * TCP_CORK / TCP_NOPUSH after send() */ else if (_MHD_OFF == connection->sk_corked) { /* The socket is not corked. */ if (_MHD_ON == connection->sk_nodelay) return; /* TCP_NODELAY was already set, * data will be pushed automatically by the next send() */ #ifdef _MHD_NODELAY_SET_PUSH_DATA else if (_MHD_UNKNOWN == connection->sk_nodelay) { /* Setting TCP_NODELAY may push data. * Cork socket here and uncork after send(). */ if (MHD_connection_set_cork_state_ (connection, true)) return; /* The connection has been corked. * Data can be pushed by resetting of * TCP_CORK / TCP_NOPUSH after send() */ else { /* The socket cannot be corked. * Really unlikely to happen on TCP connections */ /* Have to set TCP_NODELAY. * If TCP_NODELAY real system state was OFF then * already buffered data may be pushed here, but this is unlikely * to happen as it is only a backup solution when corking has failed. * Ignore possible error here as no other options exist to * push data. */ MHD_connection_set_nodelay_state_ (connection, true); /* TCP_NODELAY has been (hopefully) set for the socket. * The data will be pushed by the next send(). */ return; } } #endif /* _MHD_NODELAY_SET_PUSH_DATA */ else { #ifdef _MHD_NODELAY_SET_PUSH_DATA /* TCP_NODELAY was switched off and * the socket is not corked. */ #else /* ! _MHD_NODELAY_SET_PUSH_DATA */ /* Socket is not corked and TCP_NODELAY was not set or unknown. */ #endif /* ! _MHD_NODELAY_SET_PUSH_DATA */ /* At least one additional sys-call is required. */ /* Setting TCP_NODELAY is optimal here as data will be pushed * automatically by the next send() and no additional * sys-call are needed after the send(). */ if (MHD_connection_set_nodelay_state_ (connection, true)) return; else { /* Failed to set TCP_NODELAY for the socket. * Really unlikely to happen on TCP connections. */ /* Cork the socket here and make additional sys-call * to uncork the socket after send(). */ /* Ignore possible error here as no other options exist to * push data. */ MHD_connection_set_cork_state_ (connection, true); /* The connection has been (hopefully) corked. * Data can be pushed by resetting of TCP_CORK / TCP_NOPUSH * after send() */ return; } } } /* Corked state is unknown. Need to make sys-call here otherwise * data may not be pushed. */ if (MHD_connection_set_cork_state_ (connection, true)) return; /* The connection has been corked. * Data can be pushed by resetting of * TCP_CORK / TCP_NOPUSH after send() */ /* The socket cannot be corked. * Really unlikely to happen on TCP connections */ if (_MHD_ON == connection->sk_nodelay) return; /* TCP_NODELAY was already set, * data will be pushed by the next send() */ /* Have to set TCP_NODELAY. */ #ifdef _MHD_NODELAY_SET_PUSH_DATA /* If TCP_NODELAY state was unknown (external connection) then * already buffered data may be pushed here, but this is unlikely * to happen as it is only a backup solution when corking has failed. */ #endif /* _MHD_NODELAY_SET_PUSH_DATA */ /* Ignore possible error here as no other options exist to * push data. */ MHD_connection_set_nodelay_state_ (connection, true); /* TCP_NODELAY has been (hopefully) set for the socket. * The data will be pushed by the next send(). */ return; #endif /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */ #endif /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */ #else /* ! _MHD_CORK_RESET_PUSH_DATA */ /* Neither uncorking the socket or setting TCP_NODELAY * push the data immediately. */ /* The only way to push the data is to use send() on uncorked * socket with TCP_NODELAY switched on . */ /* This is a typical *BSD (except FreeBSD) and Darwin behavior. */ /* Uncork socket if socket wasn't uncorked. */ if (_MHD_OFF != connection->sk_corked) MHD_connection_set_cork_state_ (connection, false); /* Set TCP_NODELAY if it wasn't set. */ if (_MHD_ON != connection->sk_nodelay) MHD_connection_set_nodelay_state_ (connection, true); return; #endif /* ! _MHD_CORK_RESET_PUSH_DATA */ #else /* ! MHD_TCP_CORK_NOPUSH */ /* Buffering of data is controlled only by * Nagel's algorithm. */ /* Set TCP_NODELAY if it wasn't set. */ if (_MHD_ON != connection->sk_nodelay) MHD_connection_set_nodelay_state_ (connection, true); #endif /* ! MHD_TCP_CORK_NOPUSH */ } #ifndef _MHD_CORK_RESET_PUSH_DATA_ALWAYS /** * Send zero-sized data * * This function use send of zero-sized data to kick data from the socket * buffers to the network. The socket must not be corked and must have * TCP_NODELAY switched on. * Used only as last resort option, when other options are failed due to * some errors. * Should not be called on typical data processing. * @return true if succeed, false if failed */ static bool zero_send_ (struct MHD_Connection *connection) { int dummy; if (_MHD_YES == connection->is_nonip) return false; mhd_assert (_MHD_OFF == connection->sk_corked); mhd_assert (_MHD_ON == connection->sk_nodelay); dummy = 0; /* Mute compiler and analyzer warnings */ if (0 == MHD_send_ (connection->socket_fd, &dummy, 0)) return true; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Zero-send failed: %s\n"), MHD_socket_last_strerr_ () ); #endif /* HAVE_MESSAGES */ return false; } #endif /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */ /** * Handle post-send setsockopt calls. * * @param connection the MHD_Connection structure * @param plain_send_next set to true if plain send() or sendmsg() will be * called next, * set to false if TLS socket send(), sendfile() or * writev() will be called next. * @param push_data whether to push data to the network from buffers */ static void post_send_setopt (struct MHD_Connection *connection, bool plain_send_next, bool push_data) { /* Try to buffer data if not sending the final piece. * Final piece is indicated by push_data == true. */ const bool buffer_data = (! push_data); if (_MHD_YES == connection->is_nonip) return; if (buffer_data) return; /* Nothing to do after send(). */ #ifndef MHD_USE_MSG_MORE (void) plain_send_next; /* Mute compiler warning */ #endif /* ! MHD_USE_MSG_MORE */ /* Need to push data. */ #ifdef MHD_TCP_CORK_NOPUSH #ifdef _MHD_CORK_RESET_PUSH_DATA_ALWAYS #ifdef _MHD_NODELAY_SET_PUSH_DATA_ALWAYS #ifdef MHD_USE_MSG_MORE if (_MHD_OFF == connection->sk_corked) { if (_MHD_ON == connection->sk_nodelay) return; /* Data was already pushed by send(). */ } /* This is Linux kernel. There are options: * * Push the data by setting of TCP_NODELAY (without change * of the cork on the socket), * * Push the data by resetting of TCP_CORK. * The optimal choice depends on the next final send functions * used on the same socket. If TCP_NODELAY wasn't set then push * data by setting TCP_NODELAY (TCP_NODELAY will not be removed * and is needed to push the data by send() without MSG_MORE). * If send()/sendmsg() will be used next than push data by * resetting of TCP_CORK so next send without MSG_MORE will push * data to the network (without additional sys-call to push data). * If next final send function will not support MSG_MORE (like * sendfile() or TLS-connection) than push data by setting * TCP_NODELAY so socket will remain corked (no additional * sys-call before next send()). */ if ((_MHD_ON != connection->sk_nodelay) || (! plain_send_next)) { if (MHD_connection_set_nodelay_state_ (connection, true)) return; /* Data has been pushed by TCP_NODELAY. */ /* Failed to set TCP_NODELAY for the socket. * Really unlikely to happen on TCP connections. */ if (MHD_connection_set_cork_state_ (connection, false)) return; /* Data has been pushed by uncorking the socket. */ /* Failed to uncork the socket. * Really unlikely to happen on TCP connections. */ /* The socket cannot be uncorked, no way to push data */ } else { if (MHD_connection_set_cork_state_ (connection, false)) return; /* Data has been pushed by uncorking the socket. */ /* Failed to uncork the socket. * Really unlikely to happen on TCP connections. */ if (MHD_connection_set_nodelay_state_ (connection, true)) return; /* Data has been pushed by TCP_NODELAY. */ /* Failed to set TCP_NODELAY for the socket. * Really unlikely to happen on TCP connections. */ /* The socket cannot be uncorked, no way to push data */ } #else /* ! MHD_USE_MSG_MORE */ /* Use setting of TCP_NODELAY here to avoid sys-call * for corking the socket during sending of the next response. */ if (MHD_connection_set_nodelay_state_ (connection, true)) return; /* Data was pushed by TCP_NODELAY. */ /* Failed to set TCP_NODELAY for the socket. * Really unlikely to happen on TCP connections. */ if (MHD_connection_set_cork_state_ (connection, false)) return; /* Data was pushed by uncorking the socket. */ /* Failed to uncork the socket. * Really unlikely to happen on TCP connections. */ /* The socket remains corked, no way to push data */ #endif /* ! MHD_USE_MSG_MORE */ #else /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */ if (MHD_connection_set_cork_state_ (connection, false)) return; /* Data was pushed by uncorking the socket. */ /* Failed to uncork the socket. * Really unlikely to happen on TCP connections. */ return; /* Socket remains corked, no way to push data */ #endif /* ! _MHD_NODELAY_SET_PUSH_DATA_ALWAYS */ #else /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */ /* This is a typical *BSD or Darwin kernel. */ if (_MHD_OFF == connection->sk_corked) { if (_MHD_ON == connection->sk_nodelay) return; /* Data was already pushed by send(). */ /* Unlikely to reach this code. * TCP_NODELAY should be turned on before send(). */ if (MHD_connection_set_nodelay_state_ (connection, true)) { /* TCP_NODELAY has been set on uncorked socket. * Use zero-send to push the data. */ if (zero_send_ (connection)) return; /* The data has been pushed by zero-send. */ } /* Failed to push the data by all means. */ /* There is nothing left to try. */ } else { #ifdef _MHD_CORK_RESET_PUSH_DATA enum MHD_tristate old_cork_state = connection->sk_corked; #endif /* _MHD_CORK_RESET_PUSH_DATA */ /* The socket is corked or cork state is unknown. */ if (MHD_connection_set_cork_state_ (connection, false)) { #ifdef _MHD_CORK_RESET_PUSH_DATA /* FreeBSD kernel */ if (_MHD_OFF == old_cork_state) return; /* Data has been pushed by uncorking the socket. */ #endif /* _MHD_CORK_RESET_PUSH_DATA */ /* Unlikely to reach this code. * The data should be pushed by uncorking (FreeBSD) or * the socket should be uncorked before send(). */ if ((_MHD_ON == connection->sk_nodelay) || (MHD_connection_set_nodelay_state_ (connection, true))) { /* TCP_NODELAY is turned ON on uncorked socket. * Use zero-send to push the data. */ if (zero_send_ (connection)) return; /* The data has been pushed by zero-send. */ } } /* The socket remains corked. Data cannot be pushed. */ } #endif /* ! _MHD_CORK_RESET_PUSH_DATA_ALWAYS */ #else /* ! MHD_TCP_CORK_NOPUSH */ /* Corking is not supported. Buffering is controlled * by TCP_NODELAY only. */ mhd_assert (_MHD_ON != connection->sk_corked); if (_MHD_ON == connection->sk_nodelay) return; /* Data was already pushed by send(). */ /* Unlikely to reach this code. * TCP_NODELAY should be turned on before send(). */ if (MHD_connection_set_nodelay_state_ (connection, true)) { /* TCP_NODELAY has been set. * Use zero-send to push the data. */ if (zero_send_ (connection)) return; /* The data has been pushed by zero-send. */ } /* Failed to push the data. */ #endif /* ! MHD_TCP_CORK_NOPUSH */ #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to push the data from buffers to the network. " "Client may experience some delay " "(usually in range 200ms - 5 sec).\n")); #endif /* HAVE_MESSAGES */ return; } ssize_t MHD_send_data_ (struct MHD_Connection *connection, const char *buffer, size_t buffer_size, bool push_data) { MHD_socket s = connection->socket_fd; ssize_t ret; #ifdef HTTPS_SUPPORT const bool tls_conn = (connection->daemon->options & MHD_USE_TLS); #else /* ! HTTPS_SUPPORT */ const bool tls_conn = false; #endif /* ! HTTPS_SUPPORT */ if ( (MHD_INVALID_SOCKET == s) || (MHD_CONNECTION_CLOSED == connection->state) ) { return MHD_ERR_NOTCONN_; } if (buffer_size > SSIZE_MAX) { buffer_size = SSIZE_MAX; /* Max return value */ push_data = false; /* Incomplete send */ } if (tls_conn) { #ifdef HTTPS_SUPPORT pre_send_setopt (connection, (! tls_conn), push_data); ret = gnutls_record_send (connection->tls_session, buffer, buffer_size); if (GNUTLS_E_AGAIN == ret) { #ifdef EPOLL_SUPPORT connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif return MHD_ERR_AGAIN_; } if (GNUTLS_E_INTERRUPTED == ret) return MHD_ERR_AGAIN_; if ( (GNUTLS_E_ENCRYPTION_FAILED == ret) || (GNUTLS_E_INVALID_SESSION == ret) || (GNUTLS_E_COMPRESSION_FAILED == ret) || (GNUTLS_E_EXPIRED == ret) || (GNUTLS_E_HASH_FAILED == ret) ) return MHD_ERR_TLS_; if ( (GNUTLS_E_PUSH_ERROR == ret) || (GNUTLS_E_INTERNAL_ERROR == ret) || (GNUTLS_E_CRYPTODEV_IOCTL_ERROR == ret) || (GNUTLS_E_CRYPTODEV_DEVICE_ERROR == ret) ) return MHD_ERR_PIPE_; #if defined(GNUTLS_E_PREMATURE_TERMINATION) if (GNUTLS_E_PREMATURE_TERMINATION == ret) return MHD_ERR_CONNRESET_; #elif defined(GNUTLS_E_UNEXPECTED_PACKET_LENGTH) if (GNUTLS_E_UNEXPECTED_PACKET_LENGTH == ret) return MHD_ERR_CONNRESET_; #endif /* GNUTLS_E_UNEXPECTED_PACKET_LENGTH */ if (GNUTLS_E_MEMORY_ERROR == ret) return MHD_ERR_NOMEM_; if (ret < 0) { /* Treat any other error as hard error. */ return MHD_ERR_NOTCONN_; } #ifdef EPOLL_SUPPORT /* Unlike non-TLS connections, do not reset "write-ready" if * sent amount smaller than provided amount, as TLS * connections may break data into smaller parts for sending. */ #endif /* EPOLL_SUPPORT */ #else /* ! HTTPS_SUPPORT */ ret = MHD_ERR_NOTCONN_; #endif /* ! HTTPS_SUPPORT */ } else { /* plaintext transmission */ if (buffer_size > MHD_SCKT_SEND_MAX_SIZE_) { buffer_size = MHD_SCKT_SEND_MAX_SIZE_; /* send() return value limit */ push_data = false; /* Incomplete send */ } pre_send_setopt (connection, (! tls_conn), push_data); #ifdef MHD_USE_MSG_MORE ret = MHD_send4_ (s, buffer, buffer_size, push_data ? 0 : MSG_MORE); #else ret = MHD_send4_ (s, buffer, buffer_size, 0); #endif if (0 > ret) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) { #ifdef EPOLL_SUPPORT /* EAGAIN, no longer write-ready */ connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ return MHD_ERR_AGAIN_; } if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_ERR_AGAIN_; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) return MHD_ERR_CONNRESET_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_)) return MHD_ERR_PIPE_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_)) return MHD_ERR_OPNOTSUPP_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_)) return MHD_ERR_NOTCONN_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_)) return MHD_ERR_INVAL_; if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) return MHD_ERR_NOMEM_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_)) return MHD_ERR_BADF_; /* Treat any other error as a hard error. */ return MHD_ERR_NOTCONN_; } #ifdef EPOLL_SUPPORT else if (buffer_size > (size_t) ret) connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ } /* If there is a need to push the data from network buffers * call post_send_setopt(). */ /* If TLS connection is used then next final send() will be * without MSG_MORE support. If non-TLS connection is used * it's unknown whether sendfile() will be used or not so * assume that next call will be the same, like this call. */ if ( (push_data) && (buffer_size == (size_t) ret) ) post_send_setopt (connection, (! tls_conn), push_data); return ret; } ssize_t MHD_send_hdr_and_body_ (struct MHD_Connection *connection, const char *header, size_t header_size, bool never_push_hdr, const char *body, size_t body_size, bool complete_response) { ssize_t ret; bool push_hdr; bool push_body; MHD_socket s = connection->socket_fd; #ifndef _WIN32 #define _MHD_SEND_VEC_MAX MHD_SCKT_SEND_MAX_SIZE_ #else /* ! _WIN32 */ #define _MHD_SEND_VEC_MAX UINT32_MAX #endif /* ! _WIN32 */ #ifdef MHD_VECT_SEND #if defined(HAVE_SENDMSG) || defined(HAVE_WRITEV) struct iovec vector[2]; #ifdef HAVE_SENDMSG struct msghdr msg; #endif /* HAVE_SENDMSG */ #endif /* HAVE_SENDMSG || HAVE_WRITEV */ #ifdef _WIN32 WSABUF vector[2]; DWORD vec_sent; #endif /* _WIN32 */ bool no_vec; /* Is vector-send() disallowed? */ no_vec = false; #ifdef HTTPS_SUPPORT no_vec = no_vec || (connection->daemon->options & MHD_USE_TLS); #endif /* HTTPS_SUPPORT */ #if (! defined(HAVE_SENDMSG) || ! defined(MSG_NOSIGNAL) ) && \ defined(MHD_SEND_SPIPE_SEND_SUPPRESS_POSSIBLE) && \ defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) no_vec = no_vec || (! connection->daemon->sigpipe_blocked && ! connection->sk_spipe_suppress); #endif /* (!HAVE_SENDMSG || ! MSG_NOSIGNAL) && MHD_SEND_SPIPE_SEND_SUPPRESS_POSSIBLE && MHD_SEND_SPIPE_SUPPRESS_NEEDED */ #endif /* MHD_VECT_SEND */ mhd_assert ( (NULL != body) || (0 == body_size) ); if ( (MHD_INVALID_SOCKET == s) || (MHD_CONNECTION_CLOSED == connection->state) ) { return MHD_ERR_NOTCONN_; } push_body = complete_response; if (! never_push_hdr) { if (! complete_response) push_hdr = true; /* Push the header as the client may react * on header alone while the body data is * being prepared. */ else { if (1400 > (header_size + body_size)) push_hdr = false; /* Do not push the header as complete * reply is already ready and the whole * reply most probably will fit into * the single IP packet. */ else push_hdr = true; /* Push header alone so client may react * on it while reply body is being delivered. */ } } else push_hdr = false; if (complete_response && (0 == body_size)) push_hdr = true; /* The header alone is equal to the whole response. */ if ( #ifdef MHD_VECT_SEND (no_vec) || (0 == body_size) || ((size_t) SSIZE_MAX <= header_size) || ((size_t) _MHD_SEND_VEC_MAX < header_size) #ifdef _WIN32 || ((size_t) UINT_MAX < header_size) #endif /* _WIN32 */ #else /* ! MHD_VECT_SEND */ true #endif /* ! MHD_VECT_SEND */ ) { ret = MHD_send_data_ (connection, header, header_size, push_hdr); if ( (header_size == (size_t) ret) && ((size_t) SSIZE_MAX > header_size) && (0 != body_size) && (connection->sk_nonblck) ) { ssize_t ret2; /* The header has been sent completely. * Try to send the reply body without waiting for * the next round. */ /* Make sure that sum of ret + ret2 will not exceed SSIZE_MAX as * function needs to return positive value if succeed. */ if ( (((size_t) SSIZE_MAX) - ((size_t) ret)) < body_size) { body_size = (((size_t) SSIZE_MAX) - ((size_t) ret)); complete_response = false; push_body = complete_response; } ret2 = MHD_send_data_ (connection, body, body_size, push_body); if (0 < ret2) return ret + ret2; /* Total data sent */ if (MHD_ERR_AGAIN_ == ret2) return ret; return ret2; /* Error code */ } return ret; } #ifdef MHD_VECT_SEND if ( ((size_t) SSIZE_MAX <= body_size) || ((size_t) SSIZE_MAX < (header_size + body_size)) ) { /* Return value limit */ body_size = SSIZE_MAX - header_size; complete_response = false; push_body = complete_response; } #if (SSIZE_MAX != _MHD_SEND_VEC_MAX) || (_MHD_SEND_VEC_MAX + 0 == 0) if (((size_t) _MHD_SEND_VEC_MAX <= body_size) || ((size_t) _MHD_SEND_VEC_MAX < (header_size + body_size))) { /* Send total amount limit */ body_size = _MHD_SEND_VEC_MAX - header_size; complete_response = false; push_body = complete_response; } #endif /* SSIZE_MAX != _MHD_SEND_VEC_MAX */ pre_send_setopt (connection, #ifdef HAVE_SENDMSG true, #else /* ! HAVE_SENDMSG */ false, #endif /* ! HAVE_SENDMSG */ push_hdr || push_body); #if defined(HAVE_SENDMSG) || defined(HAVE_WRITEV) vector[0].iov_base = _MHD_DROP_CONST (header); vector[0].iov_len = header_size; vector[1].iov_base = _MHD_DROP_CONST (body); vector[1].iov_len = body_size; #if defined(HAVE_SENDMSG) memset (&msg, 0, sizeof(msg)); msg.msg_iov = vector; msg.msg_iovlen = 2; ret = sendmsg (s, &msg, MSG_NOSIGNAL_OR_ZERO); #elif defined(HAVE_WRITEV) ret = writev (s, vector, 2); #endif /* HAVE_WRITEV */ #endif /* HAVE_SENDMSG || HAVE_WRITEV */ #ifdef _WIN32 if ((size_t) UINT_MAX < body_size) { /* Send item size limit */ body_size = UINT_MAX; complete_response = false; push_body = complete_response; } vector[0].buf = (char *) _MHD_DROP_CONST (header); vector[0].len = (unsigned long) header_size; vector[1].buf = (char *) _MHD_DROP_CONST (body); vector[1].len = (unsigned long) body_size; ret = WSASend (s, vector, 2, &vec_sent, 0, NULL, NULL); if (0 == ret) ret = (ssize_t) vec_sent; else ret = -1; #endif /* _WIN32 */ if (0 > ret) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) { #ifdef EPOLL_SUPPORT /* EAGAIN, no longer write-ready */ connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ return MHD_ERR_AGAIN_; } if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_ERR_AGAIN_; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) return MHD_ERR_CONNRESET_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_)) return MHD_ERR_PIPE_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_)) return MHD_ERR_OPNOTSUPP_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_)) return MHD_ERR_NOTCONN_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_)) return MHD_ERR_INVAL_; if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) return MHD_ERR_NOMEM_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_)) return MHD_ERR_BADF_; /* Treat any other error as a hard error. */ return MHD_ERR_NOTCONN_; } #ifdef EPOLL_SUPPORT else if ((header_size + body_size) > (size_t) ret) connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ /* If there is a need to push the data from network buffers * call post_send_setopt(). */ if ( (push_body) && ((header_size + body_size) == (size_t) ret) ) { /* Complete reply has been sent. */ /* If TLS connection is used then next final send() will be * without MSG_MORE support. If non-TLS connection is used * it's unknown whether next 'send' will be plain send() / sendmsg() or * sendfile() will be used so assume that next final send() will be * the same, like for this response. */ post_send_setopt (connection, #ifdef HAVE_SENDMSG true, #else /* ! HAVE_SENDMSG */ false, #endif /* ! HAVE_SENDMSG */ true); } else if ( (push_hdr) && (header_size <= (size_t) ret)) { /* The header has been sent completely and there is a * need to push the header data. */ /* Luckily the type of send function will be used next is known. */ post_send_setopt (connection, #if defined(_MHD_HAVE_SENDFILE) MHD_resp_sender_std == connection->rp.resp_sender, #else /* ! _MHD_HAVE_SENDFILE */ true, #endif /* ! _MHD_HAVE_SENDFILE */ true); } return ret; #else /* ! MHD_VECT_SEND */ mhd_assert (false); return MHD_ERR_CONNRESET_; /* Unreachable. Mute warnings. */ #endif /* ! MHD_VECT_SEND */ } #if defined(_MHD_HAVE_SENDFILE) ssize_t MHD_send_sendfile_ (struct MHD_Connection *connection) { ssize_t ret; const int file_fd = connection->rp.response->fd; uint64_t left; uint64_t offsetu64; #ifndef HAVE_SENDFILE64 const uint64_t max_off_t = (uint64_t) OFF_T_MAX; #else /* HAVE_SENDFILE64 */ const uint64_t max_off_t = (uint64_t) OFF64_T_MAX; #endif /* HAVE_SENDFILE64 */ #ifdef MHD_LINUX_SOLARIS_SENDFILE #ifndef HAVE_SENDFILE64 off_t offset; #else /* HAVE_SENDFILE64 */ off64_t offset; #endif /* HAVE_SENDFILE64 */ #endif /* MHD_LINUX_SOLARIS_SENDFILE */ #ifdef HAVE_FREEBSD_SENDFILE off_t sent_bytes; int flags = 0; #endif #ifdef HAVE_DARWIN_SENDFILE off_t len; #endif /* HAVE_DARWIN_SENDFILE */ const bool used_thr_p_c = MHD_D_IS_USING_THREAD_PER_CONN_ (connection->daemon); const size_t chunk_size = used_thr_p_c ? MHD_SENFILE_CHUNK_THR_P_C_ : MHD_SENFILE_CHUNK_; size_t send_size = 0; bool push_data; mhd_assert (MHD_resp_sender_sendfile == connection->rp.resp_sender); mhd_assert (0 == (connection->daemon->options & MHD_USE_TLS)); offsetu64 = connection->rp.rsp_write_position + connection->rp.response->fd_off; if (max_off_t < offsetu64) { /* Retry to send with standard 'send()'. */ connection->rp.resp_sender = MHD_resp_sender_std; return MHD_ERR_AGAIN_; } left = connection->rp.response->total_size - connection->rp.rsp_write_position; if ( (uint64_t) SSIZE_MAX < left) left = SSIZE_MAX; /* Do not allow system to stick sending on single fast connection: * use 128KiB chunks (2MiB for thread-per-connection). */ if (chunk_size < left) { send_size = chunk_size; push_data = false; /* No need to push data, there is more to send. */ } else { send_size = (size_t) left; push_data = true; /* Final piece of data, need to push to the network. */ } pre_send_setopt (connection, false, push_data); #ifdef MHD_LINUX_SOLARIS_SENDFILE #ifndef HAVE_SENDFILE64 offset = (off_t) offsetu64; ret = sendfile (connection->socket_fd, file_fd, &offset, send_size); #else /* HAVE_SENDFILE64 */ offset = (off64_t) offsetu64; ret = sendfile64 (connection->socket_fd, file_fd, &offset, send_size); #endif /* HAVE_SENDFILE64 */ if (0 > ret) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) { #ifdef EPOLL_SUPPORT /* EAGAIN --- no longer write-ready */ connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ return MHD_ERR_AGAIN_; } if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_ERR_AGAIN_; #ifdef HAVE_LINUX_SENDFILE if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_)) return MHD_ERR_BADF_; /* sendfile() failed with EINVAL if mmap()-like operations are not supported for FD or other 'unusual' errors occurred, so we should try to fall back to 'SEND'; see also this thread for info on odd libc/Linux behavior with sendfile: http://lists.gnu.org/archive/html/libmicrohttpd/2011-02/msg00015.html */ connection->rp.resp_sender = MHD_resp_sender_std; return MHD_ERR_AGAIN_; #else /* HAVE_SOLARIS_SENDFILE */ if ( (EAFNOSUPPORT == err) || (EINVAL == err) || (EOPNOTSUPP == err) ) { /* Retry with standard file reader. */ connection->rp.resp_sender = MHD_resp_sender_std; return MHD_ERR_AGAIN_; } if ( (ENOTCONN == err) || (EPIPE == err) ) { return MHD_ERR_CONNRESET_; } return MHD_ERR_BADF_; /* Fail hard */ #endif /* HAVE_SOLARIS_SENDFILE */ } #ifdef EPOLL_SUPPORT else if (send_size > (size_t) ret) connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ #elif defined(HAVE_FREEBSD_SENDFILE) #ifdef SF_FLAGS flags = used_thr_p_c ? freebsd_sendfile_flags_thd_p_c_ : freebsd_sendfile_flags_; #endif /* SF_FLAGS */ if (0 != sendfile (file_fd, connection->socket_fd, (off_t) offsetu64, send_size, NULL, &sent_bytes, flags)) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err) || MHD_SCKT_ERR_IS_EINTR_ (err) || (EBUSY == err) ) { mhd_assert (SSIZE_MAX >= sent_bytes); if (0 != sent_bytes) return (ssize_t) sent_bytes; return MHD_ERR_AGAIN_; } /* Some unrecoverable error. Possibly file FD is not suitable * for sendfile(). Retry with standard send(). */ connection->rp.resp_sender = MHD_resp_sender_std; return MHD_ERR_AGAIN_; } mhd_assert (0 < sent_bytes); mhd_assert (SSIZE_MAX >= sent_bytes); ret = (ssize_t) sent_bytes; #elif defined(HAVE_DARWIN_SENDFILE) len = (off_t) send_size; /* chunk always fit */ if (0 != sendfile (file_fd, connection->socket_fd, (off_t) offsetu64, &len, NULL, 0)) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err) || MHD_SCKT_ERR_IS_EINTR_ (err)) { mhd_assert (0 <= len); mhd_assert (SSIZE_MAX >= len); mhd_assert (send_size >= (size_t) len); if (0 != len) return (ssize_t) len; return MHD_ERR_AGAIN_; } if ((ENOTCONN == err) || (EPIPE == err) ) return MHD_ERR_CONNRESET_; if ((ENOTSUP == err) || (EOPNOTSUPP == err) ) { /* This file FD is not suitable for sendfile(). * Retry with standard send(). */ connection->rp.resp_sender = MHD_resp_sender_std; return MHD_ERR_AGAIN_; } return MHD_ERR_BADF_; /* Return hard error. */ } mhd_assert (0 <= len); mhd_assert (SSIZE_MAX >= len); mhd_assert (send_size >= (size_t) len); ret = (ssize_t) len; #endif /* HAVE_FREEBSD_SENDFILE */ /* If there is a need to push the data from network buffers * call post_send_setopt(). */ /* It's unknown whether sendfile() will be used in the next * response so assume that next response will be the same. */ if ( (push_data) && (send_size == (size_t) ret) ) post_send_setopt (connection, false, push_data); return ret; } #endif /* _MHD_HAVE_SENDFILE */ #if defined(MHD_VECT_SEND) /** * Function sends iov data by system sendmsg or writev function. * * Connection must be in non-TLS (non-HTTPS) mode. * * @param connection the MHD connection structure * @param r_iov the pointer to iov data structure with tracking * @param push_data set to true to force push the data to the network from * system buffers (usually set for the last piece of data), * set to false to prefer holding incomplete network packets * (more data will be send for the same reply). * @return actual number of bytes sent */ static ssize_t send_iov_nontls (struct MHD_Connection *connection, struct MHD_iovec_track_ *const r_iov, bool push_data) { ssize_t res; size_t items_to_send; #ifdef HAVE_SENDMSG struct msghdr msg; #elif defined(MHD_WINSOCK_SOCKETS) DWORD bytes_sent; DWORD cnt_w; #endif /* MHD_WINSOCK_SOCKETS */ mhd_assert (0 == (connection->daemon->options & MHD_USE_TLS)); if ( (MHD_INVALID_SOCKET == connection->socket_fd) || (MHD_CONNECTION_CLOSED == connection->state) ) { return MHD_ERR_NOTCONN_; } items_to_send = r_iov->cnt - r_iov->sent; #ifdef _MHD_IOV_MAX if (_MHD_IOV_MAX < items_to_send) { mhd_assert (0 < _MHD_IOV_MAX); if (0 == _MHD_IOV_MAX) return MHD_ERR_NOTCONN_; /* Should never happen */ items_to_send = _MHD_IOV_MAX; push_data = false; /* Incomplete response */ } #endif /* _MHD_IOV_MAX */ #ifdef HAVE_SENDMSG memset (&msg, 0, sizeof(struct msghdr)); msg.msg_iov = r_iov->iov + r_iov->sent; msg.msg_iovlen = items_to_send; pre_send_setopt (connection, true, push_data); #ifdef MHD_USE_MSG_MORE res = sendmsg (connection->socket_fd, &msg, MSG_NOSIGNAL_OR_ZERO | (push_data ? 0 : MSG_MORE)); #else /* ! MHD_USE_MSG_MORE */ res = sendmsg (connection->socket_fd, &msg, MSG_NOSIGNAL_OR_ZERO); #endif /* ! MHD_USE_MSG_MORE */ #elif defined(HAVE_WRITEV) pre_send_setopt (connection, true, push_data); res = writev (connection->socket_fd, r_iov->iov + r_iov->sent, items_to_send); #elif defined(MHD_WINSOCK_SOCKETS) #ifdef _WIN64 if (items_to_send > UINT32_MAX) { cnt_w = UINT32_MAX; push_data = false; /* Incomplete response */ } else cnt_w = (DWORD) items_to_send; #else /* ! _WIN64 */ cnt_w = (DWORD) items_to_send; #endif /* ! _WIN64 */ pre_send_setopt (connection, true, push_data); if (0 == WSASend (connection->socket_fd, (LPWSABUF) (r_iov->iov + r_iov->sent), cnt_w, &bytes_sent, 0, NULL, NULL)) res = (ssize_t) bytes_sent; else res = -1; #else /* !HAVE_SENDMSG && !HAVE_WRITEV && !MHD_WINSOCK_SOCKETS */ #error No vector-send function available #endif if (0 > res) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) { #ifdef EPOLL_SUPPORT /* EAGAIN --- no longer write-ready */ connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ return MHD_ERR_AGAIN_; } if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_ERR_AGAIN_; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) return MHD_ERR_CONNRESET_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_)) return MHD_ERR_PIPE_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_)) return MHD_ERR_OPNOTSUPP_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_)) return MHD_ERR_NOTCONN_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_)) return MHD_ERR_INVAL_; if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) return MHD_ERR_NOMEM_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_)) return MHD_ERR_BADF_; /* Treat any other error as a hard error. */ return MHD_ERR_NOTCONN_; } /* Some data has been sent */ if (1) { size_t track_sent = (size_t) res; /* Adjust the internal tracking information for the iovec to * take this last send into account. */ while ((0 != track_sent) && (r_iov->iov[r_iov->sent].iov_len <= track_sent)) { track_sent -= r_iov->iov[r_iov->sent].iov_len; r_iov->sent++; /* The iov element has been completely sent */ mhd_assert ((r_iov->cnt > r_iov->sent) || (0 == track_sent)); } if (r_iov->cnt == r_iov->sent) post_send_setopt (connection, true, push_data); else { #ifdef EPOLL_SUPPORT connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); #endif /* EPOLL_SUPPORT */ if (0 != track_sent) { mhd_assert (r_iov->cnt > r_iov->sent); /* The last iov element has been partially sent */ r_iov->iov[r_iov->sent].iov_base = (void *) ((uint8_t *) r_iov->iov[r_iov->sent].iov_base + track_sent); r_iov->iov[r_iov->sent].iov_len -= (MHD_iov_size_) track_sent; } } } return res; } #endif /* MHD_VECT_SEND */ #if ! defined(MHD_VECT_SEND) || defined(HTTPS_SUPPORT) || \ defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED) /** * Function sends iov data by sending buffers one-by-one by standard * data send function. * * Connection could be in HTTPS or non-HTTPS mode. * * @param connection the MHD connection structure * @param r_iov the pointer to iov data structure with tracking * @param push_data set to true to force push the data to the network from * system buffers (usually set for the last piece of data), * set to false to prefer holding incomplete network packets * (more data will be send for the same reply). * @return actual number of bytes sent */ static ssize_t send_iov_emu (struct MHD_Connection *connection, struct MHD_iovec_track_ *const r_iov, bool push_data) { const bool non_blk = connection->sk_nonblck; size_t total_sent; ssize_t res; mhd_assert (NULL != r_iov->iov); total_sent = 0; do { if ((size_t) SSIZE_MAX - total_sent < r_iov->iov[r_iov->sent].iov_len) return (ssize_t) total_sent; /* return value would overflow */ res = MHD_send_data_ (connection, r_iov->iov[r_iov->sent].iov_base, r_iov->iov[r_iov->sent].iov_len, push_data && (r_iov->cnt == r_iov->sent + 1)); if (0 > res) { /* Result is an error */ if (0 == total_sent) return res; /* Nothing was sent, return result as is */ if (MHD_ERR_AGAIN_ == res) return (ssize_t) total_sent; /* Return the amount of the sent data */ return res; /* Any kind of a hard error */ } total_sent += (size_t) res; if (r_iov->iov[r_iov->sent].iov_len != (size_t) res) { const size_t sent = (size_t) res; /* Incomplete buffer has been sent. * Adjust buffer of the last element. */ r_iov->iov[r_iov->sent].iov_base = (void *) ((uint8_t *) r_iov->iov[r_iov->sent].iov_base + sent); r_iov->iov[r_iov->sent].iov_len -= (MHD_iov_size_) sent; return (ssize_t) total_sent; } /* The iov element has been completely sent */ r_iov->sent++; } while ((r_iov->cnt > r_iov->sent) && (non_blk)); return (ssize_t) total_sent; } #endif /* !MHD_VECT_SEND || HTTPS_SUPPORT || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */ ssize_t MHD_send_iovec_ (struct MHD_Connection *connection, struct MHD_iovec_track_ *const r_iov, bool push_data) { #ifdef MHD_VECT_SEND #if defined(HTTPS_SUPPORT) || \ defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED) bool use_iov_send = true; #endif /* HTTPS_SUPPORT || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */ #endif /* MHD_VECT_SEND */ mhd_assert (NULL != connection->rp.resp_iov.iov); mhd_assert (NULL != connection->rp.response->data_iov); mhd_assert (connection->rp.resp_iov.cnt > connection->rp.resp_iov.sent); #ifdef MHD_VECT_SEND #if defined(HTTPS_SUPPORT) || \ defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED) #ifdef HTTPS_SUPPORT use_iov_send = use_iov_send && (0 == (connection->daemon->options & MHD_USE_TLS)); #endif /* HTTPS_SUPPORT */ #ifdef _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED use_iov_send = use_iov_send && (connection->daemon->sigpipe_blocked || connection->sk_spipe_suppress); #endif /* _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */ if (use_iov_send) #endif /* HTTPS_SUPPORT || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */ return send_iov_nontls (connection, r_iov, push_data); #endif /* MHD_VECT_SEND */ #if ! defined(MHD_VECT_SEND) || defined(HTTPS_SUPPORT) || \ defined(_MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED) return send_iov_emu (connection, r_iov, push_data); #endif /* !MHD_VECT_SEND || HTTPS_SUPPORT || _MHD_VECT_SEND_NEEDS_SPIPE_SUPPRESSED */ } libmicrohttpd-1.0.10/src/microhttpd/sha256.h0000644000175000017500000000610415035214301014236 /* This file is part of libmicrohttpd Copyright (C) 2019-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha256.h * @brief Calculation of SHA-256 digest * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA256_H #define MHD_SHA256_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * Digest is kept internally as 8 32-bit words. */ #define SHA256_DIGEST_SIZE_WORDS 8 /** * Number of bits in single SHA-256 word */ #define SHA256_WORD_SIZE_BITS 32 /** * Number of bytes in single SHA-256 word * used to process data */ #define SHA256_BYTES_IN_WORD (SHA256_WORD_SIZE_BITS / 8) /** * Size of SHA-256 digest in bytes */ #define SHA256_DIGEST_SIZE (SHA256_DIGEST_SIZE_WORDS * SHA256_BYTES_IN_WORD) /** * Size of SHA-256 digest string in chars including termination NUL */ #define SHA256_DIGEST_STRING_SIZE ((SHA256_DIGEST_SIZE) * 2 + 1) /** * Size of single processing block in bits */ #define SHA256_BLOCK_SIZE_BITS 512 /** * Size of single processing block in bytes */ #define SHA256_BLOCK_SIZE (SHA256_BLOCK_SIZE_BITS / 8) /** * Size of single processing block in bytes */ #define SHA256_BLOCK_SIZE_WORDS (SHA256_BLOCK_SIZE_BITS / SHA256_WORD_SIZE_BITS) struct Sha256Ctx { uint32_t H[SHA256_DIGEST_SIZE_WORDS]; /**< Intermediate hash value / digest at end of calculation */ uint32_t buffer[SHA256_BLOCK_SIZE_WORDS]; /**< SHA256 input data buffer */ uint64_t count; /**< number of bytes, mod 2^64 */ }; /** * Initialise structure for SHA256 calculation. * * @param ctx must be a `struct Sha256Ctx *` */ void MHD_SHA256_init (struct Sha256Ctx *ctx); /** * Process portion of bytes. * * @param ctx must be a `struct Sha256Ctx *` * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA256_update (struct Sha256Ctx *ctx, const uint8_t *data, size_t length); /** * Finalise SHA256 calculation, return digest. * * @param ctx must be a `struct Sha256Ctx *` * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes */ void MHD_SHA256_finish (struct Sha256Ctx *ctx, uint8_t digest[SHA256_DIGEST_SIZE]); /** * Indicates that function MHD_SHA256_finish() (without context reset) is available */ #define MHD_SHA256_HAS_FINISH 1 #endif /* MHD_SHA256_H */ libmicrohttpd-1.0.10/src/microhttpd/md5_ext.c0000664000175000017500000000554515232103064014602 /* This file is part of GNU libmicrohttpd Copyright (C) 2022-2023 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/md5_ext.c * @brief Wrapper for MD5 calculation performed by TLS library * @author Karlson2k (Evgeny Grin) */ #include #include "md5_ext.h" #include "mhd_assert.h" /** * Initialise structure for MD5 calculation, allocate resources. * * This function must not be called more than one time for @a ctx. * * @param ctx the calculation context */ void MHD_MD5_init_one_time (struct Md5CtxExt *ctx) { ctx->handle = NULL; ctx->ext_error = gnutls_hash_init (&ctx->handle, GNUTLS_DIG_MD5); if ((0 != ctx->ext_error) && (NULL != ctx->handle)) { /* GnuTLS may return initialisation error and set the handle at the same time. Such handle cannot be used for calculations. Note: GnuTLS may also return an error and NOT set the handle. */ gnutls_free (ctx->handle); ctx->handle = NULL; } /* If handle is NULL, the error must be set */ mhd_assert ((NULL != ctx->handle) || (0 != ctx->ext_error)); /* If error is set, the handle must be NULL */ mhd_assert ((0 == ctx->ext_error) || (NULL == ctx->handle)); } /** * Process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_MD5_update (struct Md5CtxExt *ctx, const uint8_t *data, size_t length) { if (0 == ctx->ext_error) ctx->ext_error = gnutls_hash (ctx->handle, data, length); } /** * Finalise MD5 calculation, return digest, reset hash calculation. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes */ void MHD_MD5_finish_reset (struct Md5CtxExt *ctx, uint8_t digest[MD5_DIGEST_SIZE]) { if (0 == ctx->ext_error) gnutls_hash_output (ctx->handle, digest); else gnutls_hash_deinit (ctx->handle, NULL); } /** * Free allocated resources. * * @param ctx the calculation context */ void MHD_MD5_deinit (struct Md5CtxExt *ctx) { if (NULL != ctx->handle) gnutls_hash_deinit (ctx->handle, NULL); } libmicrohttpd-1.0.10/src/microhttpd/mhd_locks.h0000644000175000017500000001375414760713577015231 /* This file is part of libmicrohttpd Copyright (C) 2016-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_locks.h * @brief Header for platform-independent locks abstraction * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff * * Provides basic abstraction for locks/mutex. * Any functions can be implemented as macro on some platforms * unless explicitly marked otherwise. * Any function argument can be skipped in macro, so avoid * variable modification in function parameters. * * @warning Unlike pthread functions, most of functions return * nonzero on success. */ #ifndef MHD_LOCKS_H #define MHD_LOCKS_H 1 #include "mhd_options.h" #ifdef MHD_USE_THREADS #if defined(MHD_USE_W32_THREADS) # define MHD_W32_MUTEX_ 1 # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif /* !WIN32_LEAN_AND_MEAN */ # include #elif defined(HAVE_PTHREAD_H) && defined(MHD_USE_POSIX_THREADS) # define MHD_PTHREAD_MUTEX_ 1 # undef HAVE_CONFIG_H # include # define HAVE_CONFIG_H 1 #else # error No base mutex API is available. #endif #ifndef MHD_PANIC # include # ifdef HAVE_STDLIB_H # include # endif /* HAVE_STDLIB_H */ /* Simple implementation of MHD_PANIC, to be used outside lib */ # define MHD_PANIC(msg) \ do { fprintf (stderr, \ "Abnormal termination at %d line in file %s: %s\n", \ (int) __LINE__, __FILE__, msg); abort (); \ } while (0) #endif /* ! MHD_PANIC */ #if defined(MHD_PTHREAD_MUTEX_) typedef pthread_mutex_t MHD_mutex_; #elif defined(MHD_W32_MUTEX_) typedef CRITICAL_SECTION MHD_mutex_; #endif #if defined(MHD_PTHREAD_MUTEX_) /** * Initialise new mutex. * @param pmutex pointer to the mutex * @return nonzero on success, zero otherwise */ #define MHD_mutex_init_(pmutex) (! (pthread_mutex_init ((pmutex), NULL))) #elif defined(MHD_W32_MUTEX_) /** * Initialise new mutex. * @param pmutex pointer to mutex * @return nonzero on success, zero otherwise */ #define MHD_mutex_init_(pmutex) \ (InitializeCriticalSectionAndSpinCount ((pmutex),16)) #endif #if defined(MHD_PTHREAD_MUTEX_) # if defined(PTHREAD_MUTEX_INITIALIZER) /** * Define static mutex and statically initialise it. */ # define MHD_MUTEX_STATIC_DEFN_INIT_(m) \ static MHD_mutex_ m = PTHREAD_MUTEX_INITIALIZER # endif /* PTHREAD_MUTEX_INITIALIZER */ #endif #if defined(MHD_PTHREAD_MUTEX_) /** * Destroy previously initialised mutex. * @param pmutex pointer to mutex * @return nonzero on success, zero otherwise */ #define MHD_mutex_destroy_(pmutex) (! (pthread_mutex_destroy ((pmutex)))) #elif defined(MHD_W32_MUTEX_) /** * Destroy previously initialised mutex. * @param pmutex pointer to mutex * @return Always nonzero */ #define MHD_mutex_destroy_(pmutex) (DeleteCriticalSection ((pmutex)), ! 0) #endif /** * Destroy previously initialised mutex and abort execution * if error is detected. * @param pmutex pointer to mutex */ #define MHD_mutex_destroy_chk_(pmutex) do { \ if (! MHD_mutex_destroy_ (pmutex)) \ MHD_PANIC (_ ("Failed to destroy mutex.\n")); \ } while (0) #if defined(MHD_PTHREAD_MUTEX_) /** * Acquire lock on previously initialised mutex. * If mutex was already locked by other thread, function * blocks until mutex becomes available. * @param pmutex pointer to mutex * @return nonzero on success, zero otherwise */ #define MHD_mutex_lock_(pmutex) (! (pthread_mutex_lock ((pmutex)))) #elif defined(MHD_W32_MUTEX_) /** * Acquire lock on previously initialised mutex. * If mutex was already locked by other thread, function * blocks until mutex becomes available. * @param pmutex pointer to mutex * @return Always nonzero */ #define MHD_mutex_lock_(pmutex) (EnterCriticalSection ((pmutex)), ! 0) #endif /** * Acquire lock on previously initialised mutex. * If mutex was already locked by other thread, function * blocks until mutex becomes available. * If error is detected, execution will be aborted. * @param pmutex pointer to mutex */ #define MHD_mutex_lock_chk_(pmutex) do { \ if (! MHD_mutex_lock_ (pmutex)) \ MHD_PANIC (_ ("Failed to lock mutex.\n")); \ } while (0) #if defined(MHD_PTHREAD_MUTEX_) /** * Unlock previously initialised and locked mutex. * @param pmutex pointer to mutex * @return nonzero on success, zero otherwise */ #define MHD_mutex_unlock_(pmutex) (! (pthread_mutex_unlock ((pmutex)))) #elif defined(MHD_W32_MUTEX_) /** * Unlock previously initialised and locked mutex. * @param pmutex pointer to mutex * @return Always nonzero */ #define MHD_mutex_unlock_(pmutex) (LeaveCriticalSection ((pmutex)), ! 0) #endif /** * Unlock previously initialised and locked mutex. * If error is detected, execution will be aborted. * @param pmutex pointer to mutex */ #define MHD_mutex_unlock_chk_(pmutex) do { \ if (! MHD_mutex_unlock_ (pmutex)) \ MHD_PANIC (_ ("Failed to unlock mutex.\n")); \ } while (0) #else /* ! MHD_USE_THREADS */ #define MHD_mutex_init_(ignore) (! 0) #define MHD_mutex_destroy_(ignore) (! 0) #define MHD_mutex_destroy_chk_(ignore) (void)0 #define MHD_mutex_lock_(ignore) (! 0) #define MHD_mutex_lock_chk_(ignore) (void)0 #define MHD_mutex_unlock_(ignore) (! 0) #define MHD_mutex_unlock_chk_(ignore) (void)0 #endif /* ! MHD_USE_THREADS */ #endif /* ! MHD_LOCKS_H */ libmicrohttpd-1.0.10/src/microhttpd/test_options.c0000664000175000017500000001770315232103064015766 /* This file is part of libmicrohttpd Copyright (C) 2007 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_options.c * @brief Testcase for libmicrohttpd HTTPS GET operations * @author Sagie Amir */ #include "platform.h" #include "microhttpd.h" #include "mhd_sockets.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; (void) connection; (void) url; (void) method; (void) version; (void) upload_data; (void) upload_data_size; (void) req_cls; return 0; } static unsigned int test_wrap_loc (const char *test_name, unsigned int (*test)(void)) { unsigned int ret; fprintf (stdout, "running test: %s ", test_name); ret = test (); if (ret == 0) { fprintf (stdout, "[pass]\n"); } else { fprintf (stdout, "[fail]\n"); } return ret; } /** * Test daemon initialization with the MHD_OPTION_SOCK_ADDR or * the MHD_OPTION_SOCK_ADDR_LEN options */ static unsigned int test_ip_addr_option (void) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; struct sockaddr_in daemon_ip_addr; uint16_t port4; #if defined(HAVE_INET6) && defined(USE_IPV6_TESTING) struct sockaddr_in6 daemon_ip_addr6; uint16_t port6; #endif unsigned int ret; memset (&daemon_ip_addr, 0, sizeof (struct sockaddr_in)); daemon_ip_addr.sin_family = AF_INET; daemon_ip_addr.sin_port = 0; daemon_ip_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); port4 = 0; #if defined(HAVE_INET6) && defined(USE_IPV6_TESTING) memset (&daemon_ip_addr6, 0, sizeof (struct sockaddr_in6)); daemon_ip_addr6.sin6_family = AF_INET6; daemon_ip_addr6.sin6_port = 0; daemon_ip_addr6.sin6_addr = in6addr_loopback; port6 = 0; #endif ret = 0; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR, &daemon_ip_addr, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else port4 = dinfo->port; MHD_stop_daemon (d); daemon_ip_addr.sin_port = htons (port4); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr), &daemon_ip_addr, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else if (port4 != dinfo->port) ret |= 1 << 2; MHD_stop_daemon (d); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) (sizeof(daemon_ip_addr) / 2), &daemon_ip_addr, MHD_OPTION_END); if (NULL != d) { MHD_stop_daemon (d); return 1 << 3; } #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN daemon_ip_addr.sin_len = (socklen_t) sizeof(daemon_ip_addr); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr), &daemon_ip_addr, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else if (port4 != dinfo->port) ret |= 1 << 2; MHD_stop_daemon (d); daemon_ip_addr.sin_len = (socklen_t) (sizeof(daemon_ip_addr) / 2); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr), &daemon_ip_addr, MHD_OPTION_END); if (NULL != d) { MHD_stop_daemon (d); return 1 << 3; } #endif /* HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */ #if defined(HAVE_INET6) && defined(USE_IPV6_TESTING) d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_IPv6 | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR, &daemon_ip_addr6, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else port6 = dinfo->port; MHD_stop_daemon (d); daemon_ip_addr6.sin6_port = htons (port6); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr6), &daemon_ip_addr6, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else if (port6 != dinfo->port) ret |= 1 << 2; MHD_stop_daemon (d); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) (sizeof(daemon_ip_addr6) / 2), &daemon_ip_addr6, MHD_OPTION_END); if (NULL != d) { MHD_stop_daemon (d); return 1 << 3; } #if defined(HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN) daemon_ip_addr6.sin6_len = (socklen_t) sizeof(daemon_ip_addr6); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr6), &daemon_ip_addr6, MHD_OPTION_END); if (d == 0) return 1; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if (NULL == dinfo) ret |= 1 << 1; else if (port6 != dinfo->port) ret |= 1 << 2; MHD_stop_daemon (d); daemon_ip_addr6.sin6_len = (socklen_t) (sizeof(daemon_ip_addr6) / 2); d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_SOCK_ADDR_LEN, (socklen_t) sizeof(daemon_ip_addr6), &daemon_ip_addr6, MHD_OPTION_END); if (NULL != d) { MHD_stop_daemon (d); return 1 << 3; } #endif /* HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */ #endif /* HAVE_INET6 && USE_IPV6_TESTING */ return ret; } /* setup a temporary transfer test file */ int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errorCount += test_wrap_loc ("ip addr option", &test_ip_addr_option); return errorCount != 0; } libmicrohttpd-1.0.10/src/microhttpd/test_str.c0000664000175000017500000046267315232103064015115 /* This file is part of libmicrohttpd Copyright (C) 2016 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/unit_str_test.h * @brief Unit tests for mhd_str functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #ifdef HAVE_INTTYPES_H #include #else /* ! HAVE_INTTYPES_H */ #define PRIu64 "llu" #define PRIuPTR "u" #define PRIX64 "llX" #endif /* ! HAVE_INTTYPES_H */ #include #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #include "mhd_limits.h" #include "mhd_str.h" #include "test_helpers.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static int verbose = 0; /* verbose level (0-3)*/ /* Locale names to test. * Functions must not depend of current current locale, * so result must be the same in any locale. */ static const char *const locale_names[] = { "C", "", /* System default locale */ #if defined(_WIN32) && ! defined(__CYGWIN__) ".OCP", /* W32 system default OEM code page */ ".ACP", /* W32 system default ANSI code page */ ".65001", /* UTF-8 */ ".437", ".850", ".857", ".866", ".1250", ".1251", ".1252", "en", "english", "French_France", "Turkish_Turkey.1254", "de", "zh-Hans", "ru-RU.1251" #if 0 /* Disabled extra checks */ , ".1254", ".20866", /* number for KOI8-R */ ".28591", /* number for ISO-8859-1 */ ".28595", /* number for ISO-8859-5 */ ".28599", /* number for ISO-8859-9 */ ".28605", /* number for ISO-8859-15 */ "en-US", "English-US", "en-US.437", "English_United States.437", "en-US.1252", "English_United States.1252", "English_United States.28591", "English_United States.65001", "fra", "french", "fr-FR", "fr-FR.850", "french_france.850", "fr-FR.1252", "French_france.1252", "French_france.28605", "French_France.65001", "de-DE", "de-DE.850", "German_Germany.850", "German_Germany.1250", "de-DE.1252", "German_Germany.1252", "German_Germany.28605", "German_Germany.65001", "tr", "trk", "turkish", "tr-TR", "tr-TR.1254", "tr-TR.857", "Turkish_Turkey.857", "Turkish_Turkey.28599", "Turkish_Turkey.65001", "ru", "ru-RU", "Russian", "ru-RU.866", "Russian_Russia.866", "Russian_Russia.1251", "Russian_Russia.20866", "Russian_Russia.28595", "Russian_Russia.65001", "zh-Hans.936", "chinese-simplified" #endif /* Disabled extra checks */ #else /* ! _WIN32 || __CYGWIN__ */ "C.UTF-8", "POSIX", "en", "en_US", "en_US.ISO-8859-1", "en_US.ISO_8859-1", "en_US.ISO8859-1", "en_US.iso88591", "en_US.ISO-8859-15", "en_US.DIS_8859-15", "en_US.ISO8859-15", "en_US.iso885915", "en_US.1252", "en_US.CP1252", "en_US.UTF-8", "en_US.utf8", "fr", "fr_FR", "fr_FR.850", "fr_FR.IBM850", "fr_FR.1252", "fr_FR.CP1252", "fr_FR.ISO-8859-1", "fr_FR.ISO_8859-1", "fr_FR.ISO8859-1", "fr_FR.iso88591", "fr_FR.ISO-8859-15", "fr_FR.DIS_8859-15", "fr_FR.ISO8859-15", "fr_FR.iso8859-15", "fr_FR.UTF-8", "fr_FR.utf8", "de", "de_DE", "de_DE.850", "de_DE.IBM850", "de_DE.1250", "de_DE.CP1250", "de_DE.1252", "de_DE.CP1252", "de_DE.ISO-8859-1", "de_DE.ISO_8859-1", "de_DE.ISO8859-1", "de_DE.iso88591", "de_DE.ISO-8859-15", "de_DE.DIS_8859-15", "de_DE.ISO8859-15", "de_DE.iso885915", "de_DE.UTF-8", "de_DE.utf8", "tr", "tr_TR", "tr_TR.1254", "tr_TR.CP1254", "tr_TR.857", "tr_TR.IBM857", "tr_TR.ISO-8859-9", "tr_TR.ISO8859-9", "tr_TR.iso88599", "tr_TR.UTF-8", "tr_TR.utf8", "ru", "ru_RU", "ru_RU.1251", "ru_RU.CP1251", "ru_RU.866", "ru_RU.IBM866", "ru_RU.KOI8-R", "ru_RU.koi8-r", "ru_RU.KOI8-RU", "ru_RU.ISO-8859-5", "ru_RU.ISO_8859-5", "ru_RU.ISO8859-5", "ru_RU.iso88595", "ru_RU.UTF-8", "zh_CN", "zh_CN.GB2312", "zh_CN.UTF-8", #endif /* ! _WIN32 || __CYGWIN__ */ }; static const unsigned int locale_name_count = sizeof(locale_names) / sizeof(locale_names[0]); /* * Helper functions */ static int set_test_locale (size_t num) { if (num >= locale_name_count) { fprintf (stderr, "Unexpected number of locale.\n"); exit (99); } if (verbose > 2) printf ("Setting locale \"%s\":", locale_names[num]); if (setlocale (LC_ALL, locale_names[num])) { if (verbose > 2) printf (" succeed.\n"); return 1; } if (verbose > 2) printf (" failed.\n"); return 0; } static const char * get_current_locale_str (void) { char const *loc_str = setlocale (LC_ALL, NULL); return loc_str ? loc_str : "unknown"; } static char tmp_bufs[4][4 * 1024]; /* should be enough for testing */ static size_t buf_idx = 0; /* print non-printable chars as char codes */ static char * n_prnt (const char *str) { static char *buf; /* should be enough for testing */ static const size_t buf_size = sizeof(tmp_bufs[0]); const unsigned char *p = (const unsigned char *) str; size_t w_pos = 0; if (++buf_idx > 3) buf_idx = 0; buf = tmp_bufs[buf_idx]; while (*p && w_pos + 1 < buf_size) { const unsigned char c = *p; if ((c == '\\') || (c == '"') ) { if (w_pos + 2 >= buf_size) break; buf[w_pos++] = '\\'; buf[w_pos++] = (char) c; } else if ((c >= 0x20) && (c <= 0x7E) ) buf[w_pos++] = (char) c; else { if (w_pos + 4 >= buf_size) break; if (snprintf (buf + w_pos, buf_size - w_pos, "\\x%02hX", (short unsigned int) c) != 4) break; w_pos += 4; } p++; } if (*p) { /* not full string is printed */ /* enough space for "..." ? */ if (w_pos + 3 > buf_size) w_pos = buf_size - 4; buf[w_pos++] = '.'; buf[w_pos++] = '.'; buf[w_pos++] = '.'; } buf[w_pos] = 0; return buf; } struct str_with_len { const char *const str; const size_t len; }; #define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1} /* * String caseless equality functions tests */ struct two_eq_strs { const struct str_with_len s1; const struct str_with_len s2; }; static const struct two_eq_strs eq_strings[] = { {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`.")}, {D_STR_W_LEN ("Simple string."), D_STR_W_LEN ("Simple string.")}, {D_STR_W_LEN ("SIMPLE STRING."), D_STR_W_LEN ("SIMPLE STRING.")}, {D_STR_W_LEN ("simple string."), D_STR_W_LEN ("simple string.")}, {D_STR_W_LEN ("simple string."), D_STR_W_LEN ("Simple String.")}, {D_STR_W_LEN ("sImPlE StRiNg."), D_STR_W_LEN ("SiMpLe sTrInG.")}, {D_STR_W_LEN ("SIMPLE STRING."), D_STR_W_LEN ("simple string.")}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz")}, {D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ")}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ")}, {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"), D_STR_W_LEN ("ZYXWVUTSRQPONmlkjihgfedcba")}, {D_STR_W_LEN ("Cha\x8cne pour le test."), D_STR_W_LEN ("Cha\x8cne pour le test.")}, /* "Chaîne pour le test." in CP850 */ {D_STR_W_LEN ("cha\x8cne pOur Le TEst."), D_STR_W_LEN ("Cha\x8cne poUr Le teST.")}, {D_STR_W_LEN ("Cha\xeene pour le test."), D_STR_W_LEN ("Cha\xeene pour le test.")}, /* "Chaîne pour le test." in CP1252/ISO-8859-1/ISO-8859-15 */ {D_STR_W_LEN ("CHa\xeene POUR le test."), D_STR_W_LEN ("Cha\xeeNe pour lE TEST.")}, {D_STR_W_LEN ("Cha\xc3\xaene pour le Test."), D_STR_W_LEN ("Cha\xc3\xaene pour le Test.")}, /* "Chaîne pour le test." in UTF-8 */ {D_STR_W_LEN ("ChA\xc3\xaene pouR lE TesT."), D_STR_W_LEN ("Cha\xc3\xaeNe Pour le teSt.")}, {D_STR_W_LEN (".Beispiel Zeichenfolge"), D_STR_W_LEN (".Beispiel Zeichenfolge")}, {D_STR_W_LEN (".bEisPiel ZEIchenfoLgE"), D_STR_W_LEN (".BEiSpiEl zeIcheNfolge")}, {D_STR_W_LEN ("Do\xa7rulama \x87izgi!"), D_STR_W_LEN ("Do\xa7rulama \x87izgi!")}, /* "Doğrulama çizgi!" in CP857 */ {D_STR_W_LEN ("Do\xa7rulama \x87IzgI!"), /* Spelling intentionally incorrect here */ D_STR_W_LEN ("Do\xa7rulama \x87izgi!")}, /* Note: 'i' is not caseless equal to 'I' in Turkish */ {D_STR_W_LEN ("Do\xf0rulama \xe7izgi!"), D_STR_W_LEN ("Do\xf0rulama \xe7izgi!")}, /* "Doğrulama çizgi!" in CP1254/ISO-8859-9 */ {D_STR_W_LEN ("Do\xf0rulamA \xe7Izgi!"), D_STR_W_LEN ("do\xf0rulama \xe7izgi!")}, {D_STR_W_LEN ("Do\xc4\x9frulama \xc3\xa7izgi!"), D_STR_W_LEN ("Do\xc4\x9frulama \xc3\xa7izgi!")}, /* "Doğrulama çizgi!" in UTF-8 */ {D_STR_W_LEN ("do\xc4\x9fruLAMA \xc3\xa7Izgi!"), /* Spelling intentionally incorrect here */ D_STR_W_LEN ("DO\xc4\x9frulama \xc3\xa7izgI!")}, /* Spelling intentionally incorrect here */ {D_STR_W_LEN ("\x92\xa5\xe1\xe2\xae\xa2\xa0\xef \x91\xe2\xe0\xae\xaa\xa0."), D_STR_W_LEN ("\x92\xa5\xe1\xe2\xae\xa2\xa0\xef \x91\xe2\xe0\xae\xaa\xa0.")}, /* "Тестовая Строка." in CP866 */ {D_STR_W_LEN ("\xd2\xe5\xf1\xf2\xee\xe2\xe0\xff \xd1\xf2\xf0\xee\xea\xe0."), D_STR_W_LEN ("\xd2\xe5\xf1\xf2\xee\xe2\xe0\xff \xd1\xf2\xf0\xee\xea\xe0.")}, /* "Тестовая Строка." in CP1251 */ {D_STR_W_LEN ("\xf4\xc5\xd3\xd4\xcf\xd7\xc1\xd1 \xf3\xd4\xd2\xcf\xcb\xc1."), D_STR_W_LEN ("\xf4\xc5\xd3\xd4\xcf\xd7\xc1\xd1 \xf3\xd4\xd2\xcf\xcb\xc1.")}, /* "Тестовая Строка." in KOI8-R */ {D_STR_W_LEN ("\xc2\xd5\xe1\xe2\xde\xd2\xd0\xef \xc1\xe2\xe0\xde\xda\xd0."), D_STR_W_LEN ("\xc2\xd5\xe1\xe2\xde\xd2\xd0\xef \xc1\xe2\xe0\xde\xda\xd0.")}, /* "Тестовая Строка." in ISO-8859-5 */ {D_STR_W_LEN ("\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbe\xd0\xb2\xd0\xb0\xd1" "\x8f \xd0\xa1\xd1\x82\xd1\x80\xd0\xbe\xd0\xba\xd0\xb0."), D_STR_W_LEN ("\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbe\xd0\xb2\xd0\xb0\xd1" "\x8f \xd0\xa1\xd1\x82\xd1\x80\xd0\xbe\xd0\xba\xd0\xb0.")}, /* "Тестовая Строка." in UTF-8 */ {D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@[\\]" "^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90" "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4" "\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8" "\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc" "\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0" "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4" "\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"), D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@[\\]" "^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90" "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4" "\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8" "\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc" "\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0" "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4" "\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff")}, /* Full sequence without a-z */ {D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@AB" "CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83" "\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97" "\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab" "\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf" "\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3" "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7" "\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff"), D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@AB" "CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83" "\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97" "\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab" "\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf" "\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3" "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7" "\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff")}, /* Full sequence */ {D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@AB" "CDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89" "\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d" "\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1" "\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5" "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9" "\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed" "\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff") , D_STR_W_LEN ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ab" "cdefghijklmnopqrstuvwxyz[\\]^_`{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89" "\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d" "\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1" "\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5" "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9" "\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed" "\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff") } /* Full with A/a match */ }; struct two_neq_strs { const struct str_with_len s1; const struct str_with_len s2; const size_t dif_pos; }; static const struct two_neq_strs neq_strings[] = { {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`"), 27}, {D_STR_W_LEN (".1234567890!@~%&$@#{}[]\\/!?`."), D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`"), 0}, {D_STR_W_LEN ("Simple string."), D_STR_W_LEN ("Simple ctring."), 7}, {D_STR_W_LEN ("simple string."), D_STR_W_LEN ("simple string"), 13}, {D_STR_W_LEN ("simple strings"), D_STR_W_LEN ("Simple String."), 13}, {D_STR_W_LEN ("sImPlE StRiNg."), D_STR_W_LEN ("SYMpLe sTrInG."), 1}, {D_STR_W_LEN ("SIMPLE STRING."), D_STR_W_LEN ("simple string.2"), 14}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz,"), D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz."), 26}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz!"), D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZ?"), 26}, {D_STR_W_LEN ("zyxwvutsrqponwMLKJIHGFEDCBA"), D_STR_W_LEN ("ZYXWVUTSRQPON%mlkjihgfedcba"), 13}, {D_STR_W_LEN ("S\xbdur veulent plus d'\xbdufs."), /* "Sœur veulent plus d'œufs." in ISO-8859-15 */ D_STR_W_LEN ("S\xbcUR VEULENT PLUS D'\xbcUFS."), 1}, /* "SŒUR VEULENT PLUS D'ŒUFS." in ISO-8859-15 */ {D_STR_W_LEN ("S\x9cur veulent plus d'\x9cufs."), /* "Sœur veulent plus d'œufs." in CP1252 */ D_STR_W_LEN ("S\x8cUR VEULENT PLUS D'\x8cUFS."), 1}, /* "SŒUR VEULENT PLUS D'ŒUFS." in CP1252 */ {D_STR_W_LEN ("S\xc5\x93ur veulent plus d'\xc5\x93ufs."), /* "Sœur veulent plus d'œufs." in UTF-8 */ D_STR_W_LEN ("S\xc5\x92UR VEULENT PLUS D'\xc5\x92UFS."), 2}, /* "SŒUR VEULENT PLUS D'ŒUFS." in UTF-8 */ {D_STR_W_LEN ("Um ein sch\x94nes M\x84" "dchen zu k\x81ssen."), /* "Um ein schönes Mädchen zu küssen." in CP850 */ D_STR_W_LEN ("UM EIN SCH\x99NES M\x8e" "DCHEN ZU K\x9aSSEN."), 10}, /* "UM EIN SCHÖNES MÄDCHEN ZU KÜSSEN." in CP850 */ {D_STR_W_LEN ("Um ein sch\xf6nes M\xe4" "dchen zu k\xfcssen."), /* "Um ein schönes Mädchen zu küssen." in ISO-8859-1/ISO-8859-15/CP1250/CP1252 */ D_STR_W_LEN ("UM EIN SCH\xd6NES M\xc4" "DCHEN ZU K\xdcSSEN."), 10}, /* "UM EIN SCHÖNES MÄDCHEN ZU KÜSSEN." in ISO-8859-1/ISO-8859-15/CP1250/CP1252 */ {D_STR_W_LEN ("Um ein sch\xc3\xb6nes M\xc3\xa4" "dchen zu k\xc3\xbcssen."), /* "Um ein schönes Mädchen zu küssen." in UTF-8 */ D_STR_W_LEN ("UM EIN SCH\xc3\x96NES M\xc3\x84" "DCHEN ZU K\xc3\x9cSSEN."), 11}, /* "UM EIN SCHÖNES MÄDCHEN ZU KÜSSEN." in UTF-8 */ {D_STR_W_LEN ("\x98stanbul"), /* "İstanbul" in CP857 */ D_STR_W_LEN ("istanbul"), 0}, /* "istanbul" in CP857 */ {D_STR_W_LEN ("\xddstanbul"), /* "İstanbul" in ISO-8859-9/CP1254 */ D_STR_W_LEN ("istanbul"), 0}, /* "istanbul" in ISO-8859-9/CP1254 */ {D_STR_W_LEN ("\xc4\xb0stanbul"), /* "İstanbul" in UTF-8 */ D_STR_W_LEN ("istanbul"), 0}, /* "istanbul" in UTF-8 */ {D_STR_W_LEN ("Diyarbak\x8dr"), /* "Diyarbakır" in CP857 */ D_STR_W_LEN ("DiyarbakIR"), 8}, /* "DiyarbakIR" in CP857 */ {D_STR_W_LEN ("Diyarbak\xfdr"), /* "Diyarbakır" in ISO-8859-9/CP1254 */ D_STR_W_LEN ("DiyarbakIR"), 8}, /* "DiyarbakIR" in ISO-8859-9/CP1254 */ {D_STR_W_LEN ("Diyarbak\xc4\xb1r"), /* "Diyarbakır" in UTF-8 */ D_STR_W_LEN ("DiyarbakIR"), 8}, /* "DiyarbakIR" in UTF-8 */ {D_STR_W_LEN ("\x92\xa5\xe1\xe2\xae\xa2\xa0\xef \x91\xe2\xe0\xae\xaa\xa0."), /* "Тестовая Строка." in CP866 */ D_STR_W_LEN ("\x92\x85\x91\x92\x8e\x82\x80\x9f \x91\x92\x90\x8e\x8a\x80."), 1}, /* "ТЕСТОВАЯ СТРОКА." in CP866 */ {D_STR_W_LEN ("\xd2\xe5\xf1\xf2\xee\xe2\xe0\xff \xd1\xf2\xf0\xee\xea\xe0."), /* "Тестовая Строка." in CP1251 */ D_STR_W_LEN ("\xd2\xc5\xd1\xd2\xce\xc2\xc0\xdf \xd1\xd2\xd0\xce\xca\xc0."), 1}, /* "ТЕСТОВАЯ СТРОКА." in CP1251 */ {D_STR_W_LEN ("\xf4\xc5\xd3\xd4\xcf\xd7\xc1\xd1 \xf3\xd4\xd2\xcf\xcb\xc1."), /* "Тестовая Строка." in KOI8-R */ D_STR_W_LEN ("\xf4\xe5\xf3\xf4\xef\xf7\xe1\xf1 \xf3\xf4\xf2\xef\xeb\xe1."), 1}, /* "ТЕСТОВАЯ СТРОКА." in KOI8-R */ {D_STR_W_LEN ("\xc2\xd5\xe1\xe2\xde\xd2\xd0\xef \xc1\xe2\xe0\xde\xda\xd0."), /* "Тестовая Строка." in ISO-8859-5 */ D_STR_W_LEN ("\xc2\xb5\xc1\xc2\xbe\xb2\xb0\xcf \xc1\xc2\xc0\xbe\xba\xb0."), 1}, /* "ТЕСТОВАЯ СТРОКА." in ISO-8859-5 */ {D_STR_W_LEN ("\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbe\xd0\xb2\xd0\xb0\xd1" "\x8f \xd0\xa1\xd1\x82\xd1\x80\xd0\xbe\xd0\xba\xd0\xb0."), /* "Тестовая Строка." in UTF-8 */ D_STR_W_LEN ("\xd0\xa2\xd0\x95\xd0\xa1\xd0\xa2\xd0\x9e\xd0\x92\xd0\x90\xd0" "\xaf \xd0\xa1\xd0\xa2\xd0\xa0\xd0\x9e\xd0\x9a\xd0\x90."), 3} /* "ТЕСТОВАЯ СТРОКА." in UTF-8 */ }; static size_t check_eq_strings (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(eq_strings) / sizeof(eq_strings[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { const struct two_eq_strs *const t = eq_strings + i; if (c_failed[i]) continue; /* skip already failed checks */ if (! MHD_str_equal_caseless_ (t->s1.str, t->s2.str)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned zero, while expected non-zero." " Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str), get_current_locale_str ()); } else if (! MHD_str_equal_caseless_ (t->s2.str, t->s1.str)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned zero, while expected non-zero." " Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str), get_current_locale_str ()); } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_equal_caseless_(\"%s\", \"%s\") != 0 && \\\n" " MHD_str_equal_caseless_(\"%s\", \"%s\") != 0\n", n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str), n_prnt (t->s1.str)); } } return t_failed; } static size_t check_neq_strings (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(neq_strings) / sizeof(neq_strings[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { const struct two_neq_strs *const t = neq_strings + i; if (c_failed[i]) continue; /* skip already failed checks */ if (MHD_str_equal_caseless_ (t->s1.str, t->s2.str)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned non-zero, while expected zero." " Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str), get_current_locale_str ()); } else if (MHD_str_equal_caseless_ (t->s2.str, t->s1.str)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_(\"%s\", \"%s\") returned non-zero, while expected zero." " Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str), get_current_locale_str ()); } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_equal_caseless_(\"%s\", \"%s\") == 0 && \\\n" " MHD_str_equal_caseless_(\"%s\", \"%s\") == 0\n", n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str), n_prnt (t->s1.str)); } } return t_failed; } static size_t check_eq_strings_n (void) { size_t t_failed = 0; size_t i, j, k; int c_failed[sizeof(eq_strings) / sizeof(eq_strings[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t m_len; const struct two_eq_strs *const t = eq_strings + i; m_len = (t->s1.len > t->s2.len) ? t->s1.len : t->s2.len; for (k = 0; k <= m_len + 1 && ! c_failed[i]; k++) { if (! MHD_str_equal_caseless_n_ (t->s1.str, t->s2.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero," " while expected non-zero. Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str), (unsigned int) k, get_current_locale_str ()); } else if (! MHD_str_equal_caseless_n_ (t->s2.str, t->s1.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero," " while expected non-zero. Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) k, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) " \ "!= 0 && \\\n" \ " MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) " \ "!= 0, where N is 0..%u\n", n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) m_len + 1); } } return t_failed; } static size_t check_neq_strings_n (void) { size_t t_failed = 0; size_t i, j, k; int c_failed[sizeof(neq_strings) / sizeof(neq_strings[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t m_len; const struct two_neq_strs *const t = neq_strings + i; m_len = t->s1.len > t->s2.len ? t->s1.len : t->s2.len; if (t->dif_pos >= m_len) { fprintf (stderr, "ERROR: neq_strings[%u] has wrong dif_pos (%u): dif_pos is expected to be less than " "s1.len (%u) or s2.len (%u).\n", (unsigned int) i, (unsigned int) t-> dif_pos, (unsigned int) t->s1.len, (unsigned int) t->s2.len); exit (99); } if (t->dif_pos > t->s1.len) { fprintf (stderr, "ERROR: neq_strings[%u] has wrong dif_pos (%u): dif_pos is expected to be less or " "equal to s1.len (%u).\n", (unsigned int) i, (unsigned int) t->dif_pos, (unsigned int) t->s1.len); exit (99); } if (t->dif_pos > t->s2.len) { fprintf (stderr, "ERROR: neq_strings[%u] has wrong dif_pos (%u): dif_pos is expected to be less or " "equal to s2.len (%u).\n", (unsigned int) i, (unsigned int) t->dif_pos, (unsigned int) t->s2.len); exit (99); } for (k = 0; k <= m_len + 1 && ! c_failed[i]; k++) { if (k <= t->dif_pos) { if (! MHD_str_equal_caseless_n_ (t->s1.str, t->s2.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero," " while expected non-zero. Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str), (unsigned int) k, get_current_locale_str ()); } else if (! MHD_str_equal_caseless_n_ (t->s2.str, t->s1.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned zero," " while expected non-zero. Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) k, get_current_locale_str ()); } } else { if (MHD_str_equal_caseless_n_ (t->s1.str, t->s2.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned non-zero," " while expected zero. Locale: %s\n", n_prnt (t->s1.str), n_prnt (t->s2.str), (unsigned int) k, get_current_locale_str ()); } else if (MHD_str_equal_caseless_n_ (t->s2.str, t->s1.str, k)) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", %u) returned non-zero," " while expected zero. Locale: %s\n", n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) k, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) { printf ( "PASSED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) != 0 && \\\n" " MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) != 0, where N is 0..%u\n", n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) t->dif_pos); printf ( "PASSED: MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) == 0 && \\\n" " MHD_str_equal_caseless_n_(\"%s\", \"%s\", N) == 0, where N is %u..%u\n", n_prnt (t->s1.str), n_prnt (t->s2.str), n_prnt (t->s2.str), n_prnt (t->s1.str), (unsigned int) t->dif_pos + 1, (unsigned int) m_len + 1); } } } return t_failed; } /* * Run eq/neq strings tests */ static int run_eq_neq_str_tests (void) { size_t str_equal_caseless_fails = 0; size_t str_equal_caseless_n_fails = 0; size_t res; res = check_eq_strings (); if (res != 0) { str_equal_caseless_fails += res; fprintf (stderr, "FAILED: testcase check_eq_strings() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_eq_strings() successfully passed.\n\n"); res = check_neq_strings (); if (res != 0) { str_equal_caseless_fails += res; fprintf (stderr, "FAILED: testcase check_neq_strings() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_neq_strings() successfully passed.\n\n"); if (str_equal_caseless_fails) fprintf (stderr, "FAILED: function MHD_str_equal_caseless_() failed %lu time%s.\n\n", (unsigned long) str_equal_caseless_fails, str_equal_caseless_fails == 1 ? "" : "s"); else if (verbose > 0) printf ( "PASSED: function MHD_str_equal_caseless_() successfully passed all checks.\n\n"); res = check_eq_strings_n (); if (res != 0) { str_equal_caseless_n_fails += res; fprintf (stderr, "FAILED: testcase check_eq_strings_n() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_eq_strings_n() successfully passed.\n\n"); res = check_neq_strings_n (); if (res != 0) { str_equal_caseless_n_fails += res; fprintf (stderr, "FAILED: testcase check_neq_strings_n() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_neq_strings_n() successfully passed.\n\n"); if (str_equal_caseless_n_fails) fprintf (stderr, "FAILED: function MHD_str_equal_caseless_n_() failed %lu time%s.\n\n", (unsigned long) str_equal_caseless_n_fails, str_equal_caseless_n_fails == 1 ? "" : "s"); else if (verbose > 0) printf ( "PASSED: function MHD_str_equal_caseless_n_() successfully passed all checks.\n\n"); if (str_equal_caseless_fails || str_equal_caseless_n_fails) { if (verbose > 0) printf ("At least one test failed.\n"); return 1; } if (verbose > 0) printf ("All tests passed successfully.\n"); return 0; } /* * Digits in string -> value tests */ struct str_with_value { const struct str_with_len str; const size_t num_of_digt; const uint64_t val; }; /* valid string for conversion to unsigned integer value */ static const struct str_with_value dstrs_w_values[] = { /* simplest strings */ {D_STR_W_LEN ("1"), 1, 1}, {D_STR_W_LEN ("0"), 1, 0}, {D_STR_W_LEN ("10000"), 5, 10000}, /* all digits */ {D_STR_W_LEN ("1234"), 4, 1234}, {D_STR_W_LEN ("4567"), 4, 4567}, {D_STR_W_LEN ("7890"), 4, 7890}, {D_STR_W_LEN ("8021"), 4, 8021}, {D_STR_W_LEN ("9754"), 4, 9754}, {D_STR_W_LEN ("6392"), 4, 6392}, /* various prefixes */ {D_STR_W_LEN ("00000000"), 8, 0}, {D_STR_W_LEN ("0755"), 4, 755}, /* not to be interpreted as octal value! */ {D_STR_W_LEN ("002"), 3, 2}, {D_STR_W_LEN ("0001"), 4, 1}, {D_STR_W_LEN ("00000000000000000000000031295483"), 32, 31295483}, /* numbers below and above limits */ {D_STR_W_LEN ("127"), 3, 127}, /* 0x7F, SCHAR_MAX */ {D_STR_W_LEN ("128"), 3, 128}, /* 0x80, SCHAR_MAX+1 */ {D_STR_W_LEN ("255"), 3, 255}, /* 0xFF, UCHAR_MAX */ {D_STR_W_LEN ("256"), 3, 256}, /* 0x100, UCHAR_MAX+1 */ {D_STR_W_LEN ("32767"), 5, 32767}, /* 0x7FFF, INT16_MAX */ {D_STR_W_LEN ("32768"), 5, 32768}, /* 0x8000, INT16_MAX+1 */ {D_STR_W_LEN ("65535"), 5, 65535}, /* 0xFFFF, UINT16_MAX */ {D_STR_W_LEN ("65536"), 5, 65536}, /* 0x10000, UINT16_MAX+1 */ {D_STR_W_LEN ("2147483647"), 10, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */ {D_STR_W_LEN ("2147483648"), 10, UINT64_C (2147483648)}, /* 0x80000000, INT32_MAX+1 */ {D_STR_W_LEN ("4294967295"), 10, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */ {D_STR_W_LEN ("4294967296"), 10, UINT64_C (4294967296)}, /* 0x100000000, UINT32_MAX+1 */ {D_STR_W_LEN ("9223372036854775807"), 19, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */ {D_STR_W_LEN ("9223372036854775808"), 19, UINT64_C (9223372036854775808)}, /* 0x8000000000000000, INT64_MAX+1 */ {D_STR_W_LEN ("18446744073709551615"), 20, UINT64_C (18446744073709551615)}, /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */ /* random numbers */ {D_STR_W_LEN ("10186753"), 8, 10186753}, {D_STR_W_LEN ("144402566"), 9, 144402566}, {D_STR_W_LEN ("151903144"), 9, 151903144}, {D_STR_W_LEN ("139264621"), 9, 139264621}, {D_STR_W_LEN ("730348"), 6, 730348}, {D_STR_W_LEN ("21584377"), 8, 21584377}, {D_STR_W_LEN ("709"), 3, 709}, {D_STR_W_LEN ("54"), 2, 54}, {D_STR_W_LEN ("8452"), 4, 8452}, {D_STR_W_LEN ("17745098750013624977"), 20, UINT64_C (17745098750013624977)}, {D_STR_W_LEN ("06786878769931678000"), 20, UINT64_C (6786878769931678000)}, /* non-digit suffixes */ {D_STR_W_LEN ("1234oa"), 4, 1234}, {D_STR_W_LEN ("20h"), 2, 20}, /* not to be interpreted as hex value! */ {D_STR_W_LEN ("0x1F"), 1, 0}, /* not to be interpreted as hex value! */ {D_STR_W_LEN ("0564`~}"), 4, 564}, {D_STR_W_LEN ("7240146.724"), 7, 7240146}, {D_STR_W_LEN ("2,9"), 1, 2}, {D_STR_W_LEN ("200+1"), 3, 200}, {D_STR_W_LEN ("1a"), 1, 1}, {D_STR_W_LEN ("2E"), 1, 2}, {D_STR_W_LEN ("6c"), 1, 6}, {D_STR_W_LEN ("8F"), 1, 8}, {D_STR_W_LEN ("287416997! And the not too long string."), 9, 287416997} }; /* strings that should overflow uint64_t */ static const struct str_with_len str_ovflw[] = { D_STR_W_LEN ("18446744073709551616"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("18446744073709551620"), D_STR_W_LEN ("18446744083709551615"), D_STR_W_LEN ("19234761020556472143"), D_STR_W_LEN ("184467440737095516150"), D_STR_W_LEN ("1844674407370955161500"), D_STR_W_LEN ("000018446744073709551616"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("20000000000000000000"), D_STR_W_LEN ("020000000000000000000"), D_STR_W_LEN ("0020000000000000000000"), D_STR_W_LEN ("100000000000000000000"), D_STR_W_LEN ("434532891232591226417"), D_STR_W_LEN ("99999999999999999999"), D_STR_W_LEN ("18446744073709551616abcd"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("20000000000000000000 suffix"), D_STR_W_LEN ("020000000000000000000x") }; /* strings that should not be convertible to numeric value */ static const struct str_with_len str_no_num[] = { D_STR_W_LEN ("zero"), D_STR_W_LEN ("one"), D_STR_W_LEN ("\xb9\xb2\xb3"), /* superscript "123" in ISO-8859-1/CP1252 */ D_STR_W_LEN ("\xc2\xb9\xc2\xb2\xc2\xb3"), /* superscript "123" in UTF-8 */ D_STR_W_LEN ("\xd9\xa1\xd9\xa2\xd9\xa3"), /* Arabic-Indic "١٢٣" in UTF-8 */ D_STR_W_LEN ("\xdb\xb1\xdb\xb2\xdb\xb3"), /* Ext Arabic-Indic "۱۲۳" in UTF-8 */ D_STR_W_LEN ("\xe0\xa5\xa7\xe0\xa5\xa8\xe0\xa5\xa9"), /* Devanagari "१२३" in UTF-8 */ D_STR_W_LEN ("\xe4\xb8\x80\xe4\xba\x8c\xe4\xb8\x89"), /* Chinese "一二三" in UTF-8 */ D_STR_W_LEN ("\xd2\xbb\xb6\xfe\xc8\xfd"), /* Chinese "一二三" in GB2312/CP936 */ D_STR_W_LEN ("\x1B\x24\x29\x41\x0E\x52\x3B\x36\x7E\x48\x7D\x0F") /* Chinese "一二三" in ISO-2022-CN */ }; /* valid hex string for conversion to unsigned integer value */ static const struct str_with_value xdstrs_w_values[] = { /* simplest strings */ {D_STR_W_LEN ("1"), 1, 0x1}, {D_STR_W_LEN ("0"), 1, 0x0}, {D_STR_W_LEN ("10000"), 5, 0x10000}, /* all digits */ {D_STR_W_LEN ("1234"), 4, 0x1234}, {D_STR_W_LEN ("4567"), 4, 0x4567}, {D_STR_W_LEN ("7890"), 4, 0x7890}, {D_STR_W_LEN ("8021"), 4, 0x8021}, {D_STR_W_LEN ("9754"), 4, 0x9754}, {D_STR_W_LEN ("6392"), 4, 0x6392}, {D_STR_W_LEN ("abcd"), 4, 0xABCD}, {D_STR_W_LEN ("cdef"), 4, 0xCDEF}, {D_STR_W_LEN ("FEAB"), 4, 0xFEAB}, {D_STR_W_LEN ("BCED"), 4, 0xBCED}, {D_STR_W_LEN ("bCeD"), 4, 0xBCED}, {D_STR_W_LEN ("1A5F"), 4, 0x1A5F}, {D_STR_W_LEN ("12AB"), 4, 0x12AB}, {D_STR_W_LEN ("CD34"), 4, 0xCD34}, {D_STR_W_LEN ("56EF"), 4, 0x56EF}, {D_STR_W_LEN ("7a9f"), 4, 0x7A9F}, /* various prefixes */ {D_STR_W_LEN ("00000000"), 8, 0x0}, {D_STR_W_LEN ("0755"), 4, 0x755}, /* not to be interpreted as octal value! */ {D_STR_W_LEN ("002"), 3, 0x2}, {D_STR_W_LEN ("0001"), 4, 0x1}, {D_STR_W_LEN ("00a"), 3, 0xA}, {D_STR_W_LEN ("0F"), 2, 0xF}, {D_STR_W_LEN ("0000000000000000000000003A29e4C3"), 32, 0x3A29E4C3}, /* numbers below and above limits */ {D_STR_W_LEN ("7F"), 2, 127}, /* 0x7F, SCHAR_MAX */ {D_STR_W_LEN ("7f"), 2, 127}, /* 0x7F, SCHAR_MAX */ {D_STR_W_LEN ("80"), 2, 128}, /* 0x80, SCHAR_MAX+1 */ {D_STR_W_LEN ("fF"), 2, 255}, /* 0xFF, UCHAR_MAX */ {D_STR_W_LEN ("Ff"), 2, 255}, /* 0xFF, UCHAR_MAX */ {D_STR_W_LEN ("FF"), 2, 255}, /* 0xFF, UCHAR_MAX */ {D_STR_W_LEN ("ff"), 2, 255}, /* 0xFF, UCHAR_MAX */ {D_STR_W_LEN ("100"), 3, 256}, /* 0x100, UCHAR_MAX+1 */ {D_STR_W_LEN ("7fff"), 4, 32767}, /* 0x7FFF, INT16_MAX */ {D_STR_W_LEN ("7FFF"), 4, 32767}, /* 0x7FFF, INT16_MAX */ {D_STR_W_LEN ("7Fff"), 4, 32767}, /* 0x7FFF, INT16_MAX */ {D_STR_W_LEN ("8000"), 4, 32768}, /* 0x8000, INT16_MAX+1 */ {D_STR_W_LEN ("ffff"), 4, 65535}, /* 0xFFFF, UINT16_MAX */ {D_STR_W_LEN ("FFFF"), 4, 65535}, /* 0xFFFF, UINT16_MAX */ {D_STR_W_LEN ("FffF"), 4, 65535}, /* 0xFFFF, UINT16_MAX */ {D_STR_W_LEN ("10000"), 5, 65536}, /* 0x10000, UINT16_MAX+1 */ {D_STR_W_LEN ("7FFFFFFF"), 8, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */ {D_STR_W_LEN ("7fffffff"), 8, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */ {D_STR_W_LEN ("7FFffFff"), 8, 2147483647}, /* 0x7FFFFFFF, INT32_MAX */ {D_STR_W_LEN ("80000000"), 8, UINT64_C (2147483648)}, /* 0x80000000, INT32_MAX+1 */ {D_STR_W_LEN ("FFFFFFFF"), 8, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */ {D_STR_W_LEN ("ffffffff"), 8, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */ {D_STR_W_LEN ("FfFfFfFf"), 8, UINT64_C (4294967295)}, /* 0xFFFFFFFF, UINT32_MAX */ {D_STR_W_LEN ("100000000"), 9, UINT64_C (4294967296)}, /* 0x100000000, UINT32_MAX+1 */ {D_STR_W_LEN ("7fffffffffffffff"), 16, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */ {D_STR_W_LEN ("7FFFFFFFFFFFFFFF"), 16, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */ {D_STR_W_LEN ("7FfffFFFFffFFffF"), 16, UINT64_C (9223372036854775807)}, /* 0x7FFFFFFFFFFFFFFF, INT64_MAX */ {D_STR_W_LEN ("8000000000000000"), 16, UINT64_C (9223372036854775808)}, /* 0x8000000000000000, INT64_MAX+1 */ {D_STR_W_LEN ("ffffffffffffffff"), 16, UINT64_C (18446744073709551615)}, /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */ {D_STR_W_LEN ("FFFFFFFFFFFFFFFF"), 16, UINT64_C (18446744073709551615)}, /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */ {D_STR_W_LEN ("FffFffFFffFFfFFF"), 16, UINT64_C (18446744073709551615)}, /* 0xFFFFFFFFFFFFFFFF, UINT64_MAX */ /* random numbers */ {D_STR_W_LEN ("10186753"), 8, 0x10186753}, {D_STR_W_LEN ("144402566"), 9, 0x144402566}, {D_STR_W_LEN ("151903144"), 9, 0x151903144}, {D_STR_W_LEN ("139264621"), 9, 0x139264621}, {D_STR_W_LEN ("730348"), 6, 0x730348}, {D_STR_W_LEN ("21584377"), 8, 0x21584377}, {D_STR_W_LEN ("709"), 3, 0x709}, {D_STR_W_LEN ("54"), 2, 0x54}, {D_STR_W_LEN ("8452"), 4, 0x8452}, {D_STR_W_LEN ("22353EC6"), 8, 0x22353EC6}, {D_STR_W_LEN ("307F1655"), 8, 0x307F1655}, {D_STR_W_LEN ("1FCB7226"), 8, 0x1FCB7226}, {D_STR_W_LEN ("82480560"), 8, 0x82480560}, {D_STR_W_LEN ("7386D95"), 7, 0x7386D95}, {D_STR_W_LEN ("EC3AB"), 5, 0xEC3AB}, {D_STR_W_LEN ("6DD05"), 5, 0x6DD05}, {D_STR_W_LEN ("C5DF"), 4, 0xC5DF}, {D_STR_W_LEN ("6CE"), 3, 0x6CE}, {D_STR_W_LEN ("CE6"), 3, 0xCE6}, {D_STR_W_LEN ("ce6"), 3, 0xCE6}, {D_STR_W_LEN ("F27"), 3, 0xF27}, {D_STR_W_LEN ("8497D54277D7E1"), 14, UINT64_C (37321639124785121)}, {D_STR_W_LEN ("8497d54277d7e1"), 14, UINT64_C (37321639124785121)}, {D_STR_W_LEN ("8497d54277d7E1"), 14, UINT64_C (37321639124785121)}, {D_STR_W_LEN ("8C8112D0A06"), 11, UINT64_C (9655374645766)}, {D_STR_W_LEN ("8c8112d0a06"), 11, UINT64_C (9655374645766)}, {D_STR_W_LEN ("8c8112d0A06"), 11, UINT64_C (9655374645766)}, {D_STR_W_LEN ("1774509875001362"), 16, UINT64_C (1690064375898968930)}, {D_STR_W_LEN ("0678687876998000"), 16, UINT64_C (466237428027981824)}, /* non-digit suffixes */ {D_STR_W_LEN ("1234oa"), 4, 0x1234}, {D_STR_W_LEN ("20h"), 2, 0x20}, {D_STR_W_LEN ("2CH"), 2, 0x2C}, {D_STR_W_LEN ("2ch"), 2, 0x2C}, {D_STR_W_LEN ("0x1F"), 1, 0x0}, /* not to be interpreted as hex prefix! */ {D_STR_W_LEN ("0564`~}"), 4, 0x564}, {D_STR_W_LEN ("0A64`~}"), 4, 0xA64}, {D_STR_W_LEN ("056c`~}"), 4, 0X56C}, {D_STR_W_LEN ("7240146.724"), 7, 0x7240146}, {D_STR_W_LEN ("7E4c1AB.724"), 7, 0X7E4C1AB}, {D_STR_W_LEN ("F24B1B6.724"), 7, 0xF24B1B6}, {D_STR_W_LEN ("2,9"), 1, 0x2}, {D_STR_W_LEN ("a,9"), 1, 0xA}, {D_STR_W_LEN ("200+1"), 3, 0x200}, {D_STR_W_LEN ("2cc+1"), 3, 0x2CC}, {D_STR_W_LEN ("2cC+1"), 3, 0x2CC}, {D_STR_W_LEN ("27416997! And the not too long string."), 8, 0x27416997}, {D_STR_W_LEN ("27555416997! And the not too long string."), 11, 0x27555416997}, {D_STR_W_LEN ("416997And the not too long string."), 7, 0x416997A}, {D_STR_W_LEN ("0F4C3Dabstract addition to make string even longer"), 8, 0xF4C3DAB} }; /* hex strings that should overflow uint64_t */ static const struct str_with_len strx_ovflw[] = { D_STR_W_LEN ("10000000000000000"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("10000000000000001"), D_STR_W_LEN ("10000000000000002"), D_STR_W_LEN ("1000000000000000A"), D_STR_W_LEN ("11000000000000000"), D_STR_W_LEN ("010000000000000000"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("000010000000000000000"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("20000000000000000000"), D_STR_W_LEN ("020000000000000000000"), D_STR_W_LEN ("0020000000000000000000"), D_STR_W_LEN ("20000000000000000"), D_STR_W_LEN ("A0000000000000000"), D_STR_W_LEN ("F0000000000000000"), D_STR_W_LEN ("a0000000000000000"), D_STR_W_LEN ("11111111111111111"), D_STR_W_LEN ("CcCcCCccCCccCCccC"), D_STR_W_LEN ("f0000000000000000"), D_STR_W_LEN ("100000000000000000000"), D_STR_W_LEN ("434532891232591226417"), D_STR_W_LEN ("10000000000000000a"), D_STR_W_LEN ("10000000000000000E"), D_STR_W_LEN ("100000000000000000 and nothing"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("100000000000000000xx"), /* 0x10000000000000000, UINT64_MAX+1 */ D_STR_W_LEN ("99999999999999999999"), D_STR_W_LEN ("18446744073709551616abcd"), D_STR_W_LEN ("20000000000000000000 suffix"), D_STR_W_LEN ("020000000000000000000x") }; static size_t check_str_to_uint64_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(dstrs_w_values) / sizeof(dstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint64_t rv; size_t rs; const struct str_with_value *const t = dstrs_w_values + i; if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } rv = 9435223; /* some random value */ rs = MHD_str_to_uint64_ (t->str.str, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", n_prnt (t->str.str), rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") converted string to value %" PRIu64 "," " while expecting result %" PRIu64 ". Locale: %s\n", n_prnt (t->str.str), rv, rv, t->val, get_current_locale_str ()); } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") == %" \ PRIuPTR "\n", n_prnt (t->str.str), rv, rs); } } return t_failed; } static size_t check_str_to_uint64_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint64_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint64_t rnd_val = 24941852; size_t rs; if ((c >= '0') && (c <= '9') ) continue; /* skip digits */ for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint64_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_str_to_uint64_ (test_str, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (test_str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: %" PRIu64 ", after call %" PRIu64 "). Locale: %s\n", n_prnt (test_str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_str_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_str_to_uint64_overflow (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_ovflw) / sizeof(str_ovflw[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_ovflw + i; static const uint64_t rnd_val = 2; uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_str_to_uint64_ (t->str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: %" PRIu64 ", after call %" PRIu64 "). Locale: %s\n", n_prnt (t->str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (t->str)); } } return t_failed; } static size_t check_str_to_uint64_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint64_t rnd_val = 74218431; uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_str_to_uint64_ (t->str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", ->%" PRIu64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: %" PRIu64 ", after call %" PRIu64 "). Locale: %s\n", n_prnt (t->str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (t->str)); } } return t_failed; } static size_t check_str_to_uint64_n_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(dstrs_w_values) / sizeof(dstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint64_t rv = 1235572; /* some random value */ size_t rs = 0; size_t len; const struct str_with_value *const t = dstrs_w_values + i; if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } for (len = t->num_of_digt; len <= t->str.len + 1 && ! c_failed[i]; len++) { rs = MHD_str_to_uint64_n_ (t->str.str, len, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%" PRIu64 ")" " returned %" PRIuPTR ", while expecting %d. Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%" PRIu64 ")" " converted string to value %" PRIu64 ", while expecting result %" PRIu64 ". Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, rv, rv, t->val, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", ->%" PRIu64 ")" " == %" PRIuPTR "\n", n_prnt (t->str.str), (uintptr_t) t->num_of_digt, (uintptr_t) t->str.len + 1, rv, rs); } } return t_failed; } static size_t check_str_to_uint64_n_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint64_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint64_t rnd_val = 98372558; size_t rs; size_t len; if ((c >= '0') && (c <= '9') ) continue; /* skip digits */ for (len = 0; len <= 5; len++) { for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint64_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_str_to_uint64_n_ (test_str, len, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%" PRIu64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (test_str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: %" PRIu64 ", after call %" PRIu64 ")." " Locale: %s\n", n_prnt (test_str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", 0..5, &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_str_to_uint64_n_overflow (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_ovflw) / sizeof(str_ovflw[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_ovflw + i; static const uint64_t rnd_val = 3; size_t len; for (len = t->len; len <= t->len + 1; len++) { uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_str_to_uint64_n_ (t->str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%" PRIu64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: %" PRIu64 ", after call %" PRIu64 ")." " Locale: %s\n", n_prnt (t->str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (t->str), (uintptr_t) t->len, (uintptr_t) t->len + 1); } } return t_failed; } static size_t check_str_to_uint64_n_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint64_t rnd_val = 43255654342; size_t len; for (len = 0; len <= t->len + 1; len++) { uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_str_to_uint64_n_ (t->str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", ->%" PRIu64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_str_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: %" PRIu64 ", after call %" PRIu64 ")." " Locale: %s\n", n_prnt (t->str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_str_to_uint64_n_(\"%s\", 0..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (t->str), (uintptr_t) t->len + 1); } } return t_failed; } static size_t check_strx_to_uint32_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint32_t rv; size_t rs; const struct str_with_value *const t = xdstrs_w_values + i; if (t->val > UINT32_MAX) continue; /* number is too high for this function */ if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } rv = 1458532; /* some random value */ rs = MHD_strx_to_uint32_ (t->str.str, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", n_prnt (t->str.str), (uint64_t) rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") converted string to value 0x%" PRIX64 "," " while expecting result 0x%" PRIX64 ". Locale: %s\n", n_prnt (t->str.str), (uint64_t) rv, (uint64_t) rv, t->val, get_current_locale_str ()); } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") == %" PRIuPTR "\n", n_prnt (t->str.str), (uint64_t) rv, rs); } } return t_failed; } static size_t check_strx_to_uint32_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint32_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint32_t rnd_val = 234234; size_t rs; if (( (c >= '0') && (c <= '9') ) || ( (c >= 'A') && (c <= 'F') ) || ( (c >= 'a') && (c <= 'f') )) continue; /* skip xdigits */ for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint32_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_strx_to_uint32_ (test_str, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (test_str), (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (test_str), (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_strx_to_uint32_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_strx_to_uint32_overflow (void) { size_t t_failed = 0; size_t i, j; static const size_t n_checks1 = sizeof(strx_ovflw) / sizeof(strx_ovflw[0]); int c_failed[(sizeof(strx_ovflw) / sizeof(strx_ovflw[0])) + (sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0]))]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; static const uint32_t rnd_val = 74218431; uint32_t test_val; const char *str; if (i < n_checks1) { const struct str_with_len *const t = strx_ovflw + i; str = t->str; } else { const struct str_with_value *const t = xdstrs_w_values + (i - n_checks1); if (t->val <= UINT32_MAX) continue; /* check only strings that should overflow uint32_t */ str = t->str.str; } for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint32_t rv = test_val; rs = MHD_strx_to_uint32_ (str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (str), (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (str), (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint32_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (str)); } } return t_failed; } static size_t check_strx_to_uint32_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint32_t rnd_val = 74218431; uint32_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint32_t rv = test_val; rs = MHD_strx_to_uint32_ (t->str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (t->str), (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (t->str), (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint32_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (t->str)); } } return t_failed; } static size_t check_strx_to_uint32_n_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint32_t rv = 2352932; /* some random value */ size_t rs = 0; size_t len; const struct str_with_value *const t = xdstrs_w_values + i; if (t->val > UINT32_MAX) continue; /* number is too high for this function */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } for (len = t->num_of_digt; len <= t->str.len + 1 && ! c_failed[i]; len++) { rs = MHD_strx_to_uint32_n_ (t->str.str, len, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting %d. Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, (uint64_t) rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " converted string to value 0x%" PRIX64 ", while expecting result 0x%" PRIX64 ". Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, (uint64_t) rv, (uint64_t) rv, t->val, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ( "PASSED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", ->0x%" PRIX64 ")" " == %" PRIuPTR "\n", n_prnt (t->str.str), (uintptr_t) t->num_of_digt, (uintptr_t) t->str.len + 1, (uint64_t) rv, rs); } } return t_failed; } static size_t check_strx_to_uint32_n_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint32_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint32_t rnd_val = 98372558; size_t rs; size_t len; if (( (c >= '0') && (c <= '9') ) || ( (c >= 'A') && (c <= 'F') ) || ( (c >= 'a') && (c <= 'f') )) continue; /* skip xdigits */ for (len = 0; len <= 5; len++) { for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint32_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_strx_to_uint32_n_ (test_str, len, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (test_str), (uintptr_t) len, (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (test_str), (uintptr_t) len, (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_strx_to_uint32_n_(\"%s\", 0..5, &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_strx_to_uint32_n_overflow (void) { size_t t_failed = 0; size_t i, j; static const size_t n_checks1 = sizeof(strx_ovflw) / sizeof(strx_ovflw[0]); int c_failed[(sizeof(strx_ovflw) / sizeof(strx_ovflw[0])) + (sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0]))]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; static const uint32_t rnd_val = 4; size_t len; const char *str; size_t min_len, max_len; if (i < n_checks1) { const struct str_with_len *const t = strx_ovflw + i; str = t->str; min_len = t->len; max_len = t->len + 1; } else { const struct str_with_value *const t = xdstrs_w_values + (i - n_checks1); if (t->val <= UINT32_MAX) continue; /* check only strings that should overflow uint32_t */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) (i - n_checks1), (unsigned int) t->num_of_digt, (unsigned int) t->str.len); exit (99); } str = t->str.str; min_len = t->num_of_digt; max_len = t->str.len + 1; } for (len = min_len; len <= max_len; len++) { uint32_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint32_t rv = test_val; rs = MHD_strx_to_uint32_n_ (str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (str), (uintptr_t) len, (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (str), (uintptr_t) len, (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (str), (uintptr_t) min_len, (uintptr_t) max_len); } } return t_failed; } static size_t check_strx_to_uint32_n_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint32_t rnd_val = 3214314212UL; size_t len; for (len = 0; len <= t->len + 1; len++) { uint32_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint32_t rv = test_val; rs = MHD_strx_to_uint32_n_ (t->str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (t->str), (uintptr_t) len, (uint64_t) rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint32_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (t->str), (uintptr_t) len, (uint64_t) test_val, (uint64_t) rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint32_n_(\"%s\", 0..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (t->str), (uintptr_t) t->len + 1); } } return t_failed; } static size_t check_strx_to_uint64_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint64_t rv; size_t rs; const struct str_with_value *const t = xdstrs_w_values + i; if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } rv = 1458532; /* some random value */ rs = MHD_strx_to_uint64_ (t->str.str, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", n_prnt (t->str.str), rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") converted string to value 0x%" PRIX64 "," " while expecting result 0x%" PRIX64 ". Locale: %s\n", n_prnt (t->str.str), rv, rv, t->val, get_current_locale_str ()); } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") == %" PRIuPTR "\n", n_prnt (t->str.str), rv, rs); } } return t_failed; } static size_t check_strx_to_uint64_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint64_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint64_t rnd_val = 234234; size_t rs; if (( (c >= '0') && (c <= '9') ) || ( (c >= 'A') && (c <= 'F') ) || ( (c >= 'a') && (c <= 'f') )) continue; /* skip xdigits */ for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint64_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_strx_to_uint64_ (test_str, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (test_str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (test_str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_strx_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_strx_to_uint64_overflow (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(strx_ovflw) / sizeof(strx_ovflw[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = strx_ovflw + i; static const uint64_t rnd_val = 74218431; uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_strx_to_uint64_ (t->str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (t->str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (t->str)); } } return t_failed; } static size_t check_strx_to_uint64_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint64_t rnd_val = 74218431; uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_strx_to_uint64_ (t->str, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", ->0x%" PRIX64 ") returned %" PRIuPTR ", while expecting zero." " Locale: %s\n", n_prnt (t->str), rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_(\"%s\", &ret_val) modified value of ret_val" " (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 "). Locale: %s\n", n_prnt (t->str), test_val, rv, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_(\"%s\", &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (t->str)); } } return t_failed; } static size_t check_strx_to_uint64_n_valid (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { uint64_t rv = 2352932; /* some random value */ size_t rs = 0; size_t len; const struct str_with_value *const t = xdstrs_w_values + i; if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: xdstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } for (len = t->num_of_digt; len <= t->str.len + 1 && ! c_failed[i]; len++) { rs = MHD_strx_to_uint64_n_ (t->str.str, len, &rv); if (rs != t->num_of_digt) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting %d. Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, rv, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } if (rv != t->val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " converted string to value 0x%" PRIX64 ", while expecting result 0x%" PRIX64 ". Locale: %s\n", n_prnt (t->str.str), (uintptr_t) len, rv, rv, t->val, get_current_locale_str ()); } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", ->0x%" PRIX64 ")" " == %" PRIuPTR "\n", n_prnt (t->str.str), (uintptr_t) t->num_of_digt, (uintptr_t) t->str.len + 1, rv, rs); } } return t_failed; } static size_t check_strx_to_uint64_n_all_chars (void) { int c_failed[256]; /* from 0 to 255 */ static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); size_t t_failed = 0; size_t j; memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { unsigned int c; uint64_t test_val; set_test_locale (j); /* setlocale() can be slow! */ for (c = 0; c < n_checks; c++) { static const uint64_t rnd_val = 98372558; size_t rs; size_t len; if (( (c >= '0') && (c <= '9') ) || ( (c >= 'A') && (c <= 'F') ) || ( (c >= 'a') && (c <= 'f') )) continue; /* skip xdigits */ for (len = 0; len <= 5; len++) { for (test_val = 0; test_val <= rnd_val && ! c_failed[c]; test_val += rnd_val) { char test_str[] = "0123"; uint64_t rv = test_val; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ rs = MHD_strx_to_uint64_n_ (test_str, len, &rv); if (rs != 0) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (test_str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[c] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (test_str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[c]) { char test_str[] = "0123"; test_str[0] = (char) (unsigned char) c; /* replace first char with non-digit char */ printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", 0..5, &ret_val) == 0, " "value of ret_val is unmodified\n", n_prnt (test_str)); } } } return t_failed; } static size_t check_strx_to_uint64_n_overflow (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(strx_ovflw) / sizeof(strx_ovflw[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = strx_ovflw + i; static const uint64_t rnd_val = 4; size_t len; for (len = t->len; len <= t->len + 1; len++) { uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_strx_to_uint64_n_ (t->str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (t->str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR "..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (t->str), (uintptr_t) t->len, (uintptr_t) t->len + 1); } } return t_failed; } static size_t check_strx_to_uint64_n_no_val (void) { size_t t_failed = 0; size_t i, j; int c_failed[sizeof(str_no_num) / sizeof(str_no_num[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { size_t rs; const struct str_with_len *const t = str_no_num + i; static const uint64_t rnd_val = 3214314212UL; size_t len; for (len = 0; len <= t->len + 1; len++) { uint64_t test_val; for (test_val = 0; test_val <= rnd_val && ! c_failed[i]; test_val += rnd_val) { uint64_t rv = test_val; rs = MHD_strx_to_uint64_n_ (t->str, len, &rv); if (rs != 0) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", ->0x%" PRIX64 ")" " returned %" PRIuPTR ", while expecting zero. Locale: %s\n", n_prnt (t->str), (uintptr_t) len, rv, (uintptr_t) rs, get_current_locale_str ()); } else if (rv != test_val) { t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_strx_to_uint64_n_(\"%s\", %" PRIuPTR ", &ret_val)" " modified value of ret_val (before call: 0x%" PRIX64 ", after call 0x%" PRIX64 ")." " Locale: %s\n", n_prnt (t->str), (uintptr_t) len, test_val, rv, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_strx_to_uint64_n_(\"%s\", 0..%" PRIuPTR ", &ret_val) == 0," " value of ret_val is unmodified\n", n_prnt (t->str), (uintptr_t) t->len + 1); } } return t_failed; } static int run_str_to_X_tests (void) { size_t str_to_uint64_fails = 0; size_t str_to_uint64_n_fails = 0; size_t strx_to_uint32_fails = 0; size_t strx_to_uint32_n_fails = 0; size_t strx_to_uint64_fails = 0; size_t strx_to_uint64_n_fails = 0; size_t res; res = check_str_to_uint64_valid (); if (res != 0) { str_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_valid() failed.\n\n"); } else if (verbose > 1) printf ( "PASSED: testcase check_str_to_uint64_valid() successfully passed.\n\n"); res = check_str_to_uint64_all_chars (); if (res != 0) { str_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_all_chars() " "successfully passed.\n\n"); res = check_str_to_uint64_overflow (); if (res != 0) { str_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_overflow() " "successfully passed.\n\n"); res = check_str_to_uint64_no_val (); if (res != 0) { str_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_no_val() " "successfully passed.\n\n"); if (str_to_uint64_fails) fprintf (stderr, "FAILED: function MHD_str_to_uint64_() failed %lu time%s.\n\n", (unsigned long) str_to_uint64_fails, str_to_uint64_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_str_to_uint64_() successfully " "passed all checks.\n\n"); res = check_str_to_uint64_n_valid (); if (res != 0) { str_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_n_valid() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_n_valid() " "successfully passed.\n\n"); res = check_str_to_uint64_n_all_chars (); if (res != 0) { str_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_n_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_n_all_chars() " "successfully passed.\n\n"); res = check_str_to_uint64_n_overflow (); if (res != 0) { str_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_n_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_n_overflow() " "successfully passed.\n\n"); res = check_str_to_uint64_n_no_val (); if (res != 0) { str_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_str_to_uint64_n_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_str_to_uint64_n_no_val() " "successfully passed.\n\n"); if (str_to_uint64_n_fails) fprintf (stderr, "FAILED: function MHD_str_to_uint64_n_() failed %lu time%s.\n\n", (unsigned long) str_to_uint64_n_fails, str_to_uint64_n_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_str_to_uint64_n_() successfully " "passed all checks.\n\n"); res = check_strx_to_uint32_valid (); if (res != 0) { strx_to_uint32_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_valid() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_valid() " "successfully passed.\n\n"); res = check_strx_to_uint32_all_chars (); if (res != 0) { strx_to_uint32_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_all_chars() " "successfully passed.\n\n"); res = check_strx_to_uint32_overflow (); if (res != 0) { strx_to_uint32_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_overflow() " "successfully passed.\n\n"); res = check_strx_to_uint32_no_val (); if (res != 0) { strx_to_uint32_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_no_val() " "successfully passed.\n\n"); if (strx_to_uint32_fails) fprintf (stderr, "FAILED: function MHD_strx_to_uint32_() failed %lu time%s.\n\n", (unsigned long) strx_to_uint32_fails, strx_to_uint32_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_strx_to_uint32_() successfully " "passed all checks.\n\n"); res = check_strx_to_uint32_n_valid (); if (res != 0) { strx_to_uint32_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_n_valid() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_n_valid() " "successfully passed.\n\n"); res = check_strx_to_uint32_n_all_chars (); if (res != 0) { strx_to_uint32_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_n_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_n_all_chars() " "successfully passed.\n\n"); res = check_strx_to_uint32_n_overflow (); if (res != 0) { strx_to_uint32_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_n_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_n_overflow() " "successfully passed.\n\n"); res = check_strx_to_uint32_n_no_val (); if (res != 0) { strx_to_uint32_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint32_n_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint32_n_no_val() " "successfully passed.\n\n"); if (strx_to_uint32_n_fails) fprintf (stderr, "FAILED: function MHD_strx_to_uint32_n_() failed %lu time%s.\n\n", (unsigned long) strx_to_uint32_n_fails, strx_to_uint32_n_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_strx_to_uint32_n_() successfully " "passed all checks.\n\n"); res = check_strx_to_uint64_valid (); if (res != 0) { strx_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_valid() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_valid() " "successfully passed.\n\n"); res = check_strx_to_uint64_all_chars (); if (res != 0) { strx_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_all_chars() " "successfully passed.\n\n"); res = check_strx_to_uint64_overflow (); if (res != 0) { strx_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_overflow() " "successfully passed.\n\n"); res = check_strx_to_uint64_no_val (); if (res != 0) { strx_to_uint64_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_no_val() " "successfully passed.\n\n"); if (strx_to_uint64_fails) fprintf (stderr, "FAILED: function MHD_strx_to_uint64_() failed %lu time%s.\n\n", (unsigned long) strx_to_uint64_fails, strx_to_uint64_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_strx_to_uint64_() successfully " "passed all checks.\n\n"); res = check_strx_to_uint64_n_valid (); if (res != 0) { strx_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_n_valid() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_n_valid() " "successfully passed.\n\n"); res = check_strx_to_uint64_n_all_chars (); if (res != 0) { strx_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_n_all_chars() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_n_all_chars() " "successfully passed.\n\n"); res = check_strx_to_uint64_n_overflow (); if (res != 0) { strx_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_n_overflow() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_n_overflow() " "successfully passed.\n\n"); res = check_strx_to_uint64_n_no_val (); if (res != 0) { strx_to_uint64_n_fails += res; fprintf (stderr, "FAILED: testcase check_strx_to_uint64_n_no_val() failed.\n\n"); } else if (verbose > 1) printf ("PASSED: testcase check_strx_to_uint64_n_no_val() " "successfully passed.\n\n"); if (strx_to_uint64_n_fails) fprintf (stderr, "FAILED: function MHD_strx_to_uint64_n_() failed %lu time%s.\n\n", (unsigned long) strx_to_uint64_n_fails, strx_to_uint64_n_fails == 1 ? "" : "s"); else if (verbose > 0) printf ("PASSED: function MHD_strx_to_uint64_n_() successfully " "passed all checks.\n\n"); if (str_to_uint64_fails || str_to_uint64_n_fails || strx_to_uint32_fails || strx_to_uint32_n_fails || strx_to_uint64_fails || strx_to_uint64_n_fails) { if (verbose > 0) printf ("At least one test failed.\n"); return 1; } if (verbose > 0) printf ("All tests passed successfully.\n"); return 0; } static size_t check_str_from_uint16 (void) { size_t t_failed = 0; size_t i, j; char buf[70]; const char *erase = "-@=sd#+&(pdiren456qwe#@C3S!DAS45AOIPUQWESAdFzxcv1s*()&#$%34`" "32452d098poiden45SADFFDA3S4D3SDFdfgsdfgsSADFzxdvs$*()द`" "adsf##$$@&*^%*^&56qwe#3C@S!DAScFAOIP$#%#$Ad1zs3v1$*()ӌ`"; int c_failed[sizeof(dstrs_w_values) / sizeof(dstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { const struct str_with_value *const t = dstrs_w_values + i; size_t b_size; size_t rs; if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } if ('0' == t->str.str[0]) continue; /* Skip strings prefixed with zeros */ if (t->num_of_digt != t->str.len) continue; /* Skip strings with suffixes */ if (UINT16_MAX < t->val) continue; /* Too large value to convert */ if (sizeof(buf) < t->str.len + 1) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has too long (%u) string, " "size of 'buf' should be increased.\n", (unsigned int) i, (unsigned int) t->str.len); exit (99); } rs = 0; /* Only to mute compiler warning */ for (b_size = 0; b_size <= t->str.len + 1; ++b_size) { /* fill buffer with pseudo-random values */ memcpy (buf, erase, sizeof(buf)); rs = MHD_uint16_to_str ((uint16_t) t->val, buf, b_size); if (t->num_of_digt > b_size) { /* Must fail, buffer is too small for result */ if (0 != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting 0." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } else { if (t->num_of_digt != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } else if (0 != memcmp (buf, t->str.str, t->num_of_digt)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR "." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } else if (0 != memcmp (buf + rs, erase + rs, sizeof(buf) - rs)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint16_to_str(%" PRIu64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR " and touched data after the resulting string." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_uint16_to_str(%" PRIu64 ", -> \"%.*s\", %d) " "== %" PRIuPTR "\n", t->val, (int) rs, buf, (int) b_size - 1, (uintptr_t) rs); } } return t_failed; } static size_t check_str_from_uint64 (void) { size_t t_failed = 0; size_t i, j; char buf[70]; const char *erase = "-@=sd#+&(pdirenDSFGSe#@C&S!DAS*!AOIPUQWESAdFzxcvSs*()&#$%KH`" "32452d098poiden45SADFFDA3S4D3SDFdfgsdfgsSADFzxdvs$*()द`" "adsf##$$@&*^%*^&56qwe#3C@S!DAScFAOIP$#%#$Ad1zs3v1$*()ӌ`"; int c_failed[sizeof(dstrs_w_values) / sizeof(dstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { const struct str_with_value *const t = dstrs_w_values + i; size_t b_size; size_t rs; if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } if ('0' == t->str.str[0]) continue; /* Skip strings prefixed with zeros */ if (t->num_of_digt != t->str.len) continue; /* Skip strings with suffixes */ if (sizeof(buf) < t->str.len + 1) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has too long (%u) string, " "size of 'buf' should be increased.\n", (unsigned int) i, (unsigned int) t->str.len); exit (99); } rs = 0; /* Only to mute compiler warning */ for (b_size = 0; b_size <= t->str.len + 1; ++b_size) { /* fill buffer with pseudo-random values */ memcpy (buf, erase, sizeof(buf)); rs = MHD_uint64_to_str (t->val, buf, b_size); if (t->num_of_digt > b_size) { /* Must fail, buffer is too small for result */ if (0 != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting 0." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } else { if (t->num_of_digt != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } else if (0 != memcmp (buf, t->str.str, t->num_of_digt)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR "." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } else if (0 != memcmp (buf + rs, erase + rs, sizeof(buf) - rs)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint64_to_str(%" PRIu64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR " and touched data after the resulting string." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_uint64_to_str(%" PRIu64 ", -> \"%.*s\", %d) " "== %" PRIuPTR "\n", t->val, (int) rs, buf, (int) b_size - 1, (uintptr_t) rs); } } return t_failed; } static size_t check_strx_from_uint32 (void) { size_t t_failed = 0; size_t i, j; char buf[70]; const char *erase = "jrlkjssfhjfvrjntJHLJ$@%$#adsfdkj;k$##$%#$%FGDF%$#^FDFG%$#$D`" ";skjdhjflsdkjhdjfalskdjhdfalkjdhf$%##%$$#%FSDGFSDDGDFSSDSDF`" "#5#$%#$#$DFSFDDFSGSDFSDF354FDDSGFDFfdssfddfswqemn,.zxih,.sx`"; int c_failed[sizeof(xdstrs_w_values) / sizeof(xdstrs_w_values[0])]; static const size_t n_checks = sizeof(c_failed) / sizeof(c_failed[0]); memset (c_failed, 0, sizeof(c_failed)); for (j = 0; j < locale_name_count; j++) { set_test_locale (j); /* setlocale() can be slow! */ for (i = 0; i < n_checks; i++) { const struct str_with_value *const t = xdstrs_w_values + i; size_t b_size; size_t rs; if (c_failed[i]) continue; /* skip already failed checks */ if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } if ('0' == t->str.str[0]) continue; /* Skip strings prefixed with zeros */ if (t->num_of_digt != t->str.len) continue; /* Skip strings with suffixes */ if (UINT32_MAX < t->val) continue; /* Too large value to convert */ if (sizeof(buf) < t->str.len + 1) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has too long (%u) string, " "size of 'buf' should be increased.\n", (unsigned int) i, (unsigned int) t->str.len); exit (99); } rs = 0; /* Only to mute compiler warning */ for (b_size = 0; b_size <= t->str.len + 1; ++b_size) { /* fill buffer with pseudo-random values */ memcpy (buf, erase, sizeof(buf)); rs = MHD_uint32_to_strx ((uint32_t) t->val, buf, b_size); if (t->num_of_digt > b_size) { /* Must fail, buffer is too small for result */ if (0 != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting 0." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } else { if (t->num_of_digt != rs) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> buf," " %d) returned %" PRIuPTR ", while expecting %d." " Locale: %s\n", t->val, (int) b_size, (uintptr_t) rs, (int) t->num_of_digt, get_current_locale_str ()); } else if (0 == MHD_str_equal_caseless_bin_n_ (buf, t->str.str, t->num_of_digt)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR "." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } else if (sizeof(buf) <= rs) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has string with too many" "(%u) digits, size of 'buf' should be increased.\n", (unsigned int) i, (unsigned int) rs); exit (99); } else if (0 != memcmp (buf + rs, erase + rs, sizeof(buf) - rs)) { if (0 == c_failed[i]) t_failed++; c_failed[i] = ! 0; fprintf (stderr, "FAILED: MHD_uint32_to_strx(0x%" PRIX64 ", -> \"%.*s\"," " %d) returned %" PRIuPTR " and touched data after the resulting string." " Locale: %s\n", t->val, (int) rs, buf, (int) b_size, (uintptr_t) rs, get_current_locale_str ()); } } } if ((verbose > 1) && (j == locale_name_count - 1) && ! c_failed[i]) printf ("PASSED: MHD_uint32_to_strx(0x%" PRIX64 ", -> \"%.*s\", %d) " "== %" PRIuPTR "\n", t->val, (int) rs, buf, (int) b_size - 1, (uintptr_t) rs); } } return t_failed; } static const struct str_with_value duint8_w_values_p1[] = { {D_STR_W_LEN ("0"), 1, 0}, {D_STR_W_LEN ("1"), 1, 1}, {D_STR_W_LEN ("2"), 1, 2}, {D_STR_W_LEN ("3"), 1, 3}, {D_STR_W_LEN ("4"), 1, 4}, {D_STR_W_LEN ("5"), 1, 5}, {D_STR_W_LEN ("6"), 1, 6}, {D_STR_W_LEN ("7"), 1, 7}, {D_STR_W_LEN ("8"), 1, 8}, {D_STR_W_LEN ("9"), 1, 9}, {D_STR_W_LEN ("10"), 2, 10}, {D_STR_W_LEN ("11"), 2, 11}, {D_STR_W_LEN ("12"), 2, 12}, {D_STR_W_LEN ("13"), 2, 13}, {D_STR_W_LEN ("14"), 2, 14}, {D_STR_W_LEN ("15"), 2, 15}, {D_STR_W_LEN ("16"), 2, 16}, {D_STR_W_LEN ("17"), 2, 17}, {D_STR_W_LEN ("18"), 2, 18}, {D_STR_W_LEN ("19"), 2, 19}, {D_STR_W_LEN ("20"), 2, 20}, {D_STR_W_LEN ("21"), 2, 21}, {D_STR_W_LEN ("22"), 2, 22}, {D_STR_W_LEN ("23"), 2, 23}, {D_STR_W_LEN ("24"), 2, 24}, {D_STR_W_LEN ("25"), 2, 25}, {D_STR_W_LEN ("26"), 2, 26}, {D_STR_W_LEN ("27"), 2, 27}, {D_STR_W_LEN ("28"), 2, 28}, {D_STR_W_LEN ("29"), 2, 29}, {D_STR_W_LEN ("30"), 2, 30}, {D_STR_W_LEN ("31"), 2, 31}, {D_STR_W_LEN ("32"), 2, 32}, {D_STR_W_LEN ("33"), 2, 33}, {D_STR_W_LEN ("34"), 2, 34}, {D_STR_W_LEN ("35"), 2, 35}, {D_STR_W_LEN ("36"), 2, 36}, {D_STR_W_LEN ("37"), 2, 37}, {D_STR_W_LEN ("38"), 2, 38}, {D_STR_W_LEN ("39"), 2, 39}, {D_STR_W_LEN ("40"), 2, 40}, {D_STR_W_LEN ("41"), 2, 41}, {D_STR_W_LEN ("42"), 2, 42}, {D_STR_W_LEN ("43"), 2, 43}, {D_STR_W_LEN ("44"), 2, 44}, {D_STR_W_LEN ("45"), 2, 45}, {D_STR_W_LEN ("46"), 2, 46}, {D_STR_W_LEN ("47"), 2, 47}, {D_STR_W_LEN ("48"), 2, 48}, {D_STR_W_LEN ("49"), 2, 49}, {D_STR_W_LEN ("50"), 2, 50}, {D_STR_W_LEN ("51"), 2, 51}, {D_STR_W_LEN ("52"), 2, 52}, {D_STR_W_LEN ("53"), 2, 53}, {D_STR_W_LEN ("54"), 2, 54}, {D_STR_W_LEN ("55"), 2, 55}, {D_STR_W_LEN ("56"), 2, 56}, {D_STR_W_LEN ("57"), 2, 57}, {D_STR_W_LEN ("58"), 2, 58}, {D_STR_W_LEN ("59"), 2, 59}, {D_STR_W_LEN ("60"), 2, 60}, {D_STR_W_LEN ("61"), 2, 61}, {D_STR_W_LEN ("62"), 2, 62}, {D_STR_W_LEN ("63"), 2, 63}, {D_STR_W_LEN ("64"), 2, 64}, {D_STR_W_LEN ("65"), 2, 65}, {D_STR_W_LEN ("66"), 2, 66}, {D_STR_W_LEN ("67"), 2, 67}, {D_STR_W_LEN ("68"), 2, 68}, {D_STR_W_LEN ("69"), 2, 69}, {D_STR_W_LEN ("70"), 2, 70}, {D_STR_W_LEN ("71"), 2, 71}, {D_STR_W_LEN ("72"), 2, 72}, {D_STR_W_LEN ("73"), 2, 73}, {D_STR_W_LEN ("74"), 2, 74}, {D_STR_W_LEN ("75"), 2, 75}, {D_STR_W_LEN ("76"), 2, 76}, {D_STR_W_LEN ("77"), 2, 77}, {D_STR_W_LEN ("78"), 2, 78}, {D_STR_W_LEN ("79"), 2, 79}, {D_STR_W_LEN ("80"), 2, 80}, {D_STR_W_LEN ("81"), 2, 81}, {D_STR_W_LEN ("82"), 2, 82}, {D_STR_W_LEN ("83"), 2, 83}, {D_STR_W_LEN ("84"), 2, 84}, {D_STR_W_LEN ("85"), 2, 85}, {D_STR_W_LEN ("86"), 2, 86}, {D_STR_W_LEN ("87"), 2, 87}, {D_STR_W_LEN ("88"), 2, 88}, {D_STR_W_LEN ("89"), 2, 89}, {D_STR_W_LEN ("90"), 2, 90}, {D_STR_W_LEN ("91"), 2, 91}, {D_STR_W_LEN ("92"), 2, 92}, {D_STR_W_LEN ("93"), 2, 93}, {D_STR_W_LEN ("94"), 2, 94}, {D_STR_W_LEN ("95"), 2, 95}, {D_STR_W_LEN ("96"), 2, 96}, {D_STR_W_LEN ("97"), 2, 97}, {D_STR_W_LEN ("98"), 2, 98}, {D_STR_W_LEN ("99"), 2, 99}, {D_STR_W_LEN ("100"), 3, 100}, {D_STR_W_LEN ("101"), 3, 101}, {D_STR_W_LEN ("102"), 3, 102}, {D_STR_W_LEN ("103"), 3, 103}, {D_STR_W_LEN ("104"), 3, 104}, {D_STR_W_LEN ("105"), 3, 105}, {D_STR_W_LEN ("106"), 3, 106}, {D_STR_W_LEN ("107"), 3, 107}, {D_STR_W_LEN ("108"), 3, 108}, {D_STR_W_LEN ("109"), 3, 109}, {D_STR_W_LEN ("110"), 3, 110}, {D_STR_W_LEN ("111"), 3, 111}, {D_STR_W_LEN ("112"), 3, 112}, {D_STR_W_LEN ("113"), 3, 113}, {D_STR_W_LEN ("114"), 3, 114}, {D_STR_W_LEN ("115"), 3, 115}, {D_STR_W_LEN ("116"), 3, 116}, {D_STR_W_LEN ("117"), 3, 117}, {D_STR_W_LEN ("118"), 3, 118}, {D_STR_W_LEN ("119"), 3, 119}, {D_STR_W_LEN ("120"), 3, 120}, {D_STR_W_LEN ("121"), 3, 121}, {D_STR_W_LEN ("122"), 3, 122}, {D_STR_W_LEN ("123"), 3, 123}, {D_STR_W_LEN ("124"), 3, 124}, {D_STR_W_LEN ("125"), 3, 125}, {D_STR_W_LEN ("126"), 3, 126}, {D_STR_W_LEN ("127"), 3, 127}, {D_STR_W_LEN ("128"), 3, 128}, {D_STR_W_LEN ("129"), 3, 129}, {D_STR_W_LEN ("130"), 3, 130}, {D_STR_W_LEN ("131"), 3, 131}, {D_STR_W_LEN ("132"), 3, 132}, {D_STR_W_LEN ("133"), 3, 133}, {D_STR_W_LEN ("134"), 3, 134}, {D_STR_W_LEN ("135"), 3, 135}, {D_STR_W_LEN ("136"), 3, 136}, {D_STR_W_LEN ("137"), 3, 137}, {D_STR_W_LEN ("138"), 3, 138}, {D_STR_W_LEN ("139"), 3, 139}, {D_STR_W_LEN ("140"), 3, 140}, {D_STR_W_LEN ("141"), 3, 141}, {D_STR_W_LEN ("142"), 3, 142}, {D_STR_W_LEN ("143"), 3, 143}, {D_STR_W_LEN ("144"), 3, 144}, {D_STR_W_LEN ("145"), 3, 145}, {D_STR_W_LEN ("146"), 3, 146}, {D_STR_W_LEN ("147"), 3, 147}, {D_STR_W_LEN ("148"), 3, 148}, {D_STR_W_LEN ("149"), 3, 149}, {D_STR_W_LEN ("150"), 3, 150}, {D_STR_W_LEN ("151"), 3, 151}, {D_STR_W_LEN ("152"), 3, 152}, {D_STR_W_LEN ("153"), 3, 153}, {D_STR_W_LEN ("154"), 3, 154}, {D_STR_W_LEN ("155"), 3, 155}, {D_STR_W_LEN ("156"), 3, 156}, {D_STR_W_LEN ("157"), 3, 157}, {D_STR_W_LEN ("158"), 3, 158}, {D_STR_W_LEN ("159"), 3, 159}, {D_STR_W_LEN ("160"), 3, 160}, {D_STR_W_LEN ("161"), 3, 161}, {D_STR_W_LEN ("162"), 3, 162}, {D_STR_W_LEN ("163"), 3, 163}, {D_STR_W_LEN ("164"), 3, 164}, {D_STR_W_LEN ("165"), 3, 165}, {D_STR_W_LEN ("166"), 3, 166}, {D_STR_W_LEN ("167"), 3, 167}, {D_STR_W_LEN ("168"), 3, 168}, {D_STR_W_LEN ("169"), 3, 169}, {D_STR_W_LEN ("170"), 3, 170}, {D_STR_W_LEN ("171"), 3, 171}, {D_STR_W_LEN ("172"), 3, 172}, {D_STR_W_LEN ("173"), 3, 173}, {D_STR_W_LEN ("174"), 3, 174}, {D_STR_W_LEN ("175"), 3, 175}, {D_STR_W_LEN ("176"), 3, 176}, {D_STR_W_LEN ("177"), 3, 177}, {D_STR_W_LEN ("178"), 3, 178}, {D_STR_W_LEN ("179"), 3, 179}, {D_STR_W_LEN ("180"), 3, 180}, {D_STR_W_LEN ("181"), 3, 181}, {D_STR_W_LEN ("182"), 3, 182}, {D_STR_W_LEN ("183"), 3, 183}, {D_STR_W_LEN ("184"), 3, 184}, {D_STR_W_LEN ("185"), 3, 185}, {D_STR_W_LEN ("186"), 3, 186}, {D_STR_W_LEN ("187"), 3, 187}, {D_STR_W_LEN ("188"), 3, 188}, {D_STR_W_LEN ("189"), 3, 189}, {D_STR_W_LEN ("190"), 3, 190}, {D_STR_W_LEN ("191"), 3, 191}, {D_STR_W_LEN ("192"), 3, 192}, {D_STR_W_LEN ("193"), 3, 193}, {D_STR_W_LEN ("194"), 3, 194}, {D_STR_W_LEN ("195"), 3, 195}, {D_STR_W_LEN ("196"), 3, 196}, {D_STR_W_LEN ("197"), 3, 197}, {D_STR_W_LEN ("198"), 3, 198}, {D_STR_W_LEN ("199"), 3, 199}, {D_STR_W_LEN ("200"), 3, 200}, {D_STR_W_LEN ("201"), 3, 201}, {D_STR_W_LEN ("202"), 3, 202}, {D_STR_W_LEN ("203"), 3, 203}, {D_STR_W_LEN ("204"), 3, 204}, {D_STR_W_LEN ("205"), 3, 205}, {D_STR_W_LEN ("206"), 3, 206}, {D_STR_W_LEN ("207"), 3, 207}, {D_STR_W_LEN ("208"), 3, 208}, {D_STR_W_LEN ("209"), 3, 209}, {D_STR_W_LEN ("210"), 3, 210}, {D_STR_W_LEN ("211"), 3, 211}, {D_STR_W_LEN ("212"), 3, 212}, {D_STR_W_LEN ("213"), 3, 213}, {D_STR_W_LEN ("214"), 3, 214}, {D_STR_W_LEN ("215"), 3, 215}, {D_STR_W_LEN ("216"), 3, 216}, {D_STR_W_LEN ("217"), 3, 217}, {D_STR_W_LEN ("218"), 3, 218}, {D_STR_W_LEN ("219"), 3, 219}, {D_STR_W_LEN ("220"), 3, 220}, {D_STR_W_LEN ("221"), 3, 221}, {D_STR_W_LEN ("222"), 3, 222}, {D_STR_W_LEN ("223"), 3, 223}, {D_STR_W_LEN ("224"), 3, 224}, {D_STR_W_LEN ("225"), 3, 225}, {D_STR_W_LEN ("226"), 3, 226}, {D_STR_W_LEN ("227"), 3, 227}, {D_STR_W_LEN ("228"), 3, 228}, {D_STR_W_LEN ("229"), 3, 229}, {D_STR_W_LEN ("230"), 3, 230}, {D_STR_W_LEN ("231"), 3, 231}, {D_STR_W_LEN ("232"), 3, 232}, {D_STR_W_LEN ("233"), 3, 233}, {D_STR_W_LEN ("234"), 3, 234}, {D_STR_W_LEN ("235"), 3, 235}, {D_STR_W_LEN ("236"), 3, 236}, {D_STR_W_LEN ("237"), 3, 237}, {D_STR_W_LEN ("238"), 3, 238}, {D_STR_W_LEN ("239"), 3, 239}, {D_STR_W_LEN ("240"), 3, 240}, {D_STR_W_LEN ("241"), 3, 241}, {D_STR_W_LEN ("242"), 3, 242}, {D_STR_W_LEN ("243"), 3, 243}, {D_STR_W_LEN ("244"), 3, 244}, {D_STR_W_LEN ("245"), 3, 245}, {D_STR_W_LEN ("246"), 3, 246}, {D_STR_W_LEN ("247"), 3, 247}, {D_STR_W_LEN ("248"), 3, 248}, {D_STR_W_LEN ("249"), 3, 249}, {D_STR_W_LEN ("250"), 3, 250}, {D_STR_W_LEN ("251"), 3, 251}, {D_STR_W_LEN ("252"), 3, 252}, {D_STR_W_LEN ("253"), 3, 253}, {D_STR_W_LEN ("254"), 3, 254}, {D_STR_W_LEN ("255"), 3, 255}, }; static const struct str_with_value duint8_w_values_p2[] = { {D_STR_W_LEN ("00"), 2, 0}, {D_STR_W_LEN ("01"), 2, 1}, {D_STR_W_LEN ("02"), 2, 2}, {D_STR_W_LEN ("03"), 2, 3}, {D_STR_W_LEN ("04"), 2, 4}, {D_STR_W_LEN ("05"), 2, 5}, {D_STR_W_LEN ("06"), 2, 6}, {D_STR_W_LEN ("07"), 2, 7}, {D_STR_W_LEN ("08"), 2, 8}, {D_STR_W_LEN ("09"), 2, 9}, {D_STR_W_LEN ("10"), 2, 10}, {D_STR_W_LEN ("11"), 2, 11}, {D_STR_W_LEN ("12"), 2, 12}, {D_STR_W_LEN ("13"), 2, 13}, {D_STR_W_LEN ("14"), 2, 14}, {D_STR_W_LEN ("15"), 2, 15}, {D_STR_W_LEN ("16"), 2, 16}, {D_STR_W_LEN ("17"), 2, 17}, {D_STR_W_LEN ("18"), 2, 18}, {D_STR_W_LEN ("19"), 2, 19}, {D_STR_W_LEN ("20"), 2, 20}, {D_STR_W_LEN ("21"), 2, 21}, {D_STR_W_LEN ("22"), 2, 22}, {D_STR_W_LEN ("23"), 2, 23}, {D_STR_W_LEN ("24"), 2, 24}, {D_STR_W_LEN ("25"), 2, 25}, {D_STR_W_LEN ("26"), 2, 26}, {D_STR_W_LEN ("27"), 2, 27}, {D_STR_W_LEN ("28"), 2, 28}, {D_STR_W_LEN ("29"), 2, 29}, {D_STR_W_LEN ("30"), 2, 30}, {D_STR_W_LEN ("31"), 2, 31}, {D_STR_W_LEN ("32"), 2, 32}, {D_STR_W_LEN ("33"), 2, 33}, {D_STR_W_LEN ("34"), 2, 34}, {D_STR_W_LEN ("35"), 2, 35}, {D_STR_W_LEN ("36"), 2, 36}, {D_STR_W_LEN ("37"), 2, 37}, {D_STR_W_LEN ("38"), 2, 38}, {D_STR_W_LEN ("39"), 2, 39}, {D_STR_W_LEN ("40"), 2, 40}, {D_STR_W_LEN ("41"), 2, 41}, {D_STR_W_LEN ("42"), 2, 42}, {D_STR_W_LEN ("43"), 2, 43}, {D_STR_W_LEN ("44"), 2, 44}, {D_STR_W_LEN ("45"), 2, 45}, {D_STR_W_LEN ("46"), 2, 46}, {D_STR_W_LEN ("47"), 2, 47}, {D_STR_W_LEN ("48"), 2, 48}, {D_STR_W_LEN ("49"), 2, 49}, {D_STR_W_LEN ("50"), 2, 50}, {D_STR_W_LEN ("51"), 2, 51}, {D_STR_W_LEN ("52"), 2, 52}, {D_STR_W_LEN ("53"), 2, 53}, {D_STR_W_LEN ("54"), 2, 54}, {D_STR_W_LEN ("55"), 2, 55}, {D_STR_W_LEN ("56"), 2, 56}, {D_STR_W_LEN ("57"), 2, 57}, {D_STR_W_LEN ("58"), 2, 58}, {D_STR_W_LEN ("59"), 2, 59}, {D_STR_W_LEN ("60"), 2, 60}, {D_STR_W_LEN ("61"), 2, 61}, {D_STR_W_LEN ("62"), 2, 62}, {D_STR_W_LEN ("63"), 2, 63}, {D_STR_W_LEN ("64"), 2, 64}, {D_STR_W_LEN ("65"), 2, 65}, {D_STR_W_LEN ("66"), 2, 66}, {D_STR_W_LEN ("67"), 2, 67}, {D_STR_W_LEN ("68"), 2, 68}, {D_STR_W_LEN ("69"), 2, 69}, {D_STR_W_LEN ("70"), 2, 70}, {D_STR_W_LEN ("71"), 2, 71}, {D_STR_W_LEN ("72"), 2, 72}, {D_STR_W_LEN ("73"), 2, 73}, {D_STR_W_LEN ("74"), 2, 74}, {D_STR_W_LEN ("75"), 2, 75}, {D_STR_W_LEN ("76"), 2, 76}, {D_STR_W_LEN ("77"), 2, 77}, {D_STR_W_LEN ("78"), 2, 78}, {D_STR_W_LEN ("79"), 2, 79}, {D_STR_W_LEN ("80"), 2, 80}, {D_STR_W_LEN ("81"), 2, 81}, {D_STR_W_LEN ("82"), 2, 82}, {D_STR_W_LEN ("83"), 2, 83}, {D_STR_W_LEN ("84"), 2, 84}, {D_STR_W_LEN ("85"), 2, 85}, {D_STR_W_LEN ("86"), 2, 86}, {D_STR_W_LEN ("87"), 2, 87}, {D_STR_W_LEN ("88"), 2, 88}, {D_STR_W_LEN ("89"), 2, 89}, {D_STR_W_LEN ("90"), 2, 90}, {D_STR_W_LEN ("91"), 2, 91}, {D_STR_W_LEN ("92"), 2, 92}, {D_STR_W_LEN ("93"), 2, 93}, {D_STR_W_LEN ("94"), 2, 94}, {D_STR_W_LEN ("95"), 2, 95}, {D_STR_W_LEN ("96"), 2, 96}, {D_STR_W_LEN ("97"), 2, 97}, {D_STR_W_LEN ("98"), 2, 98}, {D_STR_W_LEN ("99"), 2, 99}, {D_STR_W_LEN ("100"), 3, 100}, {D_STR_W_LEN ("101"), 3, 101}, {D_STR_W_LEN ("102"), 3, 102}, {D_STR_W_LEN ("103"), 3, 103}, {D_STR_W_LEN ("104"), 3, 104}, {D_STR_W_LEN ("105"), 3, 105}, {D_STR_W_LEN ("106"), 3, 106}, {D_STR_W_LEN ("107"), 3, 107}, {D_STR_W_LEN ("108"), 3, 108}, {D_STR_W_LEN ("109"), 3, 109}, {D_STR_W_LEN ("110"), 3, 110}, {D_STR_W_LEN ("111"), 3, 111}, {D_STR_W_LEN ("112"), 3, 112}, {D_STR_W_LEN ("113"), 3, 113}, {D_STR_W_LEN ("114"), 3, 114}, {D_STR_W_LEN ("115"), 3, 115}, {D_STR_W_LEN ("116"), 3, 116}, {D_STR_W_LEN ("117"), 3, 117}, {D_STR_W_LEN ("118"), 3, 118}, {D_STR_W_LEN ("119"), 3, 119}, {D_STR_W_LEN ("120"), 3, 120}, {D_STR_W_LEN ("121"), 3, 121}, {D_STR_W_LEN ("122"), 3, 122}, {D_STR_W_LEN ("123"), 3, 123}, {D_STR_W_LEN ("124"), 3, 124}, {D_STR_W_LEN ("125"), 3, 125}, {D_STR_W_LEN ("126"), 3, 126}, {D_STR_W_LEN ("127"), 3, 127}, {D_STR_W_LEN ("128"), 3, 128}, {D_STR_W_LEN ("129"), 3, 129}, {D_STR_W_LEN ("130"), 3, 130}, {D_STR_W_LEN ("131"), 3, 131}, {D_STR_W_LEN ("132"), 3, 132}, {D_STR_W_LEN ("133"), 3, 133}, {D_STR_W_LEN ("134"), 3, 134}, {D_STR_W_LEN ("135"), 3, 135}, {D_STR_W_LEN ("136"), 3, 136}, {D_STR_W_LEN ("137"), 3, 137}, {D_STR_W_LEN ("138"), 3, 138}, {D_STR_W_LEN ("139"), 3, 139}, {D_STR_W_LEN ("140"), 3, 140}, {D_STR_W_LEN ("141"), 3, 141}, {D_STR_W_LEN ("142"), 3, 142}, {D_STR_W_LEN ("143"), 3, 143}, {D_STR_W_LEN ("144"), 3, 144}, {D_STR_W_LEN ("145"), 3, 145}, {D_STR_W_LEN ("146"), 3, 146}, {D_STR_W_LEN ("147"), 3, 147}, {D_STR_W_LEN ("148"), 3, 148}, {D_STR_W_LEN ("149"), 3, 149}, {D_STR_W_LEN ("150"), 3, 150}, {D_STR_W_LEN ("151"), 3, 151}, {D_STR_W_LEN ("152"), 3, 152}, {D_STR_W_LEN ("153"), 3, 153}, {D_STR_W_LEN ("154"), 3, 154}, {D_STR_W_LEN ("155"), 3, 155}, {D_STR_W_LEN ("156"), 3, 156}, {D_STR_W_LEN ("157"), 3, 157}, {D_STR_W_LEN ("158"), 3, 158}, {D_STR_W_LEN ("159"), 3, 159}, {D_STR_W_LEN ("160"), 3, 160}, {D_STR_W_LEN ("161"), 3, 161}, {D_STR_W_LEN ("162"), 3, 162}, {D_STR_W_LEN ("163"), 3, 163}, {D_STR_W_LEN ("164"), 3, 164}, {D_STR_W_LEN ("165"), 3, 165}, {D_STR_W_LEN ("166"), 3, 166}, {D_STR_W_LEN ("167"), 3, 167}, {D_STR_W_LEN ("168"), 3, 168}, {D_STR_W_LEN ("169"), 3, 169}, {D_STR_W_LEN ("170"), 3, 170}, {D_STR_W_LEN ("171"), 3, 171}, {D_STR_W_LEN ("172"), 3, 172}, {D_STR_W_LEN ("173"), 3, 173}, {D_STR_W_LEN ("174"), 3, 174}, {D_STR_W_LEN ("175"), 3, 175}, {D_STR_W_LEN ("176"), 3, 176}, {D_STR_W_LEN ("177"), 3, 177}, {D_STR_W_LEN ("178"), 3, 178}, {D_STR_W_LEN ("179"), 3, 179}, {D_STR_W_LEN ("180"), 3, 180}, {D_STR_W_LEN ("181"), 3, 181}, {D_STR_W_LEN ("182"), 3, 182}, {D_STR_W_LEN ("183"), 3, 183}, {D_STR_W_LEN ("184"), 3, 184}, {D_STR_W_LEN ("185"), 3, 185}, {D_STR_W_LEN ("186"), 3, 186}, {D_STR_W_LEN ("187"), 3, 187}, {D_STR_W_LEN ("188"), 3, 188}, {D_STR_W_LEN ("189"), 3, 189}, {D_STR_W_LEN ("190"), 3, 190}, {D_STR_W_LEN ("191"), 3, 191}, {D_STR_W_LEN ("192"), 3, 192}, {D_STR_W_LEN ("193"), 3, 193}, {D_STR_W_LEN ("194"), 3, 194}, {D_STR_W_LEN ("195"), 3, 195}, {D_STR_W_LEN ("196"), 3, 196}, {D_STR_W_LEN ("197"), 3, 197}, {D_STR_W_LEN ("198"), 3, 198}, {D_STR_W_LEN ("199"), 3, 199}, {D_STR_W_LEN ("200"), 3, 200}, {D_STR_W_LEN ("201"), 3, 201}, {D_STR_W_LEN ("202"), 3, 202}, {D_STR_W_LEN ("203"), 3, 203}, {D_STR_W_LEN ("204"), 3, 204}, {D_STR_W_LEN ("205"), 3, 205}, {D_STR_W_LEN ("206"), 3, 206}, {D_STR_W_LEN ("207"), 3, 207}, {D_STR_W_LEN ("208"), 3, 208}, {D_STR_W_LEN ("209"), 3, 209}, {D_STR_W_LEN ("210"), 3, 210}, {D_STR_W_LEN ("211"), 3, 211}, {D_STR_W_LEN ("212"), 3, 212}, {D_STR_W_LEN ("213"), 3, 213}, {D_STR_W_LEN ("214"), 3, 214}, {D_STR_W_LEN ("215"), 3, 215}, {D_STR_W_LEN ("216"), 3, 216}, {D_STR_W_LEN ("217"), 3, 217}, {D_STR_W_LEN ("218"), 3, 218}, {D_STR_W_LEN ("219"), 3, 219}, {D_STR_W_LEN ("220"), 3, 220}, {D_STR_W_LEN ("221"), 3, 221}, {D_STR_W_LEN ("222"), 3, 222}, {D_STR_W_LEN ("223"), 3, 223}, {D_STR_W_LEN ("224"), 3, 224}, {D_STR_W_LEN ("225"), 3, 225}, {D_STR_W_LEN ("226"), 3, 226}, {D_STR_W_LEN ("227"), 3, 227}, {D_STR_W_LEN ("228"), 3, 228}, {D_STR_W_LEN ("229"), 3, 229}, {D_STR_W_LEN ("230"), 3, 230}, {D_STR_W_LEN ("231"), 3, 231}, {D_STR_W_LEN ("232"), 3, 232}, {D_STR_W_LEN ("233"), 3, 233}, {D_STR_W_LEN ("234"), 3, 234}, {D_STR_W_LEN ("235"), 3, 235}, {D_STR_W_LEN ("236"), 3, 236}, {D_STR_W_LEN ("237"), 3, 237}, {D_STR_W_LEN ("238"), 3, 238}, {D_STR_W_LEN ("239"), 3, 239}, {D_STR_W_LEN ("240"), 3, 240}, {D_STR_W_LEN ("241"), 3, 241}, {D_STR_W_LEN ("242"), 3, 242}, {D_STR_W_LEN ("243"), 3, 243}, {D_STR_W_LEN ("244"), 3, 244}, {D_STR_W_LEN ("245"), 3, 245}, {D_STR_W_LEN ("246"), 3, 246}, {D_STR_W_LEN ("247"), 3, 247}, {D_STR_W_LEN ("248"), 3, 248}, {D_STR_W_LEN ("249"), 3, 249}, {D_STR_W_LEN ("250"), 3, 250}, {D_STR_W_LEN ("251"), 3, 251}, {D_STR_W_LEN ("252"), 3, 252}, {D_STR_W_LEN ("253"), 3, 253}, {D_STR_W_LEN ("254"), 3, 254}, {D_STR_W_LEN ("255"), 3, 255} }; static const struct str_with_value duint8_w_values_p3[] = { {D_STR_W_LEN ("000"), 3, 0}, {D_STR_W_LEN ("001"), 3, 1}, {D_STR_W_LEN ("002"), 3, 2}, {D_STR_W_LEN ("003"), 3, 3}, {D_STR_W_LEN ("004"), 3, 4}, {D_STR_W_LEN ("005"), 3, 5}, {D_STR_W_LEN ("006"), 3, 6}, {D_STR_W_LEN ("007"), 3, 7}, {D_STR_W_LEN ("008"), 3, 8}, {D_STR_W_LEN ("009"), 3, 9}, {D_STR_W_LEN ("010"), 3, 10}, {D_STR_W_LEN ("011"), 3, 11}, {D_STR_W_LEN ("012"), 3, 12}, {D_STR_W_LEN ("013"), 3, 13}, {D_STR_W_LEN ("014"), 3, 14}, {D_STR_W_LEN ("015"), 3, 15}, {D_STR_W_LEN ("016"), 3, 16}, {D_STR_W_LEN ("017"), 3, 17}, {D_STR_W_LEN ("018"), 3, 18}, {D_STR_W_LEN ("019"), 3, 19}, {D_STR_W_LEN ("020"), 3, 20}, {D_STR_W_LEN ("021"), 3, 21}, {D_STR_W_LEN ("022"), 3, 22}, {D_STR_W_LEN ("023"), 3, 23}, {D_STR_W_LEN ("024"), 3, 24}, {D_STR_W_LEN ("025"), 3, 25}, {D_STR_W_LEN ("026"), 3, 26}, {D_STR_W_LEN ("027"), 3, 27}, {D_STR_W_LEN ("028"), 3, 28}, {D_STR_W_LEN ("029"), 3, 29}, {D_STR_W_LEN ("030"), 3, 30}, {D_STR_W_LEN ("031"), 3, 31}, {D_STR_W_LEN ("032"), 3, 32}, {D_STR_W_LEN ("033"), 3, 33}, {D_STR_W_LEN ("034"), 3, 34}, {D_STR_W_LEN ("035"), 3, 35}, {D_STR_W_LEN ("036"), 3, 36}, {D_STR_W_LEN ("037"), 3, 37}, {D_STR_W_LEN ("038"), 3, 38}, {D_STR_W_LEN ("039"), 3, 39}, {D_STR_W_LEN ("040"), 3, 40}, {D_STR_W_LEN ("041"), 3, 41}, {D_STR_W_LEN ("042"), 3, 42}, {D_STR_W_LEN ("043"), 3, 43}, {D_STR_W_LEN ("044"), 3, 44}, {D_STR_W_LEN ("045"), 3, 45}, {D_STR_W_LEN ("046"), 3, 46}, {D_STR_W_LEN ("047"), 3, 47}, {D_STR_W_LEN ("048"), 3, 48}, {D_STR_W_LEN ("049"), 3, 49}, {D_STR_W_LEN ("050"), 3, 50}, {D_STR_W_LEN ("051"), 3, 51}, {D_STR_W_LEN ("052"), 3, 52}, {D_STR_W_LEN ("053"), 3, 53}, {D_STR_W_LEN ("054"), 3, 54}, {D_STR_W_LEN ("055"), 3, 55}, {D_STR_W_LEN ("056"), 3, 56}, {D_STR_W_LEN ("057"), 3, 57}, {D_STR_W_LEN ("058"), 3, 58}, {D_STR_W_LEN ("059"), 3, 59}, {D_STR_W_LEN ("060"), 3, 60}, {D_STR_W_LEN ("061"), 3, 61}, {D_STR_W_LEN ("062"), 3, 62}, {D_STR_W_LEN ("063"), 3, 63}, {D_STR_W_LEN ("064"), 3, 64}, {D_STR_W_LEN ("065"), 3, 65}, {D_STR_W_LEN ("066"), 3, 66}, {D_STR_W_LEN ("067"), 3, 67}, {D_STR_W_LEN ("068"), 3, 68}, {D_STR_W_LEN ("069"), 3, 69}, {D_STR_W_LEN ("070"), 3, 70}, {D_STR_W_LEN ("071"), 3, 71}, {D_STR_W_LEN ("072"), 3, 72}, {D_STR_W_LEN ("073"), 3, 73}, {D_STR_W_LEN ("074"), 3, 74}, {D_STR_W_LEN ("075"), 3, 75}, {D_STR_W_LEN ("076"), 3, 76}, {D_STR_W_LEN ("077"), 3, 77}, {D_STR_W_LEN ("078"), 3, 78}, {D_STR_W_LEN ("079"), 3, 79}, {D_STR_W_LEN ("080"), 3, 80}, {D_STR_W_LEN ("081"), 3, 81}, {D_STR_W_LEN ("082"), 3, 82}, {D_STR_W_LEN ("083"), 3, 83}, {D_STR_W_LEN ("084"), 3, 84}, {D_STR_W_LEN ("085"), 3, 85}, {D_STR_W_LEN ("086"), 3, 86}, {D_STR_W_LEN ("087"), 3, 87}, {D_STR_W_LEN ("088"), 3, 88}, {D_STR_W_LEN ("089"), 3, 89}, {D_STR_W_LEN ("090"), 3, 90}, {D_STR_W_LEN ("091"), 3, 91}, {D_STR_W_LEN ("092"), 3, 92}, {D_STR_W_LEN ("093"), 3, 93}, {D_STR_W_LEN ("094"), 3, 94}, {D_STR_W_LEN ("095"), 3, 95}, {D_STR_W_LEN ("096"), 3, 96}, {D_STR_W_LEN ("097"), 3, 97}, {D_STR_W_LEN ("098"), 3, 98}, {D_STR_W_LEN ("099"), 3, 99}, {D_STR_W_LEN ("100"), 3, 100}, {D_STR_W_LEN ("101"), 3, 101}, {D_STR_W_LEN ("102"), 3, 102}, {D_STR_W_LEN ("103"), 3, 103}, {D_STR_W_LEN ("104"), 3, 104}, {D_STR_W_LEN ("105"), 3, 105}, {D_STR_W_LEN ("106"), 3, 106}, {D_STR_W_LEN ("107"), 3, 107}, {D_STR_W_LEN ("108"), 3, 108}, {D_STR_W_LEN ("109"), 3, 109}, {D_STR_W_LEN ("110"), 3, 110}, {D_STR_W_LEN ("111"), 3, 111}, {D_STR_W_LEN ("112"), 3, 112}, {D_STR_W_LEN ("113"), 3, 113}, {D_STR_W_LEN ("114"), 3, 114}, {D_STR_W_LEN ("115"), 3, 115}, {D_STR_W_LEN ("116"), 3, 116}, {D_STR_W_LEN ("117"), 3, 117}, {D_STR_W_LEN ("118"), 3, 118}, {D_STR_W_LEN ("119"), 3, 119}, {D_STR_W_LEN ("120"), 3, 120}, {D_STR_W_LEN ("121"), 3, 121}, {D_STR_W_LEN ("122"), 3, 122}, {D_STR_W_LEN ("123"), 3, 123}, {D_STR_W_LEN ("124"), 3, 124}, {D_STR_W_LEN ("125"), 3, 125}, {D_STR_W_LEN ("126"), 3, 126}, {D_STR_W_LEN ("127"), 3, 127}, {D_STR_W_LEN ("128"), 3, 128}, {D_STR_W_LEN ("129"), 3, 129}, {D_STR_W_LEN ("130"), 3, 130}, {D_STR_W_LEN ("131"), 3, 131}, {D_STR_W_LEN ("132"), 3, 132}, {D_STR_W_LEN ("133"), 3, 133}, {D_STR_W_LEN ("134"), 3, 134}, {D_STR_W_LEN ("135"), 3, 135}, {D_STR_W_LEN ("136"), 3, 136}, {D_STR_W_LEN ("137"), 3, 137}, {D_STR_W_LEN ("138"), 3, 138}, {D_STR_W_LEN ("139"), 3, 139}, {D_STR_W_LEN ("140"), 3, 140}, {D_STR_W_LEN ("141"), 3, 141}, {D_STR_W_LEN ("142"), 3, 142}, {D_STR_W_LEN ("143"), 3, 143}, {D_STR_W_LEN ("144"), 3, 144}, {D_STR_W_LEN ("145"), 3, 145}, {D_STR_W_LEN ("146"), 3, 146}, {D_STR_W_LEN ("147"), 3, 147}, {D_STR_W_LEN ("148"), 3, 148}, {D_STR_W_LEN ("149"), 3, 149}, {D_STR_W_LEN ("150"), 3, 150}, {D_STR_W_LEN ("151"), 3, 151}, {D_STR_W_LEN ("152"), 3, 152}, {D_STR_W_LEN ("153"), 3, 153}, {D_STR_W_LEN ("154"), 3, 154}, {D_STR_W_LEN ("155"), 3, 155}, {D_STR_W_LEN ("156"), 3, 156}, {D_STR_W_LEN ("157"), 3, 157}, {D_STR_W_LEN ("158"), 3, 158}, {D_STR_W_LEN ("159"), 3, 159}, {D_STR_W_LEN ("160"), 3, 160}, {D_STR_W_LEN ("161"), 3, 161}, {D_STR_W_LEN ("162"), 3, 162}, {D_STR_W_LEN ("163"), 3, 163}, {D_STR_W_LEN ("164"), 3, 164}, {D_STR_W_LEN ("165"), 3, 165}, {D_STR_W_LEN ("166"), 3, 166}, {D_STR_W_LEN ("167"), 3, 167}, {D_STR_W_LEN ("168"), 3, 168}, {D_STR_W_LEN ("169"), 3, 169}, {D_STR_W_LEN ("170"), 3, 170}, {D_STR_W_LEN ("171"), 3, 171}, {D_STR_W_LEN ("172"), 3, 172}, {D_STR_W_LEN ("173"), 3, 173}, {D_STR_W_LEN ("174"), 3, 174}, {D_STR_W_LEN ("175"), 3, 175}, {D_STR_W_LEN ("176"), 3, 176}, {D_STR_W_LEN ("177"), 3, 177}, {D_STR_W_LEN ("178"), 3, 178}, {D_STR_W_LEN ("179"), 3, 179}, {D_STR_W_LEN ("180"), 3, 180}, {D_STR_W_LEN ("181"), 3, 181}, {D_STR_W_LEN ("182"), 3, 182}, {D_STR_W_LEN ("183"), 3, 183}, {D_STR_W_LEN ("184"), 3, 184}, {D_STR_W_LEN ("185"), 3, 185}, {D_STR_W_LEN ("186"), 3, 186}, {D_STR_W_LEN ("187"), 3, 187}, {D_STR_W_LEN ("188"), 3, 188}, {D_STR_W_LEN ("189"), 3, 189}, {D_STR_W_LEN ("190"), 3, 190}, {D_STR_W_LEN ("191"), 3, 191}, {D_STR_W_LEN ("192"), 3, 192}, {D_STR_W_LEN ("193"), 3, 193}, {D_STR_W_LEN ("194"), 3, 194}, {D_STR_W_LEN ("195"), 3, 195}, {D_STR_W_LEN ("196"), 3, 196}, {D_STR_W_LEN ("197"), 3, 197}, {D_STR_W_LEN ("198"), 3, 198}, {D_STR_W_LEN ("199"), 3, 199}, {D_STR_W_LEN ("200"), 3, 200}, {D_STR_W_LEN ("201"), 3, 201}, {D_STR_W_LEN ("202"), 3, 202}, {D_STR_W_LEN ("203"), 3, 203}, {D_STR_W_LEN ("204"), 3, 204}, {D_STR_W_LEN ("205"), 3, 205}, {D_STR_W_LEN ("206"), 3, 206}, {D_STR_W_LEN ("207"), 3, 207}, {D_STR_W_LEN ("208"), 3, 208}, {D_STR_W_LEN ("209"), 3, 209}, {D_STR_W_LEN ("210"), 3, 210}, {D_STR_W_LEN ("211"), 3, 211}, {D_STR_W_LEN ("212"), 3, 212}, {D_STR_W_LEN ("213"), 3, 213}, {D_STR_W_LEN ("214"), 3, 214}, {D_STR_W_LEN ("215"), 3, 215}, {D_STR_W_LEN ("216"), 3, 216}, {D_STR_W_LEN ("217"), 3, 217}, {D_STR_W_LEN ("218"), 3, 218}, {D_STR_W_LEN ("219"), 3, 219}, {D_STR_W_LEN ("220"), 3, 220}, {D_STR_W_LEN ("221"), 3, 221}, {D_STR_W_LEN ("222"), 3, 222}, {D_STR_W_LEN ("223"), 3, 223}, {D_STR_W_LEN ("224"), 3, 224}, {D_STR_W_LEN ("225"), 3, 225}, {D_STR_W_LEN ("226"), 3, 226}, {D_STR_W_LEN ("227"), 3, 227}, {D_STR_W_LEN ("228"), 3, 228}, {D_STR_W_LEN ("229"), 3, 229}, {D_STR_W_LEN ("230"), 3, 230}, {D_STR_W_LEN ("231"), 3, 231}, {D_STR_W_LEN ("232"), 3, 232}, {D_STR_W_LEN ("233"), 3, 233}, {D_STR_W_LEN ("234"), 3, 234}, {D_STR_W_LEN ("235"), 3, 235}, {D_STR_W_LEN ("236"), 3, 236}, {D_STR_W_LEN ("237"), 3, 237}, {D_STR_W_LEN ("238"), 3, 238}, {D_STR_W_LEN ("239"), 3, 239}, {D_STR_W_LEN ("240"), 3, 240}, {D_STR_W_LEN ("241"), 3, 241}, {D_STR_W_LEN ("242"), 3, 242}, {D_STR_W_LEN ("243"), 3, 243}, {D_STR_W_LEN ("244"), 3, 244}, {D_STR_W_LEN ("245"), 3, 245}, {D_STR_W_LEN ("246"), 3, 246}, {D_STR_W_LEN ("247"), 3, 247}, {D_STR_W_LEN ("248"), 3, 248}, {D_STR_W_LEN ("249"), 3, 249}, {D_STR_W_LEN ("250"), 3, 250}, {D_STR_W_LEN ("251"), 3, 251}, {D_STR_W_LEN ("252"), 3, 252}, {D_STR_W_LEN ("253"), 3, 253}, {D_STR_W_LEN ("254"), 3, 254}, {D_STR_W_LEN ("255"), 3, 255} }; static const struct str_with_value *duint8_w_values_p[3] = {duint8_w_values_p1, duint8_w_values_p2, duint8_w_values_p3}; static size_t check_str_from_uint8_pad (void) { int i; uint8_t pad; size_t t_failed = 0; if ((256 != sizeof(duint8_w_values_p1) / sizeof(duint8_w_values_p1[0])) || (256 != sizeof(duint8_w_values_p2) / sizeof(duint8_w_values_p2[0])) || (256 != sizeof(duint8_w_values_p3) / sizeof(duint8_w_values_p3[0]))) { fprintf (stderr, "ERROR: wrong number of items in duint8_w_values_p*.\n"); exit (99); } for (pad = 0; pad <= 3; pad++) { size_t table_num; if (0 != pad) table_num = pad - 1; else table_num = 0; for (i = 0; i <= 255; i++) { const struct str_with_value *const t = duint8_w_values_p[table_num] + i; size_t b_size; size_t rs; char buf[8]; if (t->str.len < t->num_of_digt) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has wrong num_of_digt (%u): num_of_digt is expected" " to be less or equal to str.len (%u).\n", (unsigned int) i, (unsigned int) t->num_of_digt, (unsigned int) t->str. len); exit (99); } if (sizeof(buf) < t->str.len + 1) { fprintf (stderr, "ERROR: dstrs_w_values[%u] has too long (%u) string, " "size of 'buf' should be increased.\n", (unsigned int) i, (unsigned int) t->str.len); exit (99); } for (b_size = 0; b_size <= t->str.len + 1; ++b_size) { /* fill buffer with pseudo-random values */ memset (buf, '#', sizeof(buf)); rs = MHD_uint8_to_str_pad ((uint8_t) t->val, pad, buf, b_size); if (t->num_of_digt > b_size) { /* Must fail, buffer is too small for result */ if (0 != rs) { t_failed++; fprintf (stderr, "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d, -> buf," " %d) returned %" PRIuPTR ", while expecting 0.\n", t->val, (int) pad, (int) b_size, (uintptr_t) rs); } } else { if (t->num_of_digt != rs) { t_failed++; fprintf (stderr, "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d, -> buf," " %d) returned %" PRIuPTR ", while expecting %d.\n", t->val, (int) pad, (int) b_size, (uintptr_t) rs, (int) t->num_of_digt); } else if (0 != memcmp (buf, t->str.str, t->num_of_digt)) { t_failed++; fprintf (stderr, "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d, " "-> \"%.*s\", %d) returned %" PRIuPTR ".\n", t->val, (int) pad, (int) rs, buf, (int) b_size, (uintptr_t) rs); } else if (0 != memcmp (buf + rs, "########", sizeof(buf) - rs)) { t_failed++; fprintf (stderr, "FAILED: MHD_uint8_to_str_pad(%" PRIu64 ", %d," " -> \"%.*s\", %d) returned %" PRIuPTR " and touched data after the resulting string.\n", t->val, (int) pad, (int) rs, buf, (int) b_size, (uintptr_t) rs); } } } } } if ((verbose > 1) && (0 == t_failed)) printf ("PASSED: MHD_uint8_to_str_pad.\n"); return t_failed; } static int run_str_from_X_tests (void) { size_t str_from_uint16; size_t str_from_uint64; size_t strx_from_uint32; size_t str_from_uint8_pad; size_t failures; failures = 0; str_from_uint16 = check_str_from_uint16 (); if (str_from_uint16 != 0) { fprintf (stderr, "FAILED: testcase check_str_from_uint16() failed.\n\n"); failures += str_from_uint16; } else if (verbose > 1) printf ("PASSED: testcase check_str_from_uint16() successfully " "passed.\n\n"); str_from_uint64 = check_str_from_uint64 (); if (str_from_uint64 != 0) { fprintf (stderr, "FAILED: testcase check_str_from_uint16() failed.\n\n"); failures += str_from_uint64; } else if (verbose > 1) printf ("PASSED: testcase check_str_from_uint16() successfully " "passed.\n\n"); strx_from_uint32 = check_strx_from_uint32 (); if (strx_from_uint32 != 0) { fprintf (stderr, "FAILED: testcase check_strx_from_uint32() failed.\n\n"); failures += strx_from_uint32; } else if (verbose > 1) printf ("PASSED: testcase check_strx_from_uint32() successfully " "passed.\n\n"); str_from_uint8_pad = check_str_from_uint8_pad (); if (str_from_uint8_pad != 0) { fprintf (stderr, "FAILED: testcase check_str_from_uint8_pad() failed.\n\n"); failures += str_from_uint8_pad; } else if (verbose > 1) printf ("PASSED: testcase check_str_from_uint8_pad() successfully " "passed.\n\n"); if (failures) { if (verbose > 0) printf ("At least one test failed.\n"); return 1; } if (verbose > 0) printf ("All tests passed successfully.\n"); return 0; } int main (int argc, char *argv[]) { if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose") || has_param (argc, argv, "--verbose1")) verbose = 1; if (has_param (argc, argv, "-vv") || has_param (argc, argv, "--verbose2")) verbose = 2; if (has_param (argc, argv, "-vvv") || has_param (argc, argv, "--verbose3")) verbose = 3; if (has_in_name (argv[0], "_to_value")) return run_str_to_X_tests (); if (has_in_name (argv[0], "_from_value")) return run_str_from_X_tests (); return run_eq_neq_str_tests (); } libmicrohttpd-1.0.10/src/microhttpd/test_md5.c0000664000175000017500000004442315232103064014757 /* This file is part of libmicrohttpd Copyright (C) 2019-2023 Evgeny Grin (Karlson2k) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_md5.h * @brief Unit tests for md5 functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "mhd_md5_wrap.h" #include "test_helpers.h" #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_MD5_TLSLIB) && defined(MHD_HTTPS_REQUIRE_GCRYPT) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_MD5_TLSLIB && MHD_HTTPS_REQUIRE_GCRYPT */ static int verbose = 0; /* verbose level (0-1)*/ struct str_with_len { const char *const str; const size_t len; }; #define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1} struct data_unit1 { const struct str_with_len str_l; const uint8_t digest[MD5_DIGEST_SIZE]; }; static const struct data_unit1 data_units1[] = { {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), {0x1c, 0x68, 0xc2, 0xe5, 0x1f, 0x63, 0xc9, 0x5f, 0x17, 0xab, 0x1f, 0x20, 0x8b, 0x86, 0x39, 0x57}}, {D_STR_W_LEN ("Simple string."), {0xf1, 0x2b, 0x7c, 0xad, 0xa0, 0x41, 0xfe, 0xde, 0x4e, 0x68, 0x16, 0x63, 0xb4, 0x60, 0x5d, 0x78}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), {0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b}}, {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"), {0x05, 0x61, 0x3a, 0x6b, 0xde, 0x75, 0x3a, 0x45, 0x91, 0xa8, 0x81, 0xb0, 0xa7, 0xe2, 0xe2, 0x0e}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" \ "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"), {0xaf, 0xab, 0xc7, 0xe9, 0xe7, 0x17, 0xbe, 0xd6, 0xc0, 0x0f, 0x78, 0x8c, 0xde, 0xdd, 0x11, 0xd1}}, {D_STR_W_LEN ("/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/path?with%20some=parameters"), {0x7e, 0xe6, 0xdb, 0xe2, 0x76, 0x49, 0x1a, 0xd8, 0xaf, 0xf3, 0x52, 0x2d, 0xd8, 0xfc, 0x89, 0x1e}}, {D_STR_W_LEN (""), {0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e}}, {D_STR_W_LEN ("a"), {0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8, 0x31, 0xc3, 0x99, 0xe2, 0x69, 0x77, 0x26, 0x61}}, {D_STR_W_LEN ("abc"), {0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0, 0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72}}, {D_STR_W_LEN ("message digest"), {0xf9, 0x6b, 0x69, 0x7d, 0x7c, 0xb7, 0x93, 0x8d, 0x52, 0x5a, 0x2f, 0x31, 0xaa, 0xf1, 0x61, 0xd0}}, {D_STR_W_LEN ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" \ "0123456789"), {0xd1, 0x74, 0xab, 0x98, 0xd2, 0x77, 0xd9, 0xf5, 0xa5, 0x61, 0x1c, 0x2c, 0x9f, 0x41, 0x9d, 0x9f}}, {D_STR_W_LEN ("12345678901234567890123456789012345678901234567890" \ "123456789012345678901234567890"), {0x57, 0xed, 0xf4, 0xa2, 0x2b, 0xe3, 0xc9, 0x55, 0xac, 0x49, 0xda, 0x2e, 0x21, 0x07, 0xb6, 0x7a}} }; static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]); struct bin_with_len { const uint8_t bin[512]; const size_t len; }; struct data_unit2 { const struct bin_with_len bin_l; const uint8_t digest[MD5_DIGEST_SIZE]; }; static const struct data_unit2 data_units2[] = { { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */ {0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b}}, { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65}, 72 },/* 'A' x 72 times */ {0x24, 0xa5, 0xef, 0x36, 0x82, 0x80, 0x3a, 0x06, 0x2f, 0xea, 0xad, 0xad, 0x76, 0xda, 0xbd, 0xa8}}, { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73}, 55}, /* 19..73 sequence */ {0x6d, 0x2e, 0x6e, 0xde, 0x5d, 0x64, 0x6a, 0x17, 0xf1, 0x09, 0x2c, 0xac, 0x19, 0x10, 0xe3, 0xd6}}, { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */ {0x88, 0x13, 0x48, 0x47, 0x73, 0xaa, 0x92, 0xf2, 0xc9, 0xdd, 0x69, 0xb3, 0xac, 0xf4, 0xba, 0x6e}}, { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92}, 55}, /* 38..92 sequence */ {0x80, 0xf0, 0x05, 0x7e, 0xa2, 0xf7, 0xc8, 0x43, 0x12, 0xd3, 0xb1, 0x61, 0xab, 0x52, 0x3b, 0xaf}}, { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72}, 72},/* 1..72 sequence */ {0xc3, 0x28, 0xc5, 0xad, 0xc9, 0x26, 0xa9, 0x99, 0x95, 0x4a, 0x5e, 0x25, 0x50, 0x34, 0x51, 0x73}}, { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}, 256}, /* 0..255 sequence */ {0xe2, 0xc8, 0x65, 0xdb, 0x41, 0x62, 0xbe, 0xd9, 0x63, 0xbf, 0xaa, 0x9e, 0xf6, 0xac, 0x18, 0xf0}}, { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139}, 61}, /* 199..139 sequence */ {0xbb, 0x3f, 0xdb, 0x4a, 0x96, 0x03, 0x36, 0x37, 0x38, 0x78, 0x5e, 0x44, 0xbf, 0x3a, 0x85, 0x51}}, { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255}, /* 255..1 sequence */ {0x52, 0x21, 0xa5, 0x83, 0x4f, 0x38, 0x7c, 0x73, 0xba, 0x18, 0x22, 0xb1, 0xf9, 0x7e, 0xae, 0x8b}}, { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233, 235, 179, 166, 219, 60, 135, 12, 62, 153, 36, 94, 13, 28, 6, 183, 71, 222, 179, 18, 77, 200, 67, 187, 139, 166, 31, 3, 90, 125, 9, 56, 37, 31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28, 219, 174, 50, 32, 154, 80, 238, 64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220, 173, 79, 20, 242, 68, 64, 102, 208, 107, 196, 48, 183, 50, 59, 161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202, 153, 2, 185, 114, 157, 73, 44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191, 103, 214, 191, 20, 214, 126, 45, 220, 142, 102, 131, 239, 87, 73, 97, 255, 105, 143, 97, 205, 209, 30, 157, 156, 22, 114, 114, 230, 29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51, 116, 158, 12, 244, 213, 212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244, 204, 207, 211, 144, 45, 72, 211, 143, 117, 230, 217, 29, 42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212, 97, 141, 190, 123, 5, 21, 7, 59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62, 105, 21, 248, 70, 106, 4, 150, 115, 14, 217, 22, 47, 103, 104, 212, 247, 74, 74, 208, 87, 104}, 255}, /* pseudo-random data */ {0x55, 0x61, 0x2c, 0xeb, 0x29, 0xee, 0xa8, 0xb2, 0xf6, 0x10, 0x7b, 0xc1, 0x5b, 0x0f, 0x01, 0x95}} }; static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]); /* * Helper functions */ /** * Print bin as hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0')); } *hex = 0; } static int check_result (const char *test_name, unsigned int check_num, const uint8_t calculated[MD5_DIGEST_SIZE], const uint8_t expected[MD5_DIGEST_SIZE]) { int failed = memcmp (calculated, expected, MD5_DIGEST_SIZE); check_num++; /* Print 1-based numbers */ if (failed) { char calc_str[MD5_DIGEST_STRING_SIZE]; char expc_str[MD5_DIGEST_STRING_SIZE]; bin2hex (calculated, MD5_DIGEST_SIZE, calc_str); bin2hex (expected, MD5_DIGEST_SIZE, expc_str); fprintf (stderr, "FAILED: %s check %u: calculated digest %s, expected digest %s.\n", test_name, check_num, calc_str, expc_str); fflush (stderr); } else if (verbose) { char calc_str[MD5_DIGEST_STRING_SIZE]; bin2hex (calculated, MD5_DIGEST_SIZE, calc_str); printf ("PASSED: %s check %u: calculated digest %s " "matches expected digest.\n", test_name, check_num, calc_str); fflush (stdout); } return failed ? 1 : 0; } /* * Tests */ /* Calculated MD5 as one pass for whole data */ static int test1_str (void) { unsigned int i; int num_failed = 0; struct Md5CtxWr ctx; MHD_MD5_init_one_time (&ctx); for (i = 0; i < units1_num; i++) { uint8_t digest[MD5_DIGEST_SIZE]; MHD_MD5_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, data_units1[i].str_l.len); MHD_MD5_finish_reset (&ctx, digest); #ifdef MHD_MD5_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } MHD_MD5_deinit (&ctx); return num_failed; } static int test1_bin (void) { unsigned int i; int num_failed = 0; struct Md5CtxWr ctx; MHD_MD5_init_one_time (&ctx); for (i = 0; i < units2_num; i++) { uint8_t digest[MD5_DIGEST_SIZE]; MHD_MD5_update (&ctx, data_units2[i].bin_l.bin, data_units2[i].bin_l.len); MHD_MD5_finish_reset (&ctx, digest); #ifdef MHD_MD5_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } MHD_MD5_deinit (&ctx); return num_failed; } /* Calculated MD5 as two iterations for whole data */ static int test2_str (void) { unsigned int i; int num_failed = 0; struct Md5CtxWr ctx; MHD_MD5_init_one_time (&ctx); for (i = 0; i < units1_num; i++) { uint8_t digest[MD5_DIGEST_SIZE]; size_t part_s = data_units1[i].str_l.len / 4; MHD_MD5_update (&ctx, (const uint8_t *) "", 0); MHD_MD5_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, part_s); MHD_MD5_update (&ctx, (const uint8_t *) "", 0); MHD_MD5_update (&ctx, (const uint8_t *) data_units1[i].str_l.str + part_s, data_units1[i].str_l.len - part_s); MHD_MD5_update (&ctx, (const uint8_t *) "", 0); MHD_MD5_finish_reset (&ctx, digest); #ifdef MHD_MD5_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } MHD_MD5_deinit (&ctx); return num_failed; } static int test2_bin (void) { unsigned int i; int num_failed = 0; struct Md5CtxWr ctx; MHD_MD5_init_one_time (&ctx); for (i = 0; i < units2_num; i++) { uint8_t digest[MD5_DIGEST_SIZE]; size_t part_s = data_units2[i].bin_l.len * 2 / 3; MHD_MD5_update (&ctx, data_units2[i].bin_l.bin, part_s); MHD_MD5_update (&ctx, (const uint8_t *) "", 0); MHD_MD5_update (&ctx, data_units2[i].bin_l.bin + part_s, data_units2[i].bin_l.len - part_s); MHD_MD5_finish_reset (&ctx, digest); #ifdef MHD_MD5_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } MHD_MD5_deinit (&ctx); return num_failed; } /* Use data set number 7 as it has the longest sequence */ #define DATA_POS 6 #define MAX_OFFSET 31 static int test_unaligned (void) { int num_failed = 0; unsigned int offset; uint8_t *buf; uint8_t *digest_buf; struct Md5CtxWr ctx; const struct data_unit2 *const tdata = data_units2 + DATA_POS; buf = malloc (tdata->bin_l.len + MAX_OFFSET); digest_buf = malloc (MD5_DIGEST_SIZE + MAX_OFFSET); if ((NULL == buf) || (NULL == digest_buf)) exit (99); MHD_MD5_init_one_time (&ctx); for (offset = MAX_OFFSET; offset >= 1; --offset) { uint8_t *unaligned_digest; uint8_t *unaligned_buf; unaligned_buf = buf + offset; memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len); unaligned_digest = digest_buf + MAX_OFFSET - offset; memset (unaligned_digest, 0, MD5_DIGEST_SIZE); MHD_MD5_update (&ctx, unaligned_buf, tdata->bin_l.len); MHD_MD5_finish_reset (&ctx, unaligned_digest); #ifdef MHD_MD5_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif num_failed += check_result (MHD_FUNC_, MAX_OFFSET - offset, unaligned_digest, tdata->digest); } MHD_MD5_deinit (&ctx); free (digest_buf); free (buf); return num_failed; } int main (int argc, char *argv[]) { int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose")) verbose = 1; #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ num_failed += test1_str (); num_failed += test1_bin (); num_failed += test2_str (); num_failed += test2_bin (); num_failed += test_unaligned (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.10/src/microhttpd/connection_https.h0000644000175000017500000000444214760713577016641 /* This file is part of libmicrohttpd Copyright (C) 2008 Daniel Pittman and Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file connection_https.h * @brief Methods for managing connections * @author Christian Grothoff */ #ifndef CONNECTION_HTTPS_H #define CONNECTION_HTTPS_H #include "internal.h" #ifdef HTTPS_SUPPORT /** * Set connection callback function to be used through out * the processing of this secure connection. * * @param connection which callbacks should be modified */ void MHD_set_https_callbacks (struct MHD_Connection *connection); /** * Give gnuTLS chance to work on the TLS handshake. * * @param connection connection to handshake on * @return true if the handshake has completed successfully * and we should start to read/write data, * false is handshake in progress or in case * of error */ bool MHD_run_tls_handshake_ (struct MHD_Connection *connection); /** * Initiate shutdown of TLS layer of connection. * * @param connection to use * @return true if succeed, false otherwise. */ bool MHD_tls_connection_shutdown (struct MHD_Connection *connection); /** * Callback for writing data to the socket. * * @param connection the MHD connection structure * @param other data to write * @param i number of bytes to write * @return positive value for number of bytes actually sent or * negative value for error number MHD_ERR_xxx_ */ ssize_t send_tls_adapter (struct MHD_Connection *connection, const void *other, size_t i); #endif /* HTTPS_SUPPORT */ #endif libmicrohttpd-1.0.10/src/microhttpd/mhd_mono_clock.c0000664000175000017500000003465315223423441016216 /* This file is part of libmicrohttpd Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_mono_clock.h * @brief internal monotonic clock functions implementations * @author Karlson2k (Evgeny Grin) */ #include "mhd_mono_clock.h" #if defined(_WIN32) && ! defined(__CYGWIN__) /* Prefer native clock source over wrappers */ #ifdef HAVE_CLOCK_GETTIME #undef HAVE_CLOCK_GETTIME #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_GETTIMEOFDAY #undef HAVE_GETTIMEOFDAY #endif /* HAVE_GETTIMEOFDAY */ #endif /* _WIN32 && ! __CYGWIN__ */ #ifdef HAVE_TIME_H #include #endif /* HAVE_TIME_H */ #ifdef HAVE_SYS_TIME_H #include #endif /* HAVE_SYS_TIME_H */ #ifdef HAVE_CLOCK_GET_TIME #include /* for host_get_clock_service(), mach_host_self(), mach_task_self() */ #include /* for clock_get_time() */ #define _MHD_INVALID_CLOCK_SERV ((clock_serv_t) -2) static clock_serv_t mono_clock_service = _MHD_INVALID_CLOCK_SERV; #endif /* HAVE_CLOCK_GET_TIME */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN /* Do not include unneeded parts of W32 headers. */ #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #include #endif /* _WIN32 */ #ifndef NULL #define NULL ((void*)0) #endif /* ! NULL */ #ifdef HAVE_CLOCK_GETTIME #ifdef CLOCK_REALTIME #define _MHD_UNWANTED_CLOCK CLOCK_REALTIME #else /* !CLOCK_REALTIME */ #define _MHD_UNWANTED_CLOCK ((clockid_t) -2) #endif /* !CLOCK_REALTIME */ static clockid_t mono_clock_id = _MHD_UNWANTED_CLOCK; #endif /* HAVE_CLOCK_GETTIME */ /* sync clocks; reduce chance of value wrap */ #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_GET_TIME) || \ defined(HAVE_GETHRTIME) static time_t mono_clock_start; #endif /* HAVE_CLOCK_GETTIME || HAVE_CLOCK_GET_TIME || HAVE_GETHRTIME */ #if defined(HAVE_TIMESPEC_GET) || defined(HAVE_GETTIMEOFDAY) /* The start value shared for timespec_get() and gettimeofday () */ static time_t gettime_start; #endif /* HAVE_TIMESPEC_GET || HAVE_GETTIMEOFDAY */ static time_t sys_clock_start; #ifdef HAVE_GETHRTIME static hrtime_t hrtime_start; #endif /* HAVE_GETHRTIME */ #ifdef _WIN32 #if _WIN32_WINNT >= 0x0600 static uint64_t tick_start; #else /* _WIN32_WINNT < 0x0600 */ static uint64_t perf_freq; static uint64_t perf_start; #endif /* _WIN32_WINNT < 0x0600 */ #endif /* _WIN32 */ /** * Type of monotonic clock source */ enum _MHD_mono_clock_source { /** * No monotonic clock */ _MHD_CLOCK_NO_SOURCE = 0, /** * clock_gettime() with specific clock */ _MHD_CLOCK_GETTIME, /** * clock_get_time() with specific clock service */ _MHD_CLOCK_GET_TIME, /** * gethrtime() / 1000000000 */ _MHD_CLOCK_GETHRTIME, /** * GetTickCount64() / 1000 */ _MHD_CLOCK_GETTICKCOUNT64, /** * QueryPerformanceCounter() / QueryPerformanceFrequency() */ _MHD_CLOCK_PERFCOUNTER }; /** * Initialise monotonic seconds and milliseconds counters. */ void MHD_monotonic_sec_counter_init (void) { #ifdef HAVE_CLOCK_GET_TIME mach_timespec_t cur_time; #endif /* HAVE_CLOCK_GET_TIME */ enum _MHD_mono_clock_source mono_clock_source = _MHD_CLOCK_NO_SOURCE; #ifdef HAVE_CLOCK_GETTIME struct timespec ts; mono_clock_id = _MHD_UNWANTED_CLOCK; #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_CLOCK_GET_TIME mono_clock_service = _MHD_INVALID_CLOCK_SERV; #endif /* HAVE_CLOCK_GET_TIME */ /* just a little syntactic trick to get the various following ifdef's to work out nicely */ if (0) { (void) 0; /* Mute possible compiler warning */ } else #ifdef HAVE_CLOCK_GETTIME #ifdef CLOCK_MONOTONIC_COARSE /* Linux-specific fast value-getting clock */ /* Can be affected by frequency adjustment and don't count time in suspend, */ /* but preferred since it's fast */ if (0 == clock_gettime (CLOCK_MONOTONIC_COARSE, &ts)) { mono_clock_id = CLOCK_MONOTONIC_COARSE; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_MONOTONIC_COARSE */ #ifdef CLOCK_MONOTONIC_FAST /* FreeBSD/DragonFly fast value-getting clock */ /* Can be affected by frequency adjustment, but preferred since it's fast */ if (0 == clock_gettime (CLOCK_MONOTONIC_FAST, &ts)) { mono_clock_id = CLOCK_MONOTONIC_FAST; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_MONOTONIC_COARSE */ #ifdef CLOCK_MONOTONIC_RAW_APPROX /* Darwin-specific clock */ /* Not affected by frequency adjustment, returns clock value cached at * context switch. Can be "milliseconds old", but it's fast. */ if (0 == clock_gettime (CLOCK_MONOTONIC_RAW_APPROX, &ts)) { mono_clock_id = CLOCK_MONOTONIC_RAW_APPROX; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_MONOTONIC_RAW */ #ifdef CLOCK_MONOTONIC_RAW /* Linux and Darwin clock */ /* Not affected by frequency adjustment, * on Linux don't count time in suspend */ if (0 == clock_gettime (CLOCK_MONOTONIC_RAW, &ts)) { mono_clock_id = CLOCK_MONOTONIC_RAW; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_MONOTONIC_RAW */ #ifdef CLOCK_BOOTTIME /* Count time in suspend on Linux so it's real monotonic, */ /* but can be slower value-getting than other clocks */ if (0 == clock_gettime (CLOCK_BOOTTIME, &ts)) { mono_clock_id = CLOCK_BOOTTIME; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_BOOTTIME */ #ifdef CLOCK_MONOTONIC /* Monotonic clock */ /* Widely supported, may be affected by frequency adjustment */ /* On Linux it's not truly monotonic as it doesn't count time in suspend */ if (0 == clock_gettime (CLOCK_MONOTONIC, &ts)) { mono_clock_id = CLOCK_MONOTONIC; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_MONOTONIC */ #ifdef CLOCK_UPTIME /* non-Linux clock */ /* Doesn't count time in suspend */ if (0 == clock_gettime (CLOCK_UPTIME, &ts)) { mono_clock_id = CLOCK_UPTIME; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_BOOTTIME */ #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_CLOCK_GET_TIME /* Darwin-specific monotonic clock */ /* Should be monotonic as clock_set_time function always unconditionally */ /* failed on latest kernels */ if ( (KERN_SUCCESS == host_get_clock_service (mach_host_self (), SYSTEM_CLOCK, &mono_clock_service)) && (KERN_SUCCESS == clock_get_time (mono_clock_service, &cur_time)) ) { mono_clock_start = cur_time.tv_sec; mono_clock_source = _MHD_CLOCK_GET_TIME; } else #endif /* HAVE_CLOCK_GET_TIME */ #ifdef _WIN32 #if _WIN32_WINNT >= 0x0600 /* W32 Vista or later specific monotonic clock */ /* Available since Vista, ~15ms accuracy */ if (1) { tick_start = GetTickCount64 (); mono_clock_source = _MHD_CLOCK_GETTICKCOUNT64; } else #else /* _WIN32_WINNT < 0x0600 */ /* W32 specific monotonic clock */ /* Available on Windows 2000 and later */ if (1) { LARGE_INTEGER freq; LARGE_INTEGER perf_counter; QueryPerformanceFrequency (&freq); /* never fail on XP and later */ QueryPerformanceCounter (&perf_counter); /* never fail on XP and later */ perf_freq = (uint64_t) freq.QuadPart; perf_start = (uint64_t) perf_counter.QuadPart; mono_clock_source = _MHD_CLOCK_PERFCOUNTER; } else #endif /* _WIN32_WINNT < 0x0600 */ #endif /* _WIN32 */ #ifdef HAVE_CLOCK_GETTIME #ifdef CLOCK_HIGHRES /* Solaris-specific monotonic high-resolution clock */ /* Not preferred due to be potentially resource-hungry */ if (0 == clock_gettime (CLOCK_HIGHRES, &ts)) { mono_clock_id = CLOCK_HIGHRES; mono_clock_start = ts.tv_sec; mono_clock_source = _MHD_CLOCK_GETTIME; } else #endif /* CLOCK_HIGHRES */ #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_GETHRTIME /* HP-UX and Solaris monotonic clock */ /* Not preferred due to be potentially resource-hungry */ if (1) { hrtime_start = gethrtime (); mono_clock_source = _MHD_CLOCK_GETHRTIME; } else #endif /* HAVE_GETHRTIME */ { /* no suitable clock source was found */ mono_clock_source = _MHD_CLOCK_NO_SOURCE; } #ifdef HAVE_CLOCK_GET_TIME if ( (_MHD_CLOCK_GET_TIME != mono_clock_source) && (_MHD_INVALID_CLOCK_SERV != mono_clock_service) ) { /* clock service was initialised but clock_get_time failed */ mach_port_deallocate (mach_task_self (), mono_clock_service); mono_clock_service = _MHD_INVALID_CLOCK_SERV; } #else (void) mono_clock_source; /* avoid compiler warning */ #endif /* HAVE_CLOCK_GET_TIME */ #ifdef HAVE_TIMESPEC_GET if (1) { struct timespec tsg; if (TIME_UTC == timespec_get (&tsg, TIME_UTC)) gettime_start = tsg.tv_sec; else gettime_start = 0; } #elif defined(HAVE_GETTIMEOFDAY) if (1) { struct timeval tv; if (0 == gettimeofday (&tv, NULL)) gettime_start = tv.tv_sec; else gettime_start = 0; } #endif /* HAVE_GETTIMEOFDAY */ sys_clock_start = time (NULL); } /** * Deinitialise monotonic seconds and milliseconds counters by freeing * any allocated resources */ void MHD_monotonic_sec_counter_finish (void) { #ifdef HAVE_CLOCK_GET_TIME if (_MHD_INVALID_CLOCK_SERV != mono_clock_service) { mach_port_deallocate (mach_task_self (), mono_clock_service); mono_clock_service = _MHD_INVALID_CLOCK_SERV; } #endif /* HAVE_CLOCK_GET_TIME */ } /** * Monotonic seconds counter. * Tries to be not affected by manually setting the system real time * clock or adjustments by NTP synchronization. * * @return number of seconds from some fixed moment */ time_t MHD_monotonic_sec_counter (void) { #ifdef HAVE_CLOCK_GETTIME struct timespec ts; if ( (_MHD_UNWANTED_CLOCK != mono_clock_id) && (0 == clock_gettime (mono_clock_id, &ts)) ) return ts.tv_sec - mono_clock_start; #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_CLOCK_GET_TIME if (_MHD_INVALID_CLOCK_SERV != mono_clock_service) { mach_timespec_t cur_time; if (KERN_SUCCESS == clock_get_time (mono_clock_service, &cur_time)) return cur_time.tv_sec - mono_clock_start; } #endif /* HAVE_CLOCK_GET_TIME */ #if defined(_WIN32) #if _WIN32_WINNT >= 0x0600 if (1) return (time_t) (((uint64_t) (GetTickCount64 () - tick_start)) / 1000); #else /* _WIN32_WINNT < 0x0600 */ if (0 != perf_freq) { LARGE_INTEGER perf_counter; QueryPerformanceCounter (&perf_counter); /* never fail on XP and later */ return (time_t) (((uint64_t) perf_counter.QuadPart - perf_start) / perf_freq); } #endif /* _WIN32_WINNT < 0x0600 */ #endif /* _WIN32 */ #ifdef HAVE_GETHRTIME if (1) return (time_t) (((uint64_t) (gethrtime () - hrtime_start)) / 1000000000); #endif /* HAVE_GETHRTIME */ return time (NULL) - sys_clock_start; } /** * Monotonic milliseconds counter, useful for timeout calculation. * Tries to be not affected by manually setting the system real time * clock or adjustments by NTP synchronization. * * @return number of microseconds from some fixed moment */ uint64_t MHD_monotonic_msec_counter (void) { #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_TIMESPEC_GET) struct timespec ts; #endif /* HAVE_CLOCK_GETTIME || HAVE_TIMESPEC_GET */ #ifdef HAVE_CLOCK_GETTIME if ( (_MHD_UNWANTED_CLOCK != mono_clock_id) && (0 == clock_gettime (mono_clock_id, &ts)) ) return (uint64_t) (((uint64_t) (ts.tv_sec - mono_clock_start)) * 1000 + (uint64_t) (ts.tv_nsec / 1000000)); #endif /* HAVE_CLOCK_GETTIME */ #ifdef HAVE_CLOCK_GET_TIME if (_MHD_INVALID_CLOCK_SERV != mono_clock_service) { mach_timespec_t cur_time; if (KERN_SUCCESS == clock_get_time (mono_clock_service, &cur_time)) return (uint64_t) (((uint64_t) (cur_time.tv_sec - mono_clock_start)) * 1000 + (uint64_t) (cur_time.tv_nsec / 1000000)); } #endif /* HAVE_CLOCK_GET_TIME */ #if defined(_WIN32) #if _WIN32_WINNT >= 0x0600 if (1) return (uint64_t) (GetTickCount64 () - tick_start); #else /* _WIN32_WINNT < 0x0600 */ if (0 != perf_freq) { LARGE_INTEGER perf_counter; uint64_t num_ticks; uint64_t p1k; QueryPerformanceCounter (&perf_counter); /* never fail on XP and later */ num_ticks = (uint64_t) (perf_counter.QuadPart - perf_start); p1k = perf_freq / 1000; if (0 == p1k) p1k = 1; /* guard against DivBy0 if perf_freq < 1k */ return ((num_ticks / perf_freq) * 1000) + ((num_ticks % perf_freq) / p1k); } #endif /* _WIN32_WINNT < 0x0600 */ #endif /* _WIN32 */ #ifdef HAVE_GETHRTIME if (1) return ((uint64_t) (gethrtime () - hrtime_start)) / 1000000; #endif /* HAVE_GETHRTIME */ /* Fallbacks, affected by system time change */ #ifdef HAVE_TIMESPEC_GET if (TIME_UTC == timespec_get (&ts, TIME_UTC)) return (uint64_t) (((uint64_t) (ts.tv_sec - gettime_start)) * 1000 + (uint64_t) (ts.tv_nsec / 1000000)); #elif defined(HAVE_GETTIMEOFDAY) if (1) { struct timeval tv; if (0 == gettimeofday (&tv, NULL)) return (uint64_t) (((uint64_t) (tv.tv_sec - gettime_start)) * 1000 + (uint64_t) (tv.tv_usec / 1000)); } #endif /* HAVE_GETTIMEOFDAY */ /* The last resort fallback with very low resolution */ return (uint64_t) (time (NULL) - sys_clock_start) * 1000; } libmicrohttpd-1.0.10/src/microhttpd/sha1.c0000644000175000017500000003757714760713574014123 /* This file is part of libmicrohttpd Copyright (C) 2019-2022 Karlson2k (Evgeny Grin) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha1.c * @brief Calculation of SHA-1 digest as defined in FIPS PUB 180-4 (2015) * @author Karlson2k (Evgeny Grin) */ #include "sha1.h" #include #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #include "mhd_bithelpers.h" #include "mhd_assert.h" /** * Initialise structure for SHA-1 calculation. * * @param ctx_ must be a `struct sha1_ctx *` */ void MHD_SHA1_init (void *ctx_) { struct sha1_ctx *const ctx = ctx_; /* Initial hash values, see FIPS PUB 180-4 paragraph 5.3.1 */ /* Just some "magic" numbers defined by standard */ ctx->H[0] = UINT32_C (0x67452301); ctx->H[1] = UINT32_C (0xefcdab89); ctx->H[2] = UINT32_C (0x98badcfe); ctx->H[3] = UINT32_C (0x10325476); ctx->H[4] = UINT32_C (0xc3d2e1f0); /* Initialise number of bytes. */ ctx->count = 0; } /** * Base of SHA-1 transformation. * Gets full 512 bits / 64 bytes block of data and updates hash values; * @param H hash values * @param data data, must be exactly 64 bytes long */ static void sha1_transform (uint32_t H[_SHA1_DIGEST_LENGTH], const uint8_t data[SHA1_BLOCK_SIZE]) { /* Working variables, see FIPS PUB 180-4 paragraph 6.1.3 */ uint32_t a = H[0]; uint32_t b = H[1]; uint32_t c = H[2]; uint32_t d = H[3]; uint32_t e = H[4]; /* Data buffer, used as cyclic buffer. See FIPS PUB 180-4 paragraphs 5.2.1, 6.1.3 */ uint32_t W[16]; /* 'Ch' and 'Maj' macro functions are defined with widely-used optimization. See FIPS PUB 180-4 formulae 4.1. */ #define Ch(x,y,z) ( (z) ^ ((x) & ((y) ^ (z))) ) #define Maj(x,y,z) ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) ) /* Unoptimized (original) versions: */ /* #define Ch(x,y,z) ( ( (x) & (y) ) ^ ( ~(x) & (z) ) ) */ /* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */ #define Par(x,y,z) ( (x) ^ (y) ^ (z) ) /* Single step of SHA-1 computation, see FIPS PUB 180-4 paragraph 6.1.3 step 3. * Note: instead of reassigning all working variables on each step, variables are rotated for each step: SHA1STEP32 (a, b, c, d, e, func, K00, W[0]); SHA1STEP32 (e, a, b, c, d, func, K00, W[1]); so current 'vC' will be used as 'vD' on the next step, current 'vE' will be used as 'vA' on the next step. * Note: 'wt' must be used exactly one time in this macro as it change other data as well every time when used. */ #define SHA1STEP32(vA,vB,vC,vD,vE,ft,kt,wt) do { \ (vE) += _MHD_ROTL32 ((vA), 5) + ft ((vB), (vC), (vD)) + (kt) + (wt); \ (vB) = _MHD_ROTL32 ((vB), 30); } while (0) /* Get value of W(t) from input data buffer, See FIPS PUB 180-4 paragraph 6.1.3. Input data must be read in big-endian bytes order, see FIPS PUB 180-4 paragraph 3.1.2. */ /* Use cast to (void*) to mute compiler alignment warning, * data was already aligned in previous step */ #define GET_W_FROM_DATA(buf,t) \ _MHD_GET_32BIT_BE ((const void *)(((const uint8_t*) (buf)) + \ (t) * SHA1_BYTES_IN_WORD)) #ifndef _MHD_GET_32BIT_BE_UNALIGNED if (0 != (((uintptr_t) data) % _MHD_UINT32_ALIGN)) { /* Copy the unaligned input data to the aligned buffer */ memcpy (W, data, SHA1_BLOCK_SIZE); /* The W[] buffer itself will be used as the source of the data, * but data will be reloaded in correct bytes order during * the next steps */ data = (uint8_t *) W; } #endif /* _MHD_GET_32BIT_BE_UNALIGNED */ /* SHA-1 values of Kt for t=0..19, see FIPS PUB 180-4 paragraph 4.2.1. */ #define K00 UINT32_C(0x5a827999) /* SHA-1 values of Kt for t=20..39, see FIPS PUB 180-4 paragraph 4.2.1.*/ #define K20 UINT32_C(0x6ed9eba1) /* SHA-1 values of Kt for t=40..59, see FIPS PUB 180-4 paragraph 4.2.1.*/ #define K40 UINT32_C(0x8f1bbcdc) /* SHA-1 values of Kt for t=60..79, see FIPS PUB 180-4 paragraph 4.2.1.*/ #define K60 UINT32_C(0xca62c1d6) /* During first 16 steps, before making any calculations on each step, the W element is read from input data buffer as big-endian value and stored in array of W elements. */ /* Note: instead of using K constants as array, all K values are specified individually for each step. */ SHA1STEP32 (a, b, c, d, e, Ch, K00, W[0] = GET_W_FROM_DATA (data, 0)); SHA1STEP32 (e, a, b, c, d, Ch, K00, W[1] = GET_W_FROM_DATA (data, 1)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[2] = GET_W_FROM_DATA (data, 2)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[3] = GET_W_FROM_DATA (data, 3)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[4] = GET_W_FROM_DATA (data, 4)); SHA1STEP32 (a, b, c, d, e, Ch, K00, W[5] = GET_W_FROM_DATA (data, 5)); SHA1STEP32 (e, a, b, c, d, Ch, K00, W[6] = GET_W_FROM_DATA (data, 6)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[7] = GET_W_FROM_DATA (data, 7)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[8] = GET_W_FROM_DATA (data, 8)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[9] = GET_W_FROM_DATA (data, 9)); SHA1STEP32 (a, b, c, d, e, Ch, K00, W[10] = GET_W_FROM_DATA (data, 10)); SHA1STEP32 (e, a, b, c, d, Ch, K00, W[11] = GET_W_FROM_DATA (data, 11)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[12] = GET_W_FROM_DATA (data, 12)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[13] = GET_W_FROM_DATA (data, 13)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[14] = GET_W_FROM_DATA (data, 14)); SHA1STEP32 (a, b, c, d, e, Ch, K00, W[15] = GET_W_FROM_DATA (data, 15)); /* 'W' generation and assignment for 16 <= t <= 79. See FIPS PUB 180-4 paragraph 6.1.3. As only last 16 'W' are used in calculations, it is possible to use 16 elements array of W as cyclic buffer. */ #define Wgen(w,t) _MHD_ROTL32((w)[(t + 13) & 0xf] ^ (w)[(t + 8) & 0xf] \ ^ (w)[(t + 2) & 0xf] ^ (w)[t & 0xf], 1) /* During last 60 steps, before making any calculations on each step, W element is generated from W elements of cyclic buffer and generated value stored back in cyclic buffer. */ /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 paragraph 4.2.1. */ SHA1STEP32 (e, a, b, c, d, Ch, K00, W[16 & 0xf] = Wgen (W, 16)); SHA1STEP32 (d, e, a, b, c, Ch, K00, W[17 & 0xf] = Wgen (W, 17)); SHA1STEP32 (c, d, e, a, b, Ch, K00, W[18 & 0xf] = Wgen (W, 18)); SHA1STEP32 (b, c, d, e, a, Ch, K00, W[19 & 0xf] = Wgen (W, 19)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[20 & 0xf] = Wgen (W, 20)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[21 & 0xf] = Wgen (W, 21)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[22 & 0xf] = Wgen (W, 22)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[23 & 0xf] = Wgen (W, 23)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[24 & 0xf] = Wgen (W, 24)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[25 & 0xf] = Wgen (W, 25)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[26 & 0xf] = Wgen (W, 26)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[27 & 0xf] = Wgen (W, 27)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[28 & 0xf] = Wgen (W, 28)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[29 & 0xf] = Wgen (W, 29)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[30 & 0xf] = Wgen (W, 30)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[31 & 0xf] = Wgen (W, 31)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[32 & 0xf] = Wgen (W, 32)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[33 & 0xf] = Wgen (W, 33)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[34 & 0xf] = Wgen (W, 34)); SHA1STEP32 (a, b, c, d, e, Par, K20, W[35 & 0xf] = Wgen (W, 35)); SHA1STEP32 (e, a, b, c, d, Par, K20, W[36 & 0xf] = Wgen (W, 36)); SHA1STEP32 (d, e, a, b, c, Par, K20, W[37 & 0xf] = Wgen (W, 37)); SHA1STEP32 (c, d, e, a, b, Par, K20, W[38 & 0xf] = Wgen (W, 38)); SHA1STEP32 (b, c, d, e, a, Par, K20, W[39 & 0xf] = Wgen (W, 39)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[40 & 0xf] = Wgen (W, 40)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[41 & 0xf] = Wgen (W, 41)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[42 & 0xf] = Wgen (W, 42)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[43 & 0xf] = Wgen (W, 43)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[44 & 0xf] = Wgen (W, 44)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[45 & 0xf] = Wgen (W, 45)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[46 & 0xf] = Wgen (W, 46)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[47 & 0xf] = Wgen (W, 47)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[48 & 0xf] = Wgen (W, 48)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[49 & 0xf] = Wgen (W, 49)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[50 & 0xf] = Wgen (W, 50)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[51 & 0xf] = Wgen (W, 51)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[52 & 0xf] = Wgen (W, 52)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[53 & 0xf] = Wgen (W, 53)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[54 & 0xf] = Wgen (W, 54)); SHA1STEP32 (a, b, c, d, e, Maj, K40, W[55 & 0xf] = Wgen (W, 55)); SHA1STEP32 (e, a, b, c, d, Maj, K40, W[56 & 0xf] = Wgen (W, 56)); SHA1STEP32 (d, e, a, b, c, Maj, K40, W[57 & 0xf] = Wgen (W, 57)); SHA1STEP32 (c, d, e, a, b, Maj, K40, W[58 & 0xf] = Wgen (W, 58)); SHA1STEP32 (b, c, d, e, a, Maj, K40, W[59 & 0xf] = Wgen (W, 59)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[60 & 0xf] = Wgen (W, 60)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[61 & 0xf] = Wgen (W, 61)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[62 & 0xf] = Wgen (W, 62)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[63 & 0xf] = Wgen (W, 63)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[64 & 0xf] = Wgen (W, 64)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[65 & 0xf] = Wgen (W, 65)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[66 & 0xf] = Wgen (W, 66)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[67 & 0xf] = Wgen (W, 67)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[68 & 0xf] = Wgen (W, 68)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[69 & 0xf] = Wgen (W, 69)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[70 & 0xf] = Wgen (W, 70)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[71 & 0xf] = Wgen (W, 71)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[72 & 0xf] = Wgen (W, 72)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[73 & 0xf] = Wgen (W, 73)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[74 & 0xf] = Wgen (W, 74)); SHA1STEP32 (a, b, c, d, e, Par, K60, W[75 & 0xf] = Wgen (W, 75)); SHA1STEP32 (e, a, b, c, d, Par, K60, W[76 & 0xf] = Wgen (W, 76)); SHA1STEP32 (d, e, a, b, c, Par, K60, W[77 & 0xf] = Wgen (W, 77)); SHA1STEP32 (c, d, e, a, b, Par, K60, W[78 & 0xf] = Wgen (W, 78)); SHA1STEP32 (b, c, d, e, a, Par, K60, W[79 & 0xf] = Wgen (W, 79)); /* Compute intermediate hash. See FIPS PUB 180-4 paragraph 6.1.3 step 4. */ H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; } /** * Process portion of bytes. * * @param ctx_ must be a `struct sha1_ctx *` * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA1_update (void *ctx_, const uint8_t *data, size_t length) { struct sha1_ctx *const ctx = ctx_; unsigned bytes_have; /**< Number of bytes in buffer */ mhd_assert ((data != NULL) || (length == 0)); if (0 == length) return; /* Do nothing */ /* Note: (count & (SHA1_BLOCK_SIZE-1)) equal (count % SHA1_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned) (ctx->count & (SHA1_BLOCK_SIZE - 1)); ctx->count += length; if (0 != bytes_have) { unsigned bytes_left = SHA1_BLOCK_SIZE - bytes_have; if (length >= bytes_left) { /* Combine new data with the data in the buffer and process the full block. */ memcpy (ctx->buffer + bytes_have, data, bytes_left); data += bytes_left; length -= bytes_left; sha1_transform (ctx->H, ctx->buffer); bytes_have = 0; } } while (SHA1_BLOCK_SIZE <= length) { /* Process any full blocks of new data directly, without copying to the buffer. */ sha1_transform (ctx->H, data); data += SHA1_BLOCK_SIZE; length -= SHA1_BLOCK_SIZE; } if (0 != length) { /* Copy incomplete block of new data (if any) to the buffer. */ memcpy (ctx->buffer + bytes_have, data, length); } } /** * Size of "length" padding addition in bytes. * See FIPS PUB 180-4 paragraph 5.1.1. */ #define SHA1_SIZE_OF_LEN_ADD (64 / 8) /** * Finalise SHA-1 calculation, return digest. * * @param ctx_ must be a `struct sha1_ctx *` * @param[out] digest set to the hash, must be #SHA1_DIGEST_SIZE bytes */ void MHD_SHA1_finish (void *ctx_, uint8_t digest[SHA1_DIGEST_SIZE]) { struct sha1_ctx *const ctx = ctx_; uint64_t num_bits; /**< Number of processed bits */ unsigned bytes_have; /**< Number of bytes in buffer */ num_bits = ctx->count << 3; /* Note: (count & (SHA1_BLOCK_SIZE-1)) equals (count % SHA1_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned) (ctx->count & (SHA1_BLOCK_SIZE - 1)); /* Input data must be padded with bit "1" and with length of data in bits. See FIPS PUB 180-4 paragraph 5.1.1. */ /* Data is always processed in form of bytes (not by individual bits), therefore position of first padding bit in byte is always predefined (0x80). */ /* Buffer always have space at least for one byte (as full buffers are processed immediately). */ ctx->buffer[bytes_have++] = 0x80; if (SHA1_BLOCK_SIZE - bytes_have < SHA1_SIZE_OF_LEN_ADD) { /* No space in current block to put total length of message. Pad current block with zeros and process it. */ if (SHA1_BLOCK_SIZE > bytes_have) memset (ctx->buffer + bytes_have, 0, SHA1_BLOCK_SIZE - bytes_have); /* Process full block. */ sha1_transform (ctx->H, ctx->buffer); /* Start new block. */ bytes_have = 0; } /* Pad the rest of the buffer with zeros. */ memset (ctx->buffer + bytes_have, 0, SHA1_BLOCK_SIZE - SHA1_SIZE_OF_LEN_ADD - bytes_have); /* Put the number of bits in the processed message as a big-endian value. */ _MHD_PUT_64BIT_BE_SAFE (ctx->buffer + SHA1_BLOCK_SIZE - SHA1_SIZE_OF_LEN_ADD, num_bits); /* Process the full final block. */ sha1_transform (ctx->H, ctx->buffer); /* Put final hash/digest in BE mode */ #ifndef _MHD_PUT_32BIT_BE_UNALIGNED if (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN) { uint32_t alig_dgst[_SHA1_DIGEST_LENGTH]; _MHD_PUT_32BIT_BE (alig_dgst + 0, ctx->H[0]); _MHD_PUT_32BIT_BE (alig_dgst + 1, ctx->H[1]); _MHD_PUT_32BIT_BE (alig_dgst + 2, ctx->H[2]); _MHD_PUT_32BIT_BE (alig_dgst + 3, ctx->H[3]); _MHD_PUT_32BIT_BE (alig_dgst + 4, ctx->H[4]); /* Copy result to unaligned destination address */ memcpy (digest, alig_dgst, SHA1_DIGEST_SIZE); } else #else /* _MHD_PUT_32BIT_BE_UNALIGNED */ if (1) #endif /* _MHD_PUT_32BIT_BE_UNALIGNED */ { /* Use cast to (void*) here to mute compiler alignment warnings. * Compilers are not smart enough to see that alignment has been checked. */ _MHD_PUT_32BIT_BE ((void *) (digest + 0 * SHA1_BYTES_IN_WORD), ctx->H[0]); _MHD_PUT_32BIT_BE ((void *) (digest + 1 * SHA1_BYTES_IN_WORD), ctx->H[1]); _MHD_PUT_32BIT_BE ((void *) (digest + 2 * SHA1_BYTES_IN_WORD), ctx->H[2]); _MHD_PUT_32BIT_BE ((void *) (digest + 3 * SHA1_BYTES_IN_WORD), ctx->H[3]); _MHD_PUT_32BIT_BE ((void *) (digest + 4 * SHA1_BYTES_IN_WORD), ctx->H[4]); } /* Erase potentially sensitive data. */ memset (ctx, 0, sizeof(struct sha1_ctx)); } libmicrohttpd-1.0.10/src/microhttpd/test_str_token_remove.c0000664000175000017500000003002615232103064017651 /* This file is part of libmicrohttpd Copyright (C) 2017-2021 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_token.c * @brief Unit tests for MHD_str_remove_token_caseless_() function * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static int expect_result_n (const char *str, size_t str_len, const char *token, size_t token_len, const char *expected, size_t expected_len, const bool expected_removed) { char buf_in[1024]; char buf_token[256]; char buf_out[1024]; size_t buf_len; mhd_assert (sizeof(buf_in) > str_len + 2); mhd_assert (sizeof(buf_token) > token_len + 2); mhd_assert (sizeof(buf_out) > expected_len + 2); memset (buf_in, '#', sizeof(buf_in)); memset (buf_token, '#', sizeof(buf_token)); memcpy (buf_in, str, str_len); /* Copy without zero-termination */ memcpy (buf_token, token, token_len); /* Copy without zero-termination */ for (buf_len = 0; buf_len <= expected_len + 3; ++buf_len) { bool res; ssize_t result_len; memset (buf_out, '$', sizeof(buf_out)); result_len = (ssize_t) buf_len; mhd_assert (0 <= result_len); res = MHD_str_remove_token_caseless_ (buf_in, str_len, buf_token, token_len, buf_out, &result_len); if (buf_len < expected_len) { /* The result should not fit into the buffer */ if (res || (0 <= result_len)) { fprintf (stderr, "MHD_str_remove_token_caseless_() FAILED:\n" "\tMHD_str_remove_token_caseless_(\"%.*s\", %lu," " \"%.*s\", %lu, buf, &(%ld->%ld)) returned %s\n", (int) str_len + 2, buf_in, (unsigned long) str_len, (int) token_len + 2, buf_token, (unsigned long) token_len, (long) buf_len, (long) result_len, res ? "true" : "false"); return 1; } } else { /* The result should fit into the buffer */ if ( (expected_removed != res) || (result_len < 0) || (expected_len != (size_t) result_len) || ((0 != result_len) && (0 != memcmp (expected, buf_out, (size_t) result_len))) || ('$' != buf_out[result_len])) { fprintf (stderr, "MHD_str_remove_token_caseless_() FAILED:\n" "\tMHD_str_remove_token_caseless_(\"%.*s\", %lu," " \"%.*s\", %lu, \"%.*s\", &(%ld->%ld)) returned %s\n", (int) str_len + 2, buf_in, (unsigned long) str_len, (int) token_len + 2, buf_token, (unsigned long) token_len, (int) expected_len + 2, buf_out, (long) buf_len, (long) result_len, res ? "true" : "false"); return 1; } } } return 0; } #define expect_result(s,t,e,found) \ expect_result_n ((s),MHD_STATICSTR_LEN_ (s), \ (t),MHD_STATICSTR_LEN_ (t), \ (e),MHD_STATICSTR_LEN_ (e), found) static int check_result (void) { int errcount = 0; errcount += expect_result ("string", "string", "", true); errcount += expect_result ("String", "string", "", true); errcount += expect_result ("string", "String", "", true); errcount += expect_result ("strinG", "String", "", true); errcount += expect_result ("\t strinG", "String", "", true); errcount += expect_result ("strinG\t ", "String", "", true); errcount += expect_result (" \t tOkEn ", "toKEN", "", true); errcount += expect_result ("not token\t, tOkEn ", "toKEN", "not token", true); errcount += expect_result ("not token,\t tOkEn, more token", "toKEN", "not token, more token", true); errcount += expect_result ("not token,\t tOkEn\t, more token", "toKEN", "not token, more token", true); errcount += expect_result (",,,,,,test,,,,", "TESt", "", true); errcount += expect_result (",,,,,\t,test,,,,", "TESt", "", true); errcount += expect_result (",,,,,,test, ,,,", "TESt", "", true); errcount += expect_result (",,,,,, test,,,,", "TESt", "", true); errcount += expect_result (",,,,,, test not,test,,", "TESt", "test not", true); errcount += expect_result (",,,,,, test not,,test,,", "TESt", "test not", true); errcount += expect_result (",,,,,, test not ,test,,", "TESt", "test not", true); errcount += expect_result (",,,,,, test", "TESt", "", true); errcount += expect_result (",,,,,, test ", "TESt", "", true); errcount += expect_result ("no test,,,,,, test ", "TESt", "no test", true); errcount += expect_result ("the-token,, the-token , the-token" \ ",the-token ,the-token", "the-token", "", true); errcount += expect_result (" the-token,, the-token , the-token," \ "the-token ,the-token ", "the-token", "", true); errcount += expect_result (" the-token ,, the-token , the-token," \ "the-token , the-token ", "the-token", "", true); errcount += expect_result ("the-token,a, the-token , the-token,b," \ "the-token , c,the-token", "the-token", "a, b, c", true); errcount += expect_result (" the-token, a, the-token , the-token, b," \ "the-token ,c ,the-token ", "the-token", "a, b, c", true); errcount += expect_result (" the-token , a , the-token , the-token, b ," \ "the-token , c , the-token ", "the-token", "a, b, c",true); errcount += expect_result ("the-token,aa, the-token , the-token,bb," \ "the-token , cc,the-token", "the-token", "aa, bb, cc", true); errcount += expect_result (" the-token, aa, the-token , the-token, bb," \ "the-token ,cc ,the-token ", "the-token", "aa, bb, cc", true); errcount += expect_result (" the-token , aa , the-token , the-token, bb ," \ "the-token , cc , the-token ", "the-token", "aa, bb, cc", true); errcount += expect_result ("strin", "string", "strin", false); errcount += expect_result ("Stringer", "string", "Stringer", false); errcount += expect_result ("sstring", "String", "sstring", false); errcount += expect_result ("string", "Strin", "string", false); errcount += expect_result ("\t( strinG", "String", "( strinG", false); errcount += expect_result (")strinG\t ", "String", ")strinG", false); errcount += expect_result (" \t tOkEn t ", "toKEN", "tOkEn t", false); errcount += expect_result ("not token\t, tOkEner ", "toKEN", "not token, tOkEner", false); errcount += expect_result ("not token,\t tOkEns, more token", "toKEN", "not token, tOkEns, more token", false); errcount += expect_result ("not token,\t tOkEns\t, more token", "toKEN", "not token, tOkEns, more token", false); errcount += expect_result (",,,,,,testing,,,,", "TESt", "testing", false); errcount += expect_result (",,,,,\t,test,,,,", "TESting", "test", false); errcount += expect_result ("tests,,,,,,quest, ,,,", "TESt", "tests, quest", false); errcount += expect_result (",,,,,, testы,,,,", "TESt", "testы", false); errcount += expect_result (",,,,,, test not,хtest,,", "TESt", "test not, хtest", false); errcount += expect_result ("testing,,,,,, test not,,test2,,", "TESt", "testing, test not, test2", false); errcount += expect_result (",testi,,,,, test not ,test,,", "TESting", "testi, test not, test", false); errcount += expect_result (",,,,,,2 test", "TESt", "2 test", false); errcount += expect_result (",,,,,,test test ", "test", "test test", false); errcount += expect_result ("no test,,,,,,test test", "test", "no test, test test", false); errcount += expect_result (",,,,,,,,,,,,,,,,,,,", "the-token", "", false); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,", "the-token", "a, b, c, d, e, f, g", false); errcount += expect_result (",,,,,,,,,,,,,,,,,,,", "", "", false); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,", "", "a, b, c, d, e, f, g", false); errcount += expect_result ("a,b,c,d,e,f,g", "", "a, b, c, d, e, f, g", false); errcount += expect_result ("a1,b1,c1,d1,e1,f1,g1", "", "a1, b1, c1, d1, e1, f1, g1", false); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token", "the-token", "a, b, c, d, e, f, g", true); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token,", "the-token", "a, b, c, d, e, f, g", true); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token,x", "the-token", "a, b, c, d, e, f, g, x", true); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token x", "the-token", "a, b, c, d, e, f, g, the-token x", false); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token x,", "the-token", "a, b, c, d, e, f, g, the-token x", false); errcount += expect_result (",a,b,c,d,e,f,g,,,,,,,,,,,,the-token x,x", "the-token", "a, b, c, d, e, f, g," \ " the-token x, x", false); errcount += expect_result ("the-token,a,b,c,d,e,f,g,,,,,,,,,,,,the-token", "the-token", "a, b, c, d, e, f, g", true); errcount += expect_result ("the-token ,a,b,c,d,e,f,g,,,,,,,,,,,,the-token,", "the-token", "a, b, c, d, e, f, g", true); errcount += expect_result ("the-token,a,b,c,d,e,f,g,,,,,,,,,,,,the-token,x", "the-token", "a, b, c, d, e, f, g, x", true); errcount += expect_result ("the-token x,a,b,c,d,e,f,g,,,,,,,,,,,," \ "the-token x", "the-token", "the-token x, a, b, c, d, e, f, g, the-token x", false); errcount += expect_result ("the-token x,a,b,c,d,e,f,g,,,,,,,,,,,," \ "the-token x,", "the-token", "the-token x, a, b, c, d, e, f, g, the-token x", false); errcount += expect_result ("the-token x,a,b,c,d,e,f,g,,,,,,,,,,,," \ "the-token x,x", "the-token", "the-token x, a, b, c, d, e, f, g, " \ "the-token x, x", false); return errcount; } int main (int argc, char *argv[]) { int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_result (); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.10/src/microhttpd/sysfdsetsize.h0000644000175000017500000000276114760713577016021 /* This file is part of libmicrohttpd Copyright (C) 2015-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/sysfdsetsize.h * @brief Helper for obtaining FD_SETSIZE system default value * @author Karlson2k (Evgeny Grin) */ #ifndef SYSFDSETSIZE_H #define SYSFDSETSIZE_H 1 #include "mhd_options.h" #ifndef MHD_SYS_FD_SETSIZE_ /** * Get system default value of FD_SETSIZE * @return system default value of FD_SETSIZE */ unsigned int get_system_fdsetsize_value (void); #else /* MHD_SYS_FD_SETSIZE_ */ /** * Get system default value of FD_SETSIZE * @return system default value of FD_SETSIZE */ _MHD_static_inline unsigned int get_system_fdsetsize_value (void) { return (unsigned int) MHD_SYS_FD_SETSIZE_; } #endif /* MHD_SYS_FD_SETSIZE_ */ #endif /* !SYSFDSETSIZE_H */ libmicrohttpd-1.0.10/src/microhttpd/mhd_opt_matrix.c0000664000175000017500000003573215232103064016254 /* This file is part of GNU libmicrohttpd Copyright (C) 2026 Christian Grothoff GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/mhd_opt_matrix.c * @brief The environment-driven daemon option matrix shared by the tests * @author Christian Grothoff */ #include "platform.h" #include #include #include #include #include "mhd_opt_matrix.h" /** * The built-in matrix of daemon option profiles. * * Every value of every dimension listed in the header appears at least once: * * * memory limit: 0 (default), 64, 128, 256, 512, 1024, 2048, 3072, 4096; * * client discipline level: -3, -2, -1, 0, 1, 2, 3; * * #MHD_OPTION_STRICT_FOR_CLIENT with a positive and with a negative value; * * threading: external polling, one internal thread, thread-per-connection, * thread pool; * * polling backend: select(), poll(), epoll. * * Profile zero is "neutral": it is exactly the configuration the tests of * this directory used before the matrix was introduced. * * The combination "thread-per-connection + epoll" is deliberately absent: MHD * rejects it (daemon.c:8680). External polling is always paired with the * select()-style interface, as that is the only one the tests can drive. */ static const struct MHD_OptMatrixProfile opt_profiles[] = { /* name mem discp legacy threading poll pool */ { "default", 0, 0, 0, MHD_OPT_MATRIX_THR_INTERNAL, MHD_OPT_MATRIX_POLL_SELECT, 0 }, { "mem-64", 64, 0, 0, MHD_OPT_MATRIX_THR_INTERNAL, MHD_OPT_MATRIX_POLL_SELECT, 0 }, { "mem-128", 128, 0, 0, MHD_OPT_MATRIX_THR_INTERNAL, MHD_OPT_MATRIX_POLL_POLL, 0 }, { "mem-256", 256, 0, 0, MHD_OPT_MATRIX_THR_PER_CONNECTION, MHD_OPT_MATRIX_POLL_SELECT, 0 }, { "mem-512", 512, 0, 0, MHD_OPT_MATRIX_THR_PER_CONNECTION, MHD_OPT_MATRIX_POLL_POLL, 0 }, { "mem-1024", 1024, 0, 0, MHD_OPT_MATRIX_THR_INTERNAL, MHD_OPT_MATRIX_POLL_EPOLL, 0 }, { "mem-2048", 2048, 0, 0, MHD_OPT_MATRIX_THR_POOL, MHD_OPT_MATRIX_POLL_SELECT, 4 }, { "mem-3072", 3072, 0, 0, MHD_OPT_MATRIX_THR_EXTERNAL, MHD_OPT_MATRIX_POLL_SELECT, 0 }, { "mem-4096", 4096, 0, 0, MHD_OPT_MATRIX_THR_POOL, MHD_OPT_MATRIX_POLL_EPOLL, 3 }, { "strict-1", 0, 1, 0, MHD_OPT_MATRIX_THR_INTERNAL, MHD_OPT_MATRIX_POLL_SELECT, 0 }, { "strict-2", 1024, 2, 0, MHD_OPT_MATRIX_THR_INTERNAL, MHD_OPT_MATRIX_POLL_POLL, 0 }, { "strict-3", 512, 3, 0, MHD_OPT_MATRIX_THR_INTERNAL, MHD_OPT_MATRIX_POLL_EPOLL, 0 }, { "lax-1", 512, -1, 0, MHD_OPT_MATRIX_THR_INTERNAL, MHD_OPT_MATRIX_POLL_SELECT, 0 }, { "lax-2", 256, -2, 0, MHD_OPT_MATRIX_THR_PER_CONNECTION, MHD_OPT_MATRIX_POLL_SELECT, 0 }, { "lax-3", 2048, -3, 0, MHD_OPT_MATRIX_THR_POOL, MHD_OPT_MATRIX_POLL_SELECT, 4 }, { "legacy-strict", 768, 1, 1, MHD_OPT_MATRIX_THR_INTERNAL, MHD_OPT_MATRIX_POLL_SELECT, 0 }, { "legacy-lax", 768, -1, 1, MHD_OPT_MATRIX_THR_EXTERNAL, MHD_OPT_MATRIX_POLL_SELECT, 0 } }; /** * The number of built-in profiles. */ #define NUM_PROFILES \ ((unsigned int) (sizeof(opt_profiles) / sizeof(opt_profiles[0]))) /** * Non-zero once the environment has been read into @a env_profile. */ static int env_parsed; /** * Non-zero if the environment selects a profile at all. */ static int env_selected; /** * The profile derived from the environment. */ static struct MHD_OptMatrixProfile env_profile; /** * The name of @a env_profile. */ static char env_profile_name[64]; unsigned int mhd_opt_matrix_num_profiles (void) { return NUM_PROFILES; } const struct MHD_OptMatrixProfile * mhd_opt_matrix_profile (unsigned int idx) { return opt_profiles + (idx % NUM_PROFILES); } const struct MHD_OptMatrixProfile * mhd_opt_matrix_lookup (const char *name_or_idx) { unsigned int i; if ((NULL == name_or_idx) || (0 == name_or_idx[0])) return NULL; for (i = 0; i < NUM_PROFILES; ++i) { if (0 == strcmp (name_or_idx, opt_profiles[i].name)) return opt_profiles + i; } if (('0' <= name_or_idx[0]) && ('9' >= name_or_idx[0])) { char *end; unsigned long v; v = strtoul (name_or_idx, &end, 10); if ((NULL != end) && (0 == *end) && (NUM_PROFILES > v)) return opt_profiles + v; } return NULL; } /** * Parse the threading mode name. * * @param s the name * @param[out] out the parsed mode * @return non-zero on success */ static int parse_threading (const char *s, enum MHD_OptMatrixThreading *out) { if (0 == strcmp (s, "external")) *out = MHD_OPT_MATRIX_THR_EXTERNAL; else if (0 == strcmp (s, "internal")) *out = MHD_OPT_MATRIX_THR_INTERNAL; else if ((0 == strcmp (s, "per-connection")) || (0 == strcmp (s, "tpc"))) *out = MHD_OPT_MATRIX_THR_PER_CONNECTION; else if (0 == strcmp (s, "pool")) *out = MHD_OPT_MATRIX_THR_POOL; else return 0; return ! 0; } /** * Parse the polling backend name. * * @param s the name * @param[out] out the parsed backend * @return non-zero on success */ static int parse_poll (const char *s, enum MHD_OptMatrixPoll *out) { if (0 == strcmp (s, "select")) *out = MHD_OPT_MATRIX_POLL_SELECT; else if (0 == strcmp (s, "poll")) *out = MHD_OPT_MATRIX_POLL_POLL; else if (0 == strcmp (s, "epoll")) *out = MHD_OPT_MATRIX_POLL_EPOLL; else return 0; return ! 0; } /** * Report a broken environment variable and terminate: a typo in a driver * script must not silently produce a run with the default configuration. * * @param name the name of the variable * @param value the offending value */ _MHD_NORETURN static void env_error (const char *name, const char *value) { fprintf (stderr, "Invalid value '%s' for the environment variable %s.\n", (NULL != value) ? value : "(null)", name); fflush (stderr); exit (99); } const struct MHD_OptMatrixProfile * mhd_opt_matrix_from_env (void) { const char *prof_env; const char *mem_env; const char *discp_env; const char *strict_env; const char *thr_env; const char *poll_env; if (0 != env_parsed) return env_selected ? &env_profile : NULL; env_parsed = ! 0; prof_env = getenv (MHD_OPT_MATRIX_PROFILE_ENV); mem_env = getenv (MHD_OPT_MATRIX_MEM_ENV); discp_env = getenv (MHD_OPT_MATRIX_DISCP_ENV); strict_env = getenv (MHD_OPT_MATRIX_STRICT_ENV); thr_env = getenv (MHD_OPT_MATRIX_THREADING_ENV); poll_env = getenv (MHD_OPT_MATRIX_POLL_ENV); if ((NULL == prof_env) && (NULL == mem_env) && (NULL == discp_env) && (NULL == strict_env) && (NULL == thr_env) && (NULL == poll_env)) return NULL; /* Nothing selected: keep the previous behaviour */ if (NULL != prof_env) { const struct MHD_OptMatrixProfile *base; base = mhd_opt_matrix_lookup (prof_env); if (NULL == base) env_error (MHD_OPT_MATRIX_PROFILE_ENV, prof_env); env_profile = *base; } else env_profile = opt_profiles[0]; strncpy (env_profile_name, env_profile.name, sizeof(env_profile_name) - 1); env_profile_name[sizeof(env_profile_name) - 1] = 0; env_profile.name = env_profile_name; /* The explicit per-dimension overrides below are NOT clamped: they are an explicit request by the caller, see the header. */ if (NULL != mem_env) { if (0 == strcmp (mem_env, "default")) env_profile.mem_limit = 0; else { char *end; unsigned long v; v = strtoul (mem_env, &end, 10); if ((NULL == end) || (0 != *end)) env_error (MHD_OPT_MATRIX_MEM_ENV, mem_env); env_profile.mem_limit = (size_t) v; } } if (NULL != discp_env) { char *end; long v; v = strtol (discp_env, &end, 10); if ((NULL == end) || (0 != *end) || (-3 > v) || (3 < v)) env_error (MHD_OPT_MATRIX_DISCP_ENV, discp_env); env_profile.discipline_lvl = (int) v; env_profile.use_legacy_strict = 0; } if (NULL != strict_env) { char *end; long v; v = strtol (strict_env, &end, 10); if ((NULL == end) || (0 != *end)) env_error (MHD_OPT_MATRIX_STRICT_ENV, strict_env); env_profile.discipline_lvl = (int) v; env_profile.use_legacy_strict = ! 0; } if (NULL != thr_env) { if (! parse_threading (thr_env, &env_profile.threading)) env_error (MHD_OPT_MATRIX_THREADING_ENV, thr_env); if ((MHD_OPT_MATRIX_THR_POOL == env_profile.threading) && (2 > env_profile.thread_pool_size)) env_profile.thread_pool_size = 4; } if (NULL != poll_env) { if (! parse_poll (poll_env, &env_profile.poll_backend)) env_error (MHD_OPT_MATRIX_POLL_ENV, poll_env); } env_selected = ! 0; return &env_profile; } int mhd_opt_matrix_effective_discipline (const struct MHD_OptMatrixProfile *prof) { if (NULL == prof) return 0; if (! prof->use_legacy_strict) return prof->discipline_lvl; /* Mirror the mapping of daemon.c:7102-7106 exactly. */ if (-1 >= prof->discipline_lvl) return -3; if (1 <= prof->discipline_lvl) return 1; return 0; } int mhd_opt_matrix_profile_supported (const struct MHD_OptMatrixProfile *prof) { if (NULL == prof) return ! 0; if ((MHD_OPT_MATRIX_THR_EXTERNAL != prof->threading) && (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_THREADS))) return 0; if (MHD_OPT_MATRIX_THR_EXTERNAL == prof->threading) { /* Only the select()-style external interface is driven by the tests. */ return (MHD_OPT_MATRIX_POLL_SELECT == prof->poll_backend) ? ! 0 : 0; } if ((MHD_OPT_MATRIX_POLL_POLL == prof->poll_backend) && (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_POLL))) return 0; if (MHD_OPT_MATRIX_POLL_EPOLL == prof->poll_backend) { if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_EPOLL)) return 0; /* MHD refuses to combine 'epoll' with a thread per connection. */ if (MHD_OPT_MATRIX_THR_PER_CONNECTION == prof->threading) return 0; } return ! 0; } const char * mhd_opt_matrix_describe (const struct MHD_OptMatrixProfile *prof, char *buf, size_t buf_size) { static const char *const thr_names[] = { "external polling", "internal thread", "thread-per-connection", "thread pool" }; static const char *const poll_names[] = { "select()", "poll()", "epoll" }; char mem[32]; char pool[32]; char discp[64]; if (NULL == prof) { snprintf (buf, buf_size, "(built-in defaults of the test)"); return buf; } if (0 == prof->mem_limit) snprintf (mem, sizeof(mem), "default"); else snprintf (mem, sizeof(mem), "%lu", (unsigned long) prof->mem_limit); if (MHD_OPT_MATRIX_THR_POOL == prof->threading) snprintf (pool, sizeof(pool), " x%u", prof->thread_pool_size); else pool[0] = 0; /* Always show the level that is really in effect: the deprecated option silently maps its value, see mhd_opt_matrix_effective_discipline(). */ if (prof->use_legacy_strict) snprintf (discp, sizeof(discp), "strict_for_client=%d -> discipline_lvl=%d", prof->discipline_lvl, mhd_opt_matrix_effective_discipline (prof)); else snprintf (discp, sizeof(discp), "discipline_lvl=%d", prof->discipline_lvl); snprintf (buf, buf_size, "'%s' (mem_limit=%s, %s, %s%s, %s)", prof->name, mem, discp, thr_names[(unsigned int) prof->threading], pool, poll_names[(unsigned int) prof->poll_backend]); return buf; } unsigned int mhd_opt_matrix_fill_options (const struct MHD_OptMatrixProfile *prof, struct MHD_OptionItem *ops, unsigned int max_ops) { unsigned int n = 0; if (4 > max_ops) return 0; if (NULL != prof) { if (0 != prof->mem_limit) { ops[n].option = MHD_OPTION_CONNECTION_MEMORY_LIMIT; ops[n].value = (intptr_t) prof->mem_limit; ops[n].ptr_value = NULL; ++n; } if (0 != prof->discipline_lvl) { ops[n].option = prof->use_legacy_strict ? MHD_OPTION_STRICT_FOR_CLIENT : MHD_OPTION_CLIENT_DISCIPLINE_LVL; ops[n].value = (intptr_t) prof->discipline_lvl; ops[n].ptr_value = NULL; ++n; } if ((MHD_OPT_MATRIX_THR_POOL == prof->threading) && (1 < prof->thread_pool_size)) { ops[n].option = MHD_OPTION_THREAD_POOL_SIZE; ops[n].value = (intptr_t) prof->thread_pool_size; ops[n].ptr_value = NULL; ++n; } } ops[n].option = MHD_OPTION_END; ops[n].value = 0; ops[n].ptr_value = NULL; ++n; return n; } unsigned int mhd_opt_matrix_daemon_flags (const struct MHD_OptMatrixProfile *prof, unsigned int base_flags, int allow_external) { unsigned int flags = base_flags; if (NULL == prof) return flags; switch (prof->threading) { case MHD_OPT_MATRIX_THR_EXTERNAL: if (allow_external) return flags; /* No internal thread, no polling backend flag */ /* The caller cannot drive MHD_run(); fall back to an internal thread. */ return flags | MHD_USE_INTERNAL_POLLING_THREAD; case MHD_OPT_MATRIX_THR_PER_CONNECTION: flags |= MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION; break; case MHD_OPT_MATRIX_THR_INTERNAL: case MHD_OPT_MATRIX_THR_POOL: default: flags |= MHD_USE_INTERNAL_POLLING_THREAD; break; } switch (prof->poll_backend) { case MHD_OPT_MATRIX_POLL_POLL: flags |= MHD_USE_POLL; break; case MHD_OPT_MATRIX_POLL_EPOLL: flags |= MHD_USE_EPOLL; break; case MHD_OPT_MATRIX_POLL_SELECT: default: break; } return flags; } int mhd_opt_matrix_is_external (const struct MHD_OptMatrixProfile *prof) { if (NULL == prof) return 0; return (MHD_OPT_MATRIX_THR_EXTERNAL == prof->threading) ? ! 0 : 0; } int mhd_opt_matrix_raise_mem_limit (struct MHD_OptMatrixProfile *prof, size_t min_limit) { if ((NULL == prof) || (0 == min_limit) || (0 == prof->mem_limit)) return 0; if (prof->mem_limit >= min_limit) return 0; prof->mem_limit = min_limit; return ! 0; } void mhd_opt_matrix_print_notice (const char *test_name) { const struct MHD_OptMatrixProfile *prof; const char *name = (NULL != test_name) ? test_name : "test"; char desc[256]; prof = mhd_opt_matrix_from_env (); printf ("%s: option matrix profile %s\n", name, mhd_opt_matrix_describe (prof, desc, sizeof(desc))); fflush (stdout); } libmicrohttpd-1.0.10/src/microhttpd/mhd_sha256_wrap.h0000664000175000017500000000575615223423441016143 /* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/mhd_sha256_wrap.h * @brief Simple wrapper for selection of built-in/external SHA-256 * implementation * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA256_WRAP_H #define MHD_SHA256_WRAP_H 1 #include "mhd_options.h" #ifndef MHD_SHA256_SUPPORT #error This file must be used only when SHA-256 is enabled #endif #ifndef MHD_SHA256_TLSLIB #include "sha256.h" #else /* MHD_SHA256_TLSLIB */ #include "sha256_ext.h" #endif /* MHD_SHA256_TLSLIB */ #ifndef SHA256_DIGEST_SIZE /** * Size of SHA-256 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define SHA256_DIGEST_SIZE (32) #endif /* ! SHA256_DIGEST_SIZE */ #ifndef SHA256_DIGEST_STRING_SIZE /** * Size of SHA256 digest string in chars including termination NUL. */ #define SHA256_DIGEST_STRING_SIZE ((SHA256_DIGEST_SIZE) * 2 + 1) #endif /* ! SHA256_DIGEST_STRING_SIZE */ #ifndef MHD_SHA256_TLSLIB /** * Universal ctx type mapped for chosen implementation */ #define Sha256CtxWr Sha256Ctx #else /* MHD_SHA256_TLSLIB */ /** * Universal ctx type mapped for chosen implementation */ #define Sha256CtxWr Sha256CtxExt #endif /* MHD_SHA256_TLSLIB */ #ifndef MHD_SHA256_HAS_INIT_ONE_TIME /** * Setup and prepare ctx for hash calculation */ #define MHD_SHA256_init_one_time(ctx) MHD_SHA256_init(ctx) #endif /* ! MHD_SHA256_HAS_INIT_ONE_TIME */ #ifndef MHD_SHA256_HAS_FINISH_RESET /** * Re-use the same ctx for the new hashing after digest calculated */ #define MHD_SHA256_reset(ctx) MHD_SHA256_init(ctx) /** * Finalise SHA256 calculation, return digest, reset hash calculation. */ #define MHD_SHA256_finish_reset(ctx,digest) MHD_SHA256_finish(ctx,digest), \ MHD_SHA256_reset(ctx) #else /* MHD_SHA256_HAS_FINISH_RESET */ #define MHD_SHA256_reset(ctx) (void)0 #endif /* MHD_SHA256_HAS_FINISH_RESET */ #ifndef MHD_SHA256_HAS_DEINIT #define MHD_SHA256_deinit(ignore) (void)0 #endif /* HAVE_SHA256_DEINIT */ /* Sanity checks */ #if ! defined(MHD_SHA256_HAS_FINISH_RESET) && ! defined(MHD_SHA256_HAS_FINISH) #error Required MHD_SHA256_finish_reset() or MHD_SHA256_finish() #endif /* ! MHD_SHA256_HAS_FINISH_RESET && ! MHD_SHA256_HAS_FINISH */ #endif /* MHD_SHA256_WRAP_H */ libmicrohttpd-1.0.10/src/microhttpd/test_str_quote.c0000664000175000017500000007533715232103064016327 /* This file is part of libmicrohttpd Copyright (C) 2022 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_quote.c * @brief Unit tests for quoted strings processing * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #define TEST_STR_MAX_LEN 1024 /* return zero if succeed, non-zero otherwise */ static unsigned int expect_result_unquote_n (const char *const quoted, const size_t quoted_len, const char *const unquoted, const size_t unquoted_len, const unsigned int line_num) { static char buf[TEST_STR_MAX_LEN]; size_t res_len; unsigned int ret1; unsigned int ret2; unsigned int ret3; unsigned int ret4; mhd_assert (NULL != quoted); mhd_assert (NULL != unquoted); mhd_assert (TEST_STR_MAX_LEN > quoted_len); mhd_assert (quoted_len >= unquoted_len); /* First check: MHD_str_unquote () */ ret1 = 0; memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */ res_len = MHD_str_unquote (quoted, quoted_len, buf); if (res_len != unquoted_len) { ret1 = 1; fprintf (stderr, "'MHD_str_unquote ()' FAILED: Wrong result size:\n"); } else if ((0 != unquoted_len) && (0 != memcmp (buf, unquoted, unquoted_len))) { ret1 = 1; fprintf (stderr, "'MHD_str_unquote ()' FAILED: Wrong result string:\n"); } if (0 != ret1) { /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_unquote('%.*s', %u, ->'%.*s') -> %u\n" "\tEXPECTED: MHD_str_unquote('%.*s', %u, ->'%.*s') -> %u\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) res_len, buf, (unsigned) res_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); } /* Second check: MHD_str_equal_quoted_bin_n () */ ret2 = 0; if (! MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret2 = 1; } /* Third check: MHD_str_equal_caseless_quoted_bin_n () */ ret3 = 0; if (! MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n") ; /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret3 = 1; } /* Fourth check: MHD_str_unquote () */ ret4 = 0; memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */ res_len = MHD_str_quote (unquoted, unquoted_len, buf, quoted_len); if (res_len != quoted_len) { ret4 = 1; fprintf (stderr, "'MHD_str_quote ()' FAILED: Wrong result size:\n"); } else if ((0 != quoted_len) && (0 != memcmp (buf, quoted, quoted_len))) { ret4 = 1; fprintf (stderr, "'MHD_str_quote ()' FAILED: Wrong result string:\n"); } if (0 != ret4) { /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_quote('%.*s', %u, ->'%.*s', %u) -> %u\n" "\tEXPECTED: MHD_str_quote('%.*s', %u, ->'%.*s', %u) -> %u\n", (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) res_len, buf, (unsigned) quoted_len, (unsigned) res_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret1 + ret2 + ret3 + ret4; } #define expect_result_unquote(q,u) \ expect_result_unquote_n(q,MHD_STATICSTR_LEN_(q),\ u,MHD_STATICSTR_LEN_(u),__LINE__) static unsigned int check_match (void) { unsigned int r = 0; /**< The number of errors */ r += expect_result_unquote ("", ""); r += expect_result_unquote ("a", "a"); r += expect_result_unquote ("abc", "abc"); r += expect_result_unquote ("abcdef", "abcdef"); r += expect_result_unquote ("a\0" "bc", "a\0" "bc"); r += expect_result_unquote ("abc\\\"", "abc\""); r += expect_result_unquote ("\\\"", "\""); r += expect_result_unquote ("\\\"abc", "\"abc"); r += expect_result_unquote ("abc\\\\", "abc\\"); r += expect_result_unquote ("\\\\", "\\"); r += expect_result_unquote ("\\\\abc", "\\abc"); r += expect_result_unquote ("123\\\\\\\\\\\\\\\\", "123\\\\\\\\"); r += expect_result_unquote ("\\\\\\\\\\\\\\\\", "\\\\\\\\"); r += expect_result_unquote ("\\\\\\\\\\\\\\\\123", "\\\\\\\\123"); r += expect_result_unquote ("\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"" \ "\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"\\\\\\\"", \ "\\\"\\\"\\\"\\\"\\\"\\\"\\\"\\\"\\\"\\\""); return r; } /* return zero if succeed, non-zero otherwise */ static unsigned int expect_result_quote_failed_n (const char *const unquoted, const size_t unquoted_len, const size_t buf_size, const unsigned int line_num) { static char buf[TEST_STR_MAX_LEN]; size_t res_len; unsigned int ret4; mhd_assert (TEST_STR_MAX_LEN > buf_size); /* The check: MHD_str_unquote () */ ret4 = 0; memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */ res_len = MHD_str_quote (unquoted, unquoted_len, buf, buf_size); if (0 != res_len) { ret4 = 1; fprintf (stderr, "'MHD_str_quote ()' FAILED: Wrong result size:\n"); } if (0 != ret4) { /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_quote('%.*s', %u, ->'%.*s', %u) -> %u\n" "\tEXPECTED: MHD_str_quote('%.*s', %u, (not checked), %u) -> 0\n", (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) res_len, buf, (unsigned) buf_size, (unsigned) res_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (unsigned) buf_size); fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret4; } #define expect_result_quote_failed(q,s) \ expect_result_quote_failed_n(q,MHD_STATICSTR_LEN_(q),\ s,__LINE__) static unsigned int check_quote_failed (void) { unsigned int r = 0; /**< The number of errors */ r += expect_result_quote_failed ("a", 0); r += expect_result_quote_failed ("aa", 1); r += expect_result_quote_failed ("abc\\", 4); r += expect_result_quote_failed ("abc\"", 4); r += expect_result_quote_failed ("abc\"\"\"\"", 6); r += expect_result_quote_failed ("abc\"\"\"\"", 7); r += expect_result_quote_failed ("abc\"\"\"\"", 8); r += expect_result_quote_failed ("abc\"\"\"\"", 9); r += expect_result_quote_failed ("abc\"\"\"\"", 10); r += expect_result_quote_failed ("abc\\\\\\\\", 9); r += expect_result_quote_failed ("abc\\\\\\\\", 10); r += expect_result_quote_failed ("abc\"\"\"\"", 9); r += expect_result_quote_failed ("abc\"\"\"\"", 10); r += expect_result_quote_failed ("abc\"\\\"\\", 9); r += expect_result_quote_failed ("abc\\\"\\\"", 10); r += expect_result_quote_failed ("\"\"\"\"abc", 6); r += expect_result_quote_failed ("\"\"\"\"abc", 7); r += expect_result_quote_failed ("\"\"\"\"abc", 8); r += expect_result_quote_failed ("\"\"\"\"abc", 9); r += expect_result_quote_failed ("\"\"\"\"abc", 10); r += expect_result_quote_failed ("\\\\\\\\abc", 9); r += expect_result_quote_failed ("\\\\\\\\abc", 10); r += expect_result_quote_failed ("\"\"\"\"abc", 9); r += expect_result_quote_failed ("\"\"\"\"abc", 10); r += expect_result_quote_failed ("\"\\\"\\abc", 9); r += expect_result_quote_failed ("\\\"\\\"abc", 10); return r; } /* return zero if succeed, one otherwise */ static unsigned int expect_match_caseless_n (const char *const quoted, const size_t quoted_len, const char *const unquoted, const size_t unquoted_len, const unsigned int line_num) { unsigned int ret3; mhd_assert (NULL != quoted); mhd_assert (NULL != unquoted); mhd_assert (TEST_STR_MAX_LEN > quoted_len); /* The check: MHD_str_equal_caseless_quoted_bin_n () */ ret3 = 0; if (! MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n") ; /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret3 = 1; } return ret3; } #define expect_match_caseless(q,u) \ expect_match_caseless_n(q,MHD_STATICSTR_LEN_(q),\ u,MHD_STATICSTR_LEN_(u),__LINE__) static unsigned int check_match_caseless (void) { unsigned int r = 0; /**< The number of errors */ r += expect_match_caseless ("a", "A"); r += expect_match_caseless ("abC", "aBc"); r += expect_match_caseless ("AbCdeF", "aBCdEF"); r += expect_match_caseless ("a\0" "Bc", "a\0" "bC"); r += expect_match_caseless ("Abc\\\"", "abC\""); r += expect_match_caseless ("\\\"", "\""); r += expect_match_caseless ("\\\"aBc", "\"abc"); r += expect_match_caseless ("abc\\\\", "ABC\\"); r += expect_match_caseless ("\\\\", "\\"); r += expect_match_caseless ("\\\\ABC", "\\abc"); r += expect_match_caseless ("\\\\ZYX", "\\ZYX"); r += expect_match_caseless ("abc", "ABC"); r += expect_match_caseless ("ABCabc", "abcABC"); r += expect_match_caseless ("abcXYZ", "ABCxyz"); r += expect_match_caseless ("AbCdEfABCabc", "ABcdEFabcABC"); r += expect_match_caseless ("a\\\\bc", "A\\BC"); r += expect_match_caseless ("ABCa\\\\bc", "abcA\\BC"); r += expect_match_caseless ("abcXYZ\\\\", "ABCxyz\\"); r += expect_match_caseless ("\\\\AbCdEfABCabc", "\\ABcdEFabcABC"); return r; } /* return zero if succeed, one otherwise */ static unsigned int expect_result_invalid_n (const char *const quoted, const size_t quoted_len, const unsigned int line_num) { static char buf[TEST_STR_MAX_LEN]; size_t res_len; unsigned int ret1; mhd_assert (NULL != quoted); mhd_assert (TEST_STR_MAX_LEN > quoted_len); /* The check: MHD_str_unquote () */ ret1 = 0; memset (buf, '#', sizeof(buf)); /* Fill buffer with character unused in the check */ res_len = MHD_str_unquote (quoted, quoted_len, buf); if (res_len != 0) { ret1 = 1; fprintf (stderr, "'MHD_str_unquote ()' FAILED: Wrong result size:\n"); } if (0 != ret1) { /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_unquote('%.*s', %u, (not checked)) -> %u\n" "\tEXPECTED: MHD_str_unquote('%.*s', %u, (not checked)) -> 0\n", (int) quoted_len, quoted, (unsigned) quoted_len, (unsigned) res_len, (int) quoted_len, quoted, (unsigned) quoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret1; } #define expect_result_invalid(q) \ expect_result_invalid_n(q,MHD_STATICSTR_LEN_(q),__LINE__) static unsigned int check_invalid (void) { unsigned int r = 0; /**< The number of errors */ r += expect_result_invalid ("\\"); r += expect_result_invalid ("\\\\\\"); r += expect_result_invalid ("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"); r += expect_result_invalid ("xyz\\"); r += expect_result_invalid ("\\\"\\"); r += expect_result_invalid ("\\\"\\\"\\\"\\"); return r; } /* return zero if succeed, non-zero otherwise */ static unsigned int expect_result_unmatch_n (const char *const quoted, const size_t quoted_len, const char *const unquoted, const size_t unquoted_len, const unsigned int line_num) { unsigned int ret2; unsigned int ret3; mhd_assert (NULL != quoted); mhd_assert (NULL != unquoted); /* The check: MHD_str_equal_quoted_bin_n () */ ret2 = 0; if (MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret2 = 1; } /* The check: MHD_str_equal_quoted_bin_n () */ ret3 = 0; if (MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n") ; /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret3 = 1; } return ret2 + ret3; } #define expect_result_unmatch(q,u) \ expect_result_unmatch_n(q,MHD_STATICSTR_LEN_(q),\ u,MHD_STATICSTR_LEN_(u),__LINE__) static unsigned int check_unmatch (void) { unsigned int r = 0; /**< The number of errors */ /* Matched sequence except invalid backslash at the end */ r += expect_result_unmatch ("\\", ""); r += expect_result_unmatch ("a\\", "a"); r += expect_result_unmatch ("abc\\", "abc"); r += expect_result_unmatch ("a\0" "bc\\", "a\0" "bc"); r += expect_result_unmatch ("abc\\\"\\", "abc\""); r += expect_result_unmatch ("\\\"\\", "\""); r += expect_result_unmatch ("\\\"abc\\", "\"abc"); r += expect_result_unmatch ("abc\\\\\\", "abc\\"); r += expect_result_unmatch ("\\\\\\", "\\"); r += expect_result_unmatch ("\\\\abc\\", "\\abc"); r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\\\", "123\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\\", "\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123\\", "\\\\\\\\123"); /* Invalid backslash at the end and empty string */ r += expect_result_unmatch ("\\", ""); r += expect_result_unmatch ("a\\", ""); r += expect_result_unmatch ("abc\\", ""); r += expect_result_unmatch ("a\0" "bc\\", ""); r += expect_result_unmatch ("abc\\\"\\", ""); r += expect_result_unmatch ("\\\"\\", ""); r += expect_result_unmatch ("\\\"abc\\", ""); r += expect_result_unmatch ("abc\\\\\\", ""); r += expect_result_unmatch ("\\\\\\", ""); r += expect_result_unmatch ("\\\\abc\\", ""); r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\\\", ""); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\\", ""); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123\\", ""); /* Difference at binary zero */ r += expect_result_unmatch ("\0", ""); r += expect_result_unmatch ("", "\0"); r += expect_result_unmatch ("a\0", "a"); r += expect_result_unmatch ("a", "a\0"); r += expect_result_unmatch ("abc\0", "abc"); r += expect_result_unmatch ("abc", "abc\0"); r += expect_result_unmatch ("a\0" "bc\0", "a\0" "bc"); r += expect_result_unmatch ("a\0" "bc", "a\0" "bc\0"); r += expect_result_unmatch ("abc\\\"\0", "abc\""); r += expect_result_unmatch ("abc\\\"", "abc\"\0"); r += expect_result_unmatch ("\\\"\0", "\""); r += expect_result_unmatch ("\\\"", "\"\0"); r += expect_result_unmatch ("\\\"abc\0", "\"abc"); r += expect_result_unmatch ("\\\"abc", "\"abc\0"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\0", "\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\\\0"); r += expect_result_unmatch ("\\\\\\\\\\\\\0" "\\\\", "\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\0" "\\"); r += expect_result_unmatch ("\0" "abc", "abc"); r += expect_result_unmatch ("abc", "\0" "abc"); r += expect_result_unmatch ("\0" "abc", "0abc"); r += expect_result_unmatch ("0abc", "\0" "abc"); r += expect_result_unmatch ("xyz", "xy" "\0" "z"); r += expect_result_unmatch ("xy" "\0" "z", "xyz"); /* Difference after binary zero */ r += expect_result_unmatch ("abc\0" "1", "abc\0" "2"); r += expect_result_unmatch ("a\0" "bcx", "a\0" "bcy"); r += expect_result_unmatch ("\0" "abc\\\"2", "\0" "abc\"1"); r += expect_result_unmatch ("\0" "abc1\\\"", "\0" "abc2\""); r += expect_result_unmatch ("\0" "\\\"c", "\0" "\"d"); r += expect_result_unmatch ("\\\"ab" "\0" "1c", "\"ab" "\0" "2c"); r += expect_result_unmatch ("a\0" "bcdef2", "a\0" "bcdef1"); r += expect_result_unmatch ("a\0" "bc2def", "a\0" "bc1def"); r += expect_result_unmatch ("a\0" "1bcdef", "a\0" "2bcdef"); r += expect_result_unmatch ("abcde\0" "f2", "abcde\0" "f1"); r += expect_result_unmatch ("123\\\\\\\\\\\\\0" "\\\\1", "123\\\\\\\0" "\\2"); r += expect_result_unmatch ("\\\\\\\\\\\\\0" "1\\\\", "\\\\\\" "2\\"); /* One side is empty */ r += expect_result_unmatch ("abc", ""); r += expect_result_unmatch ("", "abc"); r += expect_result_unmatch ("1234567890", ""); r += expect_result_unmatch ("", "1234567890"); r += expect_result_unmatch ("abc\\\"", ""); r += expect_result_unmatch ("", "abc\""); r += expect_result_unmatch ("\\\"", ""); r += expect_result_unmatch ("", "\""); r += expect_result_unmatch ("\\\"abc", ""); r += expect_result_unmatch ("", "\"abc"); r += expect_result_unmatch ("abc\\\\", ""); r += expect_result_unmatch ("", "abc\\"); r += expect_result_unmatch ("\\\\", ""); r += expect_result_unmatch ("", "\\"); r += expect_result_unmatch ("\\\\abc", ""); r += expect_result_unmatch ("", "\\abc"); r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\", ""); r += expect_result_unmatch ("", "123\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", ""); r += expect_result_unmatch ("", "\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123", ""); r += expect_result_unmatch ("", "\\\\\\\\123"); /* Various unmatched strings */ r += expect_result_unmatch ("a", "x"); r += expect_result_unmatch ("abc", "abcabc"); r += expect_result_unmatch ("abc", "abcabcabc"); r += expect_result_unmatch ("abc", "abcabcabcabc"); r += expect_result_unmatch ("ABCABC", "ABC"); r += expect_result_unmatch ("ABCABCABC", "ABC"); r += expect_result_unmatch ("ABCABCABCABC", "ABC"); r += expect_result_unmatch ("123\\\\\\\\\\\\\\\\\\\\", "123\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\\\\\", "\\\\\\\\"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\123\\\\", "\\\\\\\\123"); r += expect_result_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\\\\"); return r; } /* return zero if succeed, one otherwise */ static unsigned int expect_result_case_unmatch_n (const char *const quoted, const size_t quoted_len, const char *const unquoted, const size_t unquoted_len, const unsigned int line_num) { unsigned int ret2; mhd_assert (NULL != quoted); mhd_assert (NULL != unquoted); /* THe check: MHD_str_equal_quoted_bin_n () */ ret2 = 0; if (MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret2 = 1; } return ret2; } #define expect_result_case_unmatch(q,u) \ expect_result_case_unmatch_n(q,MHD_STATICSTR_LEN_(q),\ u,MHD_STATICSTR_LEN_(u),__LINE__) static unsigned int check_unmatch_case (void) { unsigned int r = 0; /**< The number of errors */ r += expect_result_case_unmatch ("a", "A"); r += expect_result_case_unmatch ("abC", "aBc"); r += expect_result_case_unmatch ("AbCdeF", "aBCdEF"); r += expect_result_case_unmatch ("a\0" "Bc", "a\0" "bC"); r += expect_result_case_unmatch ("Abc\\\"", "abC\""); r += expect_result_case_unmatch ("\\\"aBc", "\"abc"); r += expect_result_case_unmatch ("abc\\\\", "ABC\\"); r += expect_result_case_unmatch ("\\\\ABC", "\\abc"); r += expect_result_case_unmatch ("\\\\ZYX", "\\ZYx"); r += expect_result_case_unmatch ("abc", "ABC"); r += expect_result_case_unmatch ("ABCabc", "abcABC"); r += expect_result_case_unmatch ("abcXYZ", "ABCxyz"); r += expect_result_case_unmatch ("AbCdEfABCabc", "ABcdEFabcABC"); r += expect_result_case_unmatch ("a\\\\bc", "A\\BC"); r += expect_result_case_unmatch ("ABCa\\\\bc", "abcA\\BC"); r += expect_result_case_unmatch ("abcXYZ\\\\", "ABCxyz\\"); r += expect_result_case_unmatch ("\\\\AbCdEfABCabc", "\\ABcdEFabcABC"); return r; } /* return zero if succeed, one otherwise */ static unsigned int expect_result_caseless_unmatch_n (const char *const quoted, const size_t quoted_len, const char *const unquoted, const size_t unquoted_len, const unsigned int line_num) { unsigned int ret2; unsigned int ret3; mhd_assert (NULL != quoted); mhd_assert (NULL != unquoted); /* The check: MHD_str_equal_quoted_bin_n () */ ret2 = 0; if (MHD_str_equal_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_quoted_bin_n ()' FAILED: Wrong result:\n"); /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret2 = 1; } /* The check: MHD_str_equal_quoted_bin_n () */ ret3 = 0; if (MHD_str_equal_caseless_quoted_bin_n (quoted, quoted_len, unquoted, unquoted_len)) { fprintf (stderr, "'MHD_str_equal_caseless_quoted_bin_n ()' FAILED: Wrong result:\n") ; /* This does NOT print part of the string after binary zero */ fprintf (stderr, "\tRESULT : MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> true\n" "\tEXPECTED: MHD_str_equal_caseless_quoted_bin_n('%.*s', %u, " "'%.*s', %u) -> false\n", (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len, (int) quoted_len, quoted, (unsigned) quoted_len, (int) unquoted_len, unquoted, (unsigned) unquoted_len); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret3 = 1; } return ret2 + ret3; } #define expect_result_caseless_unmatch(q,u) \ expect_result_caseless_unmatch_n(q,MHD_STATICSTR_LEN_(q),\ u,MHD_STATICSTR_LEN_(u),__LINE__) static unsigned int check_unmatch_caseless (void) { unsigned int r = 0; /**< The number of errors */ /* Matched sequence except invalid backslash at the end */ r += expect_result_caseless_unmatch ("a\\", "A"); r += expect_result_caseless_unmatch ("abC\\", "abc"); r += expect_result_caseless_unmatch ("a\0" "Bc\\", "a\0" "bc"); r += expect_result_caseless_unmatch ("abc\\\"\\", "ABC\""); r += expect_result_caseless_unmatch ("\\\"\\", "\""); r += expect_result_caseless_unmatch ("\\\"ABC\\", "\"abc"); r += expect_result_caseless_unmatch ("Abc\\\\\\", "abC\\"); r += expect_result_caseless_unmatch ("\\\\\\", "\\"); r += expect_result_caseless_unmatch ("\\\\aBc\\", "\\abC"); /* Difference at binary zero */ r += expect_result_caseless_unmatch ("a\0", "A"); r += expect_result_caseless_unmatch ("A", "a\0"); r += expect_result_caseless_unmatch ("abC\0", "abc"); r += expect_result_caseless_unmatch ("abc", "ABc\0"); r += expect_result_caseless_unmatch ("a\0" "bC\0", "a\0" "bc"); r += expect_result_caseless_unmatch ("a\0" "bc", "A\0" "bc\0"); r += expect_result_caseless_unmatch ("ABC\\\"\0", "abc\""); r += expect_result_caseless_unmatch ("abc\\\"", "ABC\"\0"); r += expect_result_caseless_unmatch ("\\\"aBc\0", "\"abc"); r += expect_result_caseless_unmatch ("\\\"Abc", "\"abc\0"); r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\\\\\0", "\\\\\\\\"); r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\\\0"); r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\0" "\\\\", "\\\\\\\\"); r += expect_result_caseless_unmatch ("\\\\\\\\\\\\\\\\", "\\\\\\\0" "\\"); r += expect_result_caseless_unmatch ("\0" "aBc", "abc"); r += expect_result_caseless_unmatch ("abc", "\0" "abC"); r += expect_result_caseless_unmatch ("\0" "abc", "0abc"); r += expect_result_caseless_unmatch ("0abc", "\0" "aBc"); r += expect_result_caseless_unmatch ("xyZ", "xy" "\0" "z"); r += expect_result_caseless_unmatch ("Xy" "\0" "z", "xyz"); /* Difference after binary zero */ r += expect_result_caseless_unmatch ("abc\0" "1", "aBC\0" "2"); r += expect_result_caseless_unmatch ("a\0" "bcX", "a\0" "bcy"); r += expect_result_caseless_unmatch ("\0" "abc\\\"2", "\0" "Abc\"1"); r += expect_result_caseless_unmatch ("\0" "Abc1\\\"", "\0" "abc2\""); r += expect_result_caseless_unmatch ("\0" "\\\"c", "\0" "\"d"); r += expect_result_caseless_unmatch ("\\\"ab" "\0" "1C", "\"ab" "\0" "2C"); r += expect_result_caseless_unmatch ("a\0" "BCDef2", "a\0" "bcdef1"); r += expect_result_caseless_unmatch ("a\0" "bc2def", "a\0" "BC1def"); r += expect_result_caseless_unmatch ("a\0" "1bcdeF", "a\0" "2bcdef"); r += expect_result_caseless_unmatch ("abcde\0" "f2", "ABCDE\0" "f1"); r += expect_result_caseless_unmatch ("\\\"ab" "\0" "XC", "\"ab" "\0" "yC"); r += expect_result_caseless_unmatch ("a\0" "BCDefY", "a\0" "bcdefx"); r += expect_result_caseless_unmatch ("a\0" "bczdef", "a\0" "BCXdef"); r += expect_result_caseless_unmatch ("a\0" "YbcdeF", "a\0" "zbcdef"); r += expect_result_caseless_unmatch ("abcde\0" "fy", "ABCDE\0" "fX"); return r; } int main (int argc, char *argv[]) { unsigned int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_match (); errcount += check_quote_failed (); errcount += check_match_caseless (); errcount += check_invalid (); errcount += check_unmatch (); errcount += check_unmatch_case (); errcount += check_unmatch_caseless (); if (0 == errcount) printf ("All tests were passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.10/src/microhttpd/sha256_ext.c0000664000175000017500000000557415232103064015127 /* This file is part of GNU libmicrohttpd Copyright (C) 2022-2023 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/sha256_ext.c * @brief Wrapper for SHA-256 calculation performed by TLS library * @author Karlson2k (Evgeny Grin) */ #include #include "sha256_ext.h" #include "mhd_assert.h" /** * Initialise structure for SHA-256 calculation, allocate resources. * * This function must not be called more than one time for @a ctx. * * @param ctx the calculation context */ void MHD_SHA256_init_one_time (struct Sha256CtxExt *ctx) { ctx->handle = NULL; ctx->ext_error = gnutls_hash_init (&ctx->handle, GNUTLS_DIG_SHA256); if ((0 != ctx->ext_error) && (NULL != ctx->handle)) { /* GnuTLS may return initialisation error and set the handle at the same time. Such handle cannot be used for calculations. Note: GnuTLS may also return an error and NOT set the handle. */ gnutls_free (ctx->handle); ctx->handle = NULL; } /* If handle is NULL, the error must be set */ mhd_assert ((NULL != ctx->handle) || (0 != ctx->ext_error)); /* If error is set, the handle must be NULL */ mhd_assert ((0 == ctx->ext_error) || (NULL == ctx->handle)); } /** * Process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA256_update (struct Sha256CtxExt *ctx, const uint8_t *data, size_t length) { if (0 == ctx->ext_error) ctx->ext_error = gnutls_hash (ctx->handle, data, length); } /** * Finalise SHA-256 calculation, return digest, reset hash calculation. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes */ void MHD_SHA256_finish_reset (struct Sha256CtxExt *ctx, uint8_t digest[SHA256_DIGEST_SIZE]) { if (0 == ctx->ext_error) gnutls_hash_output (ctx->handle, digest); else gnutls_hash_deinit (ctx->handle, NULL); } /** * Free allocated resources. * * @param ctx the calculation context */ void MHD_SHA256_deinit (struct Sha256CtxExt *ctx) { if (NULL != ctx->handle) gnutls_hash_deinit (ctx->handle, NULL); } libmicrohttpd-1.0.10/src/microhttpd/test_str_bin_hex.c0000664000175000017500000005200715232103064016573 /* This file is part of libmicrohttpd Copyright (C) 2022 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_bin_hex.c * @brief Unit tests for hex strings <-> binary data processing * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include "mhd_str.h" #include "mhd_assert.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ static char tmp_bufs[4][4 * 1024]; /* should be enough for testing */ static size_t buf_idx = 0; /* print non-printable chars as char codes */ static char * n_prnt (const char *str, size_t len) { static char *buf; /* should be enough for testing */ static const size_t buf_size = sizeof(tmp_bufs[0]); size_t r_pos = 0; size_t w_pos = 0; if (++buf_idx >= (sizeof(tmp_bufs) / sizeof(tmp_bufs[0]))) buf_idx = 0; buf = tmp_bufs[buf_idx]; while (len > r_pos && w_pos + 1 < buf_size) { const unsigned char c = (unsigned char) str[r_pos]; if ((c == '\\') || (c == '"') ) { if (w_pos + 2 >= buf_size) break; buf[w_pos++] = '\\'; buf[w_pos++] = (char) c; } else if ((c >= 0x20) && (c <= 0x7E) ) buf[w_pos++] = (char) c; else { if (w_pos + 4 >= buf_size) break; if (snprintf (buf + w_pos, buf_size - w_pos, "\\x%02hX", (short unsigned int) c) != 4) break; w_pos += 4; } r_pos++; } if (len != r_pos) { /* not full string is printed */ /* enough space for "..." ? */ if (w_pos + 3 > buf_size) w_pos = buf_size - 4; buf[w_pos++] = '.'; buf[w_pos++] = '.'; buf[w_pos++] = '.'; } buf[w_pos] = 0; return buf; } #define TEST_BIN_MAX_SIZE (2 * 1024) /* return zero if succeed, number of failures otherwise */ static unsigned int expect_decoded_n (const char *const hex, const size_t hex_len, const uint8_t *const bin, const size_t bin_size, const unsigned int line_num) { static const char fill_chr = '#'; static char buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != hex); mhd_assert (NULL != bin); mhd_assert (TEST_BIN_MAX_SIZE > bin_size + 1); mhd_assert (TEST_BIN_MAX_SIZE > hex_len + 1); mhd_assert (hex_len >= bin_size); mhd_assert (1 >= hex_len || hex_len > bin_size); ret = 0; /* check MHD_hex_to_bin() */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_hex_to_bin (hex, hex_len, buf); if (res_size != bin_size) { check_res = 1; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "Wrong returned value:\n"); } else { if ((0 != bin_size) && (0 != memcmp (buf, bin, bin_size))) { check_res = 1; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "Wrong output data:\n"); } } if (((0 == res_size) && (fill_chr != buf[bin_size])) || ((0 != res_size) && (fill_chr != buf[res_size]))) { check_res = 1; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "A char written outside the buffer:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_hex_to_bin (\"%s\", %u, " "->\"%s\") -> %u\n", n_prnt (hex, hex_len), (unsigned) hex_len, n_prnt (buf, res_size), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_hex_to_bin (\"%s\", %u, " "->\"%s\") -> %u\n", n_prnt (hex, hex_len), (unsigned) hex_len, n_prnt ((const char *) bin, bin_size), (unsigned) bin_size); } } /* check MHD_bin_to_hex() */ if (0 == hex_len % 2) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_bin_to_hex_z (bin, bin_size, buf); if (res_size != hex_len) { check_res = 1; fprintf (stderr, "'MHD_bin_to_hex ()' FAILED: " "Wrong returned value:\n"); } else { if ((0 != hex_len) && (! MHD_str_equal_caseless_bin_n_ (buf, hex, hex_len))) { check_res = 1; fprintf (stderr, "'MHD_bin_to_hex ()' FAILED: " "Wrong output string:\n"); } } if (fill_chr != buf[res_size + 1]) { check_res = 1; fprintf (stderr, "'MHD_bin_to_hex ()' FAILED: " "A char written outside the buffer:\n"); } if (0 != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_bin_to_hex ()' FAILED: " "The result is not zero-terminated:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_bin_to_hex (\"%s\", %u, " "->\"%s\") -> %u\n", n_prnt ((const char *) bin, bin_size), (unsigned) bin_size, n_prnt (buf, res_size), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_bin_to_hex (\"%s\", %u, " "->(lower case)\"%s\") -> %u\n", n_prnt ((const char *) bin, bin_size), (unsigned) bin_size, n_prnt (hex, hex_len), (unsigned) bin_size); } } if (0 != ret) { fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_decoded_arr(h,a) \ expect_decoded_n(h,MHD_STATICSTR_LEN_(h),\ a,(sizeof(a)/sizeof(a[0])), \ __LINE__) static unsigned int check_decode_bin (void) { unsigned int r = 0; /**< The number of errors */ if (1) { static const uint8_t bin[256] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; /* The lower case */ r += expect_decoded_arr ("000102030405060708090a0b0c0d0e" \ "0f101112131415161718191a1b1c1d" \ "1e1f202122232425262728292a2b2c" \ "2d2e2f303132333435363738393a3b" \ "3c3d3e3f404142434445464748494a" \ "4b4c4d4e4f50515253545556575859" \ "5a5b5c5d5e5f606162636465666768" \ "696a6b6c6d6e6f7071727374757677" \ "78797a7b7c7d7e7f80818283848586" \ "8788898a8b8c8d8e8f909192939495" \ "969798999a9b9c9d9e9fa0a1a2a3a4" \ "a5a6a7a8a9aaabacadaeafb0b1b2b3" \ "b4b5b6b7b8b9babbbcbdbebfc0c1c2" \ "c3c4c5c6c7c8c9cacbcccdcecfd0d1" \ "d2d3d4d5d6d7d8d9dadbdcdddedfe0" \ "e1e2e3e4e5e6e7e8e9eaebecedeeef" \ "f0f1f2f3f4f5f6f7f8f9fafbfcfdfe" \ "ff", bin); } if (1) { static const uint8_t bin[256] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; /* The upper case */ r += expect_decoded_arr ("000102030405060708090A0B0C0D0E" \ "0F101112131415161718191A1B1C1D" \ "1E1F202122232425262728292A2B2C" \ "2D2E2F303132333435363738393A3B" \ "3C3D3E3F404142434445464748494A" \ "4B4C4D4E4F50515253545556575859" \ "5A5B5C5D5E5F606162636465666768" \ "696A6B6C6D6E6F7071727374757677" \ "78797A7B7C7D7E7F80818283848586" \ "8788898A8B8C8D8E8F909192939495" \ "969798999A9B9C9D9E9FA0A1A2A3A4" \ "A5A6A7A8A9AAABACADAEAFB0B1B2B3" \ "B4B5B6B7B8B9BABBBCBDBEBFC0C1C2" \ "C3C4C5C6C7C8C9CACBCCCDCECFD0D1" \ "D2D3D4D5D6D7D8D9DADBDCDDDEDFE0" \ "E1E2E3E4E5E6E7E8E9EAEBECEDEEEF" \ "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFE" \ "FF", bin); } if (1) { static const uint8_t bin[3] = {0x1, 0x2, 0x3}; r += expect_decoded_arr ("010203", bin); } if (1) { static const uint8_t bin[3] = {0x1, 0x2, 0x3}; r += expect_decoded_arr ("10203", bin); } if (1) { static const uint8_t bin[1] = {0x1}; r += expect_decoded_arr ("01", bin); } if (1) { static const uint8_t bin[1] = {0x1}; r += expect_decoded_arr ("1", bin); } return r; } /* return zero if succeed, number of failures otherwise */ static unsigned int expect_failed_n (const char *const hex, const size_t hex_len, const unsigned int line_num) { static const char fill_chr = '#'; static char buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != hex); mhd_assert (TEST_BIN_MAX_SIZE > hex_len + 1); ret = 0; /* check MHD_hex_to_bin() */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_hex_to_bin (hex, hex_len, buf); if (res_size != 0) { check_res = 1; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "Wrong returned value:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_hex_to_bin (\"%s\", %u, " "->\"%s\") -> %u\n", n_prnt (hex, hex_len), (unsigned) hex_len, n_prnt (buf, res_size), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_hex_to_bin (\"%s\", %u, " "->(not defined)) -> 0\n", n_prnt (hex, hex_len), (unsigned) hex_len); } } if (0 != ret) { fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_failed(h) \ expect_failed_n(h,MHD_STATICSTR_LEN_(h), \ __LINE__) static unsigned int check_broken_str (void) { unsigned int r = 0; /**< The number of errors */ r += expect_failed ("abcx"); r += expect_failed ("X"); r += expect_failed ("!"); r += expect_failed ("01z"); r += expect_failed ("0z"); r += expect_failed ("00z"); r += expect_failed ("000Y"); return r; } /** * The maximum length of the hexadecimal input used by the exact-sized * output buffer checks. */ #define TEST_EXACT_MAX_HEX_LEN 320 /** * The number of the guard bytes placed right after the output buffer. */ #define TEST_GUARD_SIZE 8 /** * The value used to fill the guard bytes. */ #define TEST_GUARD_CHR 0x5A /** * Check that MHD_hex_to_bin() writes no more than the documented number of * the output bytes, which is ((@a hex_len + 1) / 2). * * Every caller of MHD_hex_to_bin() must size the output buffer by that * formula. A caller that sizes the buffer by the expected size of the * decoded value instead (like the digest authentication 'response' check * used to do) can be overflown by simply sending a longer hexadecimal * string, therefore this contract is checked here with buffers that have * no slack at all: * - an exactly-sized heap allocation, so that a run-time memory checker * (ASAN, valgrind) traps any out-of-bounds write immediately, and * - an allocation with a known guard pattern right after the output area, * so that the overflow is detected even without any such tool. * * @param hex the input string with hexadecimal digits * @param hex_len the length of @a hex * @param must_succeed non-zero if the decoding is expected to succeed * @param line_num the line number to report in case of failure * @return zero if succeed, number of failures otherwise */ static unsigned int expect_exact_dest_n (const char *const hex, const size_t hex_len, const int must_succeed, const unsigned int line_num) { const size_t max_out_size = (hex_len + 1) / 2; const size_t expected_size = must_succeed ? max_out_size : 0; uint8_t *buf; size_t res_size; size_t i; unsigned int ret; ret = 0; /* (1) The exactly-sized output buffer. */ buf = (uint8_t *) malloc (0 != max_out_size ? max_out_size : 1); if (NULL == buf) { fprintf (stderr, "malloc() failed. Line: %u\n", line_num); return 1; } res_size = MHD_hex_to_bin (hex, hex_len, buf); free (buf); if (res_size != expected_size) { ret++; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "Wrong returned value with the exactly-sized buffer:\n"); fprintf (stderr, "\tRESULT : MHD_hex_to_bin (\"%s\", %u, ...) -> %u\n", n_prnt (hex, hex_len), (unsigned) hex_len, (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_hex_to_bin (\"%s\", %u, ...) -> %u\n", n_prnt (hex, hex_len), (unsigned) hex_len, (unsigned) expected_size); } /* (2) The output buffer followed by the guard bytes. */ buf = (uint8_t *) malloc (max_out_size + TEST_GUARD_SIZE); if (NULL == buf) { fprintf (stderr, "malloc() failed. Line: %u\n", line_num); return ret + 1; } memset (buf, TEST_GUARD_CHR, max_out_size + TEST_GUARD_SIZE); res_size = MHD_hex_to_bin (hex, hex_len, buf); if (res_size > max_out_size) { ret++; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "Returned value is larger than the documented maximum " "output size: %u > %u\n", (unsigned) res_size, (unsigned) max_out_size); } for (i = 0; i < TEST_GUARD_SIZE; ++i) { if (TEST_GUARD_CHR != buf[max_out_size + i]) { ret++; fprintf (stderr, "'MHD_hex_to_bin ()' FAILED: " "The guard byte number %u (of %u) after the output buffer " "has been overwritten:\n", (unsigned) i, (unsigned) TEST_GUARD_SIZE); fprintf (stderr, "\tINPUT : MHD_hex_to_bin (\"%s\", %u, ...), " "the maximum output size is %u\n", n_prnt (hex, hex_len), (unsigned) hex_len, (unsigned) max_out_size); break; } } free (buf); if (0 != ret) { fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_exact_dest(h,ms) \ expect_exact_dest_n (h, MHD_STATICSTR_LEN_ (h), ms, __LINE__) /** * Check the output size contract of MHD_hex_to_bin() for every input length * up to #TEST_EXACT_MAX_HEX_LEN, for valid and for broken input. * * @return zero if succeed, number of failures otherwise */ static unsigned int check_exact_dest_buffer (void) { static const char hex_digits[] = "0123456789abcdefABCDEF"; static char hex[TEST_EXACT_MAX_HEX_LEN + 1]; unsigned int r = 0; /**< The number of errors */ size_t len; for (len = 0; len < sizeof(hex) - 1; ++len) hex[len] = hex_digits[len % (sizeof(hex_digits) - 1)]; hex[sizeof(hex) - 1] = 0; /* Valid input of every length, including the odd lengths for which an extra leading zero is assumed and therefore one more byte is written than (hex_len / 2). */ for (len = 0; len <= TEST_EXACT_MAX_HEX_LEN; ++len) r += expect_exact_dest_n (hex, len, 1, __LINE__); /* Broken input: a non-hexadecimal character at every possible position. The decoding fails, but the bytes decoded before the broken character have already been written and must still fit into the output buffer. */ for (len = 1; len <= 64; ++len) { size_t pos; for (pos = 0; pos < len; ++pos) { const char saved = hex[pos]; hex[pos] = 'z'; r += expect_exact_dest_n (hex, len, 0, __LINE__); hex[pos] = saved; } } /* The lengths that matter for the HTTP Digest authentication code: twice the digest size is the largest input any caller may accept. */ r += expect_exact_dest ("00112233445566778899aabbccddeeff", 1); /* MD5 */ r += expect_exact_dest ("00112233445566778899aabbccddeeff" "00112233445566778899aabbccddeeff", 1); /* SHA-256 */ /* Twice as long as the largest supported digest: a caller that sizes the output buffer by the digest size only would be overflown here. */ r += expect_exact_dest ("00112233445566778899aabbccddeeff" "00112233445566778899aabbccddeeff" "00112233445566778899aabbccddeeff" "00112233445566778899aabbccddeeff", 1); return r; } int main (int argc, char *argv[]) { unsigned int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_decode_bin (); errcount += check_broken_str (); errcount += check_exact_dest_buffer (); if (0 == errcount) printf ("All tests have been passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.10/src/microhttpd/test_upgrade.c0000664000175000017500000020651515232103064015723 /* This file is part of libmicrohttpd Copyright (C) 2016-2020 Christian Grothoff Copyright (C) 2016-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_upgrade.c * @brief Testcase for libmicrohttpd upgrading a connection * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include #include #include #include #ifndef WINDOWS #include #endif #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ #include "mhd_sockets.h" #ifdef HAVE_NETINET_IP_H #include #endif /* HAVE_NETINET_IP_H */ #include "platform.h" #include "microhttpd.h" #include "test_helpers.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifdef HTTPS_SUPPORT #include #include "../testcurl/https/tls_test_keys.h" #if defined(HAVE_FORK) && defined(HAVE_WAITPID) #include #include #endif /* HAVE_FORK && HAVE_WAITPID */ #endif /* HTTPS_SUPPORT */ #if defined(MHD_POSIX_SOCKETS) # ifdef MHD_WINSOCK_SOCKETS # error Both MHD_POSIX_SOCKETS and MHD_WINSOCK_SOCKETS are defined # endif /* MHD_WINSOCK_SOCKETS */ #elif ! defined(MHD_WINSOCK_SOCKETS) # error Neither MHD_POSIX_SOCKETS nor MHD_WINSOCK_SOCKETS are defined #endif /* MHD_WINSOCK_SOCKETS */ #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } static void _testErrorLog_func (const char *errDesc, const char *funcName, int lineNum) { fflush (stdout); if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call resulted in error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); } #ifdef MHD_HAVE_MHD_FUNC_ #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, MHD_FUNC_, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, MHD_FUNC_, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, MHD_FUNC_, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, MHD_FUNC_, __LINE__) #define testErrorLog(ignore) \ _testErrorLog_func(NULL, MHD_FUNC_, __LINE__) #define testErrorLogDesc(errDesc) \ _testErrorLog_func(errDesc, MHD_FUNC_, __LINE__) #else /* ! MHD_HAVE_MHD_FUNC_ */ #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #define testErrorLog(ignore) _testErrorLog_func(NULL, NULL, __LINE__) #define testErrorLogDesc(errDesc) _testErrorLog_func(errDesc, NULL, __LINE__) #endif /* ! MHD_HAVE_MHD_FUNC_ */ /* ** External parameters ** */ static bool use_large; static bool use_vlarge; static bool test_tls; static int verbose = 0; enum tls_tool { TLS_CLI_NO_TOOL = 0, TLS_CLI_GNUTLS, TLS_CLI_OPENSSL, TLS_LIB_GNUTLS }; static enum tls_tool use_tls_tool; /* ** Internal values ** */ /* Could be increased to facilitate debugging */ static int test_timeout = 5; static uint16_t global_port; static const void *rclient_msg; static size_t rclient_msg_size; static const void *app_msg; static size_t app_msg_size; static void *alloc_ptr[2] = {NULL, NULL}; static void fflush_allstd (void) { fflush (stderr); fflush (stdout); } #if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID) /** * Fork child that connects via GnuTLS-CLI to our @a port. Allows us to * talk to our port over a socket in @a sp without having to worry * about TLS. * * @param location where the socket is returned * @return -1 on error, otherwise PID of TLS child process */ static pid_t gnutlscli_connect (int *sock, uint16_t port) { pid_t chld; int sp[2]; char destination[30]; if (0 != socketpair (AF_UNIX, SOCK_STREAM, 0, sp)) { testErrorLogDesc ("socketpair() failed"); return (pid_t) -1; } chld = fork (); if (0 != chld) { *sock = sp[1]; MHD_socket_close_chk_ (sp[0]); return chld; } MHD_socket_close_chk_ (sp[1]); (void) close (0); (void) close (1); if (-1 == dup2 (sp[0], 0)) externalErrorExitDesc ("dup2() failed"); if (-1 == dup2 (sp[0], 1)) externalErrorExitDesc ("dup2() failed"); MHD_socket_close_chk_ (sp[0]); if (TLS_CLI_GNUTLS == use_tls_tool) { snprintf (destination, sizeof(destination), "%u", (unsigned int) port); execlp ("gnutls-cli", "gnutls-cli", "--insecure", "-p", destination, "127.0.0.1", (char *) NULL); } else if (TLS_CLI_OPENSSL == use_tls_tool) { snprintf (destination, sizeof(destination), "127.0.0.1:%u", (unsigned int) port); execlp ("openssl", "openssl", "s_client", "-connect", destination, "-verify", "1", (char *) NULL); } _exit (1); } #endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */ #if 0 /* Unused code */ /** * Change socket to blocking. * * @param fd the socket to manipulate */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("fcntl() failed"); if ((flags & ~O_NONBLOCK) != flags) if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) externalErrorExitDesc ("fcntl() failed"); #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("ioctlsocket() failed"); #endif /* MHD_WINSOCK_SOCKETS */ } #endif /* Unused code */ /** * Change socket to non-blocking. * * @param fd the socket to manipulate */ static void make_nonblocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("fcntl() failed"); if (O_NONBLOCK != (flags & O_NONBLOCK)) if (-1 == fcntl (fd, F_SETFL, flags | O_NONBLOCK)) externalErrorExitDesc ("fcntl() failed"); #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 1; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("ioctlsocket() failed"); #endif /* MHD_WINSOCK_SOCKETS */ } /** * Enable TCP_NODELAY on TCP/IP socket. * * @param fd the socket to manipulate */ static void make_nodelay (MHD_socket fd) { #ifdef TCP_NODELAY const MHD_SCKT_OPT_BOOL_ on_val = 1; if (0 == setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, (const void *) &on_val, sizeof (on_val))) return; /* Success exit point */ #ifndef MHD_WINSOCK_SOCKETS fprintf (stderr, "Failed to enable TCP_NODELAY on socket (ignored). " "errno: %d (%s)\n", (int) errno, strerror (errno)); #else /* MHD_WINSOCK_SOCKETS */ fprintf (stderr, "Failed to enable TCP_NODELAY on socket (ignored). " "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); #endif /* TCP_NODELAY */ } /** * Wrapper structure for plain&TLS sockets */ struct wr_socket { /** * Real network socket */ MHD_socket fd; /** * Type of this socket */ enum wr_type { wr_invalid = 0, wr_plain = 1, wr_tls = 2 } t; bool is_nonblocking; bool eof_recieved; #ifdef HTTPS_SUPPORT /** * TLS credentials */ gnutls_certificate_credentials_t tls_crd; /** * TLS session. */ gnutls_session_t tls_s; /** * TLS handshake already succeed? */ bool tls_connected; #endif }; /** * Get underlying real socket. * @return FD of real socket */ #define wr_fd(s) ((s)->fd) #if 0 /* Unused code */ static void wr_make_blocking (struct wr_socket *s) { if (s->is_nonblocking) make_blocking (s->fd); s->is_nonblocking = false; } #endif /* Unused code */ static void wr_make_nonblocking (struct wr_socket *s) { if (! s->is_nonblocking) make_nonblocking (s->fd); s->is_nonblocking = true; } /** * Create wr_socket with plain TCP underlying socket * @return created socket on success, NULL otherwise */ static struct wr_socket * wr_create_plain_sckt (void) { struct wr_socket *s = malloc (sizeof(struct wr_socket)); if (NULL == s) { testErrorLogDesc ("malloc() failed"); return NULL; } s->t = wr_plain; s->eof_recieved = false; s->fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); s->is_nonblocking = false; if (MHD_INVALID_SOCKET != s->fd) { make_nodelay (s->fd); return s; /* Success */ } testErrorLogDesc ("socket() failed"); free (s); return NULL; } /** * Create wr_socket with TLS TCP underlying socket * @return created socket on success, NULL otherwise */ static struct wr_socket * wr_create_tls_sckt (void) { #ifdef HTTPS_SUPPORT struct wr_socket *s = malloc (sizeof(struct wr_socket)); if (NULL == s) { testErrorLogDesc ("malloc() failed"); return NULL; } s->t = wr_tls; s->eof_recieved = false; s->tls_connected = 0; s->fd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); s->is_nonblocking = false; if (MHD_INVALID_SOCKET != s->fd) { make_nodelay (s->fd); if (GNUTLS_E_SUCCESS == gnutls_init (&(s->tls_s), GNUTLS_CLIENT)) { if (GNUTLS_E_SUCCESS == gnutls_set_default_priority (s->tls_s)) { if (GNUTLS_E_SUCCESS == gnutls_certificate_allocate_credentials (&(s->tls_crd))) { if (GNUTLS_E_SUCCESS == gnutls_credentials_set (s->tls_s, GNUTLS_CRD_CERTIFICATE, s->tls_crd)) { #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64) gnutls_transport_set_int (s->tls_s, (int) (s->fd)); #else /* GnuTLS before 3.1.9 or Win x64 */ gnutls_transport_set_ptr (s->tls_s, (gnutls_transport_ptr_t) \ (intptr_t) (s->fd)); #endif /* GnuTLS before 3.1.9 or Win x64 */ return s; } else testErrorLogDesc ("gnutls_credentials_set() failed"); gnutls_certificate_free_credentials (s->tls_crd); } else testErrorLogDesc ("gnutls_certificate_allocate_credentials() failed"); } else testErrorLogDesc ("gnutls_set_default_priority() failed"); gnutls_deinit (s->tls_s); } else testErrorLogDesc ("gnutls_init() failed"); (void) MHD_socket_close_ (s->fd); } else testErrorLogDesc ("socket() failed"); free (s); #endif /* HTTPS_SUPPORT */ return NULL; } /** * Create wr_socket with plain TCP underlying socket * from already created TCP socket. * @param plain_sk real TCP socket * @return created socket on success, NULL otherwise */ static struct wr_socket * wr_create_from_plain_sckt (MHD_socket plain_sk) { struct wr_socket *s = malloc (sizeof(struct wr_socket)); if (NULL == s) { testErrorLogDesc ("malloc() failed"); return NULL; } s->t = wr_plain; s->eof_recieved = false; s->fd = plain_sk; s->is_nonblocking = false; /* The actual mode is unknown */ wr_make_nonblocking (s); /* Force set mode to have correct status */ make_nodelay (s->fd); return s; } #if 0 /* Disabled code */ /** * Check whether shutdown of connection was received from remote * @param s socket to check * @return zero if shutdown signal has not been received, * 1 if shutdown signal was already received */ static int wr_is_eof_received (struct wr_socket *s) { return s->eof_recieved ? 1 : 0; } #endif /* Disabled code */ enum wr_wait_for_type { WR_WAIT_FOR_RECV = 0, WR_WAIT_FOR_SEND = 1 }; static bool wr_wait_socket_ready_noabort_ (struct wr_socket *s, int timeout_ms, enum wr_wait_for_type wait_for) { fd_set fds; int sel_res; struct timeval tmo; struct timeval *tmo_ptr; #ifndef MHD_WINSOCK_SOCKETS if (FD_SETSIZE <= s->fd) externalErrorExitDesc ("Too large FD value"); #endif /* ! MHD_WINSOCK_SOCKETS */ FD_ZERO (&fds); FD_SET (s->fd, &fds); if (0 <= timeout_ms) { #if ! defined(_WIN32) || defined(__CYGWIN__) tmo.tv_sec = (time_t) (timeout_ms / 1000); #else /* Native W32 */ tmo.tv_sec = (long) (timeout_ms / 1000); #endif /* Native W32 */ tmo.tv_usec = ((long) (timeout_ms % 1000)) * 1000; tmo_ptr = &tmo; } else tmo_ptr = NULL; /* No timeout */ do { if (WR_WAIT_FOR_RECV == wait_for) sel_res = select (1 + (int) s->fd, &fds, NULL, NULL, tmo_ptr); else sel_res = select (1 + (int) s->fd, NULL, &fds, NULL, tmo_ptr); } while (0 > sel_res && MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())); if (1 == sel_res) return true; if (0 == sel_res) fprintf (stderr, "Timeout"); else { #ifndef MHD_WINSOCK_SOCKETS fprintf (stderr, "Error %d (%s)", (int) errno, strerror (errno)); #else /* MHD_WINSOCK_SOCKETS */ fprintf (stderr, "Error (WSAGetLastError code: %d)", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ } fprintf (stderr, " waiting for socket to be available for %s.\n", (WR_WAIT_FOR_RECV == wait_for) ? "receiving" : "sending"); return false; } static void wr_wait_socket_ready_ (struct wr_socket *s, int timeout_ms, enum wr_wait_for_type wait_for) { if (wr_wait_socket_ready_noabort_ (s, timeout_ms, wait_for)) return; if (WR_WAIT_FOR_RECV == wait_for) mhdErrorExitDesc ("Client or application failed to receive the data"); else mhdErrorExitDesc ("Client or application failed to send the data"); } /** * Connect socket to specified address. * @param s socket to use * @param addr address to connect * @param length of structure pointed by @a addr * @param timeout_ms the maximum wait time in milliseconds to send the data, * no limit if negative value is used * @return zero on success, -1 otherwise. */ static int wr_connect_tmo (struct wr_socket *s, const struct sockaddr *addr, unsigned int length, int timeout_ms) { if (0 != connect (s->fd, addr, (socklen_t) length)) { int err; bool connect_completed = false; err = MHD_socket_get_error_ (); #if defined(MHD_POSIX_SOCKETS) while (! connect_completed && (EINTR == err)) { connect_completed = (0 == connect (s->fd, addr, (socklen_t) length)); if (! connect_completed) { err = errno; if (EALREADY == err) err = EINPROGRESS; else if (EISCONN == err) connect_completed = true; } } #endif /* MHD_POSIX_SOCKETS */ if (! connect_completed && (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINPROGRESS_) || MHD_SCKT_ERR_IS_EAGAIN_ (err))) /* No modern system uses EAGAIN, except W32 */ connect_completed = wr_wait_socket_ready_noabort_ (s, timeout_ms, WR_WAIT_FOR_SEND); if (! connect_completed) { testErrorLogDesc ("connect() failed"); return -1; } } if (wr_plain == s->t) return 0; #ifdef HTTPS_SUPPORT if (wr_tls == s->t) { /* Do not try handshake here as * it requires processing on MHD side and * when testing with "external" polling, * test will call MHD processing only * after return from wr_connect(). */ s->tls_connected = 0; return 0; } #endif /* HTTPS_SUPPORT */ testErrorLogDesc ("HTTPS socket connect called, but code does not support" \ " HTTPS sockets"); return -1; } /** * Connect socket to specified address. * @param s socket to use * @param addr address to connect * @param length of structure pointed by @a addr * @return zero on success, -1 otherwise. */ static int wr_connect (struct wr_socket *s, const struct sockaddr *addr, unsigned int length) { return wr_connect_tmo (s, addr, length, test_timeout * 1000); } #ifdef HTTPS_SUPPORT /* Only to be called from wr_send() and wr_recv() ! */ static bool wr_handshake_tmo_ (struct wr_socket *s, int timeout_ms) { int res = gnutls_handshake (s->tls_s); while ((GNUTLS_E_AGAIN == res) || (GNUTLS_E_INTERRUPTED == res)) { wr_wait_socket_ready_ (s, timeout_ms, gnutls_record_get_direction (s->tls_s) ? WR_WAIT_FOR_SEND : WR_WAIT_FOR_RECV); res = gnutls_handshake (s->tls_s); } if (GNUTLS_E_SUCCESS == res) s->tls_connected = true; else { fprintf (stderr, "The error returned by gnutls_handshake() is " "'%s' ", gnutls_strerror ((int) res)); #if GNUTLS_VERSION_NUMBER >= 0x020600 fprintf (stderr, "(%s)\n", gnutls_strerror_name ((int) res)); #else /* GNUTLS_VERSION_NUMBER < 0x020600 */ fprintf (stderr, "(%d)\n", (int) res); #endif /* GNUTLS_VERSION_NUMBER < 0x020600 */ testErrorLogDesc ("gnutls_handshake() failed with hard error"); MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_); /* hard error */ } return s->tls_connected; } #if 0 /* Unused function */ /* Only to be called from wr_send() and wr_recv() ! */ static bool wr_handshake_ (struct wr_socket *s) { return wr_handshake_tmo_ (s, test_timeout * 1000); } #endif /* Unused function */ #endif /* HTTPS_SUPPORT */ /** * Send data to remote by socket. * @param s the socket to use * @param buf the buffer with data to send * @param len the length of data in @a buf * @param timeout_ms the maximum wait time in milliseconds to send the data, * no limit if negative value is used * @return number of bytes were sent if succeed, * -1 if failed. Use #MHD_socket_get_error_() * to get socket error. */ static ssize_t wr_send_tmo (struct wr_socket *s, const void *buf, size_t len, int timeout_ms) { if (wr_plain == s->t) { ssize_t res; while (! 0) { int err; res = MHD_send_ (s->fd, buf, len); if (0 <= res) break; /* Success */ err = MHD_socket_get_error_ (); if (! MHD_SCKT_ERR_IS_EAGAIN_ (err) && ! MHD_SCKT_ERR_IS_EINTR_ (err)) break; /* Failure */ wr_wait_socket_ready_ (s, timeout_ms, WR_WAIT_FOR_SEND); } return res; } #ifdef HTTPS_SUPPORT else if (wr_tls == s->t) { ssize_t ret; if (! s->tls_connected && ! wr_handshake_tmo_ (s, timeout_ms)) return -1; while (1) { ret = gnutls_record_send (s->tls_s, buf, len); if (ret >= 0) return ret; if ((GNUTLS_E_AGAIN != ret) && (GNUTLS_E_INTERRUPTED != ret)) break; wr_wait_socket_ready_ (s, timeout_ms, gnutls_record_get_direction (s->tls_s) ? WR_WAIT_FOR_SEND : WR_WAIT_FOR_RECV); } fprintf (stderr, "The error returned by gnutls_record_send() is " "'%s' ", gnutls_strerror ((int) ret)); #if GNUTLS_VERSION_NUMBER >= 0x020600 fprintf (stderr, "(%s)\n", gnutls_strerror_name ((int) ret)); #else /* GNUTLS_VERSION_NUMBER < 0x020600 */ fprintf (stderr, "(%d)\n", (int) ret); #endif /* GNUTLS_VERSION_NUMBER < 0x020600 */ testErrorLogDesc ("gnutls_record_send() failed with hard error"); MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_); /* hard error */ return -1; } #endif /* HTTPS_SUPPORT */ testErrorLogDesc ("HTTPS socket send called, but code does not support" \ " HTTPS sockets"); return -1; } /** * Send data to remote by socket. * @param s the socket to use * @param buf the buffer with data to send * @param len the length of data in @a buf * @return number of bytes were sent if succeed, * -1 if failed. Use #MHD_socket_get_error_() * to get socket error. */ static ssize_t wr_send (struct wr_socket *s, const void *buf, size_t len) { return wr_send_tmo (s, buf, len, test_timeout * 1000); } /** * Receive data from remote by socket. * @param s the socket to use * @param buf the buffer to store received data * @param len the length of @a buf * @param timeout_ms the maximum wait time in milliseconds to receive the data, * no limit if negative value is used * @return number of bytes were received if succeed, * -1 if failed. Use #MHD_socket_get_error_() * to get socket error. */ static ssize_t wr_recv_tmo (struct wr_socket *s, void *buf, size_t len, int timeout_ms) { if (wr_plain == s->t) { ssize_t res; while (! 0) { int err; res = MHD_recv_ (s->fd, buf, len); if (0 == res) s->eof_recieved = true; if (0 <= res) break; /* Success */ err = MHD_socket_get_error_ (); if (! MHD_SCKT_ERR_IS_EAGAIN_ (err) && ! MHD_SCKT_ERR_IS_EINTR_ (err)) break; /* Failure */ wr_wait_socket_ready_ (s, timeout_ms, WR_WAIT_FOR_RECV); } return res; } #ifdef HTTPS_SUPPORT if (wr_tls == s->t) { ssize_t ret; if (! s->tls_connected && ! wr_handshake_tmo_ (s, timeout_ms)) return -1; while (1) { ret = gnutls_record_recv (s->tls_s, buf, len); if (0 == ret) s->eof_recieved = true; if (ret >= 0) return ret; if ((GNUTLS_E_AGAIN != ret) && (GNUTLS_E_INTERRUPTED != ret)) break; wr_wait_socket_ready_ (s, timeout_ms, gnutls_record_get_direction (s->tls_s) ? WR_WAIT_FOR_SEND : WR_WAIT_FOR_RECV); } fprintf (stderr, "The error returned by gnutls_record_recv() is " "'%s' ", gnutls_strerror ((int) ret)); #if GNUTLS_VERSION_NUMBER >= 0x020600 fprintf (stderr, "(%s)\n", gnutls_strerror_name ((int) ret)); #else /* GNUTLS_VERSION_NUMBER < 0x020600 */ fprintf (stderr, "(%d)\n", (int) ret); #endif /* GNUTLS_VERSION_NUMBER < 0x020600 */ testErrorLogDesc ("gnutls_record_recv() failed with hard error"); MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_); /* hard error */ return -1; } #endif /* HTTPS_SUPPORT */ return -1; } /** * Receive data from remote by socket. * @param s the socket to use * @param buf the buffer to store received data * @param len the length of @a buf * @return number of bytes were received if succeed, * -1 if failed. Use #MHD_socket_get_error_() * to get socket error. */ static ssize_t wr_recv (struct wr_socket *s, void *buf, size_t len) { return wr_recv_tmo (s, buf, len, test_timeout * 1000); } /** * Shutdown send/write on the socket. * @param s the socket to shutdown * @param how the type of shutdown: SHUT_WR or SHUT_RDWR * @param timeout_ms the maximum wait time in milliseconds to receive the data, * no limit if negative value is used * @return zero on succeed, -1 otherwise */ static int wr_shutdown_tmo (struct wr_socket *s, int how, int timeout_ms) { switch (how) { case SHUT_WR: /* Valid value */ break; case SHUT_RDWR: /* Valid value */ break; case SHUT_RD: externalErrorExitDesc ("Unsupported 'how' value"); break; default: externalErrorExitDesc ("Invalid 'how' value"); break; } if (wr_plain == s->t) { (void) timeout_ms; /* Unused parameter for plain sockets */ return shutdown (s->fd, how); } #ifdef HTTPS_SUPPORT if (wr_tls == s->t) { ssize_t ret; if (! s->tls_connected && ! wr_handshake_tmo_ (s, timeout_ms)) return -1; while (1) { ret = gnutls_bye (s->tls_s, (SHUT_WR == how) ? GNUTLS_SHUT_WR : GNUTLS_SHUT_RDWR); if (GNUTLS_E_SUCCESS == ret) { #if 0 /* Disabled to test pure behaviour */ if (SHUT_RDWR == how) (void) shutdown (s->fd, how); /* Also shutdown the underlying transport layer */ #endif return 0; } if ((GNUTLS_E_AGAIN != ret) && (GNUTLS_E_INTERRUPTED != ret)) break; wr_wait_socket_ready_ (s, timeout_ms, gnutls_record_get_direction (s->tls_s) ? WR_WAIT_FOR_SEND : WR_WAIT_FOR_RECV); } fprintf (stderr, "The error returned by gnutls_bye() is " "'%s' ", gnutls_strerror ((int) ret)); #if GNUTLS_VERSION_NUMBER >= 0x020600 fprintf (stderr, "(%s)\n", gnutls_strerror_name ((int) ret)); #else /* GNUTLS_VERSION_NUMBER < 0x020600 */ fprintf (stderr, "(%d)\n", (int) ret); #endif /* GNUTLS_VERSION_NUMBER < 0x020600 */ testErrorLogDesc ("gnutls_bye() failed with hard error"); MHD_socket_set_error_ (MHD_SCKT_ECONNABORTED_); /* hard error */ return -1; } #endif /* HTTPS_SUPPORT */ return -1; } /** * Shutdown the socket. * @param s the socket to shutdown * @return zero on succeed, -1 otherwise */ static int wr_shutdown (struct wr_socket *s, int how) { return wr_shutdown_tmo (s, how, test_timeout * 1000); } /** * Close socket and release allocated resourced * @param s the socket to close * @return zero on succeed, -1 otherwise */ static int wr_close (struct wr_socket *s) { int ret = (MHD_socket_close_ (s->fd)) ? 0 : -1; #ifdef HTTPS_SUPPORT if (wr_tls == s->t) { gnutls_deinit (s->tls_s); gnutls_certificate_free_credentials (s->tls_crd); } #endif /* HTTPS_SUPPORT */ free (s); return ret; } /** * Thread we use to run the interaction with the upgraded socket. */ static pthread_t pt; /** * Will be set to the upgraded socket. */ static struct wr_socket *volatile usock; /** * Thread we use to run the interaction with the upgraded socket. */ static pthread_t pt_client; /** * Flag set to true once the client is finished. */ static volatile bool client_done; /** * Flag set to true once the app is finished. */ static volatile bool app_done; static const char * term_reason_str (enum MHD_RequestTerminationCode term_code) { switch ((int) term_code) { case MHD_REQUEST_TERMINATED_COMPLETED_OK: return "COMPLETED_OK"; case MHD_REQUEST_TERMINATED_WITH_ERROR: return "TERMINATED_WITH_ERROR"; case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED: return "TIMEOUT_REACHED"; case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN: return "DAEMON_SHUTDOWN"; case MHD_REQUEST_TERMINATED_READ_ERROR: return "READ_ERROR"; case MHD_REQUEST_TERMINATED_CLIENT_ABORT: return "CLIENT_ABORT"; case -1: return "(not called)"; default: return "(unknown code)"; } return "(problem)"; /* unreachable */ } /** * Callback used by MHD to notify the application about completed * requests. Frees memory. * * @param cls client-defined closure * @param connection connection handle * @param req_cls value as set by the last call to * the #MHD_AccessHandlerCallback * @param toe reason for request termination */ static void notify_completed_cb (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { (void) cls; (void) connection; /* Unused. Silent compiler warning. */ if (verbose) printf ("notify_completed_cb() has been called with '%s' code.\n", term_reason_str (toe)); if ( (toe != MHD_REQUEST_TERMINATED_COMPLETED_OK) && (toe != MHD_REQUEST_TERMINATED_CLIENT_ABORT) && (toe != MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN) ) mhdErrorExitDesc ("notify_completed_cb() called with wrong code"); if (NULL == req_cls) mhdErrorExitDesc ("'req_cls' parameter is NULL"); if (NULL == *req_cls) mhdErrorExitDesc ("'*req_cls' pointer is NULL"); if (! pthread_equal (**((pthread_t **) req_cls), pthread_self ())) mhdErrorExitDesc ("notify_completed_cb() is called in wrong thread"); free (*req_cls); *req_cls = NULL; } /** * Logging callback. * * @param cls logging closure (NULL) * @param uri access URI * @param connection connection handle * @return #TEST_PTR */ static void * log_cb (void *cls, const char *uri, struct MHD_Connection *connection) { pthread_t *ppth; (void) cls; (void) connection; /* Unused. Silent compiler warning. */ if (NULL == uri) mhdErrorExitDesc ("The 'uri' parameter is NULL"); if (0 != strcmp (uri, "/")) { fprintf (stderr, "Wrong 'uri' value: '%s'. ", uri); mhdErrorExit (); } ppth = malloc (sizeof (pthread_t)); if (NULL == ppth) externalErrorExitDesc ("malloc() failed"); *ppth = pthread_self (); return (void *) ppth; } /** * Function to check that MHD properly notifies about starting * and stopping. * * @param cls client-defined closure * @param connection connection handle * @param socket_context socket-specific pointer where the * client can associate some state specific * to the TCP connection; note that this is * different from the "req_cls" which is per * HTTP request. The client can initialize * during #MHD_CONNECTION_NOTIFY_STARTED and * cleanup during #MHD_CONNECTION_NOTIFY_CLOSED * and access in the meantime using * #MHD_CONNECTION_INFO_SOCKET_CONTEXT. * @param toe reason for connection notification * @see #MHD_OPTION_NOTIFY_CONNECTION * @ingroup request */ static void notify_connection_cb (void *cls, struct MHD_Connection *connection, void **socket_context, enum MHD_ConnectionNotificationCode toe) { static int started = MHD_NO; (void) cls; (void) connection; /* Unused. Silent compiler warning. */ switch (toe) { case MHD_CONNECTION_NOTIFY_STARTED: if (MHD_NO != started) mhdErrorExitDesc ("The connection has been already started"); started = MHD_YES; *socket_context = &started; break; case MHD_CONNECTION_NOTIFY_CLOSED: if (MHD_YES != started) mhdErrorExitDesc ("The connection has not been started before"); if (&started != *socket_context) mhdErrorExitDesc ("Wrong '*socket_context' value"); *socket_context = NULL; started = MHD_NO; break; } } static void send_all (struct wr_socket *sock, const void *data, size_t data_size) { ssize_t ret; size_t sent; const uint8_t *const buf = (const uint8_t *) data; wr_make_nonblocking (sock); for (sent = 0; sent < data_size; sent += (size_t) ret) { ret = wr_send (sock, buf + sent, data_size - sent); if (0 > ret) { if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()) || MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) { ret = 0; continue; } externalErrorExitDesc ("send() failed"); } } } #define send_all_stext(sk,st) send_all(sk,st,MHD_STATICSTR_LEN_(st)) /** * Read character-by-character until we * get 'CRLNCRLN'. */ static void recv_hdr (struct wr_socket *sock) { unsigned int i; char next; char c; ssize_t ret; wr_make_nonblocking (sock); next = '\r'; i = 0; while (i < 4) { ret = wr_recv (sock, &c, 1); if (0 > ret) { if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ())) continue; if (MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) continue; externalErrorExitDesc ("recv() failed"); } if (0 == ret) mhdErrorExitDesc ("The server unexpectedly closed connection"); if (c == next) { i++; if (next == '\r') next = '\n'; else next = '\r'; continue; } if (c == '\r') { i = 1; next = '\n'; continue; } i = 0; next = '\r'; } } static void recv_all (struct wr_socket *sock, const void *data, size_t data_size) { uint8_t *buf; ssize_t ret; size_t rcvd; buf = (uint8_t *) malloc (data_size); if (NULL == buf) externalErrorExitDesc ("malloc() failed"); wr_make_nonblocking (sock); for (rcvd = 0; rcvd < data_size; rcvd += (size_t) ret) { ret = wr_recv (sock, buf + rcvd, data_size - rcvd); if (0 > ret) { if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()) || MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) { ret = 0; continue; } externalErrorExitDesc ("recv() failed"); } else if (0 == ret) { fprintf (stderr, "Partial only received text. Expected: '%.*s' " "(length: %ud). Got: '%.*s' (length: %ud). ", (int) data_size, (const char *) data, (unsigned int) data_size, (int) rcvd, (const char *) buf, (unsigned int) rcvd); mhdErrorExitDesc ("The server unexpectedly closed connection"); } if ((data_size - rcvd) < (size_t) ret) externalErrorExitDesc ("recv() returned excessive amount of data"); if (0 != memcmp (data, buf, rcvd + (size_t) ret)) { fprintf (stderr, "Wrong received text. Expected: '%.*s'. " "Got: '%.*s'. ", (int) (rcvd + (size_t) ret), (const char *) data, (int) (rcvd + (size_t) ret), (const char *) buf); mhdErrorExit (); } } if (0 != memcmp (data, buf, data_size)) { fprintf (stderr, "Wrong received text. Expected: '%.*s'. " "Got: '%.*s'. ", (int) data_size, (const char *) data, (int) data_size, (const char *) buf); mhdErrorExit (); } free (buf); } #define recv_all_stext(sk,st) recv_all(sk,st,MHD_STATICSTR_LEN_(st)) /** * Shutdown write of the connection to signal end of transmission * for the remote side * @param sock the socket to shutdown */ static void send_eof (struct wr_socket *sock) { if (0 != wr_shutdown (sock, /* ** On Darwin local shutdown of RD cause error ** if remote side shut down WR before. wr_is_eof_received (sock) ? SHUT_RDWR : */ SHUT_WR)) externalErrorExitDesc ("Failed to shutdown connection"); } /** * Receive end of the transmission indication from the remote side * @param sock the socket to use */ static void receive_eof (struct wr_socket *sock) { uint8_t buf[127]; ssize_t ret; size_t rcvd; bool got_eof = false; wr_make_nonblocking (sock); for (rcvd = 0; rcvd < sizeof(buf); rcvd += (size_t) ret) { ret = wr_recv (sock, buf + rcvd, sizeof(buf) - rcvd); if (0 > ret) { if (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()) || MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) { ret = 0; continue; } externalErrorExitDesc ("recv() failed"); } else if (0 == ret) { got_eof = true; break; } } if (got_eof && (0 == rcvd)) return; /* Success */ if (0 != rcvd) { if (sizeof(buf) == rcvd) { fprintf (stderr, "Received at least %lu extra bytes while " "end-of-file is expected.\n", (unsigned long) sizeof(buf)); mhdErrorExit (); } fprintf (stderr, "Received at %lu extra bytes and then %s" "end-of-file marker.\n", (unsigned long) rcvd, got_eof ? "" : "NO "); mhdErrorExit (); } if (! got_eof) mhdErrorExitDesc ("Failed to receive end-of-file marker."); } /** * Main function for the thread that runs the interaction with * the upgraded socket. * * @param cls the handle for the upgrade */ static void * run_usock (void *cls) { struct MHD_UpgradeResponseHandle *urh = cls; recv_all (usock, rclient_msg, rclient_msg_size); send_all (usock, app_msg, app_msg_size); recv_all_stext (usock, "Finished"); if (! test_tls) { receive_eof (usock); send_eof (usock); } MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); free (usock); usock = NULL; app_done = true; return NULL; } /** * Main function for the thread that runs the client-side of the * interaction with the upgraded socket. * * @param cls the client socket */ static void * run_usock_client (void *cls) { struct wr_socket *sock = cls; send_all_stext (sock, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: Upgrade\r\n\r\n"); recv_hdr (sock); send_all (sock, rclient_msg, rclient_msg_size); recv_all (sock, app_msg, app_msg_size); send_all_stext (sock, "Finished"); if (! test_tls) { send_eof (sock); receive_eof (sock); } wr_close (sock); client_done = true; return NULL; } /** * Function called after a protocol "upgrade" response was sent * successfully and the socket should now be controlled by some * protocol other than HTTP. * * Any data already received on the socket will be made available in * @e extra_in. This can happen if the application sent extra data * before MHD send the upgrade response. The application should * treat data from @a extra_in as if it had read it from the socket. * * Note that the application must not close() @a sock directly, * but instead use #MHD_upgrade_action() for special operations * on @a sock. * * Except when in 'thread-per-connection' mode, implementations * of this function should never block (as it will still be called * from within the main event loop). * * @param cls closure, whatever was given to #MHD_create_response_for_upgrade(). * @param connection original HTTP connection handle, * giving the function a last chance * to inspect the original HTTP request * @param req_cls last value left in `req_cls` of the `MHD_AccessHandlerCallback` * @param extra_in if we happened to have read bytes after the * HTTP header already (because the client sent * more than the HTTP header of the request before * we sent the upgrade response), * these are the extra bytes already read from @a sock * by MHD. The application should treat these as if * it had read them from @a sock. * @param extra_in_size number of bytes in @a extra_in * @param sock socket to use for bi-directional communication * with the client. For HTTPS, this may not be a socket * that is directly connected to the client and thus certain * operations (TCP-specific setsockopt(), getsockopt(), etc.) * may not work as expected (as the socket could be from a * socketpair() or a TCP-loopback). The application is expected * to perform read()/recv() and write()/send() calls on the socket. * The application may also call shutdown(), but must not call * close() directly. * @param urh argument for #MHD_upgrade_action()s on this @a connection. * Applications must eventually use this callback to (indirectly) * perform the close() action on the @a sock. */ static void upgrade_cb (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) { (void) cls; (void) connection; (void) req_cls; (void) extra_in; /* Unused. Silent compiler warning. */ usock = wr_create_from_plain_sckt (sock); wr_make_nonblocking (usock); if (0 != extra_in_size) mhdErrorExitDesc ("'extra_in_size' is not zero"); if (0 != pthread_create (&pt, NULL, &run_usock, urh)) externalErrorExitDesc ("pthread_create() failed"); } /** * A client has requested the given url using the given method * (#MHD_HTTP_METHOD_GET, #MHD_HTTP_METHOD_PUT, * #MHD_HTTP_METHOD_DELETE, #MHD_HTTP_METHOD_POST, etc). The callback * must call MHD callbacks to provide content to give back to the * client and return an HTTP status code (i.e. #MHD_HTTP_OK, * #MHD_HTTP_NOT_FOUND, etc.). * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param url the requested url * @param method the HTTP method used (#MHD_HTTP_METHOD_GET, * #MHD_HTTP_METHOD_PUT, etc.) * @param version the HTTP version string (i.e. * #MHD_HTTP_VERSION_1_1) * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of #MHD_get_connection_values; very large POST * data *will* be made available incrementally in * @a upload_data) * @param upload_data_size set initially to the size of the * @a upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param req_cls pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global #MHD_RequestCompletedCallback (which * can be set with the #MHD_OPTION_NOTIFY_COMPLETED). * Initially, `*req_cls` will be NULL. * @return #MHD_YES if the connection was handled successfully, * #MHD_NO if the socket must be closed due to a serious * error while handling the request */ static enum MHD_Result ahc_upgrade (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *resp; (void) cls; (void) url; (void) method; /* Unused. Silent compiler warning. */ (void) version; (void) upload_data; (void) upload_data_size; /* Unused. Silent compiler warning. */ if (NULL == req_cls) mhdErrorExitDesc ("'req_cls' is NULL"); if (NULL == *req_cls) mhdErrorExitDesc ("'*req_cls' value is NULL"); if (! pthread_equal (**((pthread_t **) req_cls), pthread_self ())) mhdErrorExitDesc ("ahc_upgrade() is called in wrong thread"); resp = MHD_create_response_for_upgrade (&upgrade_cb, NULL); if (NULL == resp) mhdErrorExitDesc ("MHD_create_response_for_upgrade() failed"); if (MHD_YES != MHD_add_response_header (resp, MHD_HTTP_HEADER_UPGRADE, "Hello World Protocol")) mhdErrorExitDesc ("MHD_add_response_header() failed"); if (MHD_YES != MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, resp)) mhdErrorExitDesc ("MHD_queue_response() failed"); MHD_destroy_response (resp); return MHD_YES; } /** * Run the MHD external event loop using select or epoll. * * select/epoll modes are used automatically based on daemon's flags. * * @param daemon daemon to run it for */ static void run_mhd_select_loop (struct MHD_Daemon *daemon) { const time_t start_time = time (NULL); const union MHD_DaemonInfo *pdinfo; bool connection_was_accepted; bool connection_has_finished; #ifdef EPOLL_SUPPORT bool use_epoll = false; int ep = -1; pdinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_FLAGS); if (NULL == pdinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); else use_epoll = (0 != (pdinfo->flags & MHD_USE_EPOLL)); if (use_epoll) { pdinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_EPOLL_FD); if (NULL == pdinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); ep = pdinfo->listen_fd; if (0 > ep) mhdErrorExitDesc ("Invalid epoll FD value"); } #endif /* EPOLL_SUPPORT */ connection_was_accepted = false; connection_has_finished = false; while (1) { fd_set rs; fd_set ws; fd_set es; MHD_socket max_fd; struct timeval tv; uint64_t to64; bool has_mhd_timeout; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); max_fd = MHD_INVALID_SOCKET; if (time (NULL) - start_time > ((time_t) test_timeout)) mhdErrorExitDesc ("Test timeout"); pdinfo = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_CURRENT_CONNECTIONS); if (NULL == pdinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); if (0 != pdinfo->num_connections) connection_was_accepted = true; else { if (connection_was_accepted) connection_has_finished = true; } if (connection_has_finished) return; if (MHD_YES != MHD_get_fdset (daemon, &rs, &ws, &es, &max_fd)) mhdErrorExitDesc ("MHD_get_fdset() failed"); #ifdef EPOLL_SUPPORT if (use_epoll) { if (ep != max_fd) mhdErrorExitDesc ("Wrong 'max_fd' value"); if (! FD_ISSET (ep, &rs)) mhdErrorExitDesc ("Epoll FD is NOT set in read fd_set"); } #endif /* EPOLL_SUPPORT */ has_mhd_timeout = (MHD_NO != MHD_get_timeout64 (daemon, &to64)); if (has_mhd_timeout) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (to64 / 1000); #else /* Native W32 */ tv.tv_sec = (long) (to64 / 1000); #endif /* Native W32 */ tv.tv_usec = (long) (1000 * (to64 % 1000)); } else { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) test_timeout; #else /* Native W32 */ tv.tv_sec = (long) test_timeout; #endif /* Native W32 */ tv.tv_usec = 0; } #ifdef MHD_WINSOCK_SOCKETS if ((0 == rs.fd_count) && (0 == ws.fd_count) && (0 != es.fd_count)) Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); else /* Combined with the next 'if' */ #endif if (1) { int sel_res; sel_res = MHD_SYS_select_ (max_fd + 1, &rs, &ws, &es, &tv); if (0 == sel_res) { if (! has_mhd_timeout) mhdErrorExitDesc ("Timeout waiting for data on sockets"); } else if (0 > sel_res) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) #endif /* MHD_POSIX_SOCKETS */ mhdErrorExitDesc ("Unexpected select() error"); } } MHD_run_from_select (daemon, &rs, &ws, &es); } } #ifdef HAVE_POLL /** * Run the MHD external event loop using select. * * @param daemon daemon to run it for */ _MHD_NORETURN static void run_mhd_poll_loop (struct MHD_Daemon *daemon) { (void) daemon; /* Unused. Silent compiler warning. */ externalErrorExitDesc ("Not implementable with MHD API"); } #endif /* HAVE_POLL */ /** * Run the MHD external event loop using select. * * @param daemon daemon to run it for */ static void run_mhd_loop (struct MHD_Daemon *daemon, unsigned int flags) { if (0 == (flags & (MHD_USE_POLL | MHD_USE_EPOLL))) run_mhd_select_loop (daemon); #ifdef HAVE_POLL else if (0 != (flags & MHD_USE_POLL)) run_mhd_poll_loop (daemon); #endif /* HAVE_POLL */ #ifdef EPOLL_SUPPORT else if (0 != (flags & MHD_USE_EPOLL)) run_mhd_select_loop (daemon); #endif else externalErrorExitDesc ("Wrong 'flags' value"); } /** * Test upgrading a connection. * * @param flags which event loop style should be tested * @param pool size of the thread pool, 0 to disable */ static unsigned int test_upgrade (unsigned int flags, unsigned int pool) { struct MHD_Daemon *d = NULL; struct wr_socket *sock; struct sockaddr_in sa; enum MHD_FLAG used_flags; const union MHD_DaemonInfo *dinfo; #if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID) pid_t pid = -1; #endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */ size_t mem_limit; /* Handle memory limits. Actually makes sense only for TLS */ if (use_vlarge) mem_limit = 64U * 1024U; /* Half of the buffer should be large enough to take more than max TLS packet */ else if (use_large) mem_limit = 4U * 1024; /* Make sure that several iteration required to deliver a single message */ else mem_limit = 0; /* Use default value */ client_done = false; app_done = false; if (! test_tls) d = MHD_start_daemon (flags | MHD_USE_ERROR_LOG | MHD_ALLOW_UPGRADE | MHD_USE_ITC, global_port, NULL, NULL, &ahc_upgrade, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_NOTIFY_COMPLETED, ¬ify_completed_cb, NULL, MHD_OPTION_NOTIFY_CONNECTION, ¬ify_connection_cb, NULL, MHD_OPTION_THREAD_POOL_SIZE, pool, MHD_OPTION_CONNECTION_TIMEOUT, test_timeout, MHD_OPTION_CONNECTION_MEMORY_LIMIT, mem_limit, MHD_OPTION_END); #ifdef HTTPS_SUPPORT else d = MHD_start_daemon (flags | MHD_USE_ERROR_LOG | MHD_ALLOW_UPGRADE | MHD_USE_TLS | MHD_USE_ITC, global_port, NULL, NULL, &ahc_upgrade, NULL, MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, MHD_OPTION_NOTIFY_COMPLETED, ¬ify_completed_cb, NULL, MHD_OPTION_NOTIFY_CONNECTION, ¬ify_connection_cb, NULL, MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, MHD_OPTION_THREAD_POOL_SIZE, pool, MHD_OPTION_CONNECTION_TIMEOUT, test_timeout, MHD_OPTION_CONNECTION_MEMORY_LIMIT, mem_limit, MHD_OPTION_END); #endif /* HTTPS_SUPPORT */ if (NULL == d) mhdErrorExitDesc ("MHD_start_daemon() failed"); dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); used_flags = dinfo->flags; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == dinfo) || (0 == dinfo->port) ) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); global_port = dinfo->port; /* Re-use the same port for the next checks */ if (! test_tls || (TLS_LIB_GNUTLS == use_tls_tool)) { sock = test_tls ? wr_create_tls_sckt () : wr_create_plain_sckt (); if (NULL == sock) externalErrorExitDesc ("Create socket failed"); wr_make_nonblocking (sock); sa.sin_family = AF_INET; sa.sin_port = htons (dinfo->port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != wr_connect (sock, (struct sockaddr *) &sa, sizeof (sa))) externalErrorExitDesc ("Connect socket failed"); } else { #if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID) MHD_socket tls_fork_sock; uint16_t port; port = dinfo->port; if (-1 == (pid = gnutlscli_connect (&tls_fork_sock, port))) externalErrorExitDesc ("gnutlscli_connect() failed"); sock = wr_create_from_plain_sckt (tls_fork_sock); if (NULL == sock) externalErrorExitDesc ("wr_create_from_plain_sckt() failed"); wr_make_nonblocking (sock); #else /* !HTTPS_SUPPORT || !HAVE_FORK || !HAVE_WAITPID */ externalErrorExitDesc ("Unsupported 'use_tls_tool' value"); #endif /* !HTTPS_SUPPORT || !HAVE_FORK || !HAVE_WAITPID */ } if (0 != pthread_create (&pt_client, NULL, &run_usock_client, sock)) externalErrorExitDesc ("pthread_create() failed"); if (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD) ) run_mhd_loop (d, used_flags); if (0 != pthread_join (pt_client, NULL)) externalErrorExitDesc ("pthread_join() failed"); if (0 != pthread_join (pt, NULL)) externalErrorExitDesc ("pthread_join() failed"); #if defined(HTTPS_SUPPORT) && defined(HAVE_FORK) && defined(HAVE_WAITPID) if (test_tls && (TLS_LIB_GNUTLS != use_tls_tool)) { if ((pid_t) -1 == waitpid (pid, NULL, 0)) externalErrorExitDesc ("waitpid() failed"); } #endif /* HTTPS_SUPPORT && HAVE_FORK && HAVE_WAITPID */ if (! client_done) externalErrorExitDesc ("The client thread has not signalled " \ "successful finish"); if (! app_done) externalErrorExitDesc ("The application thread has not signalled " \ "successful finish"); MHD_stop_daemon (d); return 0; } enum test_msg_type { test_msg_large_app_data, test_msg_large_rclient_data, test_msg_vlarge_app_data, test_msg_vlarge_rclient_data }; /** * Initialise test message data * @param buf the pointer to the buffer to fill with the test data * @param buf_size the size of the @a buf * @param msg_type the type of the data to fill the @a buf * @return the @a buf pointer */ static void * init_test_msg (void *buf, size_t buf_size, enum test_msg_type msg_type) { size_t i; char *const text_buf = (char *) buf; uint8_t *const bin_buf = (uint8_t *) buf; if (0 == buf_size) return buf; switch (msg_type) { case test_msg_large_app_data: case test_msg_large_rclient_data: /* Simulate text data */ for (i = 0; i < buf_size; ++i) { size_t pos; if (test_msg_large_app_data == msg_type) pos = i + 43; else pos = i + 26; if ((0 == i) || (2 == pos % 100) ) text_buf[i] = (char) (unsigned char) ((test_msg_large_app_data == msg_type) ? ('Z' - pos % ('Z' - 'A' + 1)) : ('A' + pos % ('Z' - 'A' + 1))); else if (0 == pos % 100) text_buf[i] = '.'; else if (1 == pos % 100) text_buf[i] = ' '; else if ((99 != pos % 100) && (2 != pos % 100) && (0 == pos % 5)) text_buf[i] = ' '; else if (test_msg_large_app_data == msg_type) text_buf[i] = (char) (unsigned char) ('z' - pos % ('z' - 'a' + 1)); else text_buf[i] = (char) (unsigned char) ('a' + pos % ('z' - 'a' + 1)); } break; case test_msg_vlarge_app_data: /* Simulate binary data */ for (i = 0; i < buf_size; ++i) { bin_buf[i] = (uint8_t) ((i + 182) & 0xFF); } break; case test_msg_vlarge_rclient_data: /* Simulate binary data */ for (i = 0; i < buf_size; ++i) { bin_buf[i] = (uint8_t) ((111 - i) & 0xFF); } break; default: exit (99); break; } return buf; } /** * Perform initialisation of variables used in all check in this test * @return true if succeed, * false if failed. */ static bool global_test_init (void) { if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) global_port = 0; else { global_port = 1090; if (test_tls) global_port += 1U << 0; if (use_large) global_port += 1U << 1; else if (use_vlarge) global_port += 1U << 2; } if (use_large || use_vlarge) { unsigned int i; size_t alloc_size; alloc_size = use_vlarge ? (64U * 1024U) : (17U * 1024U); for (i = 0; i < (sizeof(alloc_ptr) / sizeof(alloc_ptr[0])); ++i) { alloc_ptr[i] = malloc (alloc_size); if (NULL == alloc_ptr[i]) { for (--i; i < (sizeof(alloc_ptr) / sizeof(alloc_ptr[0])); --i) { free (alloc_ptr[i]); } return false; } } rclient_msg_size = alloc_size; rclient_msg = init_test_msg (alloc_ptr[0], rclient_msg_size, use_vlarge ? test_msg_vlarge_rclient_data : test_msg_large_rclient_data); app_msg_size = alloc_size; app_msg = init_test_msg (alloc_ptr[1], app_msg_size, use_vlarge ? test_msg_vlarge_app_data : test_msg_large_app_data); } else { unsigned int i; for (i = 0; i < (sizeof(alloc_ptr) / sizeof(alloc_ptr[0])); ++i) alloc_ptr[i] = NULL; rclient_msg_size = MHD_STATICSTR_LEN_ ("Hello"); rclient_msg = "Hello"; app_msg_size = MHD_STATICSTR_LEN_ ("World"); app_msg = "World"; } return true; } /** * Perform de-initialisation of variables with memory de-allocation if required. */ static void global_test_deinit (void) { unsigned int i; for (i = ((sizeof(alloc_ptr) / sizeof(alloc_ptr[0])) - 1); i < (sizeof(alloc_ptr) / sizeof(alloc_ptr[0])); --i) { if (NULL != alloc_ptr[i]) free (alloc_ptr[i]); } } int main (int argc, char *const *argv) { unsigned int error_count = 0; unsigned int res; use_vlarge = (0 != has_in_name (argv[0], "_vlarge")); use_large = (! use_vlarge) && (0 != has_in_name (argv[0], "_large")); use_tls_tool = TLS_CLI_NO_TOOL; test_tls = has_in_name (argv[0], "_tls"); verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); if ((((int) ((~((unsigned int) 0U)) >> 1)) / 1000) < test_timeout) { fprintf (stderr, "The test timeout value (%d) is too large.\n" "The test cannot run.\n", test_timeout); fprintf (stderr, "The maximum allowed timeout value is %d.\n", (((int) ((~((unsigned int) 0U)) >> 1)) / 1000)); return 3; } if (test_tls) { use_tls_tool = TLS_LIB_GNUTLS; /* Should be always available as MHD uses it. */ #ifdef HTTPS_SUPPORT if (has_param (argc, argv, "--use-gnutls-cli")) use_tls_tool = TLS_CLI_GNUTLS; else if (has_param (argc, argv, "--use-openssl")) use_tls_tool = TLS_CLI_OPENSSL; else if (has_param (argc, argv, "--use-gnutls-lib")) use_tls_tool = TLS_LIB_GNUTLS; #if defined(HAVE_FORK) && defined(HAVE_WAITPID) else if (0 == system ("gnutls-cli --version 1> /dev/null 2> /dev/null")) use_tls_tool = TLS_CLI_GNUTLS; else if (0 == system ("openssl version 1> /dev/null 2> /dev/null")) use_tls_tool = TLS_CLI_OPENSSL; #endif /* HAVE_FORK && HAVE_WAITPID */ if (verbose) { switch (use_tls_tool) { case TLS_CLI_GNUTLS: printf ("GnuTLS-CLI will be used for testing.\n"); break; case TLS_CLI_OPENSSL: printf ("Command line version of OpenSSL will be used for testing.\n"); break; case TLS_LIB_GNUTLS: printf ("GnuTLS library will be used for testing.\n"); break; case TLS_CLI_NO_TOOL: default: externalErrorExitDesc ("Wrong 'use_tls_tool' value"); } } if ( (TLS_LIB_GNUTLS == use_tls_tool) && (GNUTLS_E_SUCCESS != gnutls_global_init ()) ) externalErrorExitDesc ("gnutls_global_init() failed"); #else /* ! HTTPS_SUPPORT */ fprintf (stderr, "HTTPS support was disabled by configure.\n"); return 77; #endif /* ! HTTPS_SUPPORT */ } if (! global_test_init ()) { #ifdef HTTPS_SUPPORT if (test_tls && (TLS_LIB_GNUTLS == use_tls_tool)) gnutls_global_deinit (); #endif /* HTTPS_SUPPORT */ fprintf (stderr, "Failed to initialise the test.\n"); return 99; } /* run tests */ if (verbose) printf ("Starting HTTP \"Upgrade\" tests with %s connections.\n", test_tls ? "TLS" : "plain"); /* try external select */ res = test_upgrade (0, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with external select, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with external select.\n"); /* Try external auto */ res = test_upgrade (MHD_USE_AUTO, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with external 'auto', return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with external 'auto'.\n"); #ifdef EPOLL_SUPPORT res = test_upgrade (MHD_USE_EPOLL, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with external select with EPOLL, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with external select with EPOLL.\n"); #endif /* Test thread-per-connection */ res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with thread per connection, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with thread per connection.\n"); res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with thread per connection and 'auto', return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with thread per connection and 'auto'.\n"); #ifdef HAVE_POLL res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with thread per connection and poll, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with thread per connection and poll.\n"); #endif /* HAVE_POLL */ /* Test different event loops, with and without thread pool */ res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with internal select, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal select.\n"); res = test_upgrade (MHD_USE_INTERNAL_POLLING_THREAD, 2); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with internal select with thread pool, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal select with thread pool.\n"); res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with internal 'auto' return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal 'auto'.\n"); res = test_upgrade (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, 2); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with internal 'auto' with thread pool, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal 'auto' with thread pool.\n"); #ifdef HAVE_POLL res = test_upgrade (MHD_USE_POLL_INTERNAL_THREAD, 0); fflush_allstd (); error_count += res; if (res) fprintf (stderr, "FAILED: Upgrade with internal poll, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal poll.\n"); res = test_upgrade (MHD_USE_POLL_INTERNAL_THREAD, 2); fflush_allstd (); if (res) fprintf (stderr, "FAILED: Upgrade with internal poll with thread pool, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal poll with thread pool.\n"); #endif #ifdef EPOLL_SUPPORT res = test_upgrade (MHD_USE_EPOLL_INTERNAL_THREAD, 0); fflush_allstd (); if (res) fprintf (stderr, "FAILED: Upgrade with internal epoll, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal epoll.\n"); res = test_upgrade (MHD_USE_EPOLL_INTERNAL_THREAD, 2); fflush_allstd (); if (res) fprintf (stderr, "FAILED: Upgrade with internal epoll, return code %u.\n", res); else if (verbose) printf ("PASSED: Upgrade with internal epoll.\n"); #endif /* report result */ if (0 != error_count) fprintf (stderr, "Error (code: %u)\n", error_count); global_test_deinit (); #ifdef HTTPS_SUPPORT if (test_tls && (TLS_LIB_GNUTLS == use_tls_tool)) gnutls_global_deinit (); #endif /* HTTPS_SUPPORT */ return error_count != 0; /* 0 == pass */ } libmicrohttpd-1.0.10/src/microhttpd/test_mhd_version.c0000664000175000017500000001527515232103064016612 /* This file is part of libmicrohttpd Copyright (C) 2023 Evgeny Grin (Karlson2k) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/test_mhd_version.с * @brief Tests for MHD versions identifiers * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #ifdef HAVE_INTTYPES_H #include #else /* ! HAVE_INTTYPES_H */ #define PRIX32 "X" #endif /* ! HAVE_INTTYPES_H */ #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #include "microhttpd.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifdef PACKAGE_VERSION static const char str_macro_pkg_ver[] = PACKAGE_VERSION; #else /* ! PACKAGE_VERSION */ static const char str_macro_pkg_ver[] = "error!"; #error No PACKAGE_VERSION defined #endif /* ! PACKAGE_VERSION */ #ifdef VERSION static const char str_macro_ver[] = VERSION; #else /* ! VERSION */ static const char str_macro_ver[] = "error!"; #error No PACKAGE_VERSION defined #endif /* ! VERSION */ #ifdef MHD_VERSION static const uint32_t bin_macro = (uint32_t) (MHD_VERSION); #else /* ! MHD_VERSION */ static const uint32_t bin_macro = 0; #error MHD_VERSION is not defined #endif /* ! MHD_VERSION */ /* 0 = success, 1 = failure */ static int test_macro1_vs_macro2_str (void) { printf ("Checking PACKAGE_VERSION macro vs VERSION macro.\n"); if (0 != strcmp (str_macro_pkg_ver, str_macro_ver)) { fflush (stdout); fprintf (stderr, "'%s' vs '%s' - FAILED.\n", str_macro_pkg_ver, str_macro_ver); return 1; } printf ("'%s' vs '%s' - success.\n", str_macro_pkg_ver, str_macro_ver); return 0; } /* 0 = success, 1 = failure */ static int test_macro2_vs_func_str (void) { const char *str_func = MHD_get_version (); printf ("Checking VERSION macro vs MHD_get_version() function.\n"); if (NULL == str_func) { fflush (stdout); fprintf (stderr, "MHD_get_version() returned NULL.\n"); fflush (stderr); return 1; } if (0 != strcmp (str_macro_ver, str_func)) { fflush (stdout); fprintf (stderr, "'%s' vs '%s' - FAILED.\n", str_macro_ver, str_func); fflush (stderr); return 1; } printf ("'%s' vs '%s' - success.\n", str_macro_ver, str_func); return 0; } /* 0 = success, 1 = failure */ static int test_func_str_vs_macro_bin (void) { char bin_print[64]; int res; const char *str_func = MHD_get_version (); printf ("Checking MHD_get_version() function vs MHD_VERSION macro.\n"); #ifdef HAVE_SNPRINTF res = snprintf (bin_print, sizeof(bin_print), "%X.%X.%X", (unsigned int) ((bin_macro >> 24) & 0xFF), (unsigned int) ((bin_macro >> 16) & 0xFF), (unsigned int) ((bin_macro >> 8) & 0xFF)); #else /* ! HAVE_SNPRINTF */ res = sprintf (bin_print, "%X.%X.%X", (unsigned int) ((bin_macro >> 24) & 0xFF), (unsigned int) ((bin_macro >> 16) & 0xFF), (unsigned int) ((bin_macro >> 8) & 0xFF)); #endif /* ! HAVE_SNPRINTF */ if ((9 < res) || (0 >= res)) { fflush (stdout); fprintf (stderr, "snprintf() error.\n"); fflush (stderr); exit (99); } if (0 != strcmp (str_func, bin_print)) { fflush (stdout); fprintf (stderr, "'%s' vs '0x%08" PRIX32 "' ('%s') - FAILED.\n", str_func, bin_macro, bin_print); fflush (stderr); return 1; } printf ("'%s' vs '0x%08" PRIX32 "' ('%s') - success.\n", str_func, bin_macro, bin_print); return 0; } /* 0 = success, 1 = failure */ static int test_macro_vs_func_bin (void) { const uint32_t bin_func = MHD_get_version_bin (); printf ("Checking MHD_VERSION macro vs MHD_get_version_bin() function.\n"); if (bin_macro != bin_func) { fflush (stdout); fprintf (stderr, "'0x%08" PRIX32 "' vs '0x%08" PRIX32 "' - FAILED.\n", bin_macro, bin_func); fflush (stderr); return 1; } printf ("'0x%08" PRIX32 "' vs '0x%08" PRIX32 "' - success.\n", bin_macro, bin_func); return 0; } /* 0 = success, 1 = failure */ static int test_func_bin_format (void) { const uint32_t bin_func = MHD_get_version_bin (); unsigned int test_byte; int ret = 0; printf ("Checking format of MHD_get_version_bin() function return value.\n"); test_byte = (unsigned int) ((bin_func >> 24) & 0xFF); if ((0xA <= (test_byte & 0xF)) || (0xA <= (test_byte >> 4))) { fflush (stdout); fprintf (stderr, "Invalid value in the first (most significant) byte: %02X\n", test_byte); fflush (stderr); ret = 1; } test_byte = (unsigned int) ((bin_func >> 16) & 0xFF); if ((0xA <= (test_byte & 0xF)) || (0xA <= (test_byte >> 4))) { fflush (stdout); fprintf (stderr, "Invalid value in the second byte: %02X\n", test_byte); fflush (stderr); ret = 1; } test_byte = (unsigned int) ((bin_func >> 8) & 0xFF); if ((0xA <= (test_byte & 0xF)) || (0xA <= (test_byte >> 4))) { fflush (stdout); fprintf (stderr, "Invalid value in the third byte: %02X\n", test_byte); fflush (stderr); ret = 1; } if (0 != ret) { fflush (stdout); fprintf (stderr, "The value (0x%08" PRIX32 ") returned by MHD_get_version_bin() " "function is invalid as it cannot be used as packed BCD form " "(its hexadecimal representation has at least one digit in " "A-F range).\n", bin_func); fflush (stderr); return 1; } printf ("'0x%08" PRIX32 "' - success.\n", bin_func); return 0; } int main (void) { int res; res = test_macro1_vs_macro2_str (); res += test_macro2_vs_func_str (); res += test_func_str_vs_macro_bin (); res += test_macro_vs_func_bin (); res += test_func_bin_format (); if (0 != res) { fflush (stdout); fprintf (stderr, "Test failed. Number of errors: %d\n", res); fflush (stderr); return 1; } printf ("Test succeed.\n"); return 0; } libmicrohttpd-1.0.10/src/microhttpd/mhd_itc.h0000644000175000017500000002533415035214301014643 /* This file is part of libmicrohttpd Copyright (C) 2016-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_itc.h * @brief Header for platform-independent inter-thread communication * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff * * Provides basic abstraction for inter-thread communication. * Any functions can be implemented as macro on some platforms * unless explicitly marked otherwise. * Any function argument can be skipped in macro, so avoid * variable modification in function parameters. */ #ifndef MHD_ITC_H #define MHD_ITC_H 1 #include "mhd_itc_types.h" #include #ifndef MHD_PANIC # include # ifdef HAVE_STDLIB_H # include # endif /* HAVE_STDLIB_H */ /* Simple implementation of MHD_PANIC, to be used outside lib */ # define MHD_PANIC(msg) \ do { fprintf (stderr, \ "Abnormal termination at %d line in file %s: %s\n", \ (int) __LINE__, __FILE__, msg); abort (); \ } while (0) #endif /* ! MHD_PANIC */ #if defined(_MHD_ITC_EVENTFD) /* **************** Optimized GNU/Linux ITC implementation by eventfd ********** */ #include #include /* for uint64_t */ #ifdef HAVE_UNISTD_H #include /* for read(), write() */ #endif /* HAVE_UNISTD_H */ #ifdef HAVE_STRING_H #include /* for strerror() */ #include #endif /** * Number of FDs used by every ITC. */ #define MHD_ITC_NUM_FDS_ (1) /** * Initialise ITC by generating eventFD * @param itc the itc to initialise * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_init_(itc) \ (-1 != ((itc).fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK))) /** * Get description string of last errno for itc operations. */ #define MHD_itc_last_strerror_() strerror (errno) /** * Internal static const helper for MHD_itc_activate_() */ static const uint64_t _MHD_itc_wr_data = 1; /** * Activate signal on @a itc * @param itc the itc to use * @param str ignored * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_activate_(itc, str) \ ((write ((itc).fd, (const void*) &_MHD_itc_wr_data, \ sizeof(_MHD_itc_wr_data)) > 0) || (EAGAIN == errno)) /** * Return read FD of @a itc which can be used for poll(), select() etc. * @param itc the itc to get FD * @return FD of read side */ #define MHD_itc_r_fd_(itc) ((itc).fd) /** * Return write FD of @a itc * @param itc the itc to get FD * @return FD of write side */ #define MHD_itc_w_fd_(itc) ((itc).fd) /** * Clear signaled state on @a itc * @param itc the itc to clear */ #define MHD_itc_clear_(itc) \ do { uint64_t __b; \ (void) read ((itc).fd, (void*)&__b, sizeof(__b)); \ } while (0) /** * Destroy previously initialised ITC. Note that close() * on some platforms returns odd errors, so we ONLY fail * if the errno is EBADF. * @param itc the itc to destroy * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_destroy_(itc) \ ((0 == close ((itc).fd)) || (EBADF != errno)) /** * Check whether ITC has valid value. * * Macro check whether @a itc value is valid (allowed), * macro does not check whether @a itc was really initialised. * @param itc the itc to check * @return boolean true if @a itc has valid value, * boolean false otherwise. */ #define MHD_ITC_IS_VALID_(itc) (-1 != ((itc).fd)) /** * Set @a itc to invalid value. * @param itc the itc to set */ #define MHD_itc_set_invalid_(itc) ((itc).fd = -1) #elif defined(_MHD_ITC_PIPE) /* **************** Standard UNIX ITC implementation by pipe ********** */ #if defined(HAVE_PIPE2_FUNC) && defined(HAVE_FCNTL_H) # include /* for O_CLOEXEC, O_NONBLOCK */ #endif /* HAVE_PIPE2_FUNC && HAVE_FCNTL_H */ #ifdef HAVE_UNISTD_H #include /* for read(), write(), errno */ #endif /* HAVE_UNISTD_H */ #ifdef HAVE_STRING_H #include /* for strerror() */ #endif /** * Number of FDs used by every ITC. */ #define MHD_ITC_NUM_FDS_ (2) /** * Initialise ITC by generating pipe * @param itc the itc to initialise * @return non-zero if succeeded, zero otherwise */ #ifdef HAVE_PIPE2_FUNC # define MHD_itc_init_(itc) (! pipe2 ((itc).fd, O_CLOEXEC | O_NONBLOCK)) #else /* ! HAVE_PIPE2_FUNC */ # define MHD_itc_init_(itc) \ ( (! pipe ((itc).fd)) ? \ (MHD_itc_nonblocking_ ((itc)) ? \ (! 0) : \ (MHD_itc_destroy_ ((itc)), 0) ) \ : (0) ) #endif /* ! HAVE_PIPE2_FUNC */ /** * Get description string of last errno for itc operations. */ #define MHD_itc_last_strerror_() strerror (errno) /** * Activate signal on @a itc * @param itc the itc to use * @param str one-symbol string, useful only for strace debug * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_activate_(itc, str) \ ((write ((itc).fd[1], (const void*) (str), 1) > 0) || (EAGAIN == errno)) /** * Return read FD of @a itc which can be used for poll(), select() etc. * @param itc the itc to get FD * @return FD of read side */ #define MHD_itc_r_fd_(itc) ((itc).fd[0]) /** * Return write FD of @a itc * @param itc the itc to get FD * @return FD of write side */ #define MHD_itc_w_fd_(itc) ((itc).fd[1]) /** * Clear signaled state on @a itc * @param itc the itc to clear */ #define MHD_itc_clear_(itc) do \ { long __b; \ while (0 < read ((itc).fd[0], (void*) &__b, sizeof(__b))) \ {(void)0;} } while (0) /** * Destroy previously initialised ITC * @param itc the itc to destroy * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_destroy_(itc) \ ( (0 == close ((itc).fd[0])) ? \ (0 == close ((itc).fd[1])) : \ ((close ((itc).fd[1])), 0) ) /** * Check whether ITC has valid value. * * Macro check whether @a itc value is valid (allowed), * macro does not check whether @a itc was really initialised. * @param itc the itc to check * @return boolean true if @a itc has valid value, * boolean false otherwise. */ #define MHD_ITC_IS_VALID_(itc) (-1 != (itc).fd[0]) /** * Set @a itc to invalid value. * @param itc the itc to set */ #define MHD_itc_set_invalid_(itc) ((itc).fd[0] = (itc).fd[1] = -1) #ifndef HAVE_PIPE2_FUNC /** * Change itc FD options to be non-blocking. * * @param fd the FD to manipulate * @return non-zero if succeeded, zero otherwise */ int MHD_itc_nonblocking_ (struct MHD_itc_ itc); #endif /* ! HAVE_PIPE2_FUNC */ #elif defined(_MHD_ITC_SOCKETPAIR) /* **************** ITC implementation by socket pair ********** */ #include "mhd_sockets.h" /** * Number of FDs used by every ITC. */ #define MHD_ITC_NUM_FDS_ (2) /** * Initialise ITC by generating socketpair * @param itc the itc to initialise * @return non-zero if succeeded, zero otherwise */ #ifdef MHD_socket_pair_nblk_ # define MHD_itc_init_(itc) MHD_socket_pair_nblk_ ((itc).sk) #else /* ! MHD_socket_pair_nblk_ */ # define MHD_itc_init_(itc) \ (MHD_socket_pair_ ((itc).sk) ? \ (MHD_itc_nonblocking_ ((itc)) ? \ (! 0) : \ (MHD_itc_destroy_ ((itc)), 0) ) \ : (0)) #endif /* ! MHD_socket_pair_nblk_ */ /** * Get description string of last error for itc operations. */ #define MHD_itc_last_strerror_() MHD_socket_last_strerr_ () /** * Activate signal on @a itc * @param itc the itc to use * @param str one-symbol string, useful only for strace debug * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_activate_(itc, str) \ ((MHD_send_ ((itc).sk[1], (str), 1) > 0) || \ (MHD_SCKT_ERR_IS_EAGAIN_ (MHD_socket_get_error_ ()))) /** * Return read FD of @a itc which can be used for poll(), select() etc. * @param itc the itc to get FD * @return FD of read side */ #define MHD_itc_r_fd_(itc) ((itc).sk[0]) /** * Return write FD of @a itc * @param itc the itc to get FD * @return FD of write side */ #define MHD_itc_w_fd_(itc) ((itc).sk[1]) /** * Clear signaled state on @a itc * @param itc the itc to clear */ #define MHD_itc_clear_(itc) do \ { long __b; \ while (0 < recv ((itc).sk[0], (void*) &__b, sizeof(__b), 0)) \ {(void)0;} } while (0) /** * Destroy previously initialised ITC * @param itc the itc to destroy * @return non-zero if succeeded, zero otherwise */ #define MHD_itc_destroy_(itc) \ (MHD_socket_close_ ((itc).sk[0]) ? \ MHD_socket_close_ ((itc).sk[1]) : \ ((void) MHD_socket_close_ ((itc).sk[1]), 0) ) /** * Check whether ITC has valid value. * * Macro check whether @a itc value is valid (allowed), * macro does not check whether @a itc was really initialised. * @param itc the itc to check * @return boolean true if @a itc has valid value, * boolean false otherwise. */ #define MHD_ITC_IS_VALID_(itc) (MHD_INVALID_SOCKET != (itc).sk[0]) /** * Set @a itc to invalid value. * @param itc the itc to set */ #define MHD_itc_set_invalid_(itc) \ ((itc).sk[0] = (itc).sk[1] = MHD_INVALID_SOCKET) #ifndef MHD_socket_pair_nblk_ # define MHD_itc_nonblocking_(pip) \ (MHD_socket_nonblocking_ ((pip).sk[0]) && \ MHD_socket_nonblocking_ ((pip).sk[1])) #endif /* ! MHD_socket_pair_nblk_ */ #endif /* _MHD_ITC_SOCKETPAIR */ /** * Destroy previously initialised ITC and abort execution * if error is detected. * @param itc the itc to destroy */ #define MHD_itc_destroy_chk_(itc) do { \ if (! MHD_itc_destroy_ (itc)) \ MHD_PANIC (_ ("Failed to destroy ITC.\n")); \ } while (0) /** * Check whether ITC has invalid value. * * Macro check whether @a itc value is invalid, * macro does not check whether @a itc was destroyed. * @param itc the itc to check * @return boolean true if @a itc has invalid value, * boolean false otherwise. */ #define MHD_ITC_IS_INVALID_(itc) (! MHD_ITC_IS_VALID_ (itc)) #endif /* MHD_ITC_H */ libmicrohttpd-1.0.10/src/microhttpd/test_postprocessor.c0000664000175000017500000006724015232103064017221 /* This file is part of libmicrohttpd Copyright (C) 2007, 2013, 2019, 2020 Christian Grothoff Copyright (C) 2021 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_postprocessor.c * @brief Testcase for postprocessor * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include "internal.h" #include #include #include #include "mhd_compat.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif #ifndef MHD_DEBUG_PP #define MHD_DEBUG_PP 0 #endif /* MHD_DEBUG_PP */ struct expResult { const char *key; const char *fname; const char *cnt_type; const char *tr_enc; const char *data; }; /** * Array of values that the value checker "wants". * Each series of checks should be terminated by * five NULL-entries. */ static struct expResult exp_results[] = { #define URL_NOVALUE1_DATA "abc&x=5" #define URL_NOVALUE1_START 0 {"abc", NULL, NULL, NULL, /* NULL */ ""}, /* change after API update */ {"x", NULL, NULL, NULL, "5"}, #define URL_NOVALUE1_END (URL_NOVALUE1_START + 2) #define URL_NOVALUE2_DATA "abc=&x=5" #define URL_NOVALUE2_START URL_NOVALUE1_END {"abc", NULL, NULL, NULL, ""}, {"x", NULL, NULL, NULL, "5"}, #define URL_NOVALUE2_END (URL_NOVALUE2_START + 2) #define URL_NOVALUE3_DATA "xyz=" #define URL_NOVALUE3_START URL_NOVALUE2_END {"xyz", NULL, NULL, NULL, ""}, #define URL_NOVALUE3_END (URL_NOVALUE3_START + 1) #define URL_NOVALUE4_DATA "xyz" #define URL_NOVALUE4_START URL_NOVALUE3_END {"xyz", NULL, NULL, NULL, /* NULL */ ""}, /* change after API update */ #define URL_NOVALUE4_END (URL_NOVALUE4_START + 1) #define URL_DATA "abc=def&x=5" #define URL_START URL_NOVALUE4_END {"abc", NULL, NULL, NULL, "def"}, {"x", NULL, NULL, NULL, "5"}, #define URL_END (URL_START + 2) #define URL_ENC_DATA "space=%20&key%201=&crlf=%0D%0a&mix%09ed=%2001%0d%0A" #define URL_ENC_START URL_END {"space", NULL, NULL, NULL, " "}, {"key 1", NULL, NULL, NULL, ""}, {"crlf", NULL, NULL, NULL, "\r\n"}, {"mix\ted", NULL, NULL, NULL, " 01\r\n"}, #define URL_ENC_END (URL_ENC_START + 4) {NULL, NULL, NULL, NULL, NULL}, #define FORM_DATA \ "--AaB03x\r\ncontent-disposition: form-data; name=\"field1\"\r\n\r\n" \ "Joe Blow\r\n--AaB03x\r\ncontent-disposition: form-data; name=\"pics\";" \ " filename=\"file1.txt\"\r\nContent-Type: text/plain\r\n" \ "Content-Transfer-Encoding: binary\r\n\r\nfiledata\r\n--AaB03x--\r\n" #define FORM_START (URL_ENC_END + 1) {"field1", NULL, NULL, NULL, "Joe Blow"}, {"pics", "file1.txt", "text/plain", "binary", "filedata"}, #define FORM_END (FORM_START + 2) {NULL, NULL, NULL, NULL, NULL}, #define FORM_NESTED_DATA \ "--AaB03x\r\ncontent-disposition: form-data; name=\"field1\"\r\n\r\n" \ "Jane Blow\r\n--AaB03x\r\ncontent-disposition: form-data; name=\"pics\"\r\n" \ "Content-type: multipart/mixed, boundary=BbC04y\r\n\r\n--BbC04y\r\n" \ "Content-disposition: attachment; filename=\"file1.txt\"\r\n" \ "Content-Type: text/plain\r\n\r\nfiledata1\r\n--BbC04y\r\n" \ "Content-disposition: attachment; filename=\"file2.gif\"\r\n" \ "Content-type: image/gif\r\nContent-Transfer-Encoding: binary\r\n\r\n" \ "filedata2\r\n--BbC04y--\r\n--AaB03x--" #define FORM_NESTED_START (FORM_END + 1) {"field1", NULL, NULL, NULL, "Jane Blow"}, {"pics", "file1.txt", "text/plain", NULL, "filedata1"}, {"pics", "file2.gif", "image/gif", "binary", "filedata2"}, #define FORM_NESTED_END (FORM_NESTED_START + 3) {NULL, NULL, NULL, NULL, NULL}, #define URL_EMPTY_VALUE_DATA "key1=value1&key2=&key3=" #define URL_EMPTY_VALUE_START (FORM_NESTED_END + 1) {"key1", NULL, NULL, NULL, "value1"}, {"key2", NULL, NULL, NULL, ""}, {"key3", NULL, NULL, NULL, ""}, #define URL_EMPTY_VALUE_END (URL_EMPTY_VALUE_START + 3) {NULL, NULL, NULL, NULL, NULL} }; static int mismatch (const char *a, const char *b) { if (a == b) return 0; if ((a == NULL) || (b == NULL)) return 1; return 0 != strcmp (a, b); } static int mismatch2 (const char *data, const char *expected, size_t offset, size_t size) { if (data == expected) return 0; if ((data == NULL) || (expected == NULL)) return 1; return 0 != memcmp (data, expected + offset, size); } static enum MHD_Result value_checker (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { unsigned int *idxp = cls; struct expResult *expect = exp_results + *idxp; (void) kind; /* Unused. Silent compiler warning. */ #if MHD_DEBUG_PP fprintf (stderr, "VC: `%s' `%s' `%s' `%s' (+%u)`%.*s' (%d)\n", key ? key : "(NULL)", filename ? filename : "(NULL)", content_type ? content_type : "(NULL)", transfer_encoding ? transfer_encoding : "(NULL)", (unsigned int) off, (int) (data ? size : 6), data ? data : "(NULL)", (int) size); #endif if (*idxp == (unsigned int) -1) exit (99); if ( (0 != off) && (0 == size) ) { if (NULL == expect->data) *idxp += 1; return MHD_YES; } if ((expect->key == NULL) || (0 != strcmp (key, expect->key)) || (mismatch (filename, expect->fname)) || (mismatch (content_type, expect->cnt_type)) || (mismatch (transfer_encoding, expect->tr_enc)) || (strlen (expect->data) < off) || (mismatch2 (data, expect->data, (size_t) off, size))) { *idxp = (unsigned int) -1; fprintf (stderr, "Failed with: `%s' `%s' `%s' `%s' `%.*s'\n", key ? key : "(NULL)", filename ? filename : "(NULL)", content_type ? content_type : "(NULL)", transfer_encoding ? transfer_encoding : "(NULL)", (int) (data ? size : 6), data ? data : "(NULL)"); fprintf (stderr, "Wanted: `%s' `%s' `%s' `%s' `%s'\n", expect->key ? expect->key : "(NULL)", expect->fname ? expect->fname : "(NULL)", expect->cnt_type ? expect->cnt_type : "(NULL)", expect->tr_enc ? expect->tr_enc : "(NULL)", expect->data ? expect->data : "(NULL)"); fprintf (stderr, "Unexpected result: %d/%d/%d/%d/%d/%d\n", (expect->key == NULL), (NULL != expect->key) && (0 != strcmp (key, expect->key)), (mismatch (filename, expect->fname)), (mismatch (content_type, expect->cnt_type)), (mismatch (transfer_encoding, expect->tr_enc)), (strlen (expect->data) < off) || (mismatch2 (data, expect->data, (size_t) off, size))); return MHD_NO; } if ( ( (NULL == expect->data) && (0 == off + size) ) || ( (NULL != expect->data) && (off + size == strlen (expect->data)) ) ) *idxp += 1; return MHD_YES; } static unsigned int test_urlencoding_case (unsigned int want_start, unsigned int want_end, const char *url_data) { size_t step; unsigned int errors = 0; const size_t size = strlen (url_data); for (step = 1; size >= step; ++step) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int want_off = want_start; size_t i; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE); header.value_size = MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker, &want_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } for (i = 0; size > i; i += step) { size_t left = size - i; if (MHD_YES != MHD_post_process (pp, &url_data[i], (left > step) ? step : left)) { fprintf (stderr, "Failed to process the data.\n" "i: %u. step: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) step, (unsigned int) __LINE__); exit (49); } } MHD_destroy_post_processor (pp); if (want_off != want_end) { fprintf (stderr, "Test failed in line %u.\tStep: %u.\tData: \"%s\"\n" \ " Got: %u\tExpected: %u\n", (unsigned int) __LINE__, (unsigned int) step, url_data, want_off, want_end); errors++; } } return errors; } static unsigned int test_urlencoding (void) { unsigned int errorCount = 0; errorCount += test_urlencoding_case (URL_START, URL_END, URL_DATA); errorCount += test_urlencoding_case (URL_ENC_START, URL_ENC_END, URL_ENC_DATA); errorCount += test_urlencoding_case (URL_NOVALUE1_START, URL_NOVALUE1_END, URL_NOVALUE1_DATA); errorCount += test_urlencoding_case (URL_NOVALUE2_START, URL_NOVALUE2_END, URL_NOVALUE2_DATA); errorCount += test_urlencoding_case (URL_NOVALUE3_START, URL_NOVALUE3_END, URL_NOVALUE3_DATA); errorCount += test_urlencoding_case (URL_NOVALUE4_START, URL_NOVALUE4_START, /* No advance */ URL_NOVALUE4_DATA); errorCount += test_urlencoding_case (URL_EMPTY_VALUE_START, URL_EMPTY_VALUE_END, URL_EMPTY_VALUE_DATA); errorCount += test_urlencoding_case (URL_START, URL_END, URL_DATA "\n"); errorCount += test_urlencoding_case (URL_ENC_START, URL_ENC_END, URL_ENC_DATA "\n"); errorCount += test_urlencoding_case (URL_NOVALUE1_START, URL_NOVALUE1_END, URL_NOVALUE1_DATA "\n"); errorCount += test_urlencoding_case (URL_NOVALUE2_START, URL_NOVALUE2_END, URL_NOVALUE2_DATA "\n"); errorCount += test_urlencoding_case (URL_NOVALUE3_START, URL_NOVALUE3_END, URL_NOVALUE3_DATA "\n"); errorCount += test_urlencoding_case (URL_NOVALUE4_START, URL_NOVALUE4_END, /* With advance */ URL_NOVALUE4_DATA "\n"); errorCount += test_urlencoding_case (URL_EMPTY_VALUE_START, URL_EMPTY_VALUE_END, URL_EMPTY_VALUE_DATA "\n"); errorCount += test_urlencoding_case (URL_START, URL_END, "&&" URL_DATA); errorCount += test_urlencoding_case (URL_ENC_START, URL_ENC_END, "&&" URL_ENC_DATA); errorCount += test_urlencoding_case (URL_NOVALUE1_START, URL_NOVALUE1_END, "&&" URL_NOVALUE1_DATA); errorCount += test_urlencoding_case (URL_NOVALUE2_START, URL_NOVALUE2_END, "&&" URL_NOVALUE2_DATA); errorCount += test_urlencoding_case (URL_NOVALUE3_START, URL_NOVALUE3_END, "&&" URL_NOVALUE3_DATA); errorCount += test_urlencoding_case (URL_NOVALUE4_START, URL_NOVALUE4_START, /* No advance */ "&&" URL_NOVALUE4_DATA); errorCount += test_urlencoding_case (URL_EMPTY_VALUE_START, URL_EMPTY_VALUE_END, "&&" URL_EMPTY_VALUE_DATA); if (0 != errorCount) fprintf (stderr, "Test failed in line %u with %u errors\n", (unsigned int) __LINE__, errorCount); return errorCount; } static unsigned int test_multipart_garbage (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int want_off; size_t size = MHD_STATICSTR_LEN_ (FORM_DATA); size_t splitpoint; char xdata[MHD_STATICSTR_LEN_ (FORM_DATA) + 3]; /* fill in evil garbage at the beginning */ xdata[0] = '-'; xdata[1] = 'x'; xdata[2] = '\r'; memcpy (&xdata[3], FORM_DATA, size); size += 3; for (splitpoint = 1; splitpoint < size; splitpoint++) { want_off = FORM_START; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x"; header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE); header.value_size = MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA \ ", boundary=AaB03x"); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker, &want_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } if (MHD_YES != MHD_post_process (pp, xdata, splitpoint)) { fprintf (stderr, "Test failed in line %u at point %d\n", (unsigned int) __LINE__, (int) splitpoint); exit (49); } if (MHD_YES != MHD_post_process (pp, &xdata[splitpoint], size - splitpoint)) { fprintf (stderr, "Test failed in line %u at point %u\n", (unsigned int) __LINE__, (unsigned int) splitpoint); exit (49); } MHD_destroy_post_processor (pp); if (want_off != FORM_END) { fprintf (stderr, "Test failed in line %u at point %u\n", (unsigned int) __LINE__, (unsigned int) splitpoint); return (unsigned int) splitpoint; } } return 0; } static unsigned int test_multipart_splits (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int want_off; size_t size; size_t splitpoint; size = strlen (FORM_DATA); for (splitpoint = 1; splitpoint < size; splitpoint++) { want_off = FORM_START; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x"; header.header_size = strlen (header.header); header.value_size = strlen (header.value); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker, &want_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } if (MHD_YES != MHD_post_process (pp, FORM_DATA, splitpoint)) { fprintf (stderr, "Test failed in line %u at point %d\n", (unsigned int) __LINE__, (int) splitpoint); exit (49); } if (MHD_YES != MHD_post_process (pp, &FORM_DATA[splitpoint], size - splitpoint)) { fprintf (stderr, "Test failed in line %u at point %u\n", (unsigned int) __LINE__, (unsigned int) splitpoint); exit (49); } MHD_destroy_post_processor (pp); if (want_off != FORM_END) { fprintf (stderr, "Test failed in line %u at point %u\n", (unsigned int) __LINE__, (unsigned int) splitpoint); return (unsigned int) splitpoint; } } return 0; } static unsigned int test_multipart (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int want_off = FORM_START; size_t i; size_t delta; size_t size; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x"; header.kind = MHD_HEADER_KIND; header.header_size = strlen (header.header); header.value_size = strlen (header.value); pp = MHD_create_post_processor (&connection, 1024, &value_checker, &want_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } i = 0; size = strlen (FORM_DATA); while (i < size) { delta = 1 + ((size_t) MHD_random_ ()) % (size - i); if (MHD_YES != MHD_post_process (pp, &FORM_DATA[i], delta)) { fprintf (stderr, "Failed to process the data.\n" "i: %u. delta: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) delta, (unsigned int) __LINE__); exit (49); } i += delta; } MHD_destroy_post_processor (pp); if (want_off != FORM_END) { fprintf (stderr, "Test failed in line %u\n", (unsigned int) __LINE__); return 2; } return 0; } static unsigned int test_nested_multipart (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int want_off = FORM_NESTED_START; size_t i; size_t delta; size_t size; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA ", boundary=AaB03x"; header.kind = MHD_HEADER_KIND; header.header_size = strlen (header.header); header.value_size = strlen (header.value); pp = MHD_create_post_processor (&connection, 1024, &value_checker, &want_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } i = 0; size = strlen (FORM_NESTED_DATA); while (i < size) { delta = 1 + ((size_t) MHD_random_ ()) % (size - i); if (MHD_YES != MHD_post_process (pp, &FORM_NESTED_DATA[i], delta)) { fprintf (stderr, "Failed to process the data.\n" "i: %u. delta: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) delta, (unsigned int) __LINE__); exit (49); } i += delta; } MHD_destroy_post_processor (pp); if (want_off != FORM_NESTED_END) { fprintf (stderr, "Test failed in line %u\n", (unsigned int) __LINE__); return 4; } return 0; } static enum MHD_Result value_checker2 (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) key; /* Mute compiler warnings */ (void) filename; (void) content_type; (void) transfer_encoding; (void) data; (void) off; (void) size; return MHD_YES; } static unsigned int test_overflow (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; size_t i; size_t j; size_t delta; char *buf; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.header_size = strlen (header.header); header.value_size = strlen (header.value); header.kind = MHD_HEADER_KIND; for (i = 128; i < 1024 * 1024; i += 1024) { pp = MHD_create_post_processor (&connection, 1024, &value_checker2, NULL); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } buf = malloc (i); if (NULL == buf) return 1; memset (buf, 'A', i); buf[i / 2] = '='; delta = 1 + (((size_t) MHD_random_ ()) % (i - 1)); j = 0; while (j < i) { if (j + delta > i) delta = i - j; if (MHD_NO == MHD_post_process (pp, &buf[j], delta)) break; j += delta; } free (buf); MHD_destroy_post_processor (pp); } return 0; } static unsigned int test_empty_key (void) { const char form_data[] = "=abcdef"; size_t step; const size_t size = MHD_STATICSTR_LEN_ (form_data); for (step = 1; size >= step; ++step) { size_t i; struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; connection.rq.headers_received_tail = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE); header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.value_size = MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker2, NULL); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } for (i = 0; size > i; i += step) { if (MHD_NO != MHD_post_process (pp, form_data + i, (step > size - i) ? (size - i) : step)) { fprintf (stderr, "Succeed to process the broken data.\n" "i: %u. step: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) step, (unsigned int) __LINE__); exit (49); } } MHD_destroy_post_processor (pp); } return 0; } static unsigned int test_double_value (void) { const char form_data[] = URL_DATA "=abcdef"; size_t step; const size_t size = MHD_STATICSTR_LEN_ (form_data); const size_t safe_size = MHD_STATICSTR_LEN_ (URL_DATA); for (step = 1; size >= step; ++step) { size_t i; struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; unsigned int results_off = URL_START; unsigned int results_final = results_off + 1; /* First value is correct */ memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; connection.rq.headers_received_tail = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_TYPE); header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.value_size = MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker, &results_off); if (NULL == pp) { fprintf (stderr, "Failed to create post processor.\n" "Line: %u\n", (unsigned int) __LINE__); exit (50); } for (i = 0; size > i; i += step) { if (MHD_NO != MHD_post_process (pp, form_data + i, (step > size - i) ? (size - i) : step)) { if (safe_size == i + step) results_final = URL_END; if (safe_size < i + step) { fprintf (stderr, "Succeed to process the broken data.\n" "i: %u. step: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) step, (unsigned int) __LINE__); exit (49); } } else { if (safe_size >= i + step) { fprintf (stderr, "Failed to process the data.\n" "i: %u. step: %u.\n" "Line: %u\n", (unsigned) i, (unsigned) step, (unsigned int) __LINE__); exit (49); } } } MHD_destroy_post_processor (pp); if (results_final != results_off) { fprintf (stderr, "Test failed in line %u.\tStep:%u\n Got: %u\tExpected: %u\n", (unsigned int) __LINE__, (unsigned int) step, results_off, results_final); return 1; } } return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errorCount += test_multipart_splits (); errorCount += test_multipart_garbage (); errorCount += test_urlencoding (); errorCount += test_multipart (); errorCount += test_nested_multipart (); errorCount += test_empty_key (); errorCount += test_double_value (); errorCount += test_overflow (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/microhttpd/mhd_mono_clock.h0000644000175000017500000000373515035214301016210 /* This file is part of libmicrohttpd Copyright (C) 2015-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_mono_clock.h * @brief internal monotonic clock functions declarations * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_MONO_CLOCK_H #define MHD_MONO_CLOCK_H 1 #include "mhd_options.h" #if defined(HAVE_TIME_H) #include #elif defined(HAVE_SYS_TYPES_H) #include #endif #include /** * Initialise monotonic seconds and milliseconds counters. */ void MHD_monotonic_sec_counter_init (void); /** * Deinitialise monotonic seconds and milliseconds counters by freeing * any allocated resources */ void MHD_monotonic_sec_counter_finish (void); /** * Monotonic seconds counter. * Tries to be not affected by manually setting the system real time * clock or adjustments by NTP synchronization. * * @return number of seconds from some fixed moment */ time_t MHD_monotonic_sec_counter (void); /** * Monotonic milliseconds counter, useful for timeout calculation. * Tries to be not affected by manually setting the system real time * clock or adjustments by NTP synchronization. * * @return number of microseconds from some fixed moment */ uint64_t MHD_monotonic_msec_counter (void); #endif /* MHD_MONO_CLOCK_H */ libmicrohttpd-1.0.10/src/microhttpd/test_str_base64.c0000664000175000017500000011452415232103064016246 /* This file is part of libmicrohttpd Copyright (C) 2022 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_base64.c * @brief Unit tests for base64 strings processing * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #define TEST_BIN_MAX_SIZE 1024 /* return zero if succeed, one otherwise */ static unsigned int expect_decoded_n (const char *const encoded, const size_t encoded_len, const uint8_t *const decoded, const size_t decoded_size, const unsigned int line_num) { static const char fill_chr = '#'; static uint8_t buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != encoded); mhd_assert (NULL != decoded); mhd_assert (TEST_BIN_MAX_SIZE > decoded_size); mhd_assert (encoded_len >= decoded_size); mhd_assert (0 == encoded_len || encoded_len > decoded_size); ret = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_base64_to_bin_n (encoded, encoded_len, buf, decoded_size); if (res_size != decoded_size) { ret = 1; fprintf (stderr, "'MHD_base64_to_bin_n ()' FAILED: Wrong returned value:\n"); } else if ((0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { ret = 1; fprintf (stderr, "'MHD_base64_to_bin_n ()' FAILED: Wrong output binary:\n"); } if (0 != ret) { static char prnt[TEST_BIN_MAX_SIZE * 2 + 1]; size_t prnt_size; if (TEST_BIN_MAX_SIZE <= res_size * 2) { fprintf (stderr, "\tRESULT : MHD_base64_to_bin_n ('%.*s', %u, ->(too long), %u)" " -> %u\n", (int) encoded_len, encoded, (unsigned) encoded_len, (unsigned) decoded_size, (unsigned) res_size); } else { prnt_size = MHD_bin_to_hex_z (buf, res_size, prnt); mhd_assert (2 * res_size == prnt_size); fprintf (stderr, "\tRESULT : MHD_base64_to_bin_n ('%.*s', %u, ->%.*sh, %u)" " -> %u\n", (int) encoded_len, encoded, (unsigned) encoded_len, (int) prnt_size, prnt, (unsigned) decoded_size, (unsigned) res_size); } prnt_size = MHD_bin_to_hex_z (decoded, decoded_size, prnt); mhd_assert (2 * decoded_size == prnt_size); fprintf (stderr, "\tEXPECTED: MHD_base64_to_bin_n ('%.*s', %u, ->%.*sh, %u)" " -> %u\n", (int) encoded_len, encoded, (unsigned) encoded_len, (int) prnt_size, prnt, (unsigned) decoded_size, (unsigned) decoded_size); fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_decoded(e,d) \ expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\ (const uint8_t*)(d),MHD_STATICSTR_LEN_(d), \ __LINE__) static unsigned int check_decode_str (void) { unsigned int r = 0; /**< The number of errors */ r += expect_decoded ("", ""); /* Base sequences without padding */ r += expect_decoded ("YWFh", "aaa"); r += expect_decoded ("YmJi", "bbb"); r += expect_decoded ("Y2Nj", "ccc"); r += expect_decoded ("ZGRk", "ddd"); r += expect_decoded ("bGxs", "lll"); r += expect_decoded ("bW1t", "mmm"); r += expect_decoded ("bm5u", "nnn"); r += expect_decoded ("b29v", "ooo"); r += expect_decoded ("d3d3", "www"); r += expect_decoded ("eHh4", "xxx"); r += expect_decoded ("eXl5", "yyy"); r += expect_decoded ("enp6", "zzz"); r += expect_decoded ("QUFB", "AAA"); r += expect_decoded ("R0dH", "GGG"); r += expect_decoded ("TU1N", "MMM"); r += expect_decoded ("VFRU", "TTT"); r += expect_decoded ("Wlpa", "ZZZ"); r += expect_decoded ("MDEy", "012"); r += expect_decoded ("MzQ1", "345"); r += expect_decoded ("Njc4", "678"); r += expect_decoded ("OTAx", "901"); r += expect_decoded ("YWFhYWFh", "aaaaaa"); r += expect_decoded ("YmJiYmJi", "bbbbbb"); r += expect_decoded ("Y2NjY2Nj", "cccccc"); r += expect_decoded ("ZGRkZGRk", "dddddd"); r += expect_decoded ("bGxsbGxs", "llllll"); r += expect_decoded ("bW1tbW1t", "mmmmmm"); r += expect_decoded ("bm5ubm5u", "nnnnnn"); r += expect_decoded ("b29vb29v", "oooooo"); r += expect_decoded ("d3d3d3d3", "wwwwww"); r += expect_decoded ("eHh4eHh4", "xxxxxx"); r += expect_decoded ("eXl5eXl5", "yyyyyy"); r += expect_decoded ("enp6enp6", "zzzzzz"); r += expect_decoded ("QUFBQUFB", "AAAAAA"); r += expect_decoded ("R0dHR0dH", "GGGGGG"); r += expect_decoded ("TU1NTU1N", "MMMMMM"); r += expect_decoded ("VFRUVFRU", "TTTTTT"); r += expect_decoded ("WlpaWlpa", "ZZZZZZ"); r += expect_decoded ("MDEyMDEy", "012012"); r += expect_decoded ("MzQ1MzQ1", "345345"); r += expect_decoded ("Njc4Njc4", "678678"); r += expect_decoded ("OTAxOTAx", "901901"); /* Various lengths */ r += expect_decoded ("YQ==", "a"); r += expect_decoded ("YmM=", "bc"); r += expect_decoded ("REVGRw==", "DEFG"); r += expect_decoded ("MTIzdA==", "123t"); r += expect_decoded ("MTIzNDU=", "12345"); r += expect_decoded ("VGVzdCBTdHI=", "Test Str"); r += expect_decoded ("VGVzdCBzdHJpbmc=", "Test string"); r += expect_decoded ("VGVzdCBzdHJpbmcu", "Test string."); r += expect_decoded ("TG9uZ2VyIHN0cmluZw==", "Longer string"); r += expect_decoded ("TG9uZ2VyIHN0cmluZy4=", "Longer string."); r += expect_decoded ("TG9uZ2VyIHN0cmluZzIu", "Longer string2."); return r; } #define expect_decoded_arr(e,a) \ expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\ a,(sizeof(a)/sizeof(a[0])), \ __LINE__) static unsigned int check_decode_bin (void) { unsigned int r = 0; /**< The number of errors */ if (1) { static const uint8_t bin[256] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; r += expect_decoded_arr ("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISI" \ "jJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERU" \ "ZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoa" \ "WprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouM" \ "jY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+" \ "wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0t" \ "PU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19" \ "vf4+fr7/P3+/w==", bin); } if (1) { static const uint8_t bin[256] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x0 }; r += expect_decoded_arr ("AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiM" \ "kJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRk" \ "dISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpa" \ "mtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yN" \ "jo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7C" \ "xsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09" \ "TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29" \ "/j5+vv8/f7/AA==", bin); } if (1) { static const uint8_t bin[256] = {0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x0, 0x1 }; r += expect_decoded_arr ("AgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQ" \ "lJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0" \ "hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa" \ "2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SFhoeIiYqLjI2O" \ "j5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLG" \ "ys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1N" \ "XW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+" \ "Pn6+/z9/v8AAQ==", bin); } if (1) { static const uint8_t bin[256] = {0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 0x0, 0x1, 0x2 }; r += expect_decoded_arr ("AwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCU" \ "mJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSE" \ "lKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprb" \ "G1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6P" \ "kJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbK" \ "ztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1d" \ "bX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+" \ "fr7/P3+/wABAg==", bin); } if (1) { static const uint8_t bin[256] = {0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0 }; r += expect_decoded_arr ("//79/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eDf3t3" \ "c29rZ2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwL++vby7ur" \ "m4t7a1tLOysbCvrq2sq6qpqKempaSjoqGgn56dnJuamZiXl" \ "pWUk5KRkI+OjYyLiomIh4aFhIOCgYB/fn18e3p5eHd2dXRz" \ "cnFwb25tbGtqaWhnZmVkY2JhYF9eXVxbWllYV1ZVVFNSUVB" \ "PTk1MS0pJSEdGRURDQkFAPz49PDs6OTg3NjU0MzIxMC8uLS" \ "wrKikoJyYlJCMiISAfHh0cGxoZGBcWFRQTEhEQDw4NDAsKC" \ "QgHBgUEAwIBAA==", bin); } if (1) { static const uint8_t bin[256] = {0x0, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1}; r += expect_decoded_arr ("AP/+/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397" \ "d3Nva2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7" \ "q5uLe2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl" \ "5aVlJOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0" \ "c3JxcG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlF" \ "QT05NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi" \ "0sKyopKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLC" \ "gkIBwYFBAMCAQ==", bin); } if (1) { static const uint8_t bin[256] = {0x1, 0x0, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2}; r += expect_decoded_arr ("AQD//v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh4N/" \ "e3dzb2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vL" \ "u6ubi3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZm" \ "JeWlZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1" \ "dHNycXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1J" \ "RUE9OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy" \ "4tLCsqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MC" \ "woJCAcGBQQDAg==", bin); } if (1) { static const uint8_t bin[256] = {0x2, 0x1, 0x0, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3}; r += expect_decoded_arr ("AgEA//79/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eD" \ "f3t3c29rZ2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwL++vb" \ "y7urm4t7a1tLOysbCvrq2sq6qpqKempaSjoqGgn56dnJuam" \ "ZiXlpWUk5KRkI+OjYyLiomIh4aFhIOCgYB/fn18e3p5eHd2" \ "dXRzcnFwb25tbGtqaWhnZmVkY2JhYF9eXVxbWllYV1ZVVFN" \ "SUVBPTk1MS0pJSEdGRURDQkFAPz49PDs6OTg3NjU0MzIxMC" \ "8uLSwrKikoJyYlJCMiISAfHh0cGxoZGBcWFRQTEhEQDw4ND" \ "AsKCQgHBgUEAw==", bin); } if (1) { static const uint8_t bin[256] = {0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0xff}; r += expect_decoded_arr ("/v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh4N/e3dz" \ "b2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vLu6ub" \ "i3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZmJeWl" \ "ZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1dHNy" \ "cXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1JRUE9" \ "OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy4tLC" \ "sqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MCwoJC" \ "AcGBQQDAgEA/w==", bin); } if (1) { static const uint8_t bin[256] = {0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0xff, 0xfe}; r += expect_decoded_arr ("/fz7+vn49/b19PPy8fDv7u3s6+rp6Ofm5eTj4uHg397d3Nv" \ "a2djX1tXU09LR0M/OzczLysnIx8bFxMPCwcC/vr28u7q5uL" \ "e2tbSzsrGwr66trKuqqainpqWko6KhoJ+enZybmpmYl5aVl" \ "JOSkZCPjo2Mi4qJiIeGhYSDgoGAf359fHt6eXh3dnV0c3Jx" \ "cG9ubWxramloZ2ZlZGNiYWBfXl1cW1pZWFdWVVRTUlFQT05" \ "NTEtKSUhHRkVEQ0JBQD8+PTw7Ojk4NzY1NDMyMTAvLi0sKy" \ "opKCcmJSQjIiEgHx4dHBsaGRgXFhUUExIREA8ODQwLCgkIB" \ "wYFBAMCAQD//g==", bin); } if (1) { static const uint8_t bin[256] = {0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0xf, 0xe, 0xd, 0xc, 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, 0xff, 0xfe, 0xfd }; r += expect_decoded_arr ("/Pv6+fj39vX08/Lx8O/u7ezr6uno5+bl5OPi4eDf3t3c29r" \ "Z2NfW1dTT0tHQz87NzMvKycjHxsXEw8LBwL++vby7urm4t7" \ "a1tLOysbCvrq2sq6qpqKempaSjoqGgn56dnJuamZiXlpWUk" \ "5KRkI+OjYyLiomIh4aFhIOCgYB/fn18e3p5eHd2dXRzcnFw" \ "b25tbGtqaWhnZmVkY2JhYF9eXVxbWllYV1ZVVFNSUVBPTk1" \ "MS0pJSEdGRURDQkFAPz49PDs6OTg3NjU0MzIxMC8uLSwrKi" \ "koJyYlJCMiISAfHh0cGxoZGBcWFRQTEhEQDw4NDAsKCQgHB" \ "gUEAwIBAP/+/Q==", bin); } if (1) { static const uint8_t bin[48] = {0x00, 0x10, 0x83, 0x10, 0x51, 0x87, 0x20, 0x92, 0x8b, 0x30, 0xd3, 0x8f, 0x41, 0x14, 0x93, 0x51, 0x55, 0x97, 0x61, 0x96, 0x9b, 0x71, 0xd7, 0x9f, 0x82, 0x18, 0xa3, 0x92, 0x59, 0xa7, 0xa2, 0x9a, 0xab, 0xb2, 0xdb, 0xaf, 0xc3, 0x1c, 0xb3, 0xd3, 0x5d, 0xb7, 0xe3, 0x9e, 0xbb, 0xf3, 0xdf, 0xbf }; r += expect_decoded_arr ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ "abcdefghijklmnopqrstuvwxyz0123456789+/", bin); } if (1) { static const uint8_t bin[49] = {0x00, 0x10, 0x83, 0x10, 0x51, 0x87, 0x20, 0x92, 0x8b, 0x30, 0xd3, 0x8f, 0x41, 0x14, 0x93, 0x51, 0x55, 0x97, 0x61, 0x96, 0x9b, 0x71, 0xd7, 0x9f, 0x82, 0x18, 0xa3, 0x92, 0x59, 0xa7, 0xa2, 0x9a, 0xab, 0xb2, 0xdb, 0xaf, 0xc3, 0x1c, 0xb3, 0xd3, 0x5d, 0xb7, 0xe3, 0x9e, 0xbb, 0xf3, 0xdf, 0xbf, 0x00 }; r += expect_decoded_arr ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ "abcdefghijklmnopqrstuvwxyz0123456789+/" \ "AA==", bin); } if (1) { static const uint8_t bin[48] = {0xff, 0xef, 0x7c, 0xef, 0xae, 0x78, 0xdf, 0x6d, 0x74, 0xcf, 0x2c, 0x70, 0xbe, 0xeb, 0x6c, 0xae, 0xaa, 0x68, 0x9e, 0x69, 0x64, 0x8e, 0x28, 0x60, 0x7d, 0xe7, 0x5c, 0x6d, 0xa6, 0x58, 0x5d, 0x65, 0x54, 0x4d, 0x24, 0x50, 0x3c, 0xe3, 0x4c, 0x2c, 0xa2, 0x48, 0x1c, 0x61, 0x44, 0x0c, 0x20, 0x40 }; r += expect_decoded_arr ("/+9876543210zyxwvutsrqponmlkjihgfedcba" \ "ZYXWVUTSRQPONMLKJIHGFEDCBA", bin); } if (1) { static const uint8_t bin[49] = {0xff, 0xef, 0x7c, 0xef, 0xae, 0x78, 0xdf, 0x6d, 0x74, 0xcf, 0x2c, 0x70, 0xbe, 0xeb, 0x6c, 0xae, 0xaa, 0x68, 0x9e, 0x69, 0x64, 0x8e, 0x28, 0x60, 0x7d, 0xe7, 0x5c, 0x6d, 0xa6, 0x58, 0x5d, 0x65, 0x54, 0x4d, 0x24, 0x50, 0x3c, 0xe3, 0x4c, 0x2c, 0xa2, 0x48, 0x1c, 0x61, 0x44, 0x0c, 0x20, 0x40, 0x00 }; r += expect_decoded_arr ("/+9876543210zyxwvutsrqponmlkjihgfedcba" \ "ZYXWVUTSRQPONMLKJIHGFEDCBAAA==", bin); } return r; } /* return zero if succeed, one otherwise */ static unsigned int expect_fail_n (const char *const encoded, const size_t encoded_len, const unsigned int line_num) { static const char fill_chr = '#'; static uint8_t buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != encoded); mhd_assert (TEST_BIN_MAX_SIZE > encoded_len); ret = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_base64_to_bin_n (encoded, encoded_len, buf, sizeof(buf)); if (res_size != 0) { ret = 1; fprintf (stderr, "'MHD_base64_to_bin_n ()' FAILED: Wrong returned value:\n"); } if (0 != ret) { static char prnt[TEST_BIN_MAX_SIZE * 2 + 1]; size_t prnt_size; if (TEST_BIN_MAX_SIZE <= res_size * 2) { fprintf (stderr, "\tRESULT : MHD_base64_to_bin_n ('%.*s', %u, ->(too long), %u)" " -> %u\n", (int) encoded_len, encoded, (unsigned) encoded_len, (unsigned) sizeof(buf), (unsigned) res_size); } else { prnt_size = MHD_bin_to_hex_z (buf, res_size, prnt); mhd_assert (2 * res_size == prnt_size); fprintf (stderr, "\tRESULT : MHD_base64_to_bin_n ('%.*s', %u, ->%.*sh, %u)" " -> %u\n", (int) encoded_len, encoded, (unsigned) encoded_len, (int) prnt_size, prnt, (unsigned) sizeof(buf), (unsigned) res_size); } fprintf (stderr, "\tEXPECTED: MHD_base64_to_bin_n ('%.*s', %u, ->(empty), %u)" " -> 0\n", (int) encoded_len, encoded, (unsigned) encoded_len, (unsigned) sizeof(buf)); fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_fail(e) \ expect_fail_n(e,MHD_STATICSTR_LEN_(e),__LINE__) static unsigned int check_fail (void) { unsigned int r = 0; /**< The number of errors */ /* Base sequences with wrong length */ r += expect_fail ("YWFh/"); r += expect_fail ("YWFh/Q"); r += expect_fail ("YWFhE/Q"); r += expect_fail ("bW1tbW1t/"); r += expect_fail ("bW1tbW1t/Q"); r += expect_fail ("bW1tbW1tE/Q"); /* Base sequences with wrong char */ r += expect_fail ("%mJi"); r += expect_fail ("Y%Nj"); r += expect_fail ("ZG%k"); r += expect_fail ("bGx%"); r += expect_fail ("#W1t"); r += expect_fail ("b#5u"); r += expect_fail ("b2#v"); r += expect_fail ("d3d#"); r += expect_fail ("^Hh4"); r += expect_fail ("e^l5"); r += expect_fail ("en^6"); r += expect_fail ("QUF^"); r += expect_fail ("~0dH"); r += expect_fail ("T~1N"); r += expect_fail ("VF~U"); r += expect_fail ("Wlp~"); r += expect_fail ("*DEy"); r += expect_fail ("M*Q1"); r += expect_fail ("Nj*4"); r += expect_fail ("OTA*"); r += expect_fail ("&WFhYWFh"); r += expect_fail ("Y&JiYmJi"); r += expect_fail ("Y2&jY2Nj"); r += expect_fail ("ZGR&ZGRk"); r += expect_fail ("bGxs&Gxs"); r += expect_fail ("bW1tb&1t"); r += expect_fail ("bm5ubm&u"); r += expect_fail ("b29vb29&"); r += expect_fail ("!3d3d3d3"); r += expect_fail ("e!h4eHh4"); r += expect_fail ("eX!5eXl5"); r += expect_fail ("enp!enp6"); r += expect_fail ("QUFB!UFB"); r += expect_fail ("R0dHR!dH"); r += expect_fail ("TU1NTU!N"); r += expect_fail ("VFRUVFR!"); /* Bad high-ASCII char */ r += expect_fail ("\xff" "WFhYWFh"); r += expect_fail ("Y\xfe" "JiYmJi"); r += expect_fail ("Y2\xfd" "jY2Nj"); r += expect_fail ("ZGR\xfc" "ZGRk"); r += expect_fail ("bGxs\xfb" "Gxs"); r += expect_fail ("bW1tbW\xfa" "1t"); r += expect_fail ("bm5ubm\xf9" "u"); r += expect_fail ("b29vb29\xf8"); r += expect_fail ("d3d3d3d\x80"); r += expect_fail ("eHh4eH\x81" "4"); r += expect_fail ("eXl5e\x82" "l5"); r += expect_fail ("enp6\x83" "np6"); r += expect_fail ("QUF\x84" "QUFB"); r += expect_fail ("TU\x85" "NTU1N"); r += expect_fail ("V\x86" "RUVFRU"); r += expect_fail ("\x87" "lpaWlpa"); /* Base sequences with wrong padding char */ r += expect_fail ("=lpaWlpa"); r += expect_fail ("M=EyMDEy"); r += expect_fail ("Mz=1MzQ1"); r += expect_fail ("Njc=Njc4"); r += expect_fail ("OTAx=TAx"); r += expect_fail ("ZGRkZ=Rk"); r += expect_fail ("bGxsbG=s"); r += expect_fail ("bW1tb==="); r += expect_fail ("bm5u===="); /* Bad last char (valid for Base64, but padding part is not zero */ r += expect_fail ("TG9uZ2VyIHN0cmluZo=="); r += expect_fail ("TG9uZ2VyIHN0cmluZyK="); return r; } int main (int argc, char *argv[]) { unsigned int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_decode_str (); errcount += check_decode_bin (); errcount += check_fail (); if (0 == errcount) printf ("All tests were passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.10/src/microhttpd/postprocessor.c0000664000175000017500000011377515232166316016200 /* This file is part of libmicrohttpd Copyright (C) 2007-2021 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file postprocessor.c * @brief Methods for parsing POST data * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "postprocessor.h" #include "internal.h" #include "mhd_str.h" #include "mhd_compat.h" #include "mhd_assert.h" /** * Size of on-stack buffer that we use for un-escaping of the value. * We use a pretty small value to be nice to the stack on embedded * systems. */ #define XBUF_SIZE 512 _MHD_EXTERN struct MHD_PostProcessor * MHD_create_post_processor (struct MHD_Connection *connection, size_t buffer_size, MHD_PostDataIterator iter, void *iter_cls) { struct MHD_PostProcessor *ret; const char *encoding; const char *boundary; size_t blen; if ( (buffer_size < 256) || (NULL == connection) || (NULL == iter)) MHD_PANIC (_ ("libmicrohttpd API violation.\n")); encoding = NULL; if (MHD_NO == MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE, MHD_STATICSTR_LEN_ ( MHD_HTTP_HEADER_CONTENT_TYPE), &encoding, NULL)) return NULL; mhd_assert (NULL != encoding); boundary = NULL; if (! MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED, encoding, MHD_STATICSTR_LEN_ ( MHD_HTTP_POST_ENCODING_FORM_URLENCODED))) { if (! MHD_str_equal_caseless_n_ ( MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA, encoding, MHD_STATICSTR_LEN_ ( MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA))) { return NULL; } boundary = &encoding[MHD_STATICSTR_LEN_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA)]; /* Q: should this be "strcasestr"? */ boundary = strstr (boundary, "boundary="); if (NULL == boundary) return NULL; /* failed to determine boundary */ boundary += MHD_STATICSTR_LEN_ ("boundary="); blen = strlen (boundary); if ( (blen < 2) || (blen * 2 + 2 > buffer_size) ) return NULL; /* (will be) out of memory or invalid boundary */ if ( (boundary[0] == '"') && (boundary[blen - 1] == '"') ) { /* remove enclosing quotes */ ++boundary; blen -= 2; } } else blen = 0; buffer_size += 4; /* round up to get nice block sizes despite boundary search */ /* add +1 to ensure we ALWAYS have a zero-termination at the end */ if (NULL == (ret = MHD_calloc_ (1, sizeof (struct MHD_PostProcessor) + buffer_size + 1))) return NULL; ret->connection = connection; ret->ikvi = iter; ret->cls = iter_cls; ret->encoding = encoding; ret->buffer_size = buffer_size; ret->state = PP_Init; ret->blen = blen; ret->boundary = boundary; ret->skip_rn = RN_Inactive; return ret; } /** * Give a (possibly partial) value to the application callback. We have some * part of the value in the 'pp->xbuf', the rest is between @a value_start and * @a value_end. If @a last_escape is non-NULL, there may be an incomplete * escape sequence at at @a value_escape between @a value_start and @a * value_end which we should preserve in 'pp->xbuf' for the future. * * Unescapes the value and calls the iterator together with the key. The key * must already be in the key buffer allocated and 0-terminated at the end of * @a pp at the time of the call. * * @param[in,out] pp post processor to act upon * @param value_start where in memory is the value * @param value_end where does the value end * @param last_escape last '%'-sign in value range, * if relevant, or NULL */ static void process_value (struct MHD_PostProcessor *pp, const char *value_start, const char *value_end, const char *last_escape) { char xbuf[XBUF_SIZE + 1]; size_t xoff; mhd_assert (pp->xbuf_pos < sizeof (xbuf)); /* 'value_start' and 'value_end' must be either both non-NULL or both NULL */ mhd_assert ( (NULL == value_start) || (NULL != value_end) ); mhd_assert ( (NULL != value_start) || (NULL == value_end) ); mhd_assert ( (NULL == last_escape) || (NULL != value_start) ); /* move remaining input from previous round into processing buffer */ if (0 != pp->xbuf_pos) memcpy (xbuf, pp->xbuf, pp->xbuf_pos); xoff = pp->xbuf_pos; pp->xbuf_pos = 0; if ( (NULL != last_escape) && (((size_t) (value_end - last_escape)) < sizeof (pp->xbuf)) ) { mhd_assert (value_end >= last_escape); pp->xbuf_pos = (size_t) (value_end - last_escape); memcpy (pp->xbuf, last_escape, (size_t) (value_end - last_escape)); value_end = last_escape; } while ( (value_start != value_end) || (pp->must_ikvi) || (xoff > 0) ) { size_t delta = (size_t) (value_end - value_start); bool cut = false; size_t clen = 0; mhd_assert (value_end >= value_start); if (delta > XBUF_SIZE - xoff) delta = XBUF_SIZE - xoff; /* move (additional) input into processing buffer */ if (0 != delta) { memcpy (&xbuf[xoff], value_start, delta); xoff += delta; value_start += delta; } /* find if escape sequence is at the end of the processing buffer; if so, exclude those from processing (reduce delta to point at end of processed region) */ if ( (xoff > 0) && ('%' == xbuf[xoff - 1]) ) { cut = (xoff != XBUF_SIZE); xoff--; if (cut) { /* move escape sequence into buffer for next function invocation */ pp->xbuf[0] = '%'; pp->xbuf_pos = 1; } else { /* just skip escape sequence for next loop iteration */ delta = xoff; clen = 1; } } else if ( (xoff > 1) && ('%' == xbuf[xoff - 2]) ) { cut = (xoff != XBUF_SIZE); xoff -= 2; if (cut) { /* move escape sequence into buffer for next function invocation */ memcpy (pp->xbuf, &xbuf[xoff], 2); pp->xbuf_pos = 2; } else { /* just skip escape sequence for next loop iteration */ delta = xoff; clen = 2; } } mhd_assert (xoff < sizeof (xbuf)); /* unescape */ xbuf[xoff] = '\0'; /* 0-terminate in preparation */ if (0 != xoff) { MHD_unescape_plus (xbuf); xoff = MHD_http_unescape (xbuf); } /* finally: call application! */ if (pp->must_ikvi || (0 != xoff) ) { pp->must_ikvi = false; if (MHD_NO == pp->ikvi (pp->cls, MHD_POSTDATA_KIND, (const char *) &pp[1], /* key */ NULL, NULL, NULL, xbuf, pp->value_offset, xoff)) { pp->state = PP_Error; return; } } pp->value_offset += xoff; if (cut) break; if (0 != clen) { xbuf[delta] = '%'; /* undo 0-termination */ memmove (xbuf, &xbuf[delta], clen); } xoff = clen; } } /** * Process url-encoded POST data. * * @param pp post processor context * @param post_data upload data * @param post_data_len number of bytes in @a post_data * @return #MHD_YES on success, #MHD_NO if there was an error processing the data */ static enum MHD_Result post_process_urlencoded (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len) { char *kbuf = (char *) &pp[1]; size_t poff; const char *start_key = NULL; const char *end_key = NULL; const char *start_value = NULL; const char *end_value = NULL; const char *last_escape = NULL; mhd_assert (PP_Callback != pp->state); poff = 0; while ( ( (poff < post_data_len) || (pp->state == PP_Callback) ) && (pp->state != PP_Error) ) { switch (pp->state) { case PP_Error: /* clearly impossible as per while loop invariant */ abort (); break; /* Unreachable */ case PP_Init: /* initial phase */ mhd_assert (NULL == start_key); mhd_assert (NULL == end_key); mhd_assert (NULL == start_value); mhd_assert (NULL == end_value); switch (post_data[poff]) { case '=': /* Case: (no key)'=' */ /* Empty key with value */ pp->state = PP_Error; continue; case '&': /* Case: (no key)'&' */ /* Empty key without value */ poff++; continue; case '\n': case '\r': /* Case: (no key)'\n' or (no key)'\r' */ pp->state = PP_Done; poff++; break; default: /* normal character, key start, advance! */ pp->state = PP_ProcessKey; start_key = &post_data[poff]; pp->must_ikvi = true; poff++; continue; } break; /* end PP_Init */ case PP_ProcessKey: /* key phase */ mhd_assert (NULL == start_value); mhd_assert (NULL == end_value); mhd_assert (NULL != start_key || 0 == poff); mhd_assert (0 != poff || NULL == start_key); mhd_assert (NULL == end_key); switch (post_data[poff]) { case '=': /* Case: 'key=' */ if (0 != poff) end_key = &post_data[poff]; poff++; pp->state = PP_ProcessValue; break; case '&': /* Case: 'key&' */ if (0 != poff) end_key = &post_data[poff]; poff++; pp->state = PP_Callback; break; case '\n': case '\r': /* Case: 'key\n' or 'key\r' */ if (0 != poff) end_key = &post_data[poff]; /* No advance here, 'PP_Done' will be selected by next 'PP_Init' phase */ pp->state = PP_Callback; break; default: /* normal character, advance! */ if (0 == poff) start_key = post_data; poff++; break; } mhd_assert (NULL == end_key || NULL != start_key); break; /* end PP_ProcessKey */ case PP_ProcessValue: if (NULL == start_value) start_value = &post_data[poff]; switch (post_data[poff]) { case '=': /* case 'key==' */ pp->state = PP_Error; continue; case '&': /* case 'value&' */ end_value = &post_data[poff]; poff++; if (pp->must_ikvi || (start_value != end_value) ) { pp->state = PP_Callback; } else { pp->buffer_pos = 0; pp->value_offset = 0; pp->state = PP_Init; start_value = NULL; end_value = NULL; } continue; case '\n': case '\r': /* Case: 'value\n' or 'value\r' */ end_value = &post_data[poff]; if (pp->must_ikvi || (start_value != end_value) ) pp->state = PP_Callback; /* No poff advance here to set PP_Done in the next iteration */ else { poff++; pp->state = PP_Done; } break; case '%': last_escape = &post_data[poff]; poff++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': /* character, may be part of escaping */ poff++; continue; default: /* normal character, no more escaping! */ last_escape = NULL; poff++; continue; } break; /* end PP_ProcessValue */ case PP_Done: switch (post_data[poff]) { case '\n': case '\r': poff++; continue; } /* unexpected data at the end, fail! */ pp->state = PP_Error; break; case PP_Callback: mhd_assert ((NULL != end_key) || (NULL == start_key)); if (1) { const size_t key_len = (size_t) (end_key - start_key); mhd_assert (end_key >= start_key); if (0 != key_len) { if ( (pp->buffer_pos + key_len >= pp->buffer_size) || (pp->buffer_pos + key_len < pp->buffer_pos) ) { /* key too long, cannot parse! */ pp->state = PP_Error; continue; } /* compute key, if we have not already */ memcpy (&kbuf[pp->buffer_pos], start_key, key_len); pp->buffer_pos += key_len; start_key = NULL; end_key = NULL; pp->must_unescape_key = true; } } #ifdef _DEBUG else mhd_assert (0 != pp->buffer_pos); #endif /* _DEBUG */ if (pp->must_unescape_key) { kbuf[pp->buffer_pos] = '\0'; /* 0-terminate key */ MHD_unescape_plus (kbuf); MHD_http_unescape (kbuf); pp->must_unescape_key = false; } process_value (pp, start_value, end_value, NULL); if (PP_Error == pp->state) continue; pp->value_offset = 0; start_value = NULL; end_value = NULL; pp->buffer_pos = 0; pp->state = PP_Init; break; case PP_NextBoundary: case PP_ProcessEntryHeaders: case PP_PerformCheckMultipart: case PP_ProcessValueToBoundary: case PP_PerformCleanup: case PP_Nested_Init: case PP_Nested_PerformMarking: case PP_Nested_ProcessEntryHeaders: case PP_Nested_ProcessValueToBoundary: case PP_Nested_PerformCleanup: default: MHD_PANIC (_ ("internal error.\n")); /* should never happen! */ } mhd_assert ((end_key == NULL) || (start_key != NULL)); mhd_assert ((end_value == NULL) || (start_value != NULL)); } mhd_assert (PP_Callback != pp->state); if (PP_Error == pp->state) { /* State in error, returning failure */ return MHD_NO; } /* save remaining data for next iteration */ if (NULL != start_key) { size_t key_len; mhd_assert ((PP_ProcessKey == pp->state) || (NULL != end_key)); if (NULL == end_key) end_key = &post_data[poff]; mhd_assert (end_key >= start_key); key_len = (size_t) (end_key - start_key); mhd_assert (0 != key_len); /* it must be always non-zero here */ if ( (pp->buffer_pos + key_len >= pp->buffer_size) || (pp->buffer_pos + key_len < pp->buffer_pos) ) { pp->state = PP_Error; return MHD_NO; } memcpy (&kbuf[pp->buffer_pos], start_key, key_len); pp->buffer_pos += key_len; pp->must_unescape_key = true; start_key = NULL; end_key = NULL; } if ( (NULL != start_value) && (PP_ProcessValue == pp->state) ) { /* compute key, if we have not already */ if (pp->must_unescape_key) { kbuf[pp->buffer_pos] = '\0'; /* 0-terminate key */ MHD_unescape_plus (kbuf); MHD_http_unescape (kbuf); pp->must_unescape_key = false; } if (NULL == end_value) end_value = &post_data[poff]; if ( (NULL != last_escape) && (2 < (end_value - last_escape)) ) last_escape = NULL; process_value (pp, start_value, end_value, last_escape); pp->must_ikvi = false; } if (PP_Error == pp->state) { /* State in error, returning failure */ return MHD_NO; } return MHD_YES; } /** * If the given line matches the prefix, strdup the * rest of the line into the suffix ptr. * * @param prefix prefix to match * @param prefix_len length of @a prefix * @param line line to match prefix in * @param suffix set to a copy of the rest of the line, starting at the end of the match * @return #MHD_YES if there was a match, #MHD_NO if not */ static int try_match_header (const char *prefix, size_t prefix_len, char *line, char **suffix) { if (NULL != *suffix) return MHD_NO; if (MHD_str_equal_caseless_n_ (prefix, line, prefix_len)) { *suffix = strdup (&line[prefix_len]); return MHD_YES; } return MHD_NO; } /** * * @param pp post processor context * @param boundary boundary to look for * @param blen number of bytes in boundary * @param ioffptr set to the end of the boundary if found, * otherwise incremented by one (FIXME: quirky API!) * @param next_state state to which we should advance the post processor * if the boundary is found * @param next_dash_state dash_state to which we should advance the * post processor if the boundary is found * @return #MHD_NO if the boundary is not found, #MHD_YES if we did find it */ static int find_boundary (struct MHD_PostProcessor *pp, const char *boundary, size_t blen, size_t *ioffptr, enum PP_State next_state, enum PP_State next_dash_state) { char *buf = (char *) &pp[1]; const char *dash; if (pp->buffer_pos < 2 + blen) { if (pp->buffer_pos == pp->buffer_size) pp->state = PP_Error; /* out of memory */ /* ++(*ioffptr); */ return MHD_NO; /* not enough data */ } if ( (0 != memcmp ("--", buf, 2)) || (0 != memcmp (&buf[2], boundary, blen))) { if (pp->state != PP_Init) { /* garbage not allowed */ pp->state = PP_Error; } else { /* skip over garbage (RFC 2046, 5.1.1) */ dash = memchr (buf, '-', pp->buffer_pos); if (NULL == dash) (*ioffptr) += pp->buffer_pos; /* skip entire buffer */ else if (dash == buf) (*ioffptr)++; /* at least skip one byte */ else (*ioffptr) += (size_t) (dash - buf); /* skip to first possible boundary */ } return MHD_NO; /* expected boundary */ } /* remove boundary from buffer */ (*ioffptr) += 2 + blen; /* next: start with headers */ pp->skip_rn = RN_Dash; pp->state = next_state; pp->dash_state = next_dash_state; return MHD_YES; } /** * In buf, there maybe an expression '$key="$value"'. If that is the * case, copy a copy of $value to destination. * * If destination is already non-NULL, do nothing. */ static void try_get_value (const char *buf, const char *key, char **destination) { const char *spos; const char *bpos; const char *endv; size_t klen; size_t vlen; if (NULL != *destination) return; bpos = buf; klen = strlen (key); while (NULL != (spos = strstr (bpos, key))) { if ( (spos[klen] != '=') || ( (spos != buf) && (spos[-1] != ' ') ) ) { /* no match */ bpos = spos + 1; continue; } if (spos[klen + 1] != '"') return; /* not quoted */ if (NULL == (endv = strchr (&spos[klen + 2], '\"'))) return; /* no end-quote */ vlen = (size_t) (endv - spos) - klen - 1; *destination = malloc (vlen); if (NULL == *destination) return; /* out of memory */ (*destination)[vlen - 1] = '\0'; memcpy (*destination, &spos[klen + 2], vlen - 1); return; /* success */ } } /** * Go over the headers of the part and update * the fields in "pp" according to what we find. * If we are at the end of the headers (as indicated * by an empty line), transition into next_state. * * @param pp post processor context * @param ioffptr set to how many bytes have been * processed * @param next_state state to which the post processor should * be advanced if we find the end of the headers * @return #MHD_YES if we can continue processing, * #MHD_NO on error or if we do not have * enough data yet */ static int process_multipart_headers (struct MHD_PostProcessor *pp, size_t *ioffptr, enum PP_State next_state) { char *buf = (char *) &pp[1]; size_t newline; newline = 0; while ( (newline < pp->buffer_pos) && (buf[newline] != '\r') && (buf[newline] != '\n') ) newline++; if (newline == pp->buffer_size) { pp->state = PP_Error; return MHD_NO; /* out of memory */ } if (newline == pp->buffer_pos) return MHD_NO; /* will need more data */ if (0 == newline) { /* empty line - end of headers */ pp->skip_rn = RN_Full; pp->state = next_state; return MHD_YES; } /* got an actual header */ if (buf[newline] == '\r') pp->skip_rn = RN_OptN; buf[newline] = '\0'; if (MHD_str_equal_caseless_n_ ("Content-disposition: ", buf, MHD_STATICSTR_LEN_ ("Content-disposition: "))) { try_get_value (&buf[MHD_STATICSTR_LEN_ ("Content-disposition: ")], "name", &pp->content_name); try_get_value (&buf[MHD_STATICSTR_LEN_ ("Content-disposition: ")], "filename", &pp->content_filename); } else { try_match_header ("Content-type: ", MHD_STATICSTR_LEN_ ("Content-type: "), buf, &pp->content_type); try_match_header ("Content-Transfer-Encoding: ", MHD_STATICSTR_LEN_ ("Content-Transfer-Encoding: "), buf, &pp->content_transfer_encoding); } (*ioffptr) += newline + 1; return MHD_YES; } /** * We have the value until we hit the given boundary; * process accordingly. * * @param pp post processor context * @param ioffptr incremented based on the number of bytes processed * @param boundary the boundary to look for * @param blen strlen(boundary) * @param next_state what state to go into after the * boundary was found * @param next_dash_state state to go into if the next * boundary ends with "--" * @return #MHD_YES if we can continue processing, * #MHD_NO on error or if we do not have * enough data yet */ static int process_value_to_boundary (struct MHD_PostProcessor *pp, size_t *ioffptr, const char *boundary, size_t blen, enum PP_State next_state, enum PP_State next_dash_state) { char *buf = (char *) &pp[1]; size_t newline; const char *r; /* all data in buf until the boundary (\r\n--+boundary) is part of the value */ newline = 0; while (1) { while (newline + 4 < pp->buffer_pos) { r = memchr (&buf[newline], '\r', pp->buffer_pos - newline - 4); if (NULL == r) { newline = pp->buffer_pos - 4; break; } newline = (size_t) (r - buf); if (0 == memcmp ("\r\n--", &buf[newline], 4)) break; newline++; } if (newline + blen + 4 <= pp->buffer_pos) { /* can check boundary */ if (0 != memcmp (&buf[newline + 4], boundary, blen)) { /* no boundary, "\r\n--" is part of content, skip */ newline += 4; continue; } else { /* boundary found, process until newline then skip boundary and go back to init */ pp->skip_rn = RN_Dash; pp->state = next_state; pp->dash_state = next_dash_state; (*ioffptr) += blen + 4; /* skip boundary as well */ buf[newline] = '\0'; break; } } else { /* cannot check for boundary, process content that we have and check again later; except, if we have no content, abort (out of memory) */ if ( (0 == newline) && (pp->buffer_pos == pp->buffer_size) ) { pp->state = PP_Error; return MHD_NO; } break; } } /* newline is either at beginning of boundary or at least at the last character that we are sure is not part of the boundary */ if ( ( (pp->must_ikvi) || (0 != newline) ) && (MHD_NO == pp->ikvi (pp->cls, MHD_POSTDATA_KIND, pp->content_name, pp->content_filename, pp->content_type, pp->content_transfer_encoding, buf, pp->value_offset, newline)) ) { pp->state = PP_Error; return MHD_NO; } pp->must_ikvi = false; pp->value_offset += newline; (*ioffptr) += newline; return MHD_YES; } /** * * @param pp post processor context */ static void free_unmarked (struct MHD_PostProcessor *pp) { if ( (NULL != pp->content_name) && (0 == (pp->have & NE_content_name)) ) { free (pp->content_name); pp->content_name = NULL; } if ( (NULL != pp->content_type) && (0 == (pp->have & NE_content_type)) ) { free (pp->content_type); pp->content_type = NULL; } if ( (NULL != pp->content_filename) && (0 == (pp->have & NE_content_filename)) ) { free (pp->content_filename); pp->content_filename = NULL; } if ( (NULL != pp->content_transfer_encoding) && (0 == (pp->have & NE_content_transfer_encoding)) ) { free (pp->content_transfer_encoding); pp->content_transfer_encoding = NULL; } } /** * Decode multipart POST data. * * @param pp post processor context * @param post_data data to decode * @param post_data_len number of bytes in @a post_data * @return #MHD_NO on error, */ static enum MHD_Result post_process_multipart (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len) { char *buf; size_t max; size_t ioff; size_t poff; int state_changed; buf = (char *) &pp[1]; ioff = 0; poff = 0; state_changed = 1; while ( (poff < post_data_len) || ( (pp->buffer_pos > 0) && (0 != state_changed) ) ) { /* first, move as much input data as possible to our internal buffer */ max = pp->buffer_size - pp->buffer_pos; if (max > post_data_len - poff) max = post_data_len - poff; memcpy (&buf[pp->buffer_pos], &post_data[poff], max); poff += max; pp->buffer_pos += max; if ( (0 == max) && (0 == state_changed) && (poff < post_data_len) ) { pp->state = PP_Error; return MHD_NO; /* out of memory */ } state_changed = 0; /* first state machine for '\r'-'\n' and '--' handling */ switch (pp->skip_rn) { case RN_Inactive: break; case RN_OptN: if (buf[0] == '\n') { ioff++; pp->skip_rn = RN_Inactive; goto AGAIN; } /* fall-through! */ case RN_Dash: if (buf[0] == '-') { ioff++; pp->skip_rn = RN_Dash2; goto AGAIN; } pp->skip_rn = RN_Full; /* fall-through! */ case RN_Full: if (buf[0] == '\r') { if ( (pp->buffer_pos > 1) && ('\n' == buf[1]) ) { pp->skip_rn = RN_Inactive; ioff += 2; } else { pp->skip_rn = RN_OptN; ioff++; } goto AGAIN; } if (buf[0] == '\n') { ioff++; pp->skip_rn = RN_Inactive; goto AGAIN; } pp->skip_rn = RN_Inactive; pp->state = PP_Error; return MHD_NO; /* no '\r\n' */ case RN_Dash2: if (buf[0] == '-') { ioff++; pp->skip_rn = RN_Full; pp->state = pp->dash_state; goto AGAIN; } pp->state = PP_Error; break; } /* main state engine */ switch (pp->state) { case PP_Error: return MHD_NO; case PP_Done: /* did not expect to receive more data */ pp->state = PP_Error; return MHD_NO; case PP_Init: /** * Per RFC2046 5.1.1 NOTE TO IMPLEMENTORS, consume anything * prior to the first multipart boundary: * * > There appears to be room for additional information prior * > to the first boundary delimiter line and following the * > final boundary delimiter line. These areas should * > generally be left blank, and implementations must ignore * > anything that appears before the first boundary delimiter * > line or after the last one. */ (void) find_boundary (pp, pp->boundary, pp->blen, &ioff, PP_ProcessEntryHeaders, PP_Done); break; case PP_NextBoundary: if (MHD_NO == find_boundary (pp, pp->boundary, pp->blen, &ioff, PP_ProcessEntryHeaders, PP_Done)) { if (pp->state == PP_Error) return MHD_NO; goto END; } break; case PP_ProcessEntryHeaders: pp->must_ikvi = true; if (MHD_NO == process_multipart_headers (pp, &ioff, PP_PerformCheckMultipart)) { if (pp->state == PP_Error) return MHD_NO; else goto END; } state_changed = 1; break; case PP_PerformCheckMultipart: if ( (NULL != pp->content_type) && (MHD_str_equal_caseless_n_ (pp->content_type, "multipart/mixed", MHD_STATICSTR_LEN_ ("multipart/mixed")))) { const char *bnd; char *nested; bnd = strstr (pp->content_type, "boundary="); if (NULL == bnd) { pp->state = PP_Error; return MHD_NO; } /* Note: 'bnd' points into 'pp->content_type', which is released below, so the copy must be taken first. It must also be taken into a local: assigning the 'strstr()' result to 'pp->nested_boundary' first would overwrite -- and leak -- a boundary already owned by this post processor. That happens whenever this state is reached twice without passing through PP_PerformCleanup, i.e. for every additional nested "multipart/mixed" part, and the leaked block is as long as the boundary the client chose. */ nested = strdup (&bnd[MHD_STATICSTR_LEN_ ("boundary=")]); if (NULL == nested) { /* out of memory */ pp->state = PP_Error; return MHD_NO; } if (NULL != pp->nested_boundary) free (pp->nested_boundary); pp->nested_boundary = nested; /* free old content type, we will need that field for the content type of the nested elements */ free (pp->content_type); pp->content_type = NULL; pp->nlen = strlen (pp->nested_boundary); pp->state = PP_Nested_Init; state_changed = 1; break; } pp->state = PP_ProcessValueToBoundary; pp->value_offset = 0; state_changed = 1; break; case PP_ProcessValueToBoundary: if (MHD_NO == process_value_to_boundary (pp, &ioff, pp->boundary, pp->blen, PP_PerformCleanup, PP_Done)) { if (pp->state == PP_Error) return MHD_NO; break; } break; case PP_PerformCleanup: /* clean up state of one multipart form-data element! */ pp->have = NE_none; free_unmarked (pp); if (NULL != pp->nested_boundary) { free (pp->nested_boundary); pp->nested_boundary = NULL; } pp->state = PP_ProcessEntryHeaders; state_changed = 1; break; case PP_Nested_Init: if (NULL == pp->nested_boundary) { pp->state = PP_Error; return MHD_NO; } if (MHD_NO == find_boundary (pp, pp->nested_boundary, pp->nlen, &ioff, PP_Nested_PerformMarking, PP_NextBoundary /* or PP_Error? */)) { if (pp->state == PP_Error) return MHD_NO; goto END; } break; case PP_Nested_PerformMarking: /* remember what headers were given globally */ pp->have = NE_none; if (NULL != pp->content_name) pp->have |= NE_content_name; if (NULL != pp->content_type) pp->have |= NE_content_type; if (NULL != pp->content_filename) pp->have |= NE_content_filename; if (NULL != pp->content_transfer_encoding) pp->have |= NE_content_transfer_encoding; pp->state = PP_Nested_ProcessEntryHeaders; state_changed = 1; break; case PP_Nested_ProcessEntryHeaders: pp->value_offset = 0; if (MHD_NO == process_multipart_headers (pp, &ioff, PP_Nested_ProcessValueToBoundary)) { if (pp->state == PP_Error) return MHD_NO; else goto END; } state_changed = 1; break; case PP_Nested_ProcessValueToBoundary: if (MHD_NO == process_value_to_boundary (pp, &ioff, pp->nested_boundary, pp->nlen, PP_Nested_PerformCleanup, PP_NextBoundary)) { if (pp->state == PP_Error) return MHD_NO; break; } break; case PP_Nested_PerformCleanup: free_unmarked (pp); pp->state = PP_Nested_ProcessEntryHeaders; state_changed = 1; break; case PP_ProcessKey: case PP_ProcessValue: case PP_Callback: default: MHD_PANIC (_ ("internal error.\n")); /* should never happen! */ } AGAIN: if (ioff > 0) { memmove (buf, &buf[ioff], pp->buffer_pos - ioff); pp->buffer_pos -= ioff; ioff = 0; state_changed = 1; } } END: if (0 != ioff) { memmove (buf, &buf[ioff], pp->buffer_pos - ioff); pp->buffer_pos -= ioff; } if (poff < post_data_len) { pp->state = PP_Error; return MHD_NO; /* serious error */ } return MHD_YES; } _MHD_EXTERN enum MHD_Result MHD_post_process (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len) { if (0 == post_data_len) return MHD_YES; if (NULL == pp) return MHD_NO; if (MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_FORM_URLENCODED, pp->encoding, MHD_STATICSTR_LEN_ ( MHD_HTTP_POST_ENCODING_FORM_URLENCODED))) return post_process_urlencoded (pp, post_data, post_data_len); if (MHD_str_equal_caseless_n_ (MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA, pp->encoding, MHD_STATICSTR_LEN_ ( MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA))) return post_process_multipart (pp, post_data, post_data_len); /* this should never be reached */ return MHD_NO; } _MHD_EXTERN enum MHD_Result MHD_destroy_post_processor (struct MHD_PostProcessor *pp) { enum MHD_Result ret; if (NULL == pp) return MHD_YES; if (PP_ProcessValue == pp->state) { /* key without terminated value left at the end of the buffer; fake receiving a termination character to ensure it is also processed */ post_process_urlencoded (pp, "\n", 1); } /* These internal strings need cleaning up since the post-processing may have been interrupted at any stage */ if ( (pp->xbuf_pos > 0) || ( (pp->state != PP_Done) && (pp->state != PP_Init) ) ) ret = MHD_NO; else ret = MHD_YES; pp->have = NE_none; free_unmarked (pp); if (NULL != pp->nested_boundary) free (pp->nested_boundary); free (pp); return ret; } /* end of postprocessor.c */ libmicrohttpd-1.0.10/src/microhttpd/mhd_threads.c0000644000175000017500000002751115035214301015510 /* This file is part of libmicrohttpd Copyright (C) 2016-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_threads.c * @brief Implementation for thread functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_threads.h" #ifdef MHD_USE_W32_THREADS #include "mhd_limits.h" #include #endif #ifdef MHD_USE_THREAD_NAME_ #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #ifdef HAVE_PTHREAD_NP_H #include #endif /* HAVE_PTHREAD_NP_H */ #endif /* MHD_USE_THREAD_NAME_ */ #include #include "mhd_assert.h" #ifndef MHD_USE_THREAD_NAME_ #define MHD_set_thread_name_(t, n) (void) #define MHD_set_cur_thread_name_(n) (void) #else /* MHD_USE_THREAD_NAME_ */ #if defined(MHD_USE_POSIX_THREADS) #if defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) || \ defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI) # define MHD_USE_THREAD_ATTR_SETNAME 1 #endif /* HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD || \ HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI */ #if defined(HAVE_PTHREAD_SETNAME_NP_GNU) || \ defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) \ || defined(HAVE_PTHREAD_SETNAME_NP_NETBSD) /** * Set thread name * * @param thread_id ID of thread * @param thread_name name to set * @return non-zero on success, zero otherwise */ static int MHD_set_thread_name_ (const MHD_thread_ID_native_ thread_id, const char *thread_name) { if (NULL == thread_name) return 0; #if defined(HAVE_PTHREAD_SETNAME_NP_GNU) return ! pthread_setname_np (thread_id, thread_name); #elif defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) /* FreeBSD and OpenBSD use different function name and void return type */ pthread_set_name_np (thread_id, thread_name); return ! 0; #elif defined(HAVE_PTHREAD_SETNAME_NP_NETBSD) /* NetBSD use 3 arguments: second argument is string in printf-like format, * third argument is a single argument for printf(); * OSF1 use 3 arguments too, but last one always must be zero (NULL). * MHD doesn't use '%' in thread names, so both form are used in same way. */ return ! pthread_setname_np (thread_id, thread_name, 0); #endif /* HAVE_PTHREAD_SETNAME_NP_NETBSD */ } #ifndef __QNXNTO__ /** * Set current thread name * @param n name to set * @return non-zero on success, zero otherwise */ #define MHD_set_cur_thread_name_(n) MHD_set_thread_name_ (pthread_self (),(n)) #else /* __QNXNTO__ */ /* Special case for QNX Neutrino - using zero for thread ID sets name faster. */ #define MHD_set_cur_thread_name_(n) MHD_set_thread_name_ (0,(n)) #endif /* __QNXNTO__ */ #elif defined(HAVE_PTHREAD_SETNAME_NP_DARWIN) /** * Set current thread name * @param n name to set * @return non-zero on success, zero otherwise */ #define MHD_set_cur_thread_name_(n) (! (pthread_setname_np ((n)))) #endif /* HAVE_PTHREAD_SETNAME_NP_DARWIN */ #elif defined(MHD_USE_W32_THREADS) #ifndef _MSC_FULL_VER /* Thread name available only for VC-compiler */ #else /* _MSC_FULL_VER */ /** * Set thread name * * @param thread_id ID of thread, -1 for current thread * @param thread_name name to set * @return non-zero on success, zero otherwise */ static int MHD_set_thread_name_ (const MHD_thread_ID_native_ thread_id, const char *thread_name) { static const DWORD VC_SETNAME_EXC = 0x406D1388; #pragma pack(push,8) struct thread_info_struct { DWORD type; /* Must be 0x1000. */ LPCSTR name; /* Pointer to name (in user address space). */ DWORD ID; /* Thread ID (-1 = caller thread). */ DWORD flags; /* Reserved for future use, must be zero. */ } thread_info; #pragma pack(pop) if (NULL == thread_name) return 0; thread_info.type = 0x1000; thread_info.name = thread_name; thread_info.ID = thread_id; thread_info.flags = 0; __try { /* This exception is intercepted by debugger */ RaiseException (VC_SETNAME_EXC, 0, sizeof (thread_info) / sizeof(ULONG_PTR), (ULONG_PTR *) &thread_info); } __except (EXCEPTION_EXECUTE_HANDLER) {} return ! 0; } /** * Set current thread name * @param n name to set * @return non-zero on success, zero otherwise */ #define MHD_set_cur_thread_name_(n) \ MHD_set_thread_name_ ((MHD_thread_ID_native_) -1,(n)) #endif /* _MSC_FULL_VER */ #endif /* MHD_USE_W32_THREADS */ #endif /* MHD_USE_THREAD_NAME_ */ /** * Create a thread and set the attributes according to our options. * * If thread is created, thread handle must be freed by MHD_join_thread_(). * * @param handle_id handle to initialise * @param stack_size size of stack for new thread, 0 for default * @param start_routine main function of thread * @param arg argument for start_routine * @return non-zero on success; zero otherwise (with errno set) */ int MHD_create_thread_ (MHD_thread_handle_ID_ *handle_id, size_t stack_size, MHD_THREAD_START_ROUTINE_ start_routine, void *arg) { #if defined(MHD_USE_POSIX_THREADS) int res; #if defined(MHD_thread_handle_ID_get_native_handle_ptr_) pthread_t *const new_tid_ptr = MHD_thread_handle_ID_get_native_handle_ptr_ (handle_id); #else /* ! MHD_thread_handle_ID_get_native_handle_ptr_ */ pthread_t new_tid; pthread_t *const new_tid_ptr = &new_tid; #endif /* ! MHD_thread_handle_ID_get_native_handle_ptr_ */ mhd_assert (! MHD_thread_handle_ID_is_valid_handle_ (*handle_id)); if (0 != stack_size) { pthread_attr_t attr; res = pthread_attr_init (&attr); if (0 == res) { res = pthread_attr_setstacksize (&attr, stack_size); if (0 == res) res = pthread_create (new_tid_ptr, &attr, start_routine, arg); pthread_attr_destroy (&attr); } } else res = pthread_create (new_tid_ptr, NULL, start_routine, arg); if (0 != res) { errno = res; MHD_thread_handle_ID_set_invalid_ (handle_id); } #if ! defined(MHD_thread_handle_ID_get_native_handle_ptr_) else MHD_thread_handle_ID_set_native_handle_ (handle_id, new_tid); #endif /* ! MHD_thread_handle_ID_set_current_thread_ID_ */ return ! res; #elif defined(MHD_USE_W32_THREADS) uintptr_t thr_handle; #if SIZEOF_SIZE_T != SIZEOF_UNSIGNED_INT mhd_assert (! MHD_thread_handle_ID_is_valid_handle_ (*handle_id)); if (stack_size > UINT_MAX) { errno = EINVAL; return 0; } #endif /* SIZEOF_SIZE_T != SIZEOF_UNSIGNED_INT */ thr_handle = (uintptr_t) _beginthreadex (NULL, (unsigned int) stack_size, start_routine, arg, 0, NULL); if ((MHD_thread_handle_native_) 0 == (MHD_thread_handle_native_) thr_handle) return 0; MHD_thread_handle_ID_set_native_handle_ (handle_id, \ (MHD_thread_handle_native_) \ thr_handle); return ! 0; #endif } #ifdef MHD_USE_THREAD_NAME_ #ifndef MHD_USE_THREAD_ATTR_SETNAME struct MHD_named_helper_param_ { /** * Real thread start routine */ MHD_THREAD_START_ROUTINE_ start_routine; /** * Argument for thread start routine */ void *arg; /** * Name for thread */ const char *name; }; static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ named_thread_starter (void *data) { struct MHD_named_helper_param_ *const param = (struct MHD_named_helper_param_ *) data; void *arg; MHD_THREAD_START_ROUTINE_ thr_func; if (NULL == data) return (MHD_THRD_RTRN_TYPE_) 0; MHD_set_cur_thread_name_ (param->name); arg = param->arg; thr_func = param->start_routine; free (data); return thr_func (arg); } #endif /* ! MHD_USE_THREAD_ATTR_SETNAME */ /** * Create a named thread and set the attributes according to our options. * * @param handle_id handle to initialise * @param thread_name name for new thread * @param stack_size size of stack for new thread, 0 for default * @param start_routine main function of thread * @param arg argument for start_routine * @return non-zero on success; zero otherwise (with errno set) */ int MHD_create_named_thread_ (MHD_thread_handle_ID_ *handle_id, const char *thread_name, size_t stack_size, MHD_THREAD_START_ROUTINE_ start_routine, void *arg) { #if defined(MHD_USE_THREAD_ATTR_SETNAME) int res; pthread_attr_t attr; #if defined(MHD_thread_handle_ID_get_native_handle_ptr_) pthread_t *const new_tid_ptr = MHD_thread_handle_ID_get_native_handle_ptr_ (handle_id); #else /* ! MHD_thread_handle_ID_get_native_handle_ptr_ */ pthread_t new_tid; pthread_t *const new_tid_ptr = &new_tid; #endif /* ! MHD_thread_handle_ID_get_native_handle_ptr_ */ res = pthread_attr_init (&attr); if (0 == res) { #if defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) /* NetBSD uses 3 arguments: second argument is string in printf-like format, * third argument is single argument for printf; * OSF1 uses 3 arguments too, but last one always must be zero (NULL). * MHD doesn't use '%' in thread names, so both forms are used in same way. */ res = pthread_attr_setname_np (&attr, thread_name, 0); #elif defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI) res = pthread_attr_setname_np (&attr, thread_name); #else #error No pthread_attr_setname_np() function. #endif if ((res == 0) && (0 != stack_size) ) res = pthread_attr_setstacksize (&attr, stack_size); if (0 == res) res = pthread_create (new_tid_ptr, &attr, start_routine, arg); pthread_attr_destroy (&attr); } if (0 != res) { errno = res; MHD_thread_handle_ID_set_invalid_ (handle_id); } #if ! defined(MHD_thread_handle_ID_get_native_handle_ptr_) else MHD_thread_handle_ID_set_native_handle_ (handle_id, new_tid); #endif /* ! MHD_thread_handle_ID_set_current_thread_ID_ */ return ! res; #else /* ! MHD_USE_THREAD_ATTR_SETNAME */ struct MHD_named_helper_param_ *param; if (NULL == thread_name) { errno = EINVAL; return 0; } param = malloc (sizeof (struct MHD_named_helper_param_)); if (NULL == param) return 0; param->start_routine = start_routine; param->arg = arg; param->name = thread_name; /* Set thread name in thread itself to avoid problems with * threads which terminated before name is set in other thread. */ if (! MHD_create_thread_ (handle_id, stack_size, &named_thread_starter, (void *) param)) { int err_num; err_num = errno; free (param); errno = err_num; return 0; } return ! 0; #endif /* ! MHD_USE_THREAD_ATTR_SETNAME */ } #endif /* MHD_USE_THREAD_NAME_ */ libmicrohttpd-1.0.10/src/microhttpd/mhd_sockets.c0000644000175000017500000004174014760713574015555 /* This file is part of libmicrohttpd Copyright (C) 2014-2024 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_sockets.c * @brief Implementation for sockets functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_sockets.h" #ifdef MHD_WINSOCK_SOCKETS /** * Return pointer to string description of specified WinSock error * @param err the WinSock error code. * @return pointer to string description of specified WinSock error. */ const char * MHD_W32_strerror_winsock_ (int err) { switch (err) { case 0: return "No error"; case WSA_INVALID_HANDLE: return "Specified event object handle is invalid"; case WSA_NOT_ENOUGH_MEMORY: return "Insufficient memory available"; case WSA_INVALID_PARAMETER: return "One or more parameters are invalid"; case WSA_OPERATION_ABORTED: return "Overlapped operation aborted"; case WSA_IO_INCOMPLETE: return "Overlapped I/O event object not in signaled state"; case WSA_IO_PENDING: return "Overlapped operations will complete later"; case WSAEINTR: return "Interrupted function call"; case WSAEBADF: return "File handle is not valid"; case WSAEACCES: return "Permission denied"; case WSAEFAULT: return "Bad address"; case WSAEINVAL: return "Invalid argument"; case WSAEMFILE: return "Too many open files"; case WSAEWOULDBLOCK: return "Resource temporarily unavailable"; case WSAEINPROGRESS: return "Operation now in progress"; case WSAEALREADY: return "Operation already in progress"; case WSAENOTSOCK: return "Socket operation on nonsocket"; case WSAEDESTADDRREQ: return "Destination address required"; case WSAEMSGSIZE: return "Message too long"; case WSAEPROTOTYPE: return "Protocol wrong type for socket"; case WSAENOPROTOOPT: return "Bad protocol option"; case WSAEPROTONOSUPPORT: return "Protocol not supported"; case WSAESOCKTNOSUPPORT: return "Socket type not supported"; case WSAEOPNOTSUPP: return "Operation not supported"; case WSAEPFNOSUPPORT: return "Protocol family not supported"; case WSAEAFNOSUPPORT: return "Address family not supported by protocol family"; case WSAEADDRINUSE: return "Address already in use"; case WSAEADDRNOTAVAIL: return "Cannot assign requested address"; case WSAENETDOWN: return "Network is down"; case WSAENETUNREACH: return "Network is unreachable"; case WSAENETRESET: return "Network dropped connection on reset"; case WSAECONNABORTED: return "Software caused connection abort"; case WSAECONNRESET: return "Connection reset by peer"; case WSAENOBUFS: return "No buffer space available"; case WSAEISCONN: return "Socket is already connected"; case WSAENOTCONN: return "Socket is not connected"; case WSAESHUTDOWN: return "Cannot send after socket shutdown"; case WSAETOOMANYREFS: return "Too many references"; case WSAETIMEDOUT: return "Connection timed out"; case WSAECONNREFUSED: return "Connection refused"; case WSAELOOP: return "Cannot translate name"; case WSAENAMETOOLONG: return "Name too long"; case WSAEHOSTDOWN: return "Host is down"; case WSAEHOSTUNREACH: return "No route to host"; case WSAENOTEMPTY: return "Directory not empty"; case WSAEPROCLIM: return "Too many processes"; case WSAEUSERS: return "User quota exceeded"; case WSAEDQUOT: return "Disk quota exceeded"; case WSAESTALE: return "Stale file handle reference"; case WSAEREMOTE: return "Item is remote"; case WSASYSNOTREADY: return "Network subsystem is unavailable"; case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range"; case WSANOTINITIALISED: return "Successful WSAStartup not yet performed"; case WSAEDISCON: return "Graceful shutdown in progress"; case WSAENOMORE: return "No more results"; case WSAECANCELLED: return "Call has been canceled"; case WSAEINVALIDPROCTABLE: return "Procedure call table is invalid"; case WSAEINVALIDPROVIDER: return "Service provider is invalid"; case WSAEPROVIDERFAILEDINIT: return "Service provider failed to initialize"; case WSASYSCALLFAILURE: return "System call failure"; case WSASERVICE_NOT_FOUND: return "Service not found"; case WSATYPE_NOT_FOUND: return "Class type not found"; case WSA_E_NO_MORE: return "No more results"; case WSA_E_CANCELLED: return "Call was canceled"; case WSAEREFUSED: return "Database query was refused"; case WSAHOST_NOT_FOUND: return "Host not found"; case WSATRY_AGAIN: return "Nonauthoritative host not found"; case WSANO_RECOVERY: return "This is a nonrecoverable error"; case WSANO_DATA: return "Valid name, no data record of requested type"; case WSA_QOS_RECEIVERS: return "QoS receivers"; case WSA_QOS_SENDERS: return "QoS senders"; case WSA_QOS_NO_SENDERS: return "No QoS senders"; case WSA_QOS_NO_RECEIVERS: return "QoS no receivers"; case WSA_QOS_REQUEST_CONFIRMED: return "QoS request confirmed"; case WSA_QOS_ADMISSION_FAILURE: return "QoS admission error"; case WSA_QOS_POLICY_FAILURE: return "QoS policy failure"; case WSA_QOS_BAD_STYLE: return "QoS bad style"; case WSA_QOS_BAD_OBJECT: return "QoS bad object"; case WSA_QOS_TRAFFIC_CTRL_ERROR: return "QoS traffic control error"; case WSA_QOS_GENERIC_ERROR: return "QoS generic error"; case WSA_QOS_ESERVICETYPE: return "QoS service type error"; case WSA_QOS_EFLOWSPEC: return "QoS flowspec error"; case WSA_QOS_EPROVSPECBUF: return "Invalid QoS provider buffer"; case WSA_QOS_EFILTERSTYLE: return "Invalid QoS filter style"; case WSA_QOS_EFILTERTYPE: return "Invalid QoS filter type"; case WSA_QOS_EFILTERCOUNT: return "Incorrect QoS filter count"; case WSA_QOS_EOBJLENGTH: return "Invalid QoS object length"; case WSA_QOS_EFLOWCOUNT: return "Incorrect QoS flow count"; case WSA_QOS_EUNKOWNPSOBJ: return "Unrecognized QoS object"; case WSA_QOS_EPOLICYOBJ: return "Invalid QoS policy object"; case WSA_QOS_EFLOWDESC: return "Invalid QoS flow descriptor"; case WSA_QOS_EPSFLOWSPEC: return "Invalid QoS provider-specific flowspec"; case WSA_QOS_EPSFILTERSPEC: return "Invalid QoS provider-specific filterspec"; case WSA_QOS_ESDMODEOBJ: return "Invalid QoS shape discard mode object"; case WSA_QOS_ESHAPERATEOBJ: return "Invalid QoS shaping rate object"; case WSA_QOS_RESERVED_PETYPE: return "Reserved policy QoS element type"; } return "Unknown winsock error"; } /** * Create pair of mutually connected TCP/IP sockets on loopback address * @param sockets_pair array to receive resulted sockets * @param non_blk if set to non-zero value, sockets created in non-blocking mode * otherwise sockets will be in blocking mode * @return non-zero if succeeded, zero otherwise */ int MHD_W32_socket_pair_ (SOCKET sockets_pair[2], int non_blk) { int i; if (! sockets_pair) { WSASetLastError (WSAEFAULT); return 0; } #define PAIRMAXTRYIES 800 for (i = 0; i < PAIRMAXTRYIES; i++) { struct sockaddr_in listen_addr; SOCKET listen_s; static const int c_addinlen = sizeof(struct sockaddr_in); /* help compiler to optimize */ int addr_len = c_addinlen; unsigned long on_val = 1; unsigned long off_val = 0; listen_s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == listen_s) break; /* can't create even single socket */ listen_addr.sin_family = AF_INET; listen_addr.sin_port = 0; /* same as htons(0) */ listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if ( ((0 == bind (listen_s, (struct sockaddr *) &listen_addr, c_addinlen)) && (0 == listen (listen_s, 1) ) && (0 == getsockname (listen_s, (struct sockaddr *) &listen_addr, &addr_len))) ) { SOCKET client_s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); struct sockaddr_in accepted_from_addr; struct sockaddr_in client_addr; SOCKET server_s; if (INVALID_SOCKET == client_s) { /* try again */ closesocket (listen_s); continue; } if ( (0 != ioctlsocket (client_s, (int) FIONBIO, &on_val)) || ( (0 != connect (client_s, (struct sockaddr *) &listen_addr, c_addinlen)) && (WSAGetLastError () != WSAEWOULDBLOCK)) ) { /* try again */ closesocket (listen_s); closesocket (client_s); continue; } addr_len = c_addinlen; server_s = accept (listen_s, (struct sockaddr *) &accepted_from_addr, &addr_len); if (INVALID_SOCKET == server_s) { /* try again */ closesocket (listen_s); closesocket (client_s); continue; } addr_len = c_addinlen; if ( (0 == getsockname (client_s, (struct sockaddr *) &client_addr, &addr_len)) && (accepted_from_addr.sin_port == client_addr.sin_port) && (accepted_from_addr.sin_addr.s_addr == client_addr.sin_addr.s_addr) && (accepted_from_addr.sin_family == client_addr.sin_family) && ( (0 != non_blk) ? (0 == ioctlsocket (server_s, (int) FIONBIO, &on_val)) : (0 == ioctlsocket (client_s, (int) FIONBIO, &off_val)) ) && (0 == setsockopt (server_s, IPPROTO_TCP, TCP_NODELAY, (const void *) (&on_val), sizeof (on_val))) && (0 == setsockopt (client_s, IPPROTO_TCP, TCP_NODELAY, (const void *) (&on_val), sizeof (on_val))) ) { closesocket (listen_s); sockets_pair[0] = server_s; sockets_pair[1] = client_s; return ! 0; } closesocket (server_s); closesocket (client_s); } closesocket (listen_s); } sockets_pair[0] = INVALID_SOCKET; sockets_pair[1] = INVALID_SOCKET; WSASetLastError (WSAECONNREFUSED); return 0; } #endif /* MHD_WINSOCK_SOCKETS */ /** * Add @a fd to the @a set. If @a fd is * greater than @a max_fd, set @a max_fd to @a fd. * * @param fd file descriptor to add to the @a set * @param set set to modify * @param max_fd maximum value to potentially update * @param fd_setsize value of FD_SETSIZE * @return non-zero if succeeded, zero otherwise */ int MHD_add_to_fd_set_ (MHD_socket fd, fd_set *set, MHD_socket *max_fd, int fd_setsize) { if ( (NULL == set) || (MHD_INVALID_SOCKET == fd) ) return 0; #ifndef HAS_FD_SETSIZE_OVERRIDABLE (void) fd_setsize; /* Mute compiler warning */ fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (! MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (fd, set, fd_setsize)) return 0; MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_ (fd, set, fd_setsize); if ( (NULL != max_fd) && ( (fd > *max_fd) || (MHD_INVALID_SOCKET == *max_fd) ) ) *max_fd = fd; return ! 0; } /** * Change socket options to be non-blocking. * * @param sock socket to manipulate * @return non-zero if succeeded, zero otherwise */ int MHD_socket_nonblocking_ (MHD_socket sock) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (sock, F_GETFL); if (-1 == flags) return 0; if ( ((flags | O_NONBLOCK) != flags) && (0 != fcntl (sock, F_SETFL, flags | O_NONBLOCK)) ) return 0; #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 1; if (0 != ioctlsocket (sock, (int) FIONBIO, &flags)) return 0; #endif /* MHD_WINSOCK_SOCKETS */ return ! 0; } /** * Change socket options to be non-inheritable. * * @param sock socket to manipulate * @return non-zero if succeeded, zero otherwise * @warning Does not set socket error on W32. */ int MHD_socket_noninheritable_ (MHD_socket sock) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (sock, F_GETFD); if (-1 == flags) return 0; if ( ((flags | FD_CLOEXEC) != flags) && (0 != fcntl (sock, F_SETFD, flags | FD_CLOEXEC)) ) return 0; #elif defined(MHD_WINSOCK_SOCKETS) if (! SetHandleInformation ((HANDLE) sock, HANDLE_FLAG_INHERIT, 0)) return 0; #endif /* MHD_WINSOCK_SOCKETS */ return ! 0; } /** * Disable Nagle's algorithm on @a sock. This is what we do by default for * all TCP sockets in MHD, unless the platform does not support the MSG_MORE * or MSG_CORK or MSG_NOPUSH options. * * @param sock socket to manipulate * @param on value to use * @return 0 on success */ int MHD_socket_set_nodelay_ (MHD_socket sock, bool on) { #ifdef TCP_NODELAY { const MHD_SCKT_OPT_BOOL_ off_val = 0; const MHD_SCKT_OPT_BOOL_ on_val = 1; /* Disable Nagle's algorithm for normal buffering */ return setsockopt (sock, IPPROTO_TCP, TCP_NODELAY, (const void *) ((on) ? &on_val : &off_val), sizeof (on_val)); } #else (void) sock; return 0; #endif /* TCP_NODELAY */ } /** * Create a listen socket, with noninheritable flag if possible. * * @param pf protocol family to use * @return created socket or MHD_INVALID_SOCKET in case of errors */ MHD_socket MHD_socket_create_listen_ (int pf) { MHD_socket fd; int cloexec_set; #if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_) int nosigpipe_set; #endif /* SOCK_NOSIGPIPE || MHD_socket_nosignal_ */ #if defined(MHD_POSIX_SOCKETS) && (defined(SOCK_CLOEXEC) || \ defined(SOCK_NOSIGPIPE) ) fd = socket (pf, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NOSIGPIPE_OR_ZERO, 0); cloexec_set = (SOCK_CLOEXEC_OR_ZERO != 0); #if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_) nosigpipe_set = (SOCK_NOSIGPIPE_OR_ZERO != 0); #endif /* SOCK_NOSIGPIPE || MHD_socket_nosignal_ */ #elif defined(MHD_WINSOCK_SOCKETS) && defined(WSA_FLAG_NO_HANDLE_INHERIT) fd = WSASocketW (pf, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT); cloexec_set = ! 0; #else /* No special socket init function / flags */ fd = MHD_INVALID_SOCKET; cloexec_set = 0; #if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_) nosigpipe_set = 0; #endif /* SOCK_NOSIGPIPE || MHD_socket_nosignal_ */ #endif /* No special socket init function / flags */ if (MHD_INVALID_SOCKET == fd) { fd = socket (pf, SOCK_STREAM, 0); cloexec_set = 0; #if defined(SOCK_NOSIGPIPE) || defined(MHD_socket_nosignal_) nosigpipe_set = 0; #endif /* SOCK_NOSIGPIPE || MHD_socket_nosignal_ */ } if (MHD_INVALID_SOCKET == fd) return MHD_INVALID_SOCKET; #if defined(MHD_socket_nosignal_) if ( (! nosigpipe_set) && (0 == MHD_socket_nosignal_ (fd)) && (0 == MSG_NOSIGNAL_OR_ZERO) ) { /* SIGPIPE disable is possible on this platform * (so application expect that it will be disabled), * but failed to be disabled here and it is not * possible to disable SIGPIPE by MSG_NOSIGNAL. */ const int err = MHD_socket_get_error_ (); (void) MHD_socket_close_ (fd); MHD_socket_fset_error_ (err); return MHD_INVALID_SOCKET; } #endif /* defined(MHD_socket_nosignal_) */ if (! cloexec_set) (void) MHD_socket_noninheritable_ (fd); return fd; } libmicrohttpd-1.0.10/src/microhttpd/connection_https.c0000644000175000017500000001542614760713574016635 /* This file is part of libmicrohttpd Copyright (C) 2007, 2008, 2010 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file connection_https.c * @brief Methods for managing SSL/TLS connections. This file is only * compiled if ENABLE_HTTPS is set. * @author Sagie Amir * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "internal.h" #include "connection.h" #include "connection_https.h" #include "memorypool.h" #include "response.h" #include "mhd_mono_clock.h" #include #include "mhd_send.h" /** * Callback for receiving data from the socket. * * @param connection the MHD_Connection structure * @param other where to write received data to * @param i maximum size of other (in bytes) * @return positive value for number of bytes actually received or * negative value for error number MHD_ERR_xxx_ */ static ssize_t recv_tls_adapter (struct MHD_Connection *connection, void *other, size_t i) { ssize_t res; if (i > SSIZE_MAX) i = SSIZE_MAX; res = gnutls_record_recv (connection->tls_session, other, i); if ( (GNUTLS_E_AGAIN == res) || (GNUTLS_E_INTERRUPTED == res) ) { #ifdef EPOLL_SUPPORT if (GNUTLS_E_AGAIN == res) connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); #endif /* Any network errors means that buffer is empty. */ connection->tls_read_ready = false; return MHD_ERR_AGAIN_; } if (res < 0) { connection->tls_read_ready = false; if ( (GNUTLS_E_DECRYPTION_FAILED == res) || (GNUTLS_E_INVALID_SESSION == res) || (GNUTLS_E_DECOMPRESSION_FAILED == res) || (GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER == res) || (GNUTLS_E_UNSUPPORTED_VERSION_PACKET == res) || (GNUTLS_E_UNEXPECTED_PACKET_LENGTH == res) || (GNUTLS_E_UNEXPECTED_PACKET == res) || (GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET == res) || (GNUTLS_E_EXPIRED == res) || (GNUTLS_E_REHANDSHAKE == res) ) return MHD_ERR_TLS_; if ( (GNUTLS_E_PULL_ERROR == res) || (GNUTLS_E_INTERNAL_ERROR == res) || (GNUTLS_E_CRYPTODEV_IOCTL_ERROR == res) || (GNUTLS_E_CRYPTODEV_DEVICE_ERROR == res) ) return MHD_ERR_PIPE_; #if defined(GNUTLS_E_PREMATURE_TERMINATION) if (GNUTLS_E_PREMATURE_TERMINATION == res) return MHD_ERR_CONNRESET_; #elif defined(GNUTLS_E_UNEXPECTED_PACKET_LENGTH) if (GNUTLS_E_UNEXPECTED_PACKET_LENGTH == res) return MHD_ERR_CONNRESET_; #endif /* GNUTLS_E_UNEXPECTED_PACKET_LENGTH */ if (GNUTLS_E_MEMORY_ERROR == res) return MHD_ERR_NOMEM_; /* Treat any other error as a hard error. */ return MHD_ERR_NOTCONN_; } #ifdef EPOLL_SUPPORT /* Unlike non-TLS connections, do not reset "read-ready" if * received amount smaller than provided amount, as TLS * connections may receive data by fixed-size chunks. */ #endif /* EPOLL_SUPPORT */ /* Check whether TLS buffers still have some unread data. */ connection->tls_read_ready = ( ((size_t) res == i) && (0 != gnutls_record_check_pending (connection->tls_session)) ); return res; } /** * Give gnuTLS chance to work on the TLS handshake. * * @param connection connection to handshake on * @return true if the handshake has completed successfully * and we should start to read/write data, * false is handshake in progress or in case * of error */ bool MHD_run_tls_handshake_ (struct MHD_Connection *connection) { int ret; if ((MHD_TLS_CONN_INIT == connection->tls_state) || (MHD_TLS_CONN_HANDSHAKING == connection->tls_state)) { #if 0 /* According to real-live testing, Nagel's Algorithm is not blocking * partial packets on just connected sockets on modern OSes. As TLS setup * is performed as the fist action upon socket connection, the next * optimisation typically is not required. If any specific OS will * require this optimization, it could be enabled by allowing the next * lines for this specific OS. */ if (_MHD_ON != connection->sk_nodelay) MHD_connection_set_nodelay_state_ (connection, true); #endif ret = gnutls_handshake (connection->tls_session); if (ret == GNUTLS_E_SUCCESS) { /* set connection TLS state to enable HTTP processing */ connection->tls_state = MHD_TLS_CONN_CONNECTED; MHD_update_last_activity_ (connection); return true; } if ( (GNUTLS_E_AGAIN == ret) || (GNUTLS_E_INTERRUPTED == ret) ) { connection->tls_state = MHD_TLS_CONN_HANDSHAKING; /* handshake not done */ return false; } /* handshake failed */ connection->tls_state = MHD_TLS_CONN_TLS_FAILED; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Error: received handshake message out of context.\n")); #endif MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_WITH_ERROR); return false; } return true; } /** * Set connection callback function to be used through out * the processing of this secure connection. * * @param connection which callbacks should be modified */ void MHD_set_https_callbacks (struct MHD_Connection *connection) { connection->recv_cls = &recv_tls_adapter; } /** * Initiate shutdown of TLS layer of connection. * * @param connection to use * @return true if succeed, false otherwise. */ bool MHD_tls_connection_shutdown (struct MHD_Connection *connection) { if (MHD_TLS_CONN_WR_CLOSED > connection->tls_state) { const int res = gnutls_bye (connection->tls_session, GNUTLS_SHUT_WR); if (GNUTLS_E_SUCCESS == res) { connection->tls_state = MHD_TLS_CONN_WR_CLOSED; return true; } if ((GNUTLS_E_AGAIN == res) || (GNUTLS_E_INTERRUPTED == res)) { connection->tls_state = MHD_TLS_CONN_WR_CLOSING; return true; } else connection->tls_state = MHD_TLS_CONN_TLS_FAILED; } return false; } /* end of connection_https.c */ libmicrohttpd-1.0.10/src/microhttpd/sysfdsetsize.c0000644000175000017500000000450014760713574016002 /* This file is part of libmicrohttpd Copyright (C) 2015-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/sysfdsetsize.c * @brief Helper for obtaining FD_SETSIZE system default value * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #ifndef MHD_SYS_FD_SETSIZE_ #include "sysfdsetsize.h" #ifdef FD_SETSIZE /* FD_SETSIZE was defined before system headers. */ /* To get system value of FD_SETSIZE, undefine FD_SETSIZE here. */ #undef FD_SETSIZE #endif /* FD_SETSIZE */ #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS) #include #endif /* OS_VXWORKS */ #ifdef HAVE_SYS_SELECT_H #include #endif /* HAVE_SYS_SELECT_H */ #ifdef HAVE_SYS_TYPES_H #include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_SYS_TIME_H #include #endif /* HAVE_SYS_TIME_H */ #ifdef HAVE_TIME_H #include #endif /* HAVE_TIME_H */ #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_SYS_SOCKET_H #include #endif /* HAVE_SYS_SOCKET_H */ #if defined(_WIN32) && ! defined(__CYGWIN__) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif /* _WIN32 && !__CYGWIN__ */ #ifndef FD_SETSIZE #error FD_SETSIZE must be defined in system headers #endif /* !FD_SETSIZE */ /** * Get system default value of FD_SETSIZE * @return system default value of FD_SETSIZE */ unsigned int get_system_fdsetsize_value (void) { return (unsigned int) FD_SETSIZE; } #endif /* ! MHD_SYS_FD_SETSIZE_ */ libmicrohttpd-1.0.10/src/microhttpd/basicauth.c0000644000175000017500000002424414760713574015215 /* This file is part of libmicrohttpd Copyright (C) 2010, 2011, 2012 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file basicauth.c * @brief Implements HTTP basic authentication methods * @author Amr Ali * @author Matthieu Speder * @author Karlson2k (Evgeny Grin) */ #include "basicauth.h" #include "gen_auth.h" #include "platform.h" #include "mhd_limits.h" #include "internal.h" #include "mhd_compat.h" #include "mhd_str.h" /** * Get the username and password from the Basic Authorisation header * sent by the client * * @param connection the MHD connection structure * @return NULL if no valid Basic Authentication header is present in * current request, or * pointer to structure with username and password, which must be * freed by #MHD_free(). * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_BasicAuthInfo * MHD_basic_auth_get_username_password3 (struct MHD_Connection *connection) { const struct MHD_RqBAuth *params; size_t decoded_max_len; struct MHD_BasicAuthInfo *ret; params = MHD_get_rq_bauth_params_ (connection); if (NULL == params) return NULL; if ((NULL == params->token68.str) || (0 == params->token68.len)) return NULL; decoded_max_len = MHD_base64_max_dec_size_ (params->token68.len); ret = (struct MHD_BasicAuthInfo *) malloc (sizeof(struct MHD_BasicAuthInfo) + decoded_max_len + 1); if (NULL != ret) { size_t decoded_len; char *decoded; decoded = (char *) (ret + 1); decoded_len = MHD_base64_to_bin_n (params->token68.str, params->token68.len, decoded, decoded_max_len); mhd_assert (decoded_max_len >= decoded_len); if (0 != decoded_len) { size_t username_len; char *colon; colon = memchr (decoded, ':', decoded_len); if (NULL != colon) { size_t password_pos; size_t password_len; username_len = (size_t) (colon - decoded); password_pos = username_len + 1; password_len = decoded_len - password_pos; ret->password = decoded + password_pos; ret->password[password_len] = 0; /* Zero-terminate the string */ ret->password_len = password_len; } else { username_len = decoded_len; ret->password = NULL; ret->password_len = 0; } ret->username = decoded; ret->username[username_len] = 0; /* Zero-terminate the string */ ret->username_len = username_len; return ret; /* Success exit point */ } #ifdef HAVE_MESSAGES else MHD_DLOG (connection->daemon, _ ("Error decoding Basic Authorization authentication.\n")); #endif /* HAVE_MESSAGES */ free (ret); } #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Failed to allocate memory to process " \ "Basic Authorization authentication.\n")); } #endif /* HAVE_MESSAGES */ return NULL; /* Failure exit point */ } /** * Get the username and password from the basic authorization header sent by the client * * @param connection The MHD connection structure * @param[out] password a pointer for the password, free using #MHD_free(). * @return NULL if no username could be found, a pointer * to the username if found, free using #MHD_free(). * @deprecated use #MHD_basic_auth_get_username_password3() * @ingroup authentication */ _MHD_EXTERN char * MHD_basic_auth_get_username_password (struct MHD_Connection *connection, char **password) { struct MHD_BasicAuthInfo *info; info = MHD_basic_auth_get_username_password3 (connection); if (NULL == info) return NULL; /* For backward compatibility this function must return NULL if * no password is provided */ if (NULL != info->password) { char *username; username = malloc (info->username_len + 1); if (NULL != username) { memcpy (username, info->username, info->username_len + 1); mhd_assert (0 == username[info->username_len]); if (NULL != password) { *password = malloc (info->password_len + 1); if (NULL != *password) { memcpy (*password, info->password, info->password_len + 1); mhd_assert (0 == (*password)[info->password_len]); free (info); return username; /* Success exit point */ } #ifdef HAVE_MESSAGES else MHD_DLOG (connection->daemon, _ ("Failed to allocate memory.\n")); #endif /* HAVE_MESSAGES */ } else { free (info); return username; /* Success exit point */ } free (username); } #ifdef HAVE_MESSAGES else MHD_DLOG (connection->daemon, _ ("Failed to allocate memory.\n")); #endif /* HAVE_MESSAGES */ } free (info); if (NULL != password) *password = NULL; return NULL; /* Failure exit point */ } /** * Queues a response to request basic authentication from the client. * * The given response object is expected to include the payload for * the response; the "WWW-Authenticate" header will be added and the * response queued with the 'UNAUTHORIZED' status code. * * See RFC 7617#section-2 for details. * * The @a response is modified by this function. The modified response object * can be used to respond subsequent requests by #MHD_queue_response() * function with status code #MHD_HTTP_UNAUTHORIZED and must not be used again * with MHD_queue_basic_auth_required_response3() function. The response could * be destroyed right after call of this function. * * @param connection the MHD connection structure * @param realm the realm presented to the client * @param prefer_utf8 if not set to #MHD_NO, parameter'charset="UTF-8"' will * be added, indicating for client that UTF-8 encoding * is preferred * @param response the response object to modify and queue; the NULL * is tolerated * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00097704 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_basic_auth_required_response3 (struct MHD_Connection *connection, const char *realm, int prefer_utf8, struct MHD_Response *response) { static const char prefix[] = "Basic realm=\""; static const char suff_charset[] = "\", charset=\"UTF-8\""; static const size_t prefix_len = MHD_STATICSTR_LEN_ (prefix); static const size_t suff_simple_len = MHD_STATICSTR_LEN_ ("\""); static const size_t suff_charset_len = MHD_STATICSTR_LEN_ (suff_charset); enum MHD_Result ret; char *h_str; size_t h_maxlen; size_t suffix_len; size_t realm_len; size_t realm_quoted_len; size_t pos; if (NULL == response) return MHD_NO; suffix_len = (0 == prefer_utf8) ? suff_simple_len : suff_charset_len; realm_len = strlen (realm); h_maxlen = prefix_len + realm_len * 2 + suffix_len; h_str = (char *) malloc (h_maxlen + 1); if (NULL == h_str) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, "Failed to allocate memory for Basic Authentication header.\n"); #endif /* HAVE_MESSAGES */ return MHD_NO; } memcpy (h_str, prefix, prefix_len); pos = prefix_len; realm_quoted_len = MHD_str_quote (realm, realm_len, h_str + pos, h_maxlen - prefix_len - suffix_len); pos += realm_quoted_len; mhd_assert (pos + suffix_len <= h_maxlen); if (0 == prefer_utf8) { h_str[pos++] = '\"'; h_str[pos++] = 0; /* Zero terminate the result */ mhd_assert (pos <= h_maxlen + 1); } else { /* Copy with the final zero-termination */ mhd_assert (pos + suff_charset_len <= h_maxlen); memcpy (h_str + pos, suff_charset, suff_charset_len + 1); mhd_assert (0 == h_str[pos + suff_charset_len]); } ret = MHD_add_response_header (response, MHD_HTTP_HEADER_WWW_AUTHENTICATE, h_str); free (h_str); if (MHD_NO != ret) { ret = MHD_queue_response (connection, MHD_HTTP_UNAUTHORIZED, response); } else { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to add Basic Authentication header.\n")); #endif /* HAVE_MESSAGES */ } return ret; } /** * Queues a response to request basic authentication from the client * The given response object is expected to include the payload for * the response; the "WWW-Authenticate" header will be added and the * response queued with the 'UNAUTHORIZED' status code. * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param response response object to modify and queue; the NULL is tolerated * @return #MHD_YES on success, #MHD_NO otherwise * @deprecated use MHD_queue_basic_auth_required_response3() * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_basic_auth_fail_response (struct MHD_Connection *connection, const char *realm, struct MHD_Response *response) { return MHD_queue_basic_auth_required_response3 (connection, realm, MHD_NO, response); } /* end of basicauth.c */ libmicrohttpd-1.0.10/src/microhttpd/test_client_put_stop.c0000664000175000017500000021014115232103064017475 /* This file is part of libmicrohttpd Copyright (C) 2021-2024 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_client_put_stop.c * @brief Testcase for handling of clients aborts * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #ifdef HAVE_SYSCTL #ifdef HAVE_SYS_TYPES_H #include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_SYS_SYSCTL_H #include #endif /* HAVE_SYS_SYSCTL_H */ #ifdef HAVE_SYS_SOCKET_H #include #endif /* HAVE_SYS_SOCKET_H */ #ifdef HAVE_NETINET_IN_SYSTM_H #include #endif /* HAVE_NETINET_IN_SYSTM_H */ #ifdef HAVE_NETINET_IN_H #include #endif /* HAVE_NETINET_IN_H */ #ifdef HAVE_NETINET_IP_H #include #endif /* HAVE_NETINET_IP_H */ #ifdef HAVE_NETINET_IP_ICMP_H #include #endif /* HAVE_NETINET_IP_ICMP_H */ #ifdef HAVE_NETINET_ICMP_VAR_H #include #endif /* HAVE_NETINET_ICMP_VAR_H */ #endif /* HAVE_SYSCTL */ #include #include "mhd_sockets.h" /* only macros used */ #include "test_helpers.h" #include "mhd_assert.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 /* Time in ms to wait for final packets to be delivered */ #define FINAL_PACKETS_MS 20 #define EXPECTED_URI_BASE_PATH "/a" #define REQ_HOST "localhost" #define REQ_METHOD "PUT" #define REQ_BODY "Some content data." #define REQ_LINE_END "\r\n" /* Mandatory request headers */ #define REQ_HEADER_HOST_NAME "Host" #define REQ_HEADER_HOST_VALUE REQ_HOST #define REQ_HEADER_HOST \ REQ_HEADER_HOST_NAME ": " REQ_HEADER_HOST_VALUE REQ_LINE_END #define REQ_HEADER_UA_NAME "User-Agent" #define REQ_HEADER_UA_VALUE "dummyclient/0.9" #define REQ_HEADER_UA REQ_HEADER_UA_NAME ": " REQ_HEADER_UA_VALUE REQ_LINE_END /* Optional request headers */ #define REQ_HEADER_CT_NAME "Content-Type" #define REQ_HEADER_CT_VALUE "text/plain" #define REQ_HEADER_CT REQ_HEADER_CT_NAME ": " REQ_HEADER_CT_VALUE REQ_LINE_END #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } /* Global generic functions */ void _MHD_sleep (uint32_t ms); /** * Pause execution for specified number of milliseconds. * @param ms the number of milliseconds to sleep */ void _MHD_sleep (uint32_t ms) { #if defined(_WIN32) Sleep (ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp = {ms / 1000, (ms % 1000) * 1000000}; struct timespec rmn; int num_retries = 0; while (0 != nanosleep (&slp, &rmn)) { if (EINTR != errno) externalErrorExit (); if (num_retries++ > 8) break; slp = rmn; } #elif defined(HAVE_USLEEP) uint64_t us = ms * 1000; do { uint64_t this_sleep; if (999999 < us) this_sleep = 999999; else this_sleep = us; /* Ignore return value as it could be void */ usleep (this_sleep); us -= this_sleep; } while (us > 0); #else externalErrorExitDesc ("No sleep function available on this system"); #endif } /* Global parameters */ static int verbose; /**< Be verbose */ static int oneone; /**< If false use HTTP/1.0 for requests*/ static uint16_t global_port; /**< MHD daemons listen port number */ static int use_shutdown; /**< Use shutdown at client side */ static int use_close; /**< Use socket close at client side */ static int use_hard_close; /**< Use socket close with RST at client side */ static int use_stress_os; /**< Stress OS by RST before getting ACKs for sent packets */ static int by_step; /**< Send request byte-by-byte */ static int upl_chunked; /**< Use chunked encoding for request body */ static unsigned int rate_limiter; /**< Maximum number of checks per second */ static void test_global_init (void) { rate_limiter = 0; if (use_hard_close) { #ifdef HAVE_SYSCTLBYNAME if (1) { int blck_hl; size_t blck_hl_size = sizeof (blck_hl); if (0 == sysctlbyname ("net.inet.tcp.blackhole", &blck_hl, &blck_hl_size, NULL, 0)) { if (2 <= blck_hl) { fprintf (stderr, "'sysctl net.inet.tcp.blackhole = %d', test is " "unreliable with this system setting, skipping.\n", blck_hl); exit (77); } } else { if (ENOENT != errno) externalErrorExitDesc ("Cannot get 'net.inet.tcp.blackhole' value"); } } #endif #if defined(HAVE_SYSCTL) && defined(HAVE_DECL_CTL_NET) && \ defined(HAVE_DECL_PF_INET) && defined(HAVE_DECL_IPPROTO_ICMP) && \ defined(HAVE_DECL_ICMPCTL_ICMPLIM) /* Macros may have zero values */ #if HAVE_DECL_CTL_NET && HAVE_DECL_PF_INET && HAVE_DECL_IPPROTO_ICMP && \ HAVE_DECL_ICMPCTL_ICMPLIM if (1) { int mib[4]; int limit; size_t limit_size = sizeof(limit); mib[0] = CTL_NET; mib[1] = PF_INET; mib[2] = IPPROTO_ICMP; mib[3] = ICMPCTL_ICMPLIM; if (0 != sysctl (mib, 4, &limit, &limit_size, NULL, 0)) { if (ENOENT == errno) limit = 0; /* No such parameter (new Darwin versions) */ else externalErrorExitDesc ("Cannot get RST rate limit value"); } else if (sizeof(limit) != limit_size) externalErrorExitDesc ("Cannot get RST rate limit value"); if (limit > 0) { #ifndef _MHD_HEAVY_TESTS fprintf (stderr, "This system has limits on number of RST packets" " per second (%d).\nThis test will be used only if configured " "with '--enable-heavy-test'.\n", limit); exit (77); #else /* _MHD_HEAVY_TESTS */ int test_limit; /**< Maximum number of checks per second */ if (use_stress_os) { fprintf (stderr, "This system has limits on number of RST packet" " per second (%d).\n'_stress_os' is not possible.\n", limit); exit (77); } test_limit = limit - limit / 10; /* Add some space to not hit the limiter */ test_limit /= 4; /* Assume that all four tests with 'hard_close' run in parallel */ test_limit -= 5; /* Add some more space to not hit the limiter */ test_limit /= 3; /* Use only one third of available limit */ if (test_limit <= 0) { fprintf (stderr, "System limit for 'net.inet.icmp.icmplim' is " "too strict for this test (value: %d).\n", limit); exit (77); } if (verbose) { printf ("Limiting number of checks to %d checks/second.\n", test_limit); fflush (stdout); } rate_limiter = (unsigned int) test_limit; #if ! defined(HAVE_USLEEP) && ! defined(HAVE_NANOSLEEP) && ! defined(_WIN32) fprintf (stderr, "Sleep function is required for this test, " "but not available on this system.\n"); exit (77); #endif #endif /* _MHD_HEAVY_TESTS */ } } #endif /* HAVE_DECL_CTL_NET && HAVE_DECL_PF_INET && HAVE_DECL_IPPROTO_ICMP && \ HAVE_DECL_ICMPCTL_ICMPLIM */ #endif /* HAVE_SYSCTL && HAVE_DECL_CTL_NET && HAVE_DECL_PF_INET && HAVE_DECL_IPPROTO_ICMP && HAVE_DECL_ICMPCTL_ICMPLIM */ } if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE)) { #if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) externalErrorExitDesc ("Error suppressing SIGPIPE signal"); #else /* ! HAVE_SIGNAL_H || ! SIGPIPE */ fprintf (stderr, "Cannot suppress SIGPIPE signal.\n"); /* exit (77); */ #endif } } static void test_global_cleanup (void) { } /** * Change socket to blocking. * * @param fd the socket to manipulate */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("Cannot make socket non-blocking"); if ((flags & ~O_NONBLOCK) != flags) { if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) externalErrorExitDesc ("Cannot make socket non-blocking"); } #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("Cannot make socket non-blocking"); #endif /* MHD_WINSOCK_SOCKETS */ } /** * Change socket to non-blocking. * * @param fd the socket to manipulate */ static void make_nonblocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("Cannot make socket non-blocking"); if ((flags | O_NONBLOCK) != flags) { if (-1 == fcntl (fd, F_SETFL, flags | O_NONBLOCK)) externalErrorExitDesc ("Cannot make socket non-blocking"); } #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 1; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("Cannot make socket non-blocking"); #endif /* MHD_WINSOCK_SOCKETS */ } /* DumbClient API */ struct _MHD_dumbClient * _MHD_dumbClient_create (uint16_t port, const char *method, const char *url, const char *add_headers, const uint8_t *req_body, size_t req_body_size, int chunked); void _MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt, size_t step_size, size_t max_total_send); void _MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt); int _MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt); /** * Process the client data with send()/recv() as needed. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process (struct _MHD_dumbClient *clnt); void _MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt, MHD_socket *maxsckt, fd_set *rs, fd_set *ws, fd_set *es); /** * Process the client data with send()/recv() as needed based on * information in fd_sets. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt, fd_set *rs, fd_set *ws, fd_set *es); /** * Perform full request. * @param clnt the client to run * @return zero if client finished processing the request, * non-zero if timeout is reached. */ int _MHD_dumbClient_perform (struct _MHD_dumbClient *clnt); /** * Close the client and free internally allocated resources. * @param clnt the client to close */ void _MHD_dumbClient_close (struct _MHD_dumbClient *clnt); /* DumbClient implementation */ enum _MHD_clientStage { DUMB_CLIENT_INIT = 0, DUMB_CLIENT_CONNECTING, DUMB_CLIENT_CONNECTED, DUMB_CLIENT_REQ_SENDING, DUMB_CLIENT_REQ_SENT, DUMB_CLIENT_HEADER_RECVEIVING, DUMB_CLIENT_HEADER_RECVEIVED, DUMB_CLIENT_BODY_RECVEIVING, DUMB_CLIENT_BODY_RECVEIVED, DUMB_CLIENT_FINISHING, DUMB_CLIENT_FINISHED }; struct _MHD_dumbClient { MHD_socket sckt; /**< the socket to communicate */ int sckt_nonblock; /**< non-zero if socket is non-blocking */ uint16_t port; /**< the port to connect to */ const char *send_buf; /**< the buffer for the request, malloced */ void *buf; /**< the buffer location */ size_t req_size; /**< the size of the request, including header */ size_t send_off; /**< the number of bytes already sent */ enum _MHD_clientStage stage; /* the test-specific variables */ size_t single_send_size; /**< the maximum number of bytes to be sent by single send() */ size_t send_size_limit; /**< the total number of send bytes limit */ }; struct _MHD_dumbClient * _MHD_dumbClient_create (uint16_t port, const char *method, const char *url, const char *add_headers, const uint8_t *req_body, size_t req_body_size, int chunked) { struct _MHD_dumbClient *clnt; size_t method_size; size_t url_size; size_t add_hdrs_size; size_t buf_alloc_size; char *send_buf; mhd_assert (0 != port); mhd_assert (NULL != req_body || 0 == req_body_size); mhd_assert (0 == req_body_size || NULL != req_body); clnt = (struct _MHD_dumbClient *) malloc (sizeof(struct _MHD_dumbClient)); if (NULL == clnt) externalErrorExit (); memset (clnt, 0, sizeof(struct _MHD_dumbClient)); clnt->sckt = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == clnt->sckt) externalErrorExitDesc ("Cannot create the client socket"); #ifdef MHD_socket_nosignal_ if (! MHD_socket_nosignal_ (clnt->sckt)) externalErrorExitDesc ("Cannot suppress SIGPIPE on the client socket"); #endif /* MHD_socket_nosignal_ */ clnt->sckt_nonblock = 0; if (clnt->sckt_nonblock) make_nonblocking (clnt->sckt); else make_blocking (clnt->sckt); if (1) { /* Always set TCP NODELAY */ const MHD_SCKT_OPT_BOOL_ on_val = 1; if (0 != setsockopt (clnt->sckt, IPPROTO_TCP, TCP_NODELAY, (const void *) &on_val, sizeof (on_val))) externalErrorExitDesc ("Cannot set TCP_NODELAY option"); } clnt->port = port; if (NULL != method) method_size = strlen (method); else { method = MHD_HTTP_METHOD_GET; method_size = MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_GET); } mhd_assert (0 != method_size); if (NULL != url) url_size = strlen (url); else { url = "/"; url_size = 1; } mhd_assert (0 != url_size); add_hdrs_size = (NULL == add_headers) ? 0 : strlen (add_headers); buf_alloc_size = 1024 + method_size + url_size + add_hdrs_size + req_body_size; send_buf = (char *) malloc (buf_alloc_size); if (NULL == send_buf) externalErrorExit (); clnt->req_size = 0; /* Form the request line */ memcpy (send_buf + clnt->req_size, method, method_size); clnt->req_size += method_size; send_buf[clnt->req_size++] = ' '; memcpy (send_buf + clnt->req_size, url, url_size); clnt->req_size += url_size; send_buf[clnt->req_size++] = ' '; memcpy (send_buf + clnt->req_size, MHD_HTTP_VERSION_1_1, MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1)); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1); send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; /* Form the header */ memcpy (send_buf + clnt->req_size, REQ_HEADER_HOST, MHD_STATICSTR_LEN_ (REQ_HEADER_HOST)); clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_HOST); memcpy (send_buf + clnt->req_size, REQ_HEADER_UA, MHD_STATICSTR_LEN_ (REQ_HEADER_UA)); clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_UA); if ((NULL != req_body) || chunked) { if (! chunked) { int prn_size; memcpy (send_buf + clnt->req_size, MHD_HTTP_HEADER_CONTENT_LENGTH ": ", MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ")); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "); prn_size = snprintf (send_buf + clnt->req_size, (buf_alloc_size - clnt->req_size), "%u", (unsigned int) req_body_size); if (0 >= prn_size) externalErrorExit (); if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size) externalErrorExit (); clnt->req_size += (unsigned int) prn_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } else { memcpy (send_buf + clnt->req_size, MHD_HTTP_HEADER_TRANSFER_ENCODING ": chunked\r\n", MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \ ": chunked\r\n")); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \ ": chunked\r\n"); } } if (0 != add_hdrs_size) { memcpy (send_buf + clnt->req_size, add_headers, add_hdrs_size); clnt->req_size += add_hdrs_size; } /* Terminate header */ send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; /* Add body (if any) */ if (! chunked) { if (0 != req_body_size) { memcpy (send_buf + clnt->req_size, req_body, req_body_size); clnt->req_size += req_body_size; } } else { if (0 != req_body_size) { int prn_size; prn_size = snprintf (send_buf + clnt->req_size, (buf_alloc_size - clnt->req_size), "%x", (unsigned int) req_body_size); if (0 >= prn_size) externalErrorExit (); if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size) externalErrorExit (); clnt->req_size += (unsigned int) prn_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; memcpy (send_buf + clnt->req_size, req_body, req_body_size); clnt->req_size += req_body_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } send_buf[clnt->req_size++] = '0'; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } mhd_assert (clnt->req_size < buf_alloc_size); clnt->buf = send_buf; clnt->send_buf = send_buf; return clnt; } void _MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt, size_t step_size, size_t max_total_send) { clnt->single_send_size = step_size; clnt->send_size_limit = max_total_send; } /* internal */ static void _MHD_dumbClient_connect_init (struct _MHD_dumbClient *clnt) { struct sockaddr_in sa; mhd_assert (DUMB_CLIENT_INIT == clnt->stage); sa.sin_family = AF_INET; sa.sin_port = htons ((uint16_t) clnt->port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != connect (clnt->sckt, (struct sockaddr *) &sa, sizeof(sa))) { const int err = MHD_socket_get_error_ (); if ( (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINPROGRESS_)) || (MHD_SCKT_ERR_IS_EAGAIN_ (err))) clnt->stage = DUMB_CLIENT_CONNECTING; else externalErrorExitDesc ("Cannot 'connect()' the client socket"); } else clnt->stage = DUMB_CLIENT_CONNECTED; } void _MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt) { mhd_assert (DUMB_CLIENT_INIT == clnt->stage); _MHD_dumbClient_connect_init (clnt); } /* internal */ static void _MHD_dumbClient_connect_finish (struct _MHD_dumbClient *clnt) { int err = 0; socklen_t err_size = sizeof(err); mhd_assert (DUMB_CLIENT_CONNECTING == clnt->stage); if (0 != getsockopt (clnt->sckt, SOL_SOCKET, SO_ERROR, (void *) &err, &err_size)) externalErrorExitDesc ("'getsockopt()' call failed"); if (0 != err) externalErrorExitDesc ("Socket connect() failed"); clnt->stage = DUMB_CLIENT_CONNECTED; } /* internal */ static void _MHD_dumbClient_send_req (struct _MHD_dumbClient *clnt) { size_t send_size; ssize_t res; mhd_assert (DUMB_CLIENT_CONNECTED <= clnt->stage); mhd_assert (DUMB_CLIENT_REQ_SENT > clnt->stage); mhd_assert (clnt->req_size > clnt->send_off); send_size = (((0 != clnt->send_size_limit) && (clnt->req_size > clnt->send_size_limit)) ? clnt->send_size_limit : clnt->req_size) - clnt->send_off; mhd_assert (0 != send_size); if ((0 != clnt->single_send_size) && (clnt->single_send_size < send_size)) send_size = clnt->single_send_size; res = MHD_send_ (clnt->sckt, clnt->send_buf + clnt->send_off, send_size); if (res < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) return; if (MHD_SCKT_ERR_IS_EINTR_ (err)) return; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) mhdErrorExitDesc ("The connection was aborted by MHD"); if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_)) mhdErrorExitDesc ("The connection was shut down on MHD side"); externalErrorExitDesc ("Unexpected network error"); } clnt->send_off += (size_t) res; mhd_assert (clnt->send_off <= clnt->req_size); mhd_assert (clnt->send_off <= clnt->send_size_limit || \ 0 == clnt->send_size_limit); if (clnt->req_size == clnt->send_off) clnt->stage = DUMB_CLIENT_REQ_SENT; if ((0 != clnt->send_size_limit) && (clnt->send_size_limit == clnt->send_off)) clnt->stage = DUMB_CLIENT_FINISHING; } /* internal */ _MHD_NORETURN /* Declared as 'noreturn' until it is implemented */ static void _MHD_dumbClient_recv_reply (struct _MHD_dumbClient *clnt) { (void) clnt; externalErrorExitDesc ("Not implemented for this test"); } int _MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt) { return DUMB_CLIENT_REQ_SENT <= clnt->stage; } /* internal */ static void _MHD_dumbClient_socket_close (struct _MHD_dumbClient *clnt) { if (MHD_INVALID_SOCKET != clnt->sckt) { if (use_hard_close) { #ifdef SO_LINGER static const struct linger hard_close = {1, 0}; mhd_assert (0 == hard_close.l_linger); if (0 != setsockopt (clnt->sckt, SOL_SOCKET, SO_LINGER, (const void *) &hard_close, sizeof (hard_close))) #endif /* SO_LINGER */ externalErrorExitDesc ("Failed to set SO_LINGER option"); } if (! MHD_socket_close_ (clnt->sckt)) externalErrorExitDesc ("Unexpected error while closing " \ "the client socket"); clnt->sckt = MHD_INVALID_SOCKET; } } /* internal */ static void _MHD_dumbClient_finalize (struct _MHD_dumbClient *clnt) { if (MHD_INVALID_SOCKET != clnt->sckt) { if (use_shutdown) { if (0 != shutdown (clnt->sckt, SHUT_WR)) { const int err = MHD_socket_get_error_ (); if (! MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_) && ! MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) mhdErrorExitDesc ("Unexpected error when shutting down " \ "the client socket"); } } else if (use_close) { _MHD_dumbClient_socket_close (clnt); } else mhd_assert (0); } clnt->stage = DUMB_CLIENT_FINISHED; } /* internal */ static int _MHD_dumbClient_needs_send (const struct _MHD_dumbClient *clnt) { return ((DUMB_CLIENT_CONNECTING <= clnt->stage) && (DUMB_CLIENT_REQ_SENT > clnt->stage)) || (DUMB_CLIENT_FINISHING == clnt->stage); } /* internal */ static int _MHD_dumbClient_needs_recv (const struct _MHD_dumbClient *clnt) { return (DUMB_CLIENT_HEADER_RECVEIVING <= clnt->stage) && (DUMB_CLIENT_BODY_RECVEIVED > clnt->stage); } /* internal */ /** * Check whether the client needs unconditionally process the data. * @param clnt the client to check * @return non-zero if client needs unconditionally process the data, * zero otherwise. */ static int _MHD_dumbClient_needs_process (const struct _MHD_dumbClient *clnt) { switch (clnt->stage) { case DUMB_CLIENT_INIT: case DUMB_CLIENT_REQ_SENT: case DUMB_CLIENT_HEADER_RECVEIVED: case DUMB_CLIENT_BODY_RECVEIVED: case DUMB_CLIENT_FINISHED: return ! 0; case DUMB_CLIENT_CONNECTING: case DUMB_CLIENT_CONNECTED: case DUMB_CLIENT_REQ_SENDING: case DUMB_CLIENT_HEADER_RECVEIVING: case DUMB_CLIENT_BODY_RECVEIVING: case DUMB_CLIENT_FINISHING: default: break; } return 0; } /** * Process the client data with send()/recv() as needed. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process (struct _MHD_dumbClient *clnt) { do { switch (clnt->stage) { case DUMB_CLIENT_INIT: _MHD_dumbClient_connect_init (clnt); break; case DUMB_CLIENT_CONNECTING: _MHD_dumbClient_connect_finish (clnt); break; case DUMB_CLIENT_CONNECTED: case DUMB_CLIENT_REQ_SENDING: _MHD_dumbClient_send_req (clnt); break; case DUMB_CLIENT_REQ_SENT: mhd_assert (0); clnt->stage = DUMB_CLIENT_HEADER_RECVEIVING; break; case DUMB_CLIENT_HEADER_RECVEIVING: _MHD_dumbClient_recv_reply (clnt); break; case DUMB_CLIENT_HEADER_RECVEIVED: clnt->stage = DUMB_CLIENT_BODY_RECVEIVING; break; case DUMB_CLIENT_BODY_RECVEIVING: _MHD_dumbClient_recv_reply (clnt); break; case DUMB_CLIENT_BODY_RECVEIVED: clnt->stage = DUMB_CLIENT_FINISHING; break; case DUMB_CLIENT_FINISHING: _MHD_dumbClient_finalize (clnt); break; case DUMB_CLIENT_FINISHED: return ! 0; default: mhd_assert (0); mhdErrorExit (); } } while (_MHD_dumbClient_needs_process (clnt)); return DUMB_CLIENT_FINISHED == clnt->stage; } void _MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt, MHD_socket *maxsckt, fd_set *rs, fd_set *ws, fd_set *es) { mhd_assert (NULL != rs); mhd_assert (NULL != ws); mhd_assert (NULL != es); if (DUMB_CLIENT_FINISHED > clnt->stage) { if (MHD_INVALID_SOCKET != clnt->sckt) { if ( (MHD_INVALID_SOCKET == *maxsckt) || (clnt->sckt > *maxsckt) ) *maxsckt = clnt->sckt; if (_MHD_dumbClient_needs_recv (clnt)) FD_SET (clnt->sckt, rs); if (_MHD_dumbClient_needs_send (clnt)) FD_SET (clnt->sckt, ws); FD_SET (clnt->sckt, es); } } } /** * Process the client data with send()/recv() as needed based on * information in fd_sets. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt, fd_set *rs, fd_set *ws, fd_set *es) { if (_MHD_dumbClient_needs_process (clnt)) return _MHD_dumbClient_process (clnt); else if (MHD_INVALID_SOCKET != clnt->sckt) { if (_MHD_dumbClient_needs_recv (clnt) && FD_ISSET (clnt->sckt, rs)) return _MHD_dumbClient_process (clnt); else if (_MHD_dumbClient_needs_send (clnt) && FD_ISSET (clnt->sckt, ws)) return _MHD_dumbClient_process (clnt); else if (FD_ISSET (clnt->sckt, es)) return _MHD_dumbClient_process (clnt); } return DUMB_CLIENT_FINISHED == clnt->stage; } /** * Perform full request. * @param clnt the client to run * @return zero if client finished processing the request, * non-zero if timeout is reached. */ int _MHD_dumbClient_perform (struct _MHD_dumbClient *clnt) { time_t start; time_t now; start = time (NULL); now = start; do { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; struct timeval tv; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (! _MHD_dumbClient_needs_process (clnt)) { maxMhdSk = MHD_INVALID_SOCKET; _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es); mhd_assert (now >= start); #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (TIMEOUTS_VAL * 2 - (now - start) + 1); #else /* Native W32 */ tv.tv_sec = (long) (TIMEOUTS_VAL * 2 - (now - start) + 1); #endif /* Native W32 */ tv.tv_usec = 250 * 1000; if (-1 == select ((int) maxMhdSk + 1, &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else /* ! MHD_POSIX_SOCKETS */ mhd_assert ((0 != rs.fd_count) || (0 != ws.fd_count) || \ (0 != es.fd_count)); externalErrorExitDesc ("Unexpected select() error"); Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif /* ! MHD_POSIX_SOCKETS */ continue; } if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es)) return 0; } /* Use double timeout value here as MHD must catch timeout situations * in this test. Timeout in client as a last resort. */ } while ((now = time (NULL)) - start <= (TIMEOUTS_VAL * 2)); return 1; } /** * Close the client and free internally allocated resources. * @param clnt the client to close */ void _MHD_dumbClient_close (struct _MHD_dumbClient *clnt) { if (DUMB_CLIENT_FINISHED != clnt->stage) _MHD_dumbClient_finalize (clnt); _MHD_dumbClient_socket_close (clnt); if (NULL != clnt->send_buf) { mhd_assert (clnt->send_buf == clnt->buf); free (clnt->buf); clnt->buf = NULL; clnt->send_buf = NULL; } free (clnt); } struct sckt_notif_cb_param { volatile unsigned int num_started; volatile unsigned int num_finished; }; static void socket_cb (void *cls, struct MHD_Connection *c, void **socket_context, enum MHD_ConnectionNotificationCode toe) { struct sckt_notif_cb_param *param = (struct sckt_notif_cb_param *) cls; if (NULL == socket_context) mhdErrorExitDesc ("'socket_context' pointer is NULL"); if (NULL == c) mhdErrorExitDesc ("'connection' pointer is NULL"); if (NULL == param) mhdErrorExitDesc ("'cls' pointer is NULL"); if (MHD_CONNECTION_NOTIFY_STARTED == toe) param->num_started++; else if (MHD_CONNECTION_NOTIFY_CLOSED == toe) param->num_finished++; else mhdErrorExitDesc ("Unknown 'toe' value"); } struct term_notif_cb_param { volatile int term_reason; volatile unsigned int num_called; }; static void term_cb (void *cls, struct MHD_Connection *c, void **req_cls, enum MHD_RequestTerminationCode term_code) { struct term_notif_cb_param *param = (struct term_notif_cb_param *) cls; if (NULL == req_cls) mhdErrorExitDesc ("'req_cls' pointer is NULL"); if (NULL == c) mhdErrorExitDesc ("'connection' pointer is NULL"); if (NULL == param) mhdErrorExitDesc ("'cls' pointer is NULL"); param->term_reason = (int) term_code; param->num_called++; } static const char * term_reason_str (enum MHD_RequestTerminationCode term_code) { switch ((int) term_code) { case MHD_REQUEST_TERMINATED_COMPLETED_OK: return "COMPLETED_OK"; case MHD_REQUEST_TERMINATED_WITH_ERROR: return "TERMINATED_WITH_ERROR"; case MHD_REQUEST_TERMINATED_TIMEOUT_REACHED: return "TIMEOUT_REACHED"; case MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN: return "DAEMON_SHUTDOWN"; case MHD_REQUEST_TERMINATED_READ_ERROR: return "READ_ERROR"; case MHD_REQUEST_TERMINATED_CLIENT_ABORT: return "CLIENT_ABORT"; case -1: return "(not called)"; default: break; } return "(unknown code)"; } struct check_uri_cls { const char *volatile uri; volatile unsigned int cb_called; }; static void * check_uri_cb (void *cls, const char *uri, struct MHD_Connection *con) { struct check_uri_cls *param = (struct check_uri_cls *) cls; if (NULL == con) mhdErrorExitDesc ("The 'con' pointer is NULL"); param->cb_called++; if (0 != strcmp (param->uri, uri)) { fprintf (stderr, "Wrong URI: '%s'\n", uri); mhdErrorExit (); } return NULL; } struct mhd_header_checker_param { int found_header_host; /**< the number of 'Host' headers */ int found_header_ua; /**< the number of 'User-Agent' headers */ int found_header_ct; /**< the number of 'Content-Type' headers */ int found_header_cl; /**< the number of 'Content-Length' headers */ int found_header_te; /**< the number of 'Transfer-Encoding' headers */ }; static enum MHD_Result headerCheckerInterator (void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct mhd_header_checker_param *const param = (struct mhd_header_checker_param *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); if (MHD_HEADER_KIND != kind) return MHD_YES; /* Continue iteration */ if (0 == key_size) mhdErrorExitDesc ("Zero key length"); if ((strlen (REQ_HEADER_HOST_NAME) == key_size) && (0 == memcmp (key, REQ_HEADER_HOST_NAME, key_size))) { if ((strlen (REQ_HEADER_HOST_VALUE) == value_size) && (0 == memcmp (value, REQ_HEADER_HOST_VALUE, value_size))) param->found_header_host++; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, REQ_HEADER_HOST_VALUE); } else if ((strlen (REQ_HEADER_UA_NAME) == key_size) && (0 == memcmp (key, REQ_HEADER_UA_NAME, key_size))) { if ((strlen (REQ_HEADER_UA_VALUE) == value_size) && (0 == memcmp (value, REQ_HEADER_UA_VALUE, value_size))) param->found_header_ua++; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, REQ_HEADER_UA_VALUE); } else if ((strlen (REQ_HEADER_CT_NAME) == key_size) && (0 == memcmp (key, REQ_HEADER_CT_NAME, key_size))) { if ((strlen (REQ_HEADER_CT_VALUE) == value_size) && (0 == memcmp (value, REQ_HEADER_CT_VALUE, value_size))) param->found_header_ct++; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, REQ_HEADER_CT_VALUE); } else if ((strlen (MHD_HTTP_HEADER_CONTENT_LENGTH) == key_size) && (0 == memcmp (key, MHD_HTTP_HEADER_CONTENT_LENGTH, key_size))) { /* do not check value of the header here for simplicity */ param->found_header_cl++; } else if ((strlen (MHD_HTTP_HEADER_TRANSFER_ENCODING) == key_size) && (0 == memcmp (key, MHD_HTTP_HEADER_TRANSFER_ENCODING, key_size))) { if ((strlen ("chunked") == value_size) && (0 == memcmp (value, "chunked", value_size))) param->found_header_te++; else fprintf (stderr, "Unexpected header value: '%.*s', expected: '%s'\n", (int) value_size, value, "chunked"); } return MHD_YES; } struct ahc_cls_type { const char *volatile rp_data; volatile size_t rp_data_size; const char *volatile rq_method; const char *volatile rq_url; const char *volatile req_body; volatile unsigned int cb_called; /* Non-zero indicates that callback was called at least one time */ size_t req_body_size; /**< The number of bytes in @a req_body */ size_t req_body_uploaded; /* Updated by callback */ }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; enum MHD_Result ret; struct mhd_header_checker_param header_check_param; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); param->cb_called++; if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) { const char *const upload_body = param->req_body; if (NULL == upload_data) mhdErrorExitDesc ("'upload_data' is NULL while " \ "'*upload_data_size' value is not zero"); if (NULL == upload_body) mhdErrorExitDesc ("'*upload_data_size' value is not zero " \ "while no request body is expected"); if (param->req_body_uploaded + *upload_data_size > param->req_body_size) { fprintf (stderr, "Too large upload body received. Got %u, expected %u", (unsigned int) (param->req_body_uploaded + *upload_data_size), (unsigned int) param->req_body_size); mhdErrorExit (); } if (0 != memcmp (upload_data, upload_body + param->req_body_uploaded, *upload_data_size)) { fprintf (stderr, "Unexpected request body at offset %u: " \ "'%.*s', expected: '%.*s'\n", (unsigned int) param->req_body_uploaded, (int) *upload_data_size, upload_data, (int) *upload_data_size, upload_body + param->req_body_uploaded); mhdErrorExit (); } param->req_body_uploaded += *upload_data_size; *upload_data_size = 0; } if (&marker != *req_cls) { /* The first call of the callback for this connection */ mhd_assert (NULL == upload_data); param->req_body_uploaded = 0; *req_cls = ▮ return MHD_YES; } memset (&header_check_param, 0, sizeof(header_check_param)); if (1 > MHD_get_connection_values_n (connection, MHD_HEADER_KIND, &headerCheckerInterator, &header_check_param)) mhdErrorExitDesc ("Wrong number of headers in the request"); if (1 != header_check_param.found_header_host) mhdErrorExitDesc ("'Host' header has not been detected in request"); if (1 != header_check_param.found_header_ua) mhdErrorExitDesc ("'User-Agent' header has not been detected in request"); if (1 != header_check_param.found_header_ct) mhdErrorExitDesc ("'Content-Type' header has not been detected in request"); if (! upl_chunked && (1 != header_check_param.found_header_cl)) mhdErrorExitDesc ("'Content-Length' header has not been detected " "in request"); if (upl_chunked && (1 != header_check_param.found_header_te)) mhdErrorExitDesc ("'Transfer-Encoding' header has not been detected " "in request"); if (NULL != upload_data) return MHD_YES; /* Full request has not been received so far */ #if 0 /* Code unused in this test */ struct MHD_Response *response; response = MHD_create_response_from_buffer (param->rp_data_size, (void *) param->rp_data, MHD_RESPMEM_MUST_COPY); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); #else if (NULL == upload_data) mhdErrorExitDesc ("Full request received, " \ "while incomplete request expected"); ret = MHD_NO; #endif return ret; } struct simpleQueryParams { /* Destination path for HTTP query */ const char *queryPath; /* Custom query method, NULL for default */ const char *method; /* Destination port for HTTP query */ uint16_t queryPort; /* Additional request headers, static */ const char *headers; /* NULL for request without body */ const uint8_t *req_body; size_t req_body_size; /* Non-zero to use chunked encoding for request body */ int chunked; /* Max size of data for single 'send()' call */ size_t step_size; /* Limit for total amount of sent data */ size_t total_send_max; /* HTTP query result error flag */ volatile int queryError; /* Response HTTP code, zero if no response */ volatile int responseCode; }; /* returns non-zero if timed-out */ static int performQueryExternal (struct MHD_Daemon *d, struct _MHD_dumbClient *clnt) { time_t start; struct timeval tv; int ret; const union MHD_DaemonInfo *di; MHD_socket lstn_sk; int client_accepted; int full_req_recieved; int full_req_sent; int some_data_recieved; di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (NULL == di) mhdErrorExitDesc ("Cannot get lister socket"); lstn_sk = di->listen_fd; ret = 1; /* will be replaced with real result */ client_accepted = 0; _MHD_dumbClient_start_connect (clnt); full_req_recieved = 0; some_data_recieved = 0; start = time (NULL); do { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int num_ready; int do_client; /**< Process data in client */ maxMhdSk = MHD_INVALID_SOCKET; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL == clnt) { /* client has finished, check whether MHD is still * processing any connections */ full_req_sent = 1; do_client = 0; if (client_accepted && (0 > MHD_get_timeout64s (d))) { ret = 0; break; /* MHD finished as well */ } } else { full_req_sent = _MHD_dumbClient_is_req_sent (clnt); if (! full_req_sent) do_client = 1; /* Request hasn't been sent yet, send the data */ else { /* All request data has been sent. * Client will close the socket as the next step. */ if (full_req_recieved) { /* All data has been received by the MHD */ do_client = 1; /* Close the client socket */ } else if (some_data_recieved && (! use_hard_close || ((0 == rate_limiter) && use_stress_os))) { /* No RST rate limiter or no "hard close", no need to avoid extra RST * and at least something was received by the MHD */ /* In case of 'hard close' this can stress the OS, especially * if 'by_step' is enabled as several ACKs (for delivered packets * containing the request) from the server may arrive to the client * when the client has closed port and may be reflected by several * RSTs from the client side to the server side (when ACK received * without active connection then RST packet should be sent). * When listening socket receives RST packets, it may block * the sender preventing the next connection. */ do_client = 1; /* Proceed with the closure of the client socket */ } else { /* When rate limiter is enabled, all sent packets must be received * before client closes connection to avoid RST for every ACK. * When rate limiter is not enabled, the MHD must receive at * least something before closing the connection. */ do_client = 0; /* Do not close the client socket yet */ } } if (do_client) _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es); } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); if (do_client) { tv.tv_sec = 1; tv.tv_usec = 250 * 1000; } else { /* Request completely sent but not yet fully received */ tv.tv_sec = 0; tv.tv_usec = FINAL_PACKETS_MS * 1000; } num_ready = select ((int) maxMhdSk + 1, &rs, &ws, &es, &tv); if (-1 == num_ready) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif continue; } if (0 == num_ready) { /* select() finished by timeout, looks like no more packets are pending */ if (do_client) externalErrorExitDesc ("Timeout waiting for sockets"); if (full_req_sent && (! full_req_recieved)) full_req_recieved = 1; } if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); if (! client_accepted) client_accepted = FD_ISSET (lstn_sk, &rs); else { /* Client connection was already accepted by MHD */ if (! some_data_recieved) { if (! do_client) { if (0 != num_ready) { /* Connection was accepted before, "ready" socket means data */ some_data_recieved = 1; } } else { if (2 == num_ready) some_data_recieved = 1; else if ((1 == num_ready) && ((MHD_INVALID_SOCKET == clnt->sckt) || ! FD_ISSET (clnt->sckt, &ws))) some_data_recieved = 1; } } } if (do_client) { if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es)) clnt = NULL; } /* Use double timeout value here so MHD would be able to catch timeout * internally */ } while (time (NULL) - start <= (TIMEOUTS_VAL * 2)); return ret; } /* Returns zero for successful response and non-zero for failed response */ static int doClientQueryInThread (struct MHD_Daemon *d, struct simpleQueryParams *p) { const union MHD_DaemonInfo *dinfo; struct _MHD_dumbClient *c; int errornum; int use_external_poll; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); use_external_poll = (0 == (dinfo->flags & MHD_USE_INTERNAL_POLLING_THREAD)); if (0 == p->queryPort) externalErrorExit (); c = _MHD_dumbClient_create (p->queryPort, p->method, p->queryPath, p->headers, p->req_body, p->req_body_size, p->chunked); _MHD_dumbClient_set_send_limits (c, p->step_size, p->total_send_max); /* 'internal' polling should not be used in this test */ mhd_assert (use_external_poll); if (! use_external_poll) errornum = _MHD_dumbClient_perform (c); else errornum = performQueryExternal (d, c); if (errornum) fprintf (stderr, "Request timeout out.\n"); _MHD_dumbClient_close (c); return errornum; } static void printTestResults (FILE *stream, struct simpleQueryParams *qParam, struct ahc_cls_type *ahc_param, struct check_uri_cls *uri_cb_param, struct term_notif_cb_param *term_result, struct sckt_notif_cb_param *sckt_result) { if (stderr != stream) fflush (stderr); fprintf (stream, " Request aborted at %u byte%s.", (unsigned int) qParam->total_send_max, 1 == qParam->total_send_max ? "" : "s"); if ((1 == sckt_result->num_started) && (1 == sckt_result->num_finished)) fprintf (stream, " One socket has been accepted and then closed."); else fprintf (stream, " Sockets have been accepted %u time%s" " and closed %u time%s.", sckt_result->num_started, (1 == sckt_result->num_started) ? "" : "s", sckt_result->num_finished, (1 == sckt_result->num_finished) ? "" : "s"); if (0 == uri_cb_param->cb_called) fprintf (stream, " URI callback has NOT been called."); else fprintf (stream, " URI callback has been called %u time%s.", uri_cb_param->cb_called, 1 == uri_cb_param->cb_called ? "" : "s"); if (0 == ahc_param->cb_called) fprintf (stream, " Access handler callback has NOT been called."); else fprintf (stream, " Access handler callback has been called %u time%s.", ahc_param->cb_called, 1 == ahc_param->cb_called ? "" : "s"); if (0 == term_result->num_called) fprintf (stream, " Final notification callback has NOT been called."); else fprintf (stream, " Final notification callback has been called %u time%s " "with %s code.", term_result->num_called, (1 == term_result->num_called) ? "" : "s", term_reason_str ((enum MHD_RequestTerminationCode) term_result->term_reason)); fprintf (stream, "\n"); fflush (stream); } /* Perform test queries, shut down MHD daemon, and free parameters */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port, struct ahc_cls_type *ahc_param, struct check_uri_cls *uri_cb_param, struct term_notif_cb_param *term_result, struct sckt_notif_cb_param *sckt_result) { struct simpleQueryParams qParam; time_t start; unsigned int ret = 0; /* Return value */ size_t req_total_size; size_t limit_send_size; size_t inc_size; int expected_reason; int found_right_reason; /* Common parameters, to be individually overridden by specific test cases * if needed */ qParam.queryPort = d_port; qParam.method = MHD_HTTP_METHOD_PUT; qParam.queryPath = EXPECTED_URI_BASE_PATH; qParam.headers = REQ_HEADER_CT; qParam.req_body = (const uint8_t *) REQ_BODY; qParam.req_body_size = MHD_STATICSTR_LEN_ (REQ_BODY); qParam.chunked = upl_chunked; qParam.step_size = by_step ? 1 : 0; uri_cb_param->uri = EXPECTED_URI_BASE_PATH; ahc_param->rq_url = EXPECTED_URI_BASE_PATH; ahc_param->rq_method = MHD_HTTP_METHOD_PUT; ahc_param->rp_data = "~"; ahc_param->rp_data_size = 1; ahc_param->req_body = (const char *) qParam.req_body; ahc_param->req_body_size = qParam.req_body_size; do { struct _MHD_dumbClient *test_c; struct simpleQueryParams *p = &qParam; test_c = _MHD_dumbClient_create (p->queryPort, p->method, p->queryPath, p->headers, p->req_body, p->req_body_size, p->chunked); req_total_size = test_c->req_size; _MHD_dumbClient_close (test_c); } while (0); expected_reason = use_hard_close ? MHD_REQUEST_TERMINATED_READ_ERROR : MHD_REQUEST_TERMINATED_CLIENT_ABORT; found_right_reason = 0; if (0 != rate_limiter) { if (verbose) { printf ("Pausing for rate limiter..."); fflush (stdout); } _MHD_sleep (1150); /* Just a bit more than one second */ if (verbose) { printf (" OK\n"); fflush (stdout); } inc_size = ((req_total_size - 1) + (rate_limiter - 1)) / rate_limiter; if (0 == inc_size) inc_size = 1; } else inc_size = 1; start = time (NULL); for (limit_send_size = 1; limit_send_size < req_total_size; limit_send_size += inc_size) { int test_succeed; test_succeed = 0; /* Make sure that maximum size is tested */ if (req_total_size - inc_size < limit_send_size) limit_send_size = req_total_size - 1; qParam.total_send_max = limit_send_size; /* To be updated by callbacks */ ahc_param->cb_called = 0; uri_cb_param->cb_called = 0; term_result->num_called = 0; term_result->term_reason = -1; sckt_result->num_started = 0; sckt_result->num_finished = 0; if (0 != doClientQueryInThread (d, &qParam)) fprintf (stderr, "FAILED: connection has NOT been closed by MHD."); else { if ((-1 != term_result->term_reason) && (MHD_REQUEST_TERMINATED_READ_ERROR != term_result->term_reason) && (MHD_REQUEST_TERMINATED_CLIENT_ABORT != term_result->term_reason) ) fprintf (stderr, "FAILED: Wrong termination code."); else if ((0 == term_result->num_called) && ((0 != uri_cb_param->cb_called) || (0 != ahc_param->cb_called))) fprintf (stderr, "FAILED: Missing required call of final notification " "callback."); else if (1 < uri_cb_param->cb_called) fprintf (stderr, "FAILED: Too many URI callbacks."); else if ((0 != ahc_param->cb_called) && (0 == uri_cb_param->cb_called)) fprintf (stderr, "FAILED: URI callback has NOT been called " "while Access Handler callback has been called."); else if (1 < term_result->num_called) fprintf (stderr, "FAILED: Too many final callbacks."); else if (1 != sckt_result->num_started) fprintf (stderr, "FAILED: Wrong number of sockets accepted."); else if (1 != sckt_result->num_finished) fprintf (stderr, "FAILED: Wrong number of sockets closed."); else { test_succeed = 1; if (expected_reason == term_result->term_reason) found_right_reason = 1; } } if (! test_succeed) { ret = 1; printTestResults (stderr, &qParam, ahc_param, uri_cb_param, term_result, sckt_result); } else if (verbose) { printf ("SUCCEED:"); printTestResults (stdout, &qParam, ahc_param, uri_cb_param, term_result, sckt_result); } if (time (NULL) - start > (time_t) ((TIMEOUTS_VAL * 25) + (rate_limiter * FINAL_PACKETS_MS) / 1000 + 1)) { ret |= 1 << 2; fprintf (stderr, "FAILED: Test total time exceeded.\n"); break; } } MHD_stop_daemon (d); free (uri_cb_param); free (ahc_param); free (term_result); free (sckt_result); if (! found_right_reason) { #ifndef __gnu_hurd__ fprintf (stderr, "FAILED: termination callback was not called with " "expected (%s) reason.\n", term_reason_str ((enum MHD_RequestTerminationCode) expected_reason)); fflush (stderr); ret |= 1 << 1; #endif /* ! __gnu_hurd__ */ (void) 0; } return ret; } enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; (void) pollType; /* Don't care about pollType for this test */ return numThreads; /* No practical limit for non-cleanup test */ } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport, struct ahc_cls_type **ahc_param, struct check_uri_cls **uri_cb_param, struct term_notif_cb_param **term_result, struct sckt_notif_cb_param **sckt_result) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; if ((NULL == ahc_param) || (NULL == uri_cb_param) || (NULL == term_result)) externalErrorExit (); *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type)); if (NULL == *ahc_param) externalErrorExit (); *uri_cb_param = (struct check_uri_cls *) malloc (sizeof(struct check_uri_cls)); if (NULL == *uri_cb_param) externalErrorExit (); *term_result = (struct term_notif_cb_param *) malloc (sizeof(struct term_notif_cb_param)); if (NULL == *term_result) externalErrorExit (); *sckt_result = (struct sckt_notif_cb_param *) malloc (sizeof(struct sckt_notif_cb_param)); if (NULL == *sckt_result) externalErrorExit (); if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 4170; if (use_shutdown) *pport = (uint16_t) (*pport + 0); if (use_close) *pport = (uint16_t) (*pport + 1); if (use_hard_close) *pport = (uint16_t) (*pport + 1); if (by_step) *pport = (uint16_t) (*pport + (1 << 2)); if (upl_chunked) *pport = (uint16_t) (*pport + (1 << 3)); if (! oneone) *pport = (uint16_t) (*pport + (1 << 4)); } if (testMhdThreadExternal == thrType) d = MHD_start_daemon (((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0) | MHD_USE_NO_THREAD_SAFETY, *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_NOTIFY_COMPLETED, &term_cb, *term_result, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, *sckt_result, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); else if (testMhdThreadInternalPool != thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_NOTIFY_COMPLETED, &term_cb, *term_result, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, *sckt_result, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_END); else d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_URI_LOG_CALLBACK, &check_uri_cb, *uri_cb_param, MHD_OPTION_NOTIFY_COMPLETED, &term_cb, *term_result, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, *sckt_result, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_END); if (NULL == d) mhdErrorExitDesc ("Failed to start MHD daemon"); if (0 == *pport) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port)) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); *pport = dinfo->port; if (0 == global_port) global_port = *pport; /* Reuse the same port for all tests */ } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; struct sckt_notif_cb_param *sckt_result; d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port, &ahc_param, &uri_cb_param, &term_result, &sckt_result); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result, sckt_result); } #if 0 /* disabled runners, not suitable for this test */ static int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port, &ahc_param, &uri_cb_param, &term_result); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } static int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } static int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } #endif /* disabled runners, not suitable for this test */ int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; verbose = 0; if ((NULL == argv) || (0 == argv[0])) return 99; oneone = ! has_in_name (argv[0], "10"); use_shutdown = has_in_name (argv[0], "_shutdown") ? 1 : 0; use_close = has_in_name (argv[0], "_close") ? 1 : 0; use_hard_close = has_in_name (argv[0], "_hard_close") ? 1 : 0; use_stress_os = has_in_name (argv[0], "_stress_os") ? 1 : 0; by_step = has_in_name (argv[0], "_steps") ? 1 : 0; upl_chunked = has_in_name (argv[0], "_chunked") ? 1 : 0; #ifndef SO_LINGER if (use_hard_close) { fprintf (stderr, "This test requires SO_LINGER socket option support.\n"); return 77; } #endif /* ! SO_LINGER */ if (1 != use_shutdown + use_close) return 99; verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); if (use_stress_os && ! use_hard_close) return 99; test_global_init (); /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet (). Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; #if 0 /* disabled runners, not suitable for this test */ if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollAuto); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; #ifdef _MHD_HEAVY_TESTS /* Actually tests are not heavy, but took too long to complete while * not really provide any additional results. */ test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; } #else /* Mute compiler warnings */ (void) testMultithreadedGet; (void) testMultithreadedPoolGet; #endif /* _MHD_HEAVY_TESTS */ } #endif /* disabled runners, not suitable for this test */ if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); test_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/microhttpd/gen_auth.h0000644000175000017500000000511715035214301015023 /* This file is part of libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/gen_auth.h * @brief Declarations for HTTP authorisation general functions * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_GET_AUTH_H #define MHD_GET_AUTH_H 1 #include "mhd_options.h" #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ struct MHD_Connection; /* Forward declaration to avoid include of the large headers */ #ifdef BAUTH_SUPPORT /* Forward declaration to avoid additional headers inclusion */ struct MHD_RqBAuth; /** * Return request's Basic Authorisation parameters. * * Function return result of parsing of the request's "Authorization" header or * returns cached parsing result if the header was already parsed for * the current request. * @param connection the connection to process * @return the pointer to structure with Authentication parameters, * NULL if no memory in memory pool, if called too early (before * header has been received) or if no valid Basic Authorisation header * found. */ const struct MHD_RqBAuth * MHD_get_rq_bauth_params_ (struct MHD_Connection *connection); #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /* Forward declaration to avoid additional headers inclusion */ struct MHD_RqDAuth; /** * Return request's Digest Authorisation parameters. * * Function return result of parsing of the request's "Authorization" header or * returns cached parsing result if the header was already parsed for * the current request. * @param connection the connection to process * @return the pointer to structure with Authentication parameters, * NULL if no memory in memory pool, if called too early (before * header has been received) or if no valid Basic Authorisation header * found. */ const struct MHD_RqDAuth * MHD_get_rq_dauth_params_ (struct MHD_Connection *connection); #endif /* DAUTH_SUPPORT */ #endif /* MHD_GET_AUTH_H */ libmicrohttpd-1.0.10/src/microhttpd/mhd_panic_tripwire.h0000664000175000017500000004022315232103064017101 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/mhd_panic_tripwire.h * @brief Test-only tripwire that turns a fatal libmicrohttpd invariant * failure into a loud, greppable, machine-classifiable test error. * @author Christian Grothoff * * Rationale (TESTING.md, proposal P5): no network input must ever be able to * reach #MHD_PANIC() or a failing mhd_assert(). When it does, the test suite * should say so in a way that a CI job or the option-matrix driver can pick * out mechanically, instead of leaving behind an anonymous SIGABRT that is * indistinguishable from an ordinary test failure. * * USAGE * ----- * Add exactly one line to a test program: * * #include "mhd_panic_tripwire.h" * * Nothing else is needed: on GCC/clang the header installs itself from a * `__attribute__((constructor))`, which runs after the libmicrohttpd shared * object has run its own initialiser (and therefore after MHD_init() has * installed the stock panic handler), so the tripwire wins. On toolchains * without constructor support, call mhd_panic_tripwire_install() as the first * statement of main() instead. * * WHAT IS INTERCEPTED * ------------------- * 1. #MHD_PANIC() - via the public MHD_set_panic_func() hook. The reference * to MHD_set_panic_func() is *weak*, so this header can also be included * by the unit tests that compile a couple of library objects directly and * do not link libmicrohttpd at all; there the hook is simply skipped. * 2. abort() - via a SIGABRT handler. This matters because in this code base * the overwhelming majority of "fatal invariant reached from network * input" sites are mhd_assert(), which goes to assert(3)/abort(3) and * never passes through mhd_panic(). Set MHD_TEST_PANIC_TRIPWIRE_ABRT=0 * to intercept #MHD_PANIC() only. * * WHY THE HANDLER MUST NOT RETURN, AND WHY IT DOES NOT longjmp() * -------------------------------------------------------------- * #MHD_PANIC(msg) expands to `mhd_panic (...); BUILTIN_NOT_REACHED;`, i.e. * __builtin_unreachable(). A panic handler that returns therefore drops the * caller straight into undefined behaviour - the compiler has already been * told that the following code is dead and may have deleted it. So the * handler has to terminate the process. * * longjmp() back into main() is not an option either: MHD_PANIC() is reached * from library code that may be running on a daemon worker thread or on a * thread-per-connection thread, and a longjmp() across threads is undefined. * Even on the right thread it would leave the daemon's mutexes locked and its * connection lists half-updated, so any "recording" done afterwards would run * in a process whose state is already corrupt. We therefore report and * terminate rather than recover. * * TERMINATION STATUS * ------------------ * The default is _exit(99). The automake parallel test harness classifies * exit status 99 as a hard ERROR rather than an ordinary FAIL, which is * exactly the "this is not a normal test failure, a fatal invariant was * reached" signal wanted here. Note that this also applies to tests listed * in XFAIL_TESTS - a test that is *expected* to trip an assertion (such as * src/microhttpd/test_known_bugs.c) must therefore NOT include this header. * * ENVIRONMENT VARIABLES * --------------------- * @c MHD_TEST_PANIC_TRIPWIRE * - unset, or any unrecognised value: enabled, terminate with _exit(99). * - @c 0 / @c off / @c no / @c disable: completely disabled; the stock * libmicrohttpd behaviour (mhd_panic_std(), plain abort()) is left in * place. Use this when a debugger or an external tool wants the * original behaviour. * - @c abort: print the marker and the stack trace, then re-raise SIGABRT * with the default disposition so that a core dump is produced. * - @c exit:N (0 <= N <= 255): print the marker and the stack trace, then * terminate with status N instead of 99. * * @c MHD_TEST_PANIC_TRIPWIRE_ABRT * - @c 0 / @c off / @c no / @c disable: do not install the SIGABRT handler; * only #MHD_PANIC() is intercepted. Failing mhd_assert()s then abort as * usual. * - unset or anything else: the SIGABRT handler is installed. * * OUTPUT FORMAT * ------------- * A single greppable marker line is written to stderr, followed (where * available) by a stack trace and a final status line: * * MHD-PANIC-TRIPWIRE: kind=MHD_PANIC file=connection.c line=1234 \ * reason=Data offset exceeds limit. * MHD-PANIC-TRIPWIRE-FRAME: ... * MHD-PANIC-TRIPWIRE: terminating with exit status 99 * * Grep for #MHD_PANIC_TRIPWIRE_MARKER ("MHD-PANIC-TRIPWIRE") to classify a * failure. Everything is emitted with write(2) and without allocating, so * the same code path is usable from the SIGABRT handler. */ #ifndef MHD_PANIC_TRIPWIRE_H #define MHD_PANIC_TRIPWIRE_H 1 #include #include #include #ifdef _WIN32 #include #else /* ! _WIN32 */ #include #endif /* ! _WIN32 */ /** * The distinctive, greppable marker that prefixes every line printed by the * tripwire. */ #define MHD_PANIC_TRIPWIRE_MARKER "MHD-PANIC-TRIPWIRE" /** * The exit status used by default. The automake test harness reports this * as a hard ERROR instead of a FAIL. */ #define MHD_PANIC_TRIPWIRE_EXIT_STATUS 99 /* Detect a usable backtrace() implementation. This must not depend on configure, because this header is also used from test directories that do not run any dedicated check for it. Degrade silently when absent. */ #if ! defined(MHD_PANIC_TRIPWIRE_BACKTRACE_) # if defined(__has_include ) # if __has_include () # define MHD_PANIC_TRIPWIRE_BACKTRACE_ 1 # endif /* __has_include() */ # elif defined(HAVE_EXECINFO_H) || defined(__GLIBC__) # define MHD_PANIC_TRIPWIRE_BACKTRACE_ 1 # endif /* HAVE_EXECINFO_H || __GLIBC__ */ #endif /* ! MHD_PANIC_TRIPWIRE_BACKTRACE_ */ #ifdef MHD_PANIC_TRIPWIRE_BACKTRACE_ #include #endif /* MHD_PANIC_TRIPWIRE_BACKTRACE_ */ /* Weak references let this header be included by the unit tests that do not link libmicrohttpd (test_str*, test_md5, test_sha*, test_auth_parse, ...). Without weak-symbol support the MHD_PANIC() hook is simply not installed and only the abort() hook remains. */ #if defined(__GNUC__) && defined(__ELF__) && ! defined(_WIN32) # define MHD_PANIC_TRIPWIRE_WEAK_ __attribute__ ((weak)) #endif /* __GNUC__ && __ELF__ && ! _WIN32 */ #ifdef MHD_PANIC_TRIPWIRE_WEAK_ /* Deliberately declared here instead of pulling in : the signature is identical to MHD_PanicCallback, so this declaration is compatible with the one in when that header is also included, and it keeps this file usable in translation units that never see the public header. */ extern MHD_PANIC_TRIPWIRE_WEAK_ void MHD_set_panic_func (void (*cb)(void *cls, const char *file, unsigned int line, const char *reason), void *cls); #endif /* MHD_PANIC_TRIPWIRE_WEAK_ */ #if defined(__GNUC__) || defined(__clang__) # define MHD_PANIC_TRIPWIRE_UNUSED_ __attribute__ ((unused)) # define MHD_PANIC_TRIPWIRE_NORETURN_ __attribute__ ((noreturn)) #else /* ! __GNUC__ */ # define MHD_PANIC_TRIPWIRE_UNUSED_ # define MHD_PANIC_TRIPWIRE_NORETURN_ #endif /* ! __GNUC__ */ /** * Selected action, resolved once by the installer so that the handlers * themselves never have to call getenv(). * 0: terminate with #mhd_panic_tripwire_status_; 1: re-raise SIGABRT. */ static volatile sig_atomic_t mhd_panic_tripwire_reraise_ = 0; /** * The exit status to use when #mhd_panic_tripwire_reraise_ is zero. */ static volatile sig_atomic_t mhd_panic_tripwire_status_ = MHD_PANIC_TRIPWIRE_EXIT_STATUS; /** * Set once a report is in progress, so that a second thread tripping at the * same time does not interleave its output with the first one. */ static volatile sig_atomic_t mhd_panic_tripwire_busy_ = 0; /** * Write a string literal to stderr. * * @param str a string literal */ #define MHD_PANIC_TRIPWIRE_WRS_(str) \ mhd_panic_tripwire_wr_ (str, sizeof(str) - 1) /** * Write a buffer to stderr. Async-signal-safe: no locking, no allocation, * no stdio. * * @param buf the bytes to write * @param len the number of bytes to write */ static void mhd_panic_tripwire_wr_ (const char *buf, size_t len) { size_t off = 0; while (off < len) { #ifdef _WIN32 int res = _write (2, buf + off, (unsigned int) (len - off)); #else /* ! _WIN32 */ ssize_t res = write (STDERR_FILENO, buf + off, len - off); #endif /* ! _WIN32 */ if (0 >= res) return; /* Give up rather than spin. */ off += (size_t) res; } } /** * Write a NUL-terminated string to stderr, replacing every control character * by a space so that the marker always stays on a single line. * * @param str the string to write, may be NULL */ static void mhd_panic_tripwire_wr_clean_ (const char *str) { char chunk[256]; size_t used = 0; if (NULL == str) { MHD_PANIC_TRIPWIRE_WRS_ ("(null)"); return; } while (0 != *str) { const unsigned char chr = (unsigned char) *str++; chunk[used++] = (0x20 > chr) ? ' ' : (char) chr; if (sizeof(chunk) == used) { mhd_panic_tripwire_wr_ (chunk, used); used = 0; } } if (0 != used) mhd_panic_tripwire_wr_ (chunk, used); } /** * Write an unsigned number in decimal to stderr. * * @param val the value to print */ static void mhd_panic_tripwire_wr_num_ (unsigned long val) { char buf[24]; size_t pos = sizeof(buf); do { buf[--pos] = (char) ('0' + (val % 10)); val /= 10; } while (0 != val); mhd_panic_tripwire_wr_ (buf + pos, sizeof(buf) - pos); } /** * Print the stack trace of the calling thread, if the platform provides one. * Silently does nothing otherwise. */ static void mhd_panic_tripwire_backtrace_ (void) { #ifdef MHD_PANIC_TRIPWIRE_BACKTRACE_ void *frames[64]; int num; num = backtrace (frames, (int) (sizeof(frames) / sizeof(frames[0]))); if (0 >= num) return; MHD_PANIC_TRIPWIRE_WRS_ (MHD_PANIC_TRIPWIRE_MARKER "-FRAMES: "); mhd_panic_tripwire_wr_num_ ((unsigned long) num); MHD_PANIC_TRIPWIRE_WRS_ (" frames follow\n"); /* backtrace_symbols_fd() does not allocate, unlike backtrace_symbols(). */ backtrace_symbols_fd (frames, num, 2); #endif /* MHD_PANIC_TRIPWIRE_BACKTRACE_ */ } /** * Print the marker line and the stack trace, then terminate the process. * Never returns; see the file comment for why recovering is not an option. * * @param kind a short token naming what was intercepted * @param file the source file of the failure, may be NULL * @param line the source line of the failure * @param reason the human-readable reason, may be NULL */ MHD_PANIC_TRIPWIRE_NORETURN_ static void mhd_panic_tripwire_report_ (const char *kind, const char *file, unsigned int line, const char *reason) { if (0 == mhd_panic_tripwire_busy_) { mhd_panic_tripwire_busy_ = 1; MHD_PANIC_TRIPWIRE_WRS_ ("\n" MHD_PANIC_TRIPWIRE_MARKER ": kind="); mhd_panic_tripwire_wr_clean_ (kind); MHD_PANIC_TRIPWIRE_WRS_ (" file="); mhd_panic_tripwire_wr_clean_ ((NULL != file) ? file : "(unknown)"); MHD_PANIC_TRIPWIRE_WRS_ (" line="); mhd_panic_tripwire_wr_num_ ((unsigned long) line); MHD_PANIC_TRIPWIRE_WRS_ (" reason="); mhd_panic_tripwire_wr_clean_ ((NULL != reason) ? reason : "(none)"); MHD_PANIC_TRIPWIRE_WRS_ ("\n"); mhd_panic_tripwire_backtrace_ (); if (0 == mhd_panic_tripwire_reraise_) { MHD_PANIC_TRIPWIRE_WRS_ (MHD_PANIC_TRIPWIRE_MARKER ": terminating with exit status "); mhd_panic_tripwire_wr_num_ ((unsigned long) mhd_panic_tripwire_status_); MHD_PANIC_TRIPWIRE_WRS_ ("\n"); } else MHD_PANIC_TRIPWIRE_WRS_ (MHD_PANIC_TRIPWIRE_MARKER ": re-raising SIGABRT for a core dump\n"); } if (0 != mhd_panic_tripwire_reraise_) { signal (SIGABRT, SIG_DFL); raise (SIGABRT); } _exit ((int) mhd_panic_tripwire_status_); } /** * The #MHD_PanicCallback installed by the tripwire. * * @param cls unused * @param file the name of the file with the problem * @param line the line number with the problem * @param reason the error message with details */ static void mhd_panic_tripwire_panic_cb_ (void *cls, const char *file, unsigned int line, const char *reason) { (void) cls; /* Mute compiler warning. */ mhd_panic_tripwire_report_ ("MHD_PANIC", file, line, reason); } /** * The SIGABRT handler installed by the tripwire. Catches a failing * mhd_assert() (which goes through assert(3) and abort(3)) and any other * abort(), for example from the C library's own consistency checks. * * @param sig the signal number, always SIGABRT */ static void mhd_panic_tripwire_abrt_cb_ (int sig) { (void) sig; /* Mute compiler warning. */ mhd_panic_tripwire_report_ ("abort", NULL, 0, "abort() reached; see the line above for the " "failed assertion, if any"); } /** * Test whether an environment variable value means "off". * * @param val the value to test, may be NULL * @return non-zero if @a val explicitly disables a feature */ static int mhd_panic_tripwire_is_off_ (const char *val) { if (NULL == val) return 0; return (0 == strcmp (val, "0")) || (0 == strcmp (val, "off")) || (0 == strcmp (val, "no")) || (0 == strcmp (val, "disable")); } /** * Install the panic tripwire. Called automatically from a constructor on * GCC-compatible toolchains; call it explicitly as the first statement of * main() on any other toolchain. Idempotent. */ MHD_PANIC_TRIPWIRE_UNUSED_ static void mhd_panic_tripwire_install (void) { const char *mode = getenv ("MHD_TEST_PANIC_TRIPWIRE"); if (mhd_panic_tripwire_is_off_ (mode)) return; /* Leave the stock behaviour completely untouched. */ if ((NULL != mode) && (0 == strcmp (mode, "abort"))) mhd_panic_tripwire_reraise_ = 1; else if ((NULL != mode) && (0 == strncmp (mode, "exit:", 5))) { const long status = strtol (mode + 5, NULL, 10); if ((0 <= status) && (255 >= status)) mhd_panic_tripwire_status_ = (sig_atomic_t) status; } #ifdef MHD_PANIC_TRIPWIRE_WEAK_ if (NULL != MHD_set_panic_func) MHD_set_panic_func (&mhd_panic_tripwire_panic_cb_, NULL); #else /* ! MHD_PANIC_TRIPWIRE_WEAK_ */ MHD_set_panic_func (&mhd_panic_tripwire_panic_cb_, NULL); #endif /* ! MHD_PANIC_TRIPWIRE_WEAK_ */ if (! mhd_panic_tripwire_is_off_ (getenv ("MHD_TEST_PANIC_TRIPWIRE_ABRT"))) signal (SIGABRT, &mhd_panic_tripwire_abrt_cb_); } #if defined(__GNUC__) || defined(__clang__) /** * Self-installer, so that adding the tripwire to a test program is a single * #include line. Runs after the libmicrohttpd initialiser (the library is a * dependency of the test executable and is therefore initialised first), so * MHD_init()'s call to MHD_set_panic_func(NULL, NULL) cannot undo this. */ __attribute__ ((constructor)) static void mhd_panic_tripwire_ctor_ (void) { mhd_panic_tripwire_install (); } #endif /* __GNUC__ || __clang__ */ #endif /* ! MHD_PANIC_TRIPWIRE_H */ libmicrohttpd-1.0.10/src/microhttpd/test_postprocessor_md.c0000664000175000017500000011335715232103064017702 /* This file is part of libmicrohttpd Copyright (C) 2020 Christian Grothoff Copyright (C) 2020-2023 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_postprocessor_md.c * @brief Testcase for postprocessor, keys with no value * @author Markus Doppelbauer * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #include "microhttpd.h" #include "internal.h" #include "postprocessor.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if 0 #include "mhd_panic.c" #include "mhd_str.c" #include "internal.c" #endif #define DEBUG 0 /* local replacement for MHD functions */ _MHD_EXTERN enum MHD_Result MHD_lookup_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char **value_ptr, size_t *value_size_ptr) { (void) connection; (void) kind; (void) key; /* Mute compiler warnings */ (void) key_size; *value_ptr = ""; if (NULL != value_size_ptr) *value_size_ptr = 0; return MHD_NO; } #define ARRAY_LENGTH(array) (sizeof(array) / sizeof(array[0])) static unsigned int found; static enum MHD_Result post_data_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) filename; /* Mute compiler warnings */ (void) content_type; (void) transfer_encoding; (void) off; /* FIXME: shouldn't be checked? */ #if DEBUG fprintf (stderr, "%s\t%s\n", key, data); #endif if (0 == strcmp (key, "xxxx")) { if ( (4 != size) || (0 != memcmp (data, "xxxx", 4)) ) exit (1); found |= 1; } if (0 == strcmp (key, "yyyy")) { if ( (4 != size) || (0 != memcmp (data, "yyyy", 4)) ) exit (1); found |= 2; } if (0 == strcmp (key, "zzzz")) { if (0 != size) exit (1); found |= 4; } if (0 == strcmp (key, "aaaa")) { if (0 != size) exit (1); found |= 8; } return MHD_YES; } static enum MHD_Result post_data_iterator2 (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { static char seen[16]; (void) cls; (void) kind; (void) filename; /* Mute compiler warnings */ (void) content_type; (void) transfer_encoding; #if DEBUG printf ("%s\t%s@ %" PRIu64 "\n", key, data, off); #endif if (0 == strcmp (key, "text")) { if (off + size > sizeof (seen)) exit (6); memcpy (&seen[off], data, size); if ( (10 == off + size) && (0 == memcmp (seen, "text, text", 10)) ) found |= 1; } return MHD_YES; } static enum MHD_Result post_data_iterator3 (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) filename; /* Mute compiler warnings */ (void) content_type; (void) transfer_encoding; (void) off; /* FIXME: shouldn't be checked? */ #if DEBUG fprintf (stderr, "%s\t%s\n", key, data); #endif if (0 == strcmp (key, "y")) { if ( (1 != size) || (0 != memcmp (data, "y", 1)) ) exit (1); found |= 1; } return MHD_YES; } static enum MHD_Result post_data_iterator4 (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) key; /* Mute compiler warnings */ (void) filename; (void) content_type; (void) transfer_encoding; (void) off; /* FIXME: shouldn't be checked? */ #if DEBUG fprintf (stderr, "%s\t%s\n", key, data); #endif if (NULL != memchr (data, 'M', size)) { found |= 1; } return MHD_YES; } static enum MHD_Result post_data_iterator5 (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) key; /* Mute compiler warnings */ (void) filename; (void) content_type; (void) transfer_encoding; (void) data; (void) off; (void) size; found++; return MHD_YES; } int main (int argc, char *argv[]) { struct MHD_PostProcessor *postprocessor; (void) argc; (void) argv; if (1) { found = 0; postprocessor = malloc (sizeof (struct MHD_PostProcessor) + 0x1000 + 1); if (NULL == postprocessor) return 77; memset (postprocessor, 0, sizeof (struct MHD_PostProcessor) + 0x1000 + 1); postprocessor->ikvi = &post_data_iterator; postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; postprocessor->buffer_size = 0x1000; postprocessor->state = PP_Init; postprocessor->skip_rn = RN_Inactive; if (MHD_YES != MHD_post_process (postprocessor, "xxxx=xxxx", 9)) exit (1); if (MHD_YES != MHD_post_process (postprocessor, "&yyyy=yyyy&zzzz=&aaaa=", 22)) exit (1); if (MHD_YES != MHD_post_process (postprocessor, "", 0)) exit (1); if (MHD_YES != MHD_destroy_post_processor (postprocessor)) exit (3); if (found != 15) exit (2); } if (1) { found = 0; postprocessor = malloc (sizeof (struct MHD_PostProcessor) + 0x1000 + 1); if (NULL == postprocessor) return 77; memset (postprocessor, 0, sizeof (struct MHD_PostProcessor) + 0x1000 + 1); postprocessor->ikvi = post_data_iterator2; postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; postprocessor->buffer_size = 0x1000; postprocessor->state = PP_Init; postprocessor->skip_rn = RN_Inactive; if (MHD_YES != MHD_post_process (postprocessor, "text=text%2", 11)) exit (1); if (MHD_YES != MHD_post_process (postprocessor, "C+text", 6)) exit (1); if (MHD_YES != MHD_post_process (postprocessor, "", 0)) exit (1); if (MHD_YES != MHD_destroy_post_processor (postprocessor)) exit (1); if (found != 1) exit (4); } if (1) { found = 0; postprocessor = malloc (sizeof (struct MHD_PostProcessor) + 0x1000 + 1); if (NULL == postprocessor) return 77; memset (postprocessor, 0, sizeof (struct MHD_PostProcessor) + 0x1000 + 1); postprocessor->ikvi = post_data_iterator3; postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; postprocessor->buffer_size = 0x1000; postprocessor->state = PP_Init; postprocessor->skip_rn = RN_Inactive; { const char *chunk = "x=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxx%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxx%2C%2Cxxxxxx" "%2Cxxxx%2C%2Cxxxxx%2Cxxxxxxxxx%2C%2Cxxx%2Cxxxxxxxxxxx_xxxxxxxxxxxxxxx" "%2Cxxxxx%2Cxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "%2Cxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxx%2C%2Cxxxxx%2C%2Cx%2Cxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C" "xxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxx%2C%2Cxx%2C%2Cx%2Cxx%2C%2Cxxxx%2Cxxx" "%2C%2Cx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C" "%2Cxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "x%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xx%2Cxxxxx%2Cxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxx%2Cxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxx" "xx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxxxxxxxxx" "xxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cx%2Cxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx" "xxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2" "Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxx%2Cxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cx" "xxxxxxxx%2Cxxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C" "%2C%2C%2C%2C%2Cxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C" "%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2" "Cxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2" "C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cxxxxxxxxx" "xxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2" "Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2" "C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cx%2C%" "2Cx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxx%2Cx" "xxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx" "xxx%2Cxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxxxxxxxxxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cx" "xxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx" "xx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx" "xxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C" "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2C" "xxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxx" "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2" "Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxx" "xxx%2Cxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxx%2Cxxxxx%2Cxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx" "xxxxxxxxxxxxxxx%2Cx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxx%2Cx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxx%2Cx%2Cxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%" "2Cxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxx%" "2Cxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxx" "xx%2Cxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxx" "xxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxx" "x%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxx" "xxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C" "%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx%2C%2C%2C%2Cxxxxxxx" "xxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxxxxxxxx%2Cxxx" "xxxx%2Cxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxx%" "2C%2C%2Cxxxxxxxxx%2Cxxxxxxxx%2C" "&y=y&z=z"; if (MHD_YES != MHD_post_process (postprocessor, chunk, strlen (chunk) )) exit (1); } if (MHD_YES != MHD_post_process (postprocessor, "", 0)) exit (1); if (MHD_YES != MHD_destroy_post_processor (postprocessor)) exit (1); if (found != 1) exit (5); } if (1) { unsigned i; const char *chunks[] = { "t=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxxxxx%2C%2Cx%2Cxxxxxxxx" "xxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cxxxxx%" "2Cxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2Cxx%2C%2Cx%2" "Cxx%2C%2Cxxxx%2Cxxx%2C%2Cx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "x%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2" "Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxx%2C%2C%2C%2Cxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxx" "xxxxxxxx%2C%2Cxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cx%2Cxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xx%2Cxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxx" "xxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2C" "xxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C" "%2C%2C%2C%2Cxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C" "%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxx" "xxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2" "C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx%2Cx%2Cxxxxxxxxxxxx" "xxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2" "C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxx", /* one chunk: second line is dropped */ "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C" "xxxxxxxxxxxxxxxx%2Cx%2C%2Cx%2Cxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2Cxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2C%2C%2Cxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxx" "xxxxxxxxxxxxx%2Cxxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2Cx%2C%2C" "%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxx%2Cxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxx" "xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "x%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxx%2C%2C%2C%2C" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx" "xxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxx" "%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxx" "x%2Cxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxx" "xx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxx%2Cxxxxxx%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%" "2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxx%2Cxx" "xxxxxxxx%2Cxxxxxxxxx%2Cxxxxxxx%2Cxxxxxxxxxx%2Cxxxxxxxxxxxxxx%2Cxxxxxxx" "xxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxx%2Cxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx%2Cxxxx" "x%2Cxxxx%2Cxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxx%" "2Cx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2Cx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xx%2Cx%2Cxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxx%2Cxx%2Cx" "xxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxx%2Cxxxxxx%2Cxxxxxxxxxxxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%" "2C%2C%2C%2Cxxxxxxxxxxx%2C%2Cxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxx%2Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2" "Cxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxx" "xxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2" "C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxx%2C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%2C%2C%2C%2C%2C%2C%2Cxxxxxxxxxxxxxx%2" "C%2C%2C%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxx%2Cxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxZZZZZZZZZZZZZ%2C%2C%2C%2C" "%E2%80%A2MMMMMMMM%2C%2C%2C%2CMMMMMMMMMMMMMMMMMMMM%2CMMMMMMMMMMMMMMMMMM" "MMMMM%2CMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMM%2C%2C%2C%2CMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM%2CMMMMMMMMMMMMMMMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM%2CMMMMMM" "MMMMMMMMMMMMMMMMMMMMMMMMMMMM" "zz", "", }; postprocessor = malloc (sizeof(struct MHD_PostProcessor) + 131076 + 1); if (NULL == postprocessor) return 77; memset (postprocessor, 0, sizeof (struct MHD_PostProcessor) + 0x1000 + 1); postprocessor->ikvi = post_data_iterator4; postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; postprocessor->buffer_size = 131076; postprocessor->state = PP_Init; postprocessor->skip_rn = RN_Inactive; for (i = 0; i < ARRAY_LENGTH (chunks); ++i) { const char *chunk = chunks[i]; if (MHD_YES != MHD_post_process (postprocessor, chunk, strlen (chunk) )) exit (1); } if (MHD_YES != MHD_destroy_post_processor (postprocessor)) exit (1); if (found != 1) return 6; } if (1) { unsigned i; const char *chunks[] = { "XXXXXXXXXXXX=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&XXXXXX=&XXXXXXXXXXXXXX=X" "XXX+&XXXXXXXXXXXXXXX=XXXXXXXXX&XXXXXXXXXXXXX=XXXX%XX%XXXXXX&XXXXXXXXXX" "X=XXXXXXXXX&XXXXXXXXXXXXX=XXXXXXXXXX&XXXXXXXXXXXXXXX=XX&XXXXXXXXXXXXXX" "X=XXXXXXXXX&XXXXXXXXXXXXX=XXXXXX&XXXXXXXXXXX=XXXXXXXXXXXXXXXXXXXXXXXXX" "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" "XXXXXXXXXX", "&XXXXXXXX=XXXX", "", }; postprocessor = malloc (sizeof(struct MHD_PostProcessor) + 131076 + 1); found = 0; if (NULL == postprocessor) return 77; memset (postprocessor, 0, sizeof (struct MHD_PostProcessor) + 0x1000 + 1); postprocessor->ikvi = post_data_iterator5; postprocessor->encoding = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; postprocessor->buffer_size = 131076; postprocessor->state = PP_Init; postprocessor->skip_rn = RN_Inactive; for (i = 0; i < ARRAY_LENGTH (chunks); ++i) { const char *chunk = chunks[i]; if (MHD_YES != MHD_post_process (postprocessor, chunk, strlen (chunk) )) exit (1); } if (MHD_YES != MHD_destroy_post_processor (postprocessor)) exit (1); if (found != 12) return 7; } return EXIT_SUCCESS; } libmicrohttpd-1.0.10/src/microhttpd/internal.c0000644000175000017500000001761114760713574015066 /* This file is part of libmicrohttpd Copyright (C) 2007 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/internal.c * @brief internal shared structures * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "internal.h" #include "mhd_str.h" #ifdef HAVE_MESSAGES #if DEBUG_STATES /** * State to string dictionary. */ const char * MHD_state_to_string (enum MHD_CONNECTION_STATE state) { switch (state) { case MHD_CONNECTION_INIT: return "connection init"; case MHD_CONNECTION_REQ_LINE_RECEIVING: return "receiving request line"; case MHD_CONNECTION_REQ_LINE_RECEIVED: return "request line received"; case MHD_CONNECTION_REQ_HEADERS_RECEIVING: return "headers receiving"; case MHD_CONNECTION_HEADERS_RECEIVED: return "headers received"; case MHD_CONNECTION_HEADERS_PROCESSED: return "headers processed"; case MHD_CONNECTION_CONTINUE_SENDING: return "continue sending"; case MHD_CONNECTION_BODY_RECEIVING: return "body receiving"; case MHD_CONNECTION_BODY_RECEIVED: return "body received"; case MHD_CONNECTION_FOOTERS_RECEIVING: return "footers receiving"; case MHD_CONNECTION_FOOTERS_RECEIVED: return "footers received"; case MHD_CONNECTION_FULL_REQ_RECEIVED: return "full request received"; case MHD_CONNECTION_START_REPLY: return "start sending reply"; case MHD_CONNECTION_HEADERS_SENDING: return "headers sending"; case MHD_CONNECTION_HEADERS_SENT: return "headers sent"; case MHD_CONNECTION_NORMAL_BODY_UNREADY: return "normal body unready"; case MHD_CONNECTION_NORMAL_BODY_READY: return "normal body ready"; case MHD_CONNECTION_CHUNKED_BODY_UNREADY: return "chunked body unready"; case MHD_CONNECTION_CHUNKED_BODY_READY: return "chunked body ready"; case MHD_CONNECTION_CHUNKED_BODY_SENT: return "chunked body sent"; case MHD_CONNECTION_FOOTERS_SENDING: return "footers sending"; case MHD_CONNECTION_FULL_REPLY_SENT: return "reply sent completely"; case MHD_CONNECTION_CLOSED: return "closed"; default: return "unrecognized connection state"; } } #endif #endif #ifdef HAVE_MESSAGES /** * fprintf-like helper function for logging debug * messages. */ void MHD_DLOG (const struct MHD_Daemon *daemon, const char *format, ...) { va_list va; if (0 == (daemon->options & MHD_USE_ERROR_LOG)) return; va_start (va, format); daemon->custom_error_log (daemon->custom_error_log_cls, format, va); va_end (va); } #endif /** * Convert all occurrences of '+' to ' '. * * @param arg string that is modified (in place), must be 0-terminated */ void MHD_unescape_plus (char *arg) { char *p; for (p = strchr (arg, '+'); NULL != p; p = strchr (p + 1, '+')) *p = ' '; } /** * Process escape sequences ('%HH') Updates val in place; the * result cannot be larger than the input. * The result is still be 0-terminated. * * @param val value to unescape (modified in the process) * @return length of the resulting val (`strlen(val)` may be * shorter afterwards due to elimination of escape sequences) */ _MHD_EXTERN size_t MHD_http_unescape (char *val) { return MHD_str_pct_decode_in_place_lenient_ (val, NULL); } /** * Parse and unescape the arguments given by the client * as part of the HTTP request URI. * * @param kind header kind to pass to @a cb * @param connection connection to add headers to * @param[in,out] args argument URI string (after "?" in URI), * clobbered in the process! * @param cb function to call on each key-value pair found * @param cls the iterator context * @return #MHD_NO on failure (@a cb returned #MHD_NO), * #MHD_YES for success (parsing succeeded, @a cb always * returned #MHD_YES) */ enum MHD_Result MHD_parse_arguments_ (struct MHD_Connection *connection, enum MHD_ValueKind kind, char *args, MHD_ArgumentIterator_ cb, void *cls) { struct MHD_Daemon *daemon = connection->daemon; char *equals; char *amper; while ( (NULL != args) && ('\0' != args[0]) ) { size_t key_len; size_t value_len; equals = strchr (args, '='); amper = strchr (args, '&'); if (NULL == amper) { /* last argument */ if (NULL == equals) { /* last argument, without '=' */ MHD_unescape_plus (args); key_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, args); if (MHD_NO == cb (cls, args, key_len, NULL, 0, kind)) return MHD_NO; break; } /* got 'foo=bar' */ equals[0] = '\0'; equals++; MHD_unescape_plus (args); key_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, args); MHD_unescape_plus (equals); value_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, equals); if (MHD_NO == cb (cls, args, key_len, equals, value_len, kind)) return MHD_NO; break; } /* amper is non-NULL here */ amper[0] = '\0'; amper++; if ( (NULL == equals) || (equals >= amper) ) { /* got 'foo&bar' or 'foo&bar=val', add key 'foo' with NULL for value */ MHD_unescape_plus (args); key_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, args); if (MHD_NO == cb (cls, args, key_len, NULL, 0, kind)) return MHD_NO; /* continue with 'bar' */ args = amper; continue; } /* equals and amper are non-NULL here, and equals < amper, so we got regular 'foo=value&bar...'-kind of argument */ equals[0] = '\0'; equals++; MHD_unescape_plus (args); key_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, args); MHD_unescape_plus (equals); value_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, equals); if (MHD_NO == cb (cls, args, key_len, equals, value_len, kind)) return MHD_NO; args = amper; } return MHD_YES; } /* end of internal.c */ libmicrohttpd-1.0.10/src/microhttpd/md5.h0000664000175000017500000000637215223423441013732 /* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/md5.h * @brief Calculation of MD5 digest * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_MD5_H #define MHD_MD5_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * Number of bits in single MD5 word. */ #define MD5_WORD_SIZE_BITS 32 /** * Number of bytes in single MD5 word. */ #define MD5_BYTES_IN_WORD (MD5_WORD_SIZE_BITS / 8) /** * Hash is kept internally as four 32-bit words. * This is intermediate hash size, used during computing the final digest. */ #define MD5_HASH_SIZE_WORDS 4 /** * Size of MD5 resulting digest in words. * This is the final digest size, not intermediate hash. */ #define MD5_DIGEST_SIZE_WORDS MD5_HASH_SIZE_WORDS /** * Size of MD5 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define MD5_DIGEST_SIZE (MD5_DIGEST_SIZE_WORDS * MD5_BYTES_IN_WORD) /** * Size of MD5 digest string in chars including termination NUL. */ #define MD5_DIGEST_STRING_SIZE ((MD5_DIGEST_SIZE) * 2 + 1) /** * Size of MD5 single processing block in bits. */ #define MD5_BLOCK_SIZE_BITS 512 /** * Size of MD5 single processing block in bytes. */ #define MD5_BLOCK_SIZE (MD5_BLOCK_SIZE_BITS / 8) /** * Size of MD5 single processing block in words. */ #define MD5_BLOCK_SIZE_WORDS (MD5_BLOCK_SIZE_BITS / MD5_WORD_SIZE_BITS) /** * MD5 calculation context */ struct Md5Ctx { uint32_t H[MD5_HASH_SIZE_WORDS]; /**< Intermediate hash value / digest at end of calculation */ uint32_t buffer[MD5_BLOCK_SIZE_WORDS]; /**< MD5 input data buffer */ uint64_t count; /**< number of bytes, mod 2^64 */ }; /** * Initialise structure for MD5 calculation. * * @param ctx the calculation context */ void MHD_MD5_init (struct Md5Ctx *ctx); /** * MD5 process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_MD5_update (struct Md5Ctx *ctx, const uint8_t *data, size_t length); /** * Finalise MD5 calculation, return digest. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes */ void MHD_MD5_finish (struct Md5Ctx *ctx, uint8_t digest[MD5_DIGEST_SIZE]); /** * Indicates that function MHD_MD5_finish() (without context reset) is available */ #define MHD_MD5_HAS_FINISH 1 #endif /* MHD_MD5_H */ libmicrohttpd-1.0.10/src/microhttpd/mhd_send.h0000644000175000017500000001244515035214301015014 /* This file is part of libmicrohttpd Copyright (C) 2017-2021 Karlson2k (Evgeny Grin) Copyright (C) 2019 ng0 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file mhd_send.h * @brief Declarations of send() wrappers. * @author ng0 * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SEND_H #define MHD_SEND_H #include "platform.h" #include "internal.h" #if defined(HAVE_STDBOOL_H) #include #endif /* HAVE_STDBOOL_H */ #include #include "mhd_sockets.h" #include "connection.h" #ifdef HTTPS_SUPPORT #include "connection_https.h" #endif #if defined(HAVE_SENDMSG) || defined(HAVE_WRITEV) || \ defined(MHD_WINSOCK_SOCKETS) #define MHD_VECT_SEND 1 #endif /* HAVE_SENDMSG || HAVE_WRITEV || MHD_WINSOCK_SOCKETS */ /** * Initialises static variables */ void MHD_send_init_static_vars_ (void); /** * Send buffer to the client, push data from network buffer if requested * and full buffer is sent. * * @param connection the MHD_Connection structure * @param buffer content of the buffer to send * @param buffer_size the size of the @a buffer (in bytes) * @param push_data set to true to force push the data to the network from * system buffers (usually set for the last piece of data), * set to false to prefer holding incomplete network packets * (more data will be send for the same reply). * @return sum of the number of bytes sent from both buffers or * error code (negative) */ ssize_t MHD_send_data_ (struct MHD_Connection *connection, const char *buffer, size_t buffer_size, bool push_data); /** * Send reply header with optional reply body. * * @param connection the MHD_Connection structure * @param header content of header to send * @param header_size the size of the @a header (in bytes) * @param never_push_hdr set to true to disable internal algorithm * that can push automatically header data * alone to the network * @param body content of the body to send (optional, may be NULL) * @param body_size the size of the @a body (in bytes) * @param complete_response set to true if complete response * is provided by @a header and @a body, * set to false if additional body data * will be sent later * @return sum of the number of bytes sent from both buffers or * error code (negative) */ ssize_t MHD_send_hdr_and_body_ (struct MHD_Connection *connection, const char *header, size_t header_size, bool never_push_hdr, const char *body, size_t body_size, bool complete_response); #if defined(_MHD_HAVE_SENDFILE) /** * Function for sending responses backed by file FD. * * @param connection the MHD connection structure * @return actual number of bytes sent */ ssize_t MHD_send_sendfile_ (struct MHD_Connection *connection); #endif /** * Set required TCP_NODELAY state for connection socket * * The function automatically updates sk_nodelay state. * @param connection the connection to manipulate * @param nodelay_state the requested new state of socket * @return true if succeed, false if failed or not supported * by the current platform / kernel. */ bool MHD_connection_set_nodelay_state_ (struct MHD_Connection *connection, bool nodelay_state); /** * Set required cork state for connection socket * * The function automatically updates sk_corked state. * * @param connection the connection to manipulate * @param cork_state the requested new state of socket * @return true if succeed, false if failed or not supported * by the current platform / kernel. */ bool MHD_connection_set_cork_state_ (struct MHD_Connection *connection, bool cork_state); /** * Function for sending responses backed by a an array of memory buffers. * * @param connection the MHD connection structure * @param r_iov the pointer to iov response structure with tracking * @param push_data set to true to force push the data to the network from * system buffers (usually set for the last piece of data), * set to false to prefer holding incomplete network packets * (more data will be send for the same reply). * @return actual number of bytes sent */ ssize_t MHD_send_iovec_ (struct MHD_Connection *connection, struct MHD_iovec_track_ *const r_iov, bool push_data); #endif /* MHD_SEND_H */ libmicrohttpd-1.0.10/src/microhttpd/mhd_md5_wrap.h0000664000175000017500000000552215223423441015607 /* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/mhd_md5_wrap.h * @brief Simple wrapper for selection of built-in/external MD5 implementation * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_MD5_WRAP_H #define MHD_MD5_WRAP_H 1 #include "mhd_options.h" #ifndef MHD_MD5_SUPPORT #error This file must be used only when MD5 is enabled #endif #ifndef MHD_MD5_TLSLIB #include "md5.h" #else /* MHD_MD5_TLSLIB */ #include "md5_ext.h" #endif /* MHD_MD5_TLSLIB */ #ifndef MD5_DIGEST_SIZE /** * Size of MD5 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define MD5_DIGEST_SIZE (16) #endif /* ! MD5_DIGEST_SIZE */ #ifndef MD5_DIGEST_STRING_SIZE /** * Size of MD5 digest string in chars including termination NUL. */ #define MD5_DIGEST_STRING_SIZE ((MD5_DIGEST_SIZE) * 2 + 1) #endif /* ! MD5_DIGEST_STRING_SIZE */ #ifndef MHD_MD5_TLSLIB /** * Universal ctx type mapped for chosen implementation */ #define Md5CtxWr Md5Ctx #else /* MHD_MD5_TLSLIB */ /** * Universal ctx type mapped for chosen implementation */ #define Md5CtxWr Md5CtxExt #endif /* MHD_MD5_TLSLIB */ #ifndef MHD_MD5_HAS_INIT_ONE_TIME /** * Setup and prepare ctx for hash calculation */ #define MHD_MD5_init_one_time(ctx) MHD_MD5_init(ctx) #endif /* ! MHD_MD5_HAS_INIT_ONE_TIME */ #ifndef MHD_MD5_HAS_FINISH_RESET /** * Re-use the same ctx for the new hashing after digest calculated */ #define MHD_MD5_reset(ctx) MHD_MD5_init(ctx) /** * Finalise MD5 calculation, return digest, reset hash calculation. */ #define MHD_MD5_finish_reset(ctx,digest) MHD_MD5_finish(ctx,digest), \ MHD_MD5_reset(ctx) #else /* MHD_MD5_HAS_FINISH_RESET */ #define MHD_MD5_reset(ctx) (void)0 #endif /* MHD_MD5_HAS_FINISH_RESET */ #ifndef MHD_MD5_HAS_DEINIT #define MHD_MD5_deinit(ignore) (void)0 #endif /* HAVE_MD5_DEINIT */ /* Sanity checks */ #if ! defined(MHD_MD5_HAS_FINISH_RESET) && ! defined(MHD_MD5_HAS_FINISH) #error Required at least one of MHD_MD5_finish_reset(), MHD_MD5_finish() #endif /* ! MHD_MD5_HAS_FINISH_RESET && ! MHD_MD5_HAS_FINISH */ #endif /* MHD_MD5_WRAP_H */ libmicrohttpd-1.0.10/src/microhttpd/test_dauth_userdigest.c0000664000175000017500000005172415232103064017637 /* This file is part of libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_dauth_userdigest.c * @brief Tests for Digest Auth calculations of userdigest * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include "microhttpd.h" #include "test_helpers.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_HTTPS_REQUIRE_GCRYPT) && \ (defined(MHD_SHA256_TLSLIB) || defined(MHD_MD5_TLSLIB)) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT && (MHD_SHA256_TLSLIB || MHD_MD5_TLSLIB) */ static int verbose = 1; /* verbose level (0-1)*/ /* Declarations and data */ struct data_md5 { unsigned int line_num; const char *const username; const char *const realm; const char *const password; const uint8_t hash[MHD_MD5_DIGEST_SIZE]; }; static const struct data_md5 md5_tests[] = { {__LINE__, "u", "r", "p", {0x44, 0xad, 0xd2, 0x2b, 0x6f, 0x31, 0x79, 0xb7, 0x51, 0xea, 0xfd, 0x68, 0xee, 0x37, 0x0f, 0x7d}}, {__LINE__, "testuser", "testrealm", "testpass", {0xeb, 0xff, 0x22, 0x5e, 0x1c, 0xeb, 0x73, 0xe0, 0x26, 0xfc, 0xc6, 0x45, 0xaf, 0x3e, 0x84, 0xf6}}, {__LINE__, /* Values from testcurl/test_digestauth2.c */ "test_user", "TestRealm", "test pass", {0xd8, 0xb4, 0xa6, 0xd0, 0x01, 0x13, 0x07, 0xb7, 0x67, 0x94, 0xea, 0x66, 0x86, 0x03, 0x6b, 0x43}}, {__LINE__, "Mufasa", "myhost@testrealm.com", "CircleOfLife", {0x7e, 0xbe, 0xcc, 0x07, 0x18, 0xa5, 0x4a, 0xb4, 0x7e, 0x21, 0x65, 0x69, 0x07, 0x66, 0x41, 0x6a}}, {__LINE__, "Mufasa", "myhost@example.com", "Circle Of Life", {0x6a, 0x6d, 0x4e, 0x7c, 0xd7, 0x15, 0x18, 0x68, 0xf9, 0xb8, 0xc7, 0xc8, 0xd1, 0xcd, 0xd4, 0xe0}}, {__LINE__, "Mufasa", "http-auth@example.org", "Circle of Life", {0x3d, 0x78, 0x80, 0x7d, 0xef, 0xe7, 0xde, 0x21, 0x57, 0xe2, 0xb0, 0xb6, 0x57, 0x3a, 0x85, 0x5f}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", "Secret, or not?", {0x83, 0xa3, 0xf7, 0xf6, 0xb8, 0x3f, 0x71, 0xc5, 0xc2, 0xeb, 0x7c, 0x6d, 0xd2, 0xdd, 0x4c, 0x4b}} }; struct data_sha256 { unsigned int line_num; const char *const username; const char *const realm; const char *const password; const uint8_t hash[MHD_SHA256_DIGEST_SIZE]; }; static const struct data_sha256 sha256_tests[] = { {__LINE__, "u", "r", "p", {0xdc, 0xb0, 0x21, 0x10, 0x2e, 0x49, 0x1e, 0x70, 0x1a, 0x4a, 0x23, 0x6d, 0xaa, 0x89, 0x23, 0xaf, 0x21, 0x61, 0x44, 0x7b, 0xce, 0x7b, 0xb7, 0x26, 0x0a, 0x35, 0x1e, 0xe8, 0x3e, 0x9f, 0x81, 0x54}}, {__LINE__, "testuser", "testrealm", "testpass", {0xa9, 0x2e, 0xf6, 0x3b, 0x3d, 0xec, 0x38, 0x95, 0xb0, 0x8f, 0x3d, 0x4d, 0x67, 0x33, 0xf0, 0x70, 0x74, 0xcb, 0xe6, 0xd4, 0xa0, 0x01, 0x27, 0xf5, 0x74, 0x1a, 0x77, 0x4f, 0x05, 0xf9, 0xd4, 0x99}}, {__LINE__, /* Values from testcurl/test_digestauth2.c */ "test_user", "TestRealm", "test pass", {0xc3, 0x4e, 0x16, 0x5a, 0x17, 0x0f, 0xe5, 0xac, 0x04, 0xf1, 0x6e, 0x46, 0x48, 0x2b, 0xa0, 0xc6, 0x56, 0xc1, 0xfb, 0x8f, 0x66, 0xa6, 0xd6, 0x3f, 0x91, 0x12, 0xf8, 0x56, 0xa5, 0xec, 0x6d, 0x6d}}, {__LINE__, "Mufasa", "myhost@testrealm.com", "CircleOfLife", {0x8e, 0x64, 0x1f, 0xaa, 0x71, 0x7d, 0x20, 0x70, 0x5a, 0xd7, 0x3c, 0x54, 0xfb, 0x04, 0x9e, 0x32, 0x6a, 0xe1, 0x1c, 0x80, 0xd6, 0x05, 0x9f, 0xc3, 0x7e, 0xbb, 0x2d, 0x7b, 0x60, 0x6c, 0x11, 0xb9}}, {__LINE__, "Mufasa", "myhost@example.com", "Circle Of Life", {0x8b, 0xc5, 0xa8, 0xed, 0xe3, 0x02, 0x15, 0x6b, 0x9f, 0x51, 0xce, 0x97, 0x81, 0xb5, 0x26, 0xff, 0x99, 0x29, 0x0b, 0xb2, 0xc3, 0xe4, 0x41, 0x71, 0x8e, 0xa3, 0xa1, 0x7e, 0x5a, 0xd9, 0xd6, 0x49}}, {__LINE__, "Mufasa", "http-auth@example.org", "Circle of Life", {0x79, 0x87, 0xc6, 0x4c, 0x30, 0xe2, 0x5f, 0x1b, 0x74, 0xbe, 0x53, 0xf9, 0x66, 0xb4, 0x9b, 0x90, 0xf2, 0x80, 0x8a, 0xa9, 0x2f, 0xaf, 0x9a, 0x00, 0x26, 0x23, 0x92, 0xd7, 0xb4, 0x79, 0x42, 0x32}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", "Secret, or not?", {0xfd, 0x0b, 0xe3, 0x93, 0x9d, 0xca, 0x4b, 0x5c, 0x2d, 0x46, 0xe8, 0xfa, 0x6a, 0x3d, 0x16, 0xdb, 0xea, 0x82, 0x47, 0x4c, 0xb9, 0xa5, 0x88, 0xd4, 0xcb, 0x14, 0x9c, 0x54, 0xf3, 0x7c, 0xff, 0x37}} }; struct data_sha512_256 { unsigned int line_num; const char *const username; const char *const realm; const char *const password; const uint8_t hash[MHD_SHA512_256_DIGEST_SIZE]; }; static const struct data_sha512_256 sha512_256_tests[] = { {__LINE__, "u", "r", "p", {0xd5, 0xe8, 0xe7, 0x3b, 0xa3, 0x47, 0xb9, 0xad, 0xf0, 0xe4, 0x7a, 0x9a, 0xce, 0x43, 0xb7, 0x08, 0x2a, 0xbc, 0x8d, 0x27, 0x27, 0x2e, 0x38, 0x7d, 0x1d, 0x9c, 0xe2, 0x44, 0x25, 0x68, 0x74, 0x04}}, {__LINE__, "testuser", "testrealm", "testpass", {0x41, 0x7d, 0xf9, 0x60, 0x7c, 0xc9, 0x60, 0x28, 0x44, 0x74, 0x75, 0xf7, 0x7b, 0x78, 0xe7, 0x60, 0xec, 0x9a, 0xe1, 0x62, 0xd4, 0x95, 0x82, 0x61, 0x68, 0xa7, 0x94, 0xe8, 0x3b, 0xdf, 0x8d, 0x59}}, {__LINE__, /* Values from testcurl/test_digestauth2.c */ "test_user", "TestRealm", "test pass", {0xe7, 0xa1, 0x9e, 0x27, 0xf6, 0x73, 0x88, 0xb2, 0xde, 0xa4, 0xe2, 0x66, 0xc5, 0x16, 0x37, 0x17, 0x4d, 0x29, 0xcc, 0xa3, 0xc1, 0xf5, 0xb2, 0x49, 0x20, 0xc1, 0x05, 0xc9, 0x20, 0x13, 0x3c, 0x3d}}, {__LINE__, "Mufasa", "myhost@testrealm.com", "CircleOfLife", {0x44, 0xbc, 0xd2, 0xb1, 0x1f, 0x6f, 0x7d, 0xd3, 0xae, 0xa6, 0x66, 0x8a, 0x24, 0x84, 0x4b, 0x87, 0x7d, 0xe1, 0x80, 0x24, 0x9a, 0x26, 0x6b, 0xe6, 0xdb, 0x7f, 0xe3, 0xc8, 0x7a, 0xf9, 0x75, 0x64}}, {__LINE__, "Mufasa", "myhost@example.com", "Circle Of Life", {0xd5, 0xf6, 0x25, 0x7c, 0x64, 0xe4, 0x01, 0xd2, 0x87, 0xd5, 0xaa, 0x19, 0xae, 0xf0, 0xa2, 0xa2, 0xce, 0x4e, 0x5d, 0xfc, 0x77, 0x70, 0x0b, 0x72, 0x90, 0x43, 0x96, 0xd2, 0x95, 0x6e, 0x83, 0x0a}}, {__LINE__, "Mufasa", "http-auth@example.org", "Circle of Life", {0xfb, 0x17, 0x4f, 0x5c, 0x3c, 0x78, 0x02, 0x72, 0x15, 0x17, 0xca, 0xe1, 0x3b, 0x98, 0xe2, 0xb8, 0xda, 0xe2, 0xe0, 0x11, 0x8c, 0xb7, 0x05, 0xd9, 0x4e, 0xe2, 0x99, 0x46, 0x31, 0x92, 0x04, 0xce}}, {__LINE__, "J" "\xC3\xA4" "s" "\xC3\xB8" "n Doe" /* "Jäsøn Doe" */, "api@example.org", "Secret, or not?", {0x2d, 0x3d, 0x9f, 0x12, 0xc9, 0xf3, 0xd3, 0x00, 0x11, 0x25, 0x9d, 0xc5, 0xfe, 0xce, 0xe0, 0x05, 0xae, 0x24, 0xde, 0x40, 0xe3, 0xe1, 0xf6, 0x18, 0x06, 0xd0, 0x3e, 0x65, 0xf1, 0xe6, 0x02, 0x4f}} }; /* * Helper functions */ /** * Print bin as lower case hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'a' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'a' - 10) : (b2 + '0')); } *hex = 0; } /* Tests */ static unsigned int check_md5 (const struct data_md5 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5; uint8_t hash_bin[MHD_MD5_DIGEST_SIZE]; char hash_hex[MHD_MD5_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_MD5_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userdigest"; if (MHD_YES != MHD_digest_auth_calc_userdigest (algo3, data->username, data->realm, data->password, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_md5 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(md5_tests) / sizeof(md5_tests[0]); i++) num_failed += check_md5 (md5_tests + i); return num_failed; } static unsigned int test_md5_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_MD5; uint8_t hash_bin[MHD_MD5_DIGEST_SIZE]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userdigest"; if (MHD_NO != MHD_digest_auth_calc_userdigest (algo3, "u", "r", "p", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userdigest (algo3, "u", "r", "p", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5)) { if (MHD_NO != MHD_digest_auth_calc_userdigest (algo3, "u", "r", "p", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } static unsigned int check_sha256 (const struct data_sha256 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256; uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE]; char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userdigest"; if (MHD_YES != MHD_digest_auth_calc_userdigest (algo3, data->username, data->realm, data->password, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_sha256 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(sha256_tests) / sizeof(sha256_tests[0]); i++) num_failed += check_sha256 (sha256_tests + i); return num_failed; } static unsigned int test_sha256_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA256; uint8_t hash_bin[MHD_SHA256_DIGEST_SIZE]; char hash_hex[MHD_SHA256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) { if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) { if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } static unsigned int check_sha512_256 (const struct data_sha512_256 *const data) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA512_256; uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE]; char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; char expected_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userdigest"; if (MHD_YES != MHD_digest_auth_calc_userdigest (algo3, data->username, data->realm, data->password, hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_YES.\n", func_name); } else if (0 != memcmp (hash_bin, data->hash, sizeof(data->hash))) { failed++; bin2hex (hash_bin, sizeof(hash_bin), hash_hex); bin2hex (data->hash, sizeof(data->hash), expected_hex); fprintf (stderr, "FAILED: %s() produced wrong hash. " "Calculated digest %s, expected digest %s.\n", func_name, hash_hex, expected_hex); } if (failed) { fprintf (stderr, "The check failed for data located at line: %u.\n", data->line_num); fflush (stderr); } else if (verbose) { printf ("PASSED: check for data at line: %u.\n", data->line_num); } return failed ? 1 : 0; } static unsigned int test_sha512_256 (void) { unsigned int num_failed = 0; size_t i; for (i = 0; i < sizeof(sha512_256_tests) / sizeof(sha512_256_tests[0]); i++) num_failed += check_sha512_256 (sha512_256_tests + i); return num_failed; } static unsigned int test_sha512_256_failure (void) { static const enum MHD_DigestAuthAlgo3 algo3 = MHD_DIGEST_AUTH_ALGO3_SHA512_256; static const enum MHD_FEATURE feature = MHD_FEATURE_DIGEST_AUTH_SHA512_256; uint8_t hash_bin[MHD_SHA512_256_DIGEST_SIZE]; char hash_hex[MHD_SHA512_256_DIGEST_SIZE * 2 + 1]; const char *func_name; unsigned int failed = 0; func_name = "MHD_digest_auth_calc_userhash"; if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (feature)) { if (MHD_NO != MHD_digest_auth_calc_userhash (algo3, "u", "r", hash_bin, sizeof(hash_bin))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } func_name = "MHD_digest_auth_calc_userhash_hex"; if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex) - 1)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, 0)) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } if (MHD_NO == MHD_is_feature_supported (feature)) { if (MHD_NO != MHD_digest_auth_calc_userhash_hex (algo3, "u", "r", hash_hex, sizeof(hash_hex))) { failed++; fprintf (stderr, "FAILED: %s() has not returned MHD_NO at line: %u.\n", func_name, (unsigned) __LINE__); } } if (! failed && verbose) { printf ("PASSED: all checks with expected MHD_NO result near line: %u.\n", (unsigned) __LINE__); } return failed ? 1 : 0; } int main (int argc, char *argv[]) { unsigned int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")) verbose = 0; #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_MD5)) num_failed += test_md5 (); num_failed += test_md5_failure (); if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA256)) num_failed += test_sha256 (); num_failed += test_sha256_failure (); if (MHD_is_feature_supported (MHD_FEATURE_DIGEST_AUTH_SHA512_256)) num_failed += test_sha512_256 (); num_failed += test_sha512_256_failure (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.10/src/microhttpd/tsearch.h0000644000175000017500000000113614760713577014706 /*- * Written by J.T. Conklin * Public domain. * * $NetBSD: search.h,v 1.12 1999/02/22 10:34:28 christos Exp $ */ #ifndef _TSEARCH_H_ #define _TSEARCH_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ void *tdelete (const void *, void **, int (*)(const void *, const void *)); void *tfind (const void *, void * const *, int (*)(const void *, const void *)); void *tsearch (const void *, void **, int (*)(const void *, const void *)); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* !_TSEARCH_H_ */ libmicrohttpd-1.0.10/src/microhttpd/mhd_compat.c0000644000175000017500000000545514760713574015370 /* This file is part of libmicrohttpd Copyright (C) 2014-2016 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_compat.c * @brief Implementation of platform missing functions. * @author Karlson2k (Evgeny Grin) */ #include "mhd_compat.h" #if defined(_WIN32) && ! defined(__CYGWIN__) #include #include #ifndef HAVE_SNPRINTF #include #include #endif /* HAVE_SNPRINTF */ #endif /* _WIN32 && !__CYGWIN__ */ #ifndef HAVE_CALLOC #include /* for memset() */ #endif /* ! HAVE_CALLOC */ #if defined(_WIN32) && ! defined(__CYGWIN__) #ifndef HAVE_SNPRINTF /* Emulate snprintf function on W32 */ int W32_snprintf (char *__restrict s, size_t n, const char *__restrict format, ...) { int ret; va_list args; if ( (0 != n) && (NULL != s) ) { va_start (args, format); ret = _vsnprintf (s, n, format, args); va_end (args); if ((int) n == ret) s[n - 1] = 0; if (ret >= 0) return ret; } va_start (args, format); ret = _vscprintf (format, args); va_end (args); if ( (0 <= ret) && (0 != n) && (NULL == s) ) return -1; return ret; } #endif /* HAVE_SNPRINTF */ #endif /* _WIN32 && !__CYGWIN__ */ #ifndef HAVE_CALLOC #ifdef __has_builtin # if __has_builtin (__builtin_mul_overflow) # define MHD_HAVE_NUL_OVERFLOW 1 # endif #elif __GNUC__ + 0 >= 5 # define MHD_HAVE_NUL_OVERFLOW 1 #endif /* __GNUC__ >= 5 */ void * MHD_calloc_ (size_t nelem, size_t elsize) { size_t alloc_size; void *ptr; #ifdef MHD_HAVE_NUL_OVERFLOW if (__builtin_mul_overflow (nelem, elsize, &alloc_size) || (0 == alloc_size)) return NULL; #else /* ! MHD_HAVE_NUL_OVERFLOW */ alloc_size = nelem * elsize; if ((0 == alloc_size) || (elsize != alloc_size / nelem)) return NULL; #endif /* ! MHD_HAVE_NUL_OVERFLOW */ ptr = malloc (alloc_size); if (NULL == ptr) return NULL; memset (ptr, 0, alloc_size); return ptr; } #endif /* ! HAVE_CALLOC */ libmicrohttpd-1.0.10/src/microhttpd/daemon.c0000664000175000017500000121256615235436227014521 /* This file is part of libmicrohttpd Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/daemon.c * @brief A minimal-HTTP server library * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #include "mhd_threads.h" #endif #include "internal.h" #include "response.h" #include "connection.h" #include "memorypool.h" #include "mhd_limits.h" #include "autoinit_funcs.h" #include "mhd_mono_clock.h" #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #include "mhd_locks.h" #endif #include "mhd_sockets.h" #include "mhd_itc.h" #include "mhd_compat.h" #include "mhd_send.h" #include "mhd_align.h" #include "mhd_str.h" #ifdef MHD_USE_SYS_TSEARCH #include #else /* ! MHD_USE_SYS_TSEARCH */ #include "tsearch.h" #endif /* ! MHD_USE_SYS_TSEARCH */ #ifdef HTTPS_SUPPORT #include "connection_https.h" #ifdef MHD_HTTPS_REQUIRE_GCRYPT #include #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ #endif /* HTTPS_SUPPORT */ #if defined(_WIN32) && ! defined(__CYGWIN__) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifdef MHD_USE_POSIX_THREADS #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #endif /* MHD_USE_POSIX_THREADS */ /** * Default connection limit. */ #ifdef MHD_POSIX_SOCKETS #define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 3 - 1 - MHD_ITC_NUM_FDS_) #else #define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 2) #endif /** * Default memory allowed per connection. */ #define MHD_POOL_SIZE_DEFAULT (32 * 1024) /* Forward declarations. */ /** * Global initialisation function. */ void MHD_init (void); /** * Global deinitialisation function. */ void MHD_fini (void); /** * Close all connections for the daemon. * Must only be called when MHD_Daemon::shutdown was set to true. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon to close down */ static void close_all_connections (struct MHD_Daemon *daemon); #ifdef EPOLL_SUPPORT /** * Do epoll()-based processing. * * @param daemon daemon to run poll loop for * @param millisec the maximum time in milliseconds to wait for events, * set to '0' for non-blocking processing, * set to '-1' to wait indefinitely. * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_epoll (struct MHD_Daemon *daemon, int32_t millisec); #endif /* EPOLL_SUPPORT */ #ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED /** * Do nothing - global initialisation is * performed by library constructor. */ #define MHD_check_global_init_() (void) 0 #else /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */ /** * Track global initialisation */ volatile int global_init_count = 0; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #ifdef MHD_MUTEX_STATIC_DEFN_INIT_ /** * Global initialisation mutex */ MHD_MUTEX_STATIC_DEFN_INIT_ (global_init_mutex_); #endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */ #endif /** * Check whether global initialisation was performed * and call initialiser if necessary. */ void MHD_check_global_init_ (void) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #ifdef MHD_MUTEX_STATIC_DEFN_INIT_ MHD_mutex_lock_chk_ (&global_init_mutex_); #endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */ #endif if (0 == global_init_count++) MHD_init (); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #ifdef MHD_MUTEX_STATIC_DEFN_INIT_ MHD_mutex_unlock_chk_ (&global_init_mutex_); #endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */ #endif } #endif /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */ #ifdef HAVE_MESSAGES /** * Default logger function */ static void MHD_default_logger_ (void *cls, const char *fm, va_list ap) { vfprintf ((FILE *) cls, fm, ap); #ifdef _DEBUG fflush ((FILE *) cls); #endif /* _DEBUG */ } #endif /* HAVE_MESSAGES */ /** * Free the memory allocated by MHD. * * If any MHD function explicitly mentions that returned pointer must be * freed by this function, then no other method must be used to free * the memory. * * @param ptr the pointer to free. * @sa #MHD_digest_auth_get_username(), #MHD_basic_auth_get_username_password3() * @sa #MHD_basic_auth_get_username_password() * @note Available since #MHD_VERSION 0x00095600 * @ingroup specialized */ _MHD_EXTERN void MHD_free (void *ptr) { free (ptr); } /** * Maintain connection count for single address. */ struct MHD_IPCount { /** * Address family. AF_INET or AF_INET6 for now. */ int family; /** * Actual address. */ union { /** * IPv4 address. */ struct in_addr ipv4; #ifdef HAVE_INET6 /** * IPv6 address. */ struct in6_addr ipv6; #endif } addr; /** * Counter. */ unsigned int count; }; /** * Lock shared structure for IP connection counts and connection DLLs. * * @param daemon handle to daemon where lock is */ static void MHD_ip_count_lock (struct MHD_Daemon *daemon) { mhd_assert (NULL == daemon->master); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->per_ip_connection_mutex); #else (void) daemon; #endif } /** * Unlock shared structure for IP connection counts and connection DLLs. * * @param daemon handle to daemon where lock is */ static void MHD_ip_count_unlock (struct MHD_Daemon *daemon) { mhd_assert (NULL == daemon->master); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->per_ip_connection_mutex); #else (void) daemon; #endif } /** * Tree comparison function for IP addresses (supplied to tsearch() family). * We compare everything in the struct up through the beginning of the * 'count' field. * * @param a1 first address to compare * @param a2 second address to compare * @return -1, 0 or 1 depending on result of compare */ static int MHD_ip_addr_compare (const void *a1, const void *a2) { return memcmp (a1, a2, offsetof (struct MHD_IPCount, count)); } /** * Parse address and initialize @a key using the address. * * @param addr address to parse * @param addrlen number of bytes in @a addr * @param key where to store the parsed address * @return #MHD_YES on success and #MHD_NO otherwise (e.g., invalid address type) */ static enum MHD_Result MHD_ip_addr_to_key (const struct sockaddr_storage *addr, socklen_t addrlen, struct MHD_IPCount *key) { memset (key, 0, sizeof(*key)); /* IPv4 addresses */ if (sizeof (struct sockaddr_in) <= (size_t) addrlen) { if (AF_INET == addr->ss_family) { key->family = AF_INET; memcpy (&key->addr.ipv4, &((const struct sockaddr_in *) addr)->sin_addr, sizeof(((const struct sockaddr_in *) NULL)->sin_addr)); return MHD_YES; } } #ifdef HAVE_INET6 if (sizeof (struct sockaddr_in6) <= (size_t) addrlen) { /* IPv6 addresses */ if (AF_INET6 == addr->ss_family) { key->family = AF_INET6; memcpy (&key->addr.ipv6, &((const struct sockaddr_in6 *) addr)->sin6_addr, sizeof(((const struct sockaddr_in6 *) NULL)->sin6_addr)); return MHD_YES; } } #endif /* Some other address */ return MHD_NO; } /** * Check if IP address is over its limit in terms of the number * of allowed concurrent connections. If the IP is still allowed, * increments the connection counter. * * @param daemon handle to daemon where connection counts are tracked * @param addr address to add (or increment counter) * @param addrlen number of bytes in @a addr * @return Return #MHD_YES if IP below limit, #MHD_NO if IP has surpassed limit. * Also returns #MHD_NO if fails to allocate memory. */ static enum MHD_Result MHD_ip_limit_add (struct MHD_Daemon *daemon, const struct sockaddr_storage *addr, socklen_t addrlen) { struct MHD_IPCount *newkeyp; struct MHD_IPCount *keyp; struct MHD_IPCount **nodep; enum MHD_Result result; daemon = MHD_get_master (daemon); /* Ignore if no connection limit assigned */ if (0 == daemon->per_ip_connection_limit) return MHD_YES; newkeyp = (struct MHD_IPCount *) malloc (sizeof(struct MHD_IPCount)); if (NULL == newkeyp) return MHD_NO; /* Initialize key */ if (MHD_NO == MHD_ip_addr_to_key (addr, addrlen, newkeyp)) { free (newkeyp); return MHD_YES; /* Allow unhandled address types through */ } MHD_ip_count_lock (daemon); /* Search for the IP address */ nodep = (struct MHD_IPCount **) tsearch (newkeyp, &daemon->per_ip_connection_count, &MHD_ip_addr_compare); if (NULL == nodep) { MHD_ip_count_unlock (daemon); free (newkeyp); #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to add IP connection count node.\n")); #endif return MHD_NO; } keyp = *nodep; /* Test if there is room for another connection; if so, * increment count */ result = (keyp->count < daemon->per_ip_connection_limit) ? MHD_YES : MHD_NO; if (MHD_NO != result) ++keyp->count; MHD_ip_count_unlock (daemon); /* If we got an existing node back, free the one we created */ if (keyp != newkeyp) free (newkeyp); return result; } /** * Decrement connection count for IP address, removing from table * count reaches 0. * * @param daemon handle to daemon where connection counts are tracked * @param addr address to remove (or decrement counter) * @param addrlen number of bytes in @a addr */ static void MHD_ip_limit_del (struct MHD_Daemon *daemon, const struct sockaddr_storage *addr, socklen_t addrlen) { struct MHD_IPCount search_key; struct MHD_IPCount *found_key; void **nodep; daemon = MHD_get_master (daemon); /* Ignore if no connection limit assigned */ if (0 == daemon->per_ip_connection_limit) return; /* Initialize search key */ if (MHD_NO == MHD_ip_addr_to_key (addr, addrlen, &search_key)) return; MHD_ip_count_lock (daemon); /* Search for the IP address */ if (NULL == (nodep = tfind (&search_key, &daemon->per_ip_connection_count, &MHD_ip_addr_compare))) { /* Something's wrong if we couldn't find an IP address * that was previously added */ MHD_PANIC (_ ("Failed to find previously-added IP address.\n")); } found_key = (struct MHD_IPCount *) *nodep; /* Validate existing count for IP address */ if (0 == found_key->count) { MHD_PANIC (_ ("Previously-added IP address had counter of zero.\n")); } /* Remove the node entirely if count reduces to 0 */ if (0 == --found_key->count) { tdelete (found_key, &daemon->per_ip_connection_count, &MHD_ip_addr_compare); MHD_ip_count_unlock (daemon); free (found_key); } else MHD_ip_count_unlock (daemon); } #ifdef HTTPS_SUPPORT /** * Read and setup our certificate and key. * * @param daemon handle to daemon to initialize * @return 0 on success */ static int MHD_init_daemon_certificate (struct MHD_Daemon *daemon) { gnutls_datum_t key; gnutls_datum_t cert; int ret; #if GNUTLS_VERSION_MAJOR >= 3 if (NULL != daemon->cert_callback) { gnutls_certificate_set_retrieve_function2 (daemon->x509_cred, daemon->cert_callback); } #endif #if GNUTLS_VERSION_NUMBER >= 0x030603 else if (NULL != daemon->cert_callback2) { gnutls_certificate_set_retrieve_function3 (daemon->x509_cred, daemon->cert_callback2); } #endif if (NULL != daemon->https_mem_trust) { size_t paramlen; paramlen = strlen (daemon->https_mem_trust); if (UINT_MAX < paramlen) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Too long trust certificate.\n")); #endif return -1; } cert.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_trust); cert.size = (unsigned int) paramlen; if (gnutls_certificate_set_x509_trust_mem (daemon->x509_cred, &cert, GNUTLS_X509_FMT_PEM) < 0) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Bad trust certificate format.\n")); #endif return -1; } } if (daemon->have_dhparams) { gnutls_certificate_set_dh_params (daemon->x509_cred, daemon->https_mem_dhparams); } /* certificate & key loaded from memory */ if ( (NULL != daemon->https_mem_cert) && (NULL != daemon->https_mem_key) ) { size_t param1len; size_t param2len; param1len = strlen (daemon->https_mem_key); param2len = strlen (daemon->https_mem_cert); if ( (UINT_MAX < param1len) || (UINT_MAX < param2len) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Too long key or certificate.\n")); #endif return -1; } key.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_key); key.size = (unsigned int) param1len; cert.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_cert); cert.size = (unsigned int) param2len; if (NULL != daemon->https_key_password) { #if GNUTLS_VERSION_NUMBER >= 0x030111 ret = gnutls_certificate_set_x509_key_mem2 (daemon->x509_cred, &cert, &key, GNUTLS_X509_FMT_PEM, daemon->https_key_password, 0); #else #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to setup x509 certificate/key: pre 3.X.X version " \ "of GnuTLS does not support setting key password.\n")); #endif return -1; #endif } else ret = gnutls_certificate_set_x509_key_mem (daemon->x509_cred, &cert, &key, GNUTLS_X509_FMT_PEM); #ifdef HAVE_MESSAGES if (0 != ret) MHD_DLOG (daemon, _ ("GnuTLS failed to setup x509 certificate/key: %s\n"), gnutls_strerror (ret)); #endif return ret; } #if GNUTLS_VERSION_MAJOR >= 3 if (NULL != daemon->cert_callback) return 0; #endif #if GNUTLS_VERSION_NUMBER >= 0x030603 else if (NULL != daemon->cert_callback2) return 0; #endif #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("You need to specify a certificate and key location.\n")); #endif return -1; } /** * Initialize security aspects of the HTTPS daemon * * @param daemon handle to daemon to initialize * @return 0 on success */ static int MHD_TLS_init (struct MHD_Daemon *daemon) { switch (daemon->cred_type) { case GNUTLS_CRD_CERTIFICATE: if (0 != gnutls_certificate_allocate_credentials (&daemon->x509_cred)) return GNUTLS_E_MEMORY_ERROR; return MHD_init_daemon_certificate (daemon); case GNUTLS_CRD_PSK: if (0 != gnutls_psk_allocate_server_credentials (&daemon->psk_cred)) return GNUTLS_E_MEMORY_ERROR; return 0; case GNUTLS_CRD_ANON: case GNUTLS_CRD_SRP: case GNUTLS_CRD_IA: default: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error: invalid credentials type %d specified.\n"), daemon->cred_type); #endif return -1; } } /** * Release the TLS resources that #MHD_start_daemon_va() may already have * allocated when it decides to fail. * * The daemon object is not usable at that point, so #MHD_stop_daemon() * (which is what frees these on the success path) cannot be called; each * failure exit therefore has to do it, and every one of them used to * forget the Diffie-Hellman parameters. Those are created by MHD itself * from the PEM blob of #MHD_OPTION_HTTPS_MEM_DHPARAMS, so the * application has no handle to free either. * * @param[in,out] daemon the half-initialised daemon */ static void tls_cleanup_failed_start (struct MHD_Daemon *daemon) { if (daemon->have_dhparams) { gnutls_dh_params_deinit (daemon->https_mem_dhparams); daemon->have_dhparams = false; } if (NULL != daemon->priority_cache) { gnutls_priority_deinit (daemon->priority_cache); daemon->priority_cache = NULL; } if (NULL != daemon->x509_cred) { gnutls_certificate_free_credentials (daemon->x509_cred); daemon->x509_cred = NULL; } if (NULL != daemon->psk_cred) { gnutls_psk_free_server_credentials (daemon->psk_cred); daemon->psk_cred = NULL; } } #endif /* HTTPS_SUPPORT */ #undef MHD_get_fdset /** * Obtain the `select()` sets for this daemon. * Daemon's FDs will be added to fd_sets. To get only * daemon FDs in fd_sets, call FD_ZERO for each fd_set * before calling this function. FD_SETSIZE is assumed * to be platform's default. * * This function should be called only when MHD is configured to * use "external" sockets polling with 'select()' or with 'epoll'. * In the latter case, it will only add the single 'epoll' file * descriptor used by MHD to the sets. * It's necessary to use #MHD_get_timeout() to get maximum timeout * value for `select()`. Usage of `select()` with indefinite timeout * (or timeout larger than returned by #MHD_get_timeout()) will * violate MHD API and may results in pending unprocessed data. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_fdset (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd) { return MHD_get_fdset2 (daemon, read_fd_set, write_fd_set, except_fd_set, max_fd, #ifdef HAS_FD_SETSIZE_OVERRIDABLE daemon->fdset_size_set_by_app ? ((unsigned int) daemon->fdset_size) : ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ ); } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /** * Obtain the select() file descriptor sets for the * given @a urh. * * @param urh upgrade handle to wait for * @param[out] rs read set to initialize * @param[out] ws write set to initialize * @param[out] es except set to initialize * @param[out] max_fd maximum FD to update * @param fd_setsize value of FD_SETSIZE * @return true on success, false on error */ static bool urh_to_fdset (struct MHD_UpgradeResponseHandle *urh, fd_set *rs, fd_set *ws, fd_set *es, MHD_socket *max_fd, int fd_setsize) { const MHD_socket conn_sckt = urh->connection->socket_fd; const MHD_socket mhd_sckt = urh->mhd.socket; bool res = true; #ifndef HAS_FD_SETSIZE_OVERRIDABLE (void) fd_setsize; /* Mute compiler warning */ fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ /* Do not add to 'es' only if socket is closed * or not used anymore. */ if (MHD_INVALID_SOCKET != conn_sckt) { if ( (urh->in_buffer_used < urh->in_buffer_size) && (! MHD_add_to_fd_set_ (conn_sckt, rs, max_fd, fd_setsize)) ) res = false; if ( (0 != urh->out_buffer_used) && (! MHD_add_to_fd_set_ (conn_sckt, ws, max_fd, fd_setsize)) ) res = false; /* Do not monitor again for errors if error was detected before as * error state is remembered. */ if ((0 == (urh->app.celi & MHD_EPOLL_STATE_ERROR)) && ((0 != urh->in_buffer_size) || (0 != urh->out_buffer_size) || (0 != urh->out_buffer_used)) && (NULL != es)) (void) MHD_add_to_fd_set_ (conn_sckt, es, max_fd, fd_setsize); } if (MHD_INVALID_SOCKET != mhd_sckt) { if ( (urh->out_buffer_used < urh->out_buffer_size) && (! MHD_add_to_fd_set_ (mhd_sckt, rs, max_fd, fd_setsize)) ) res = false; if ( (0 != urh->in_buffer_used) && (! MHD_add_to_fd_set_ (mhd_sckt, ws, max_fd, fd_setsize)) ) res = false; /* Do not monitor again for errors if error was detected before as * error state is remembered. */ if ((0 == (urh->mhd.celi & MHD_EPOLL_STATE_ERROR)) && ((0 != urh->out_buffer_size) || (0 != urh->in_buffer_size) || (0 != urh->in_buffer_used)) && (NULL != es)) MHD_add_to_fd_set_ (mhd_sckt, es, max_fd, fd_setsize); } return res; } /** * Update the @a urh based on the ready FDs in * the @a rs, @a ws, and @a es. * * @param urh upgrade handle to update * @param rs read result from select() * @param ws write result from select() * @param es except result from select() * @param fd_setsize value of FD_SETSIZE used when fd_sets were created */ static void urh_from_fdset (struct MHD_UpgradeResponseHandle *urh, const fd_set *rs, const fd_set *ws, const fd_set *es, int fd_setsize) { const MHD_socket conn_sckt = urh->connection->socket_fd; const MHD_socket mhd_sckt = urh->mhd.socket; /* Reset read/write ready, preserve error state. */ urh->app.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); urh->mhd.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); mhd_assert (urh->connection->sk_nonblck); #ifndef HAS_FD_SETSIZE_OVERRIDABLE (void) fd_setsize; /* Mute compiler warning */ mhd_assert (((int) FD_SETSIZE) <= fd_setsize); fd_setsize = FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (MHD_INVALID_SOCKET != conn_sckt) { if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (conn_sckt, NULL, fd_setsize)) { if (FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (rs))) urh->app.celi |= MHD_EPOLL_STATE_READ_READY; if (FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (ws))) urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY; if ((NULL != es) && FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (es))) urh->app.celi |= MHD_EPOLL_STATE_ERROR; } else { /* Cannot check readiness. Force ready state is safe as socket is non-blocking */ urh->app.celi |= MHD_EPOLL_STATE_READ_READY; urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY; } } if ((MHD_INVALID_SOCKET != mhd_sckt)) { if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (mhd_sckt, NULL, fd_setsize)) { if (FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (rs))) urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY; if (FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (ws))) urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY; if ((NULL != es) && FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (es))) urh->mhd.celi |= MHD_EPOLL_STATE_ERROR; } else { /* Cannot check readiness. Force ready state is safe as socket is non-blocking */ urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY; urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY; } } } #ifdef HAVE_POLL /** * Set required 'event' members in 'pollfd' elements, * assuming that @a p[0].fd is MHD side of socketpair * and @a p[1].fd is TLS connected socket. * * @param urh upgrade handle to watch for * @param p pollfd array to update */ static void urh_update_pollfd (struct MHD_UpgradeResponseHandle *urh, struct pollfd p[2]) { p[0].events = 0; p[1].events = 0; if (urh->in_buffer_used < urh->in_buffer_size) p[0].events |= POLLIN; if (0 != urh->out_buffer_used) p[0].events |= POLLOUT; /* Do not monitor again for errors if error was detected before as * error state is remembered. */ if ((0 == (urh->app.celi & MHD_EPOLL_STATE_ERROR)) && ((0 != urh->in_buffer_size) || (0 != urh->out_buffer_size) || (0 != urh->out_buffer_used))) p[0].events |= MHD_POLL_EVENTS_ERR_DISC; if (urh->out_buffer_used < urh->out_buffer_size) p[1].events |= POLLIN; if (0 != urh->in_buffer_used) p[1].events |= POLLOUT; /* Do not monitor again for errors if error was detected before as * error state is remembered. */ if ((0 == (urh->mhd.celi & MHD_EPOLL_STATE_ERROR)) && ((0 != urh->out_buffer_size) || (0 != urh->in_buffer_size) || (0 != urh->in_buffer_used))) p[1].events |= MHD_POLL_EVENTS_ERR_DISC; } /** * Set @a p to watch for @a urh. * * @param urh upgrade handle to watch for * @param p pollfd array to set */ static void urh_to_pollfd (struct MHD_UpgradeResponseHandle *urh, struct pollfd p[2]) { p[0].fd = urh->connection->socket_fd; p[1].fd = urh->mhd.socket; urh_update_pollfd (urh, p); } /** * Update ready state in @a urh based on pollfd. * @param urh upgrade handle to update * @param p 'poll()' processed pollfd. */ static void urh_from_pollfd (struct MHD_UpgradeResponseHandle *urh, struct pollfd p[2]) { /* Reset read/write ready, preserve error state. */ urh->app.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); urh->mhd.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); if (0 != (p[0].revents & POLLIN)) urh->app.celi |= MHD_EPOLL_STATE_READ_READY; if (0 != (p[0].revents & POLLOUT)) urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY; if (0 != (p[0].revents & POLLHUP)) urh->app.celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; if (0 != (p[0].revents & MHD_POLL_REVENTS_ERRROR)) urh->app.celi |= MHD_EPOLL_STATE_ERROR; if (0 != (p[1].revents & POLLIN)) urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY; if (0 != (p[1].revents & POLLOUT)) urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY; if (0 != (p[1].revents & POLLHUP)) urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; if (0 != (p[1].revents & MHD_POLL_REVENTS_ERRROR)) urh->mhd.celi |= MHD_EPOLL_STATE_ERROR; } #endif /* HAVE_POLL */ #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ /** * Internal version of #MHD_get_fdset2(). * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @param fd_setsize value of FD_SETSIZE * @return #MHD_YES on success, #MHD_NO if any FD didn't * fit fd_set. * @ingroup event */ static enum MHD_Result internal_get_fdset2 (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd, int fd_setsize) { struct MHD_Connection *pos; struct MHD_Connection *posn; enum MHD_Result result = MHD_YES; MHD_socket ls; bool itc_added; #ifndef HAS_FD_SETSIZE_OVERRIDABLE (void) fd_setsize; /* Mute compiler warning */ fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (daemon->shutdown) return MHD_YES; /* The order of FDs added is important for W32 sockets as W32 fd_set has limits for number of added FDs instead of the limit for the higher FD value. */ /* Add ITC FD first. The daemon must be able to respond on application commands issued in other threads. */ itc_added = false; if (MHD_ITC_IS_VALID_ (daemon->itc)) { itc_added = MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc), read_fd_set, max_fd, fd_setsize); if (! itc_added) result = MHD_NO; } ls = daemon->was_quiesced ? MHD_INVALID_SOCKET : daemon->listen_fd; if (! itc_added && (MHD_INVALID_SOCKET != ls)) { /* Add listen FD if ITC was not added. Listen FD could be used to signal the daemon shutdown. */ if (MHD_add_to_fd_set_ (ls, read_fd_set, max_fd, fd_setsize)) ls = MHD_INVALID_SOCKET; /* Already added */ else result = MHD_NO; } /* Add all sockets to 'except_fd_set' as well to watch for * out-of-band data. However, ignore errors if INFO_READ * or INFO_WRITE sockets will not fit 'except_fd_set'. */ /* Start from oldest connections. Make sense for W32 FDSETs. */ for (pos = daemon->connections_tail; NULL != pos; pos = posn) { posn = pos->prev; switch (pos->event_loop_info) { case MHD_EVENT_LOOP_INFO_READ: case MHD_EVENT_LOOP_INFO_PROCESS_READ: if (! MHD_add_to_fd_set_ (pos->socket_fd, read_fd_set, max_fd, fd_setsize)) result = MHD_NO; #ifdef MHD_POSIX_SOCKETS if (NULL != except_fd_set) (void) MHD_add_to_fd_set_ (pos->socket_fd, except_fd_set, max_fd, fd_setsize); #endif /* MHD_POSIX_SOCKETS */ break; case MHD_EVENT_LOOP_INFO_WRITE: if (! MHD_add_to_fd_set_ (pos->socket_fd, write_fd_set, max_fd, fd_setsize)) result = MHD_NO; #ifdef MHD_POSIX_SOCKETS if (NULL != except_fd_set) (void) MHD_add_to_fd_set_ (pos->socket_fd, except_fd_set, max_fd, fd_setsize); #endif /* MHD_POSIX_SOCKETS */ break; case MHD_EVENT_LOOP_INFO_PROCESS: if ( (NULL == except_fd_set) || ! MHD_add_to_fd_set_ (pos->socket_fd, except_fd_set, max_fd, fd_setsize)) result = MHD_NO; break; case MHD_EVENT_LOOP_INFO_CLEANUP: /* this should never happen */ break; } } #ifdef MHD_WINSOCK_SOCKETS /* W32 use limited array for fd_set so add INFO_READ/INFO_WRITE sockets * only after INFO_BLOCK sockets to ensure that INFO_BLOCK sockets will * not be pushed out. */ if (NULL != except_fd_set) { for (pos = daemon->connections_tail; NULL != pos; pos = posn) { posn = pos->prev; MHD_add_to_fd_set_ (pos->socket_fd, except_fd_set, max_fd, fd_setsize); } } #endif /* MHD_WINSOCK_SOCKETS */ #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (1) { struct MHD_UpgradeResponseHandle *urh; for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev) { if (MHD_NO == urh_to_fdset (urh, read_fd_set, write_fd_set, except_fd_set, max_fd, fd_setsize)) result = MHD_NO; } } #endif if (MHD_INVALID_SOCKET != ls) { /* The listen socket is present and hasn't been added */ if ((daemon->connections < daemon->connection_limit) && ! daemon->at_limit) { if (! MHD_add_to_fd_set_ (ls, read_fd_set, max_fd, fd_setsize)) result = MHD_NO; } } #if _MHD_DEBUG_CONNECT #ifdef HAVE_MESSAGES if (NULL != max_fd) MHD_DLOG (daemon, _ ("Maximum socket in select set: %d\n"), *max_fd); #endif #endif return result; } /** * Obtain the `select()` sets for this daemon. * Daemon's FDs will be added to fd_sets. To get only * daemon FDs in fd_sets, call FD_ZERO for each fd_set * before calling this function. * * Passing custom FD_SETSIZE as @a fd_setsize allow usage of * larger/smaller than platform's default fd_sets. * * This function should be called only when MHD is configured to * use "external" sockets polling with 'select()' or with 'epoll'. * In the latter case, it will only add the single 'epoll' file * descriptor used by MHD to the sets. * It's necessary to use #MHD_get_timeout() to get maximum timeout * value for `select()`. Usage of `select()` with indefinite timeout * (or timeout larger than returned by #MHD_get_timeout()) will * violate MHD API and may results in pending unprocessed data. * * This function must be called only for daemon started * without #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to get sets from * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param max_fd increased to largest FD added (if larger * than existing value); can be NULL * @param fd_setsize value of FD_SETSIZE * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or any FD didn't * fit fd_set. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_fdset2 (struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd, unsigned int fd_setsize) { if ( (NULL == daemon) || (NULL == read_fd_set) || (NULL == write_fd_set) || MHD_D_IS_USING_THREADS_ (daemon) || MHD_D_IS_USING_POLL_ (daemon)) return MHD_NO; #ifdef HAVE_MESSAGES if (NULL == except_fd_set) { MHD_DLOG (daemon, _ ("MHD_get_fdset2() called with except_fd_set " "set to NULL. Such behavior is unsupported.\n")); } #endif #ifdef HAS_FD_SETSIZE_OVERRIDABLE if (0 == fd_setsize) return MHD_NO; else if (((unsigned int) INT_MAX) < fd_setsize) fd_setsize = (unsigned int) INT_MAX; #ifdef HAVE_MESSAGES else if (daemon->fdset_size > ((int) fd_setsize)) { if (daemon->fdset_size_set_by_app) { MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than value set by MHD_OPTION_APP_FD_SETSIZE (%d). " \ "Some socket FDs may be not processed. " \ "Use MHD_OPTION_APP_FD_SETSIZE with the correct value.\n"), "MHD_get_fdset2", fd_setsize, daemon->fdset_size); } else { MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than FD_SETSIZE used by MHD (%d). " \ "Some socket FDs may be not processed. " \ "Consider using MHD_OPTION_APP_FD_SETSIZE option.\n"), "MHD_get_fdset2", fd_setsize, daemon->fdset_size); } } #endif /* HAVE_MESSAGES */ #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (((unsigned int) FD_SETSIZE) > fd_setsize) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than fixed FD_SETSIZE value (%d) used on the " \ "platform.\n"), "MHD_get_fdset2", fd_setsize, (int) FD_SETSIZE); #endif /* HAVE_MESSAGES */ return MHD_NO; } fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { if (daemon->shutdown) return MHD_YES; /* we're in epoll mode, use the epoll FD as a stand-in for the entire event set */ return MHD_add_to_fd_set_ (daemon->epoll_fd, read_fd_set, max_fd, (int) fd_setsize) ? MHD_YES : MHD_NO; } #endif return internal_get_fdset2 (daemon, read_fd_set, write_fd_set, except_fd_set, max_fd, (int) fd_setsize); } /** * Call the handlers for a connection in the appropriate order based * on the readiness as detected by the event loop. * * @param con connection to handle * @param read_ready set if the socket is ready for reading * @param write_ready set if the socket is ready for writing * @param force_close set if a hard error was detected on the socket; * if this information is not available, simply pass #MHD_NO * @return #MHD_YES to continue normally, * #MHD_NO if a serious error was encountered and the * connection is to be closed. */ static enum MHD_Result call_handlers (struct MHD_Connection *con, bool read_ready, bool write_ready, bool force_close) { enum MHD_Result ret; bool states_info_processed = false; /* Fast track flag */ bool on_fasttrack = (con->state == MHD_CONNECTION_INIT); ret = MHD_YES; mhd_assert ((0 == (con->daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_valid_ID_ (con->tid))); mhd_assert ((0 != (con->daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (! MHD_thread_handle_ID_is_valid_ID_ (con->tid))); mhd_assert ((0 == (con->daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_current_thread_ (con->tid))); #ifdef HTTPS_SUPPORT if (con->tls_read_ready) read_ready = true; #endif /* HTTPS_SUPPORT */ if (con->resumed) { /* The connection was resumed since its states were last updated, so 'con->event_loop_info' still describes the state the connection was in before it was suspended -- see the field's description. Dispatching on it would, for instance, call MHD_connection_handle_write() on a connection whose content reader has just reported that it has no data yet, which is not a state the write handler has an action for. */ con->resumed = false; ret = MHD_connection_handle_idle (con); if (MHD_NO == ret) return ret; /* Connection died and was cleaned up. */ states_info_processed = true; } if ( (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) && (read_ready || (force_close && con->sk_nonblck)) ) { MHD_connection_handle_read (con, force_close); /* MHD_connection_handle_read() closes the connection when @a force_close is set, but only once it gets far enough to try. It returns early, leaving 'con->state' untouched, in three cases, and all three are reachable from here: - the connection is suspended, - a TLS handshake is still in progress, - the read buffer has no free space at all. */ #ifdef HTTPS_SUPPORT mhd_assert ((! force_close) || \ (MHD_CONNECTION_CLOSED == con->state) || \ (con->suspended) || \ ( (MHD_TLS_CONN_NO_TLS != con->tls_state) && \ (MHD_TLS_CONN_CONNECTED > con->tls_state) ) || \ (con->read_buffer_size == con->read_buffer_offset)); #else /* ! HTTPS_SUPPORT */ mhd_assert ((! force_close) || \ (MHD_CONNECTION_CLOSED == con->state) || \ (con->suspended) || \ (con->read_buffer_size == con->read_buffer_offset)); #endif /* ! HTTPS_SUPPORT */ ret = MHD_connection_handle_idle (con); if (force_close) return ret; states_info_processed = true; } if (! force_close) { /* No need to check value of 'ret' here as closed connection * cannot be in MHD_EVENT_LOOP_INFO_WRITE state. */ if ( (MHD_EVENT_LOOP_INFO_WRITE == con->event_loop_info) && write_ready) { MHD_connection_handle_write (con); ret = MHD_connection_handle_idle (con); states_info_processed = true; } } else { MHD_connection_close_ (con, MHD_REQUEST_TERMINATED_WITH_ERROR); return MHD_connection_handle_idle (con); } if (! states_info_processed) { /* Connection is not read or write ready, but external conditions * may be changed and need to be processed. */ ret = MHD_connection_handle_idle (con); } /* Fast track for fast connections. */ /* If full request was read by single read_handler() invocation and headers were completely prepared by single MHD_connection_handle_idle() then try not to wait for next sockets polling and send response immediately. As writeability of socket was not checked and it may have some data pending in system buffers, use this optimization only for non-blocking sockets. */ /* No need to check 'ret' as connection is always in * MHD_CONNECTION_CLOSED state if 'ret' is equal 'MHD_NO'. */ else if (on_fasttrack && con->sk_nonblck) { if (MHD_CONNECTION_HEADERS_SENDING == con->state) { MHD_connection_handle_write (con); /* Always call 'MHD_connection_handle_idle()' after each read/write. */ ret = MHD_connection_handle_idle (con); } /* If all headers were sent by single write_handler() and * response body is prepared by single MHD_connection_handle_idle() * call - continue. */ if ((MHD_CONNECTION_NORMAL_BODY_READY == con->state) || (MHD_CONNECTION_CHUNKED_BODY_READY == con->state)) { MHD_connection_handle_write (con); ret = MHD_connection_handle_idle (con); } } /* All connection's data and states are processed for this turn. * If connection already has more data to be processed - use * zero timeout for next select()/poll(). */ /* Thread-per-connection do not need global zero timeout as * connections are processed individually. */ /* Note: no need to check for read buffer availability for * TLS read-ready connection in 'read info' state as connection * without space in read buffer will be marked as 'info block'. */ if ( (! con->daemon->data_already_pending) && (! MHD_D_IS_USING_THREAD_PER_CONN_ (con->daemon)) ) { if (0 != (MHD_EVENT_LOOP_INFO_PROCESS & con->event_loop_info)) con->daemon->data_already_pending = true; #ifdef HTTPS_SUPPORT else if ( (con->tls_read_ready) && (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) ) con->daemon->data_already_pending = true; #endif /* HTTPS_SUPPORT */ } return ret; } #ifdef UPGRADE_SUPPORT /** * Finally cleanup upgrade-related resources. It should * be called when TLS buffers have been drained and * application signaled MHD by #MHD_UPGRADE_ACTION_CLOSE. * * @param connection handle to the upgraded connection to clean */ static void cleanup_upgraded_connection (struct MHD_Connection *connection) { struct MHD_UpgradeResponseHandle *urh = connection->urh; if (NULL == urh) return; #ifdef HTTPS_SUPPORT /* Signal remote client the end of TLS connection by * gracefully closing TLS session. */ if (0 != (connection->daemon->options & MHD_USE_TLS)) gnutls_bye (connection->tls_session, GNUTLS_SHUT_WR); if (MHD_INVALID_SOCKET != urh->mhd.socket) MHD_socket_close_chk_ (urh->mhd.socket); if (MHD_INVALID_SOCKET != urh->app.socket) MHD_socket_close_chk_ (urh->app.socket); #endif /* HTTPS_SUPPORT */ connection->urh = NULL; free (urh); } #endif /* UPGRADE_SUPPORT */ #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /** * Performs bi-directional forwarding on upgraded HTTPS connections * based on the readiness state stored in the @a urh handle. * @remark To be called only from thread that processes * connection's recv(), send() and response. * * @param urh handle to process */ static void process_urh (struct MHD_UpgradeResponseHandle *urh) { /* Help compiler to optimize: * pointers to 'connection' and 'daemon' are not changed * during this processing, so no need to chain dereference * each time. */ struct MHD_Connection *const connection = urh->connection; struct MHD_Daemon *const daemon = connection->daemon; /* Prevent data races: use same value of 'was_closed' throughout * this function. If 'was_closed' changed externally in the middle * of processing - it will be processed on next iteration. */ bool was_closed; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); #endif /* MHD_USE_THREADS */ mhd_assert (0 != (daemon->options & MHD_USE_TLS)); if (daemon->shutdown) { /* Daemon shutting down, application will not receive any more data. */ #ifdef HAVE_MESSAGES if (! urh->was_closed) { MHD_DLOG (daemon, _ ("Initiated daemon shutdown while \"upgraded\" " \ "connection was not closed.\n")); } #endif urh->was_closed = true; } was_closed = urh->was_closed; if (was_closed) { /* Application was closed connections: no more data * can be forwarded to application socket. */ if (0 < urh->in_buffer_used) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to forward to application %" PRIu64 \ " bytes of data received from remote side: " \ "application closed data forwarding.\n"), (uint64_t) urh->in_buffer_used); #endif } /* Discard any data received form remote. */ urh->in_buffer_used = 0; /* Do not try to push data to application. */ urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); /* Reading from remote client is not required anymore. */ urh->in_buffer_size = 0; urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); connection->tls_read_ready = false; } /* On some platforms (W32, possibly Darwin) failed send() (send() will * always fail after remote disconnect was detected) may discard data in * system buffers received by system but not yet read by recv(). So, before * trying send() on any socket, recv() must be performed at first otherwise * last part of incoming data may be lost. If disconnect or error was * detected - try to read from socket to dry data possibly pending is system * buffers. */ /* * handle reading from remote TLS client */ if (((0 != ((MHD_EPOLL_STATE_ERROR | MHD_EPOLL_STATE_READ_READY) & urh->app.celi)) || (connection->tls_read_ready)) && (urh->in_buffer_used < urh->in_buffer_size)) { ssize_t res; size_t buf_size; buf_size = urh->in_buffer_size - urh->in_buffer_used; if (buf_size > SSIZE_MAX) buf_size = SSIZE_MAX; res = gnutls_record_recv (connection->tls_session, &urh->in_buffer[urh->in_buffer_used], buf_size); if (0 >= res) { connection->tls_read_ready = false; if (GNUTLS_E_INTERRUPTED != res) { urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); if ((GNUTLS_E_AGAIN != res) || (0 != (MHD_EPOLL_STATE_ERROR & urh->app.celi))) { /* TLS unrecoverable error has been detected, socket error was detected and all data has been read, or socket was disconnected/shut down. */ /* Stop trying to read from this TLS socket. */ urh->in_buffer_size = 0; } } } else /* 0 < res */ { urh->in_buffer_used += (size_t) res; connection->tls_read_ready = (0 < gnutls_record_check_pending (connection->tls_session)); } } /* * handle reading from application */ /* If application signalled MHD about socket closure then * check for any pending data even if socket is not marked * as 'ready' (signal may arrive after poll()/select()). * Socketpair for forwarding is always in non-blocking mode * so no risk that recv() will block the thread. */ if (((0 != ((MHD_EPOLL_STATE_ERROR | MHD_EPOLL_STATE_READ_READY) & urh->mhd.celi)) || was_closed) /* Force last reading from app if app has closed the connection */ && (urh->out_buffer_used < urh->out_buffer_size)) { ssize_t res; size_t buf_size; buf_size = urh->out_buffer_size - urh->out_buffer_used; if (buf_size > MHD_SCKT_SEND_MAX_SIZE_) buf_size = MHD_SCKT_SEND_MAX_SIZE_; res = MHD_recv_ (urh->mhd.socket, &urh->out_buffer[urh->out_buffer_used], buf_size); if (0 >= res) { const int err = MHD_socket_get_error_ (); if ((0 == res) || ((! MHD_SCKT_ERR_IS_EINTR_ (err)) && (! MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)))) { urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); if ((0 == res) || (was_closed) || (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) || (! MHD_SCKT_ERR_IS_EAGAIN_ (err))) { /* Socket disconnect/shutdown was detected; * Application signalled about closure of 'upgraded' socket and * all data has been read from application; * or persistent / unrecoverable error. */ /* Do not try to pull more data from application. */ urh->out_buffer_size = 0; } } } else /* 0 < res */ { urh->out_buffer_used += (size_t) res; if (buf_size > (size_t) res) urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); } } /* * handle writing to remote HTTPS client */ if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) && (urh->out_buffer_used > 0) ) { ssize_t res; size_t data_size; data_size = urh->out_buffer_used; if (data_size > SSIZE_MAX) data_size = SSIZE_MAX; res = gnutls_record_send (connection->tls_session, urh->out_buffer, data_size); if (0 >= res) { if (GNUTLS_E_INTERRUPTED != res) { urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); if (GNUTLS_E_AGAIN != res) { /* TLS connection shut down or * persistent / unrecoverable error. */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to forward to remote client %" PRIu64 \ " bytes of data received from application: %s\n"), (uint64_t) urh->out_buffer_used, gnutls_strerror ((int) res)); #endif /* Discard any data unsent to remote. */ urh->out_buffer_used = 0; /* Do not try to pull more data from application. */ urh->out_buffer_size = 0; urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); } } } else /* 0 < res */ { const size_t next_out_buffer_used = urh->out_buffer_used - (size_t) res; if (0 != next_out_buffer_used) { memmove (urh->out_buffer, &urh->out_buffer[res], next_out_buffer_used); } urh->out_buffer_used = next_out_buffer_used; } if ( (0 == urh->out_buffer_used) && (0 != (MHD_EPOLL_STATE_ERROR & urh->app.celi)) ) { /* Unrecoverable error on socket was detected and all * pending data was sent to remote. */ /* Do not try to send to remote anymore. */ urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); /* Do not try to pull more data from application. */ urh->out_buffer_size = 0; urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); } } /* * handle writing to application */ if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) && (urh->in_buffer_used > 0) ) { ssize_t res; size_t data_size; data_size = urh->in_buffer_used; if (data_size > MHD_SCKT_SEND_MAX_SIZE_) data_size = MHD_SCKT_SEND_MAX_SIZE_; res = MHD_send_ (urh->mhd.socket, urh->in_buffer, data_size); if (0 >= res) { const int err = MHD_socket_get_error_ (); if ( (! MHD_SCKT_ERR_IS_EINTR_ (err)) && (! MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) ) { urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); if (! MHD_SCKT_ERR_IS_EAGAIN_ (err)) { /* Socketpair connection shut down or * persistent / unrecoverable error. */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to forward to application %" PRIu64 \ " bytes of data received from remote side: %s\n"), (uint64_t) urh->in_buffer_used, MHD_socket_strerr_ (err)); #endif /* Discard any data received from remote. */ urh->in_buffer_used = 0; /* Reading from remote client is not required anymore. */ urh->in_buffer_size = 0; urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); connection->tls_read_ready = false; } } } else /* 0 < res */ { const size_t next_in_buffer_used = urh->in_buffer_used - (size_t) res; if (0 != next_in_buffer_used) { memmove (urh->in_buffer, &urh->in_buffer[res], next_in_buffer_used); if (data_size > (size_t) res) urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); } urh->in_buffer_used = next_in_buffer_used; } if ( (0 == urh->in_buffer_used) && (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) ) { /* Do not try to push data to application. */ urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); /* Reading from remote client is not required anymore. */ urh->in_buffer_size = 0; urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); connection->tls_read_ready = false; } } /* Check whether data is present in TLS buffers * and incoming forward buffer have some space. */ if ( (connection->tls_read_ready) && (urh->in_buffer_used < urh->in_buffer_size) && (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) ) daemon->data_already_pending = true; if ( (daemon->shutdown) && ( (0 != urh->out_buffer_size) || (0 != urh->out_buffer_used) ) ) { /* Daemon shutting down, discard any remaining forward data. */ #ifdef HAVE_MESSAGES if (0 < urh->out_buffer_used) MHD_DLOG (daemon, _ ("Failed to forward to remote client %" PRIu64 \ " bytes of data received from application: daemon shut down.\n"), (uint64_t) urh->out_buffer_used); #endif /* Discard any data unsent to remote. */ urh->out_buffer_used = 0; /* Do not try to sent to remote anymore. */ urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); /* Do not try to pull more data from application. */ urh->out_buffer_size = 0; urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); } if (! was_closed && urh->was_closed) daemon->data_already_pending = true; /* Force processing again */ } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #ifdef UPGRADE_SUPPORT /** * Main function of the thread that handles an individual connection * after it was "upgraded" when #MHD_USE_THREAD_PER_CONNECTION is set. * @remark To be called only from thread that process * connection's recv(), send() and response. * * @param con the connection this thread will handle */ static void thread_main_connection_upgrade (struct MHD_Connection *con) { #ifdef HTTPS_SUPPORT struct MHD_UpgradeResponseHandle *urh = con->urh; struct MHD_Daemon *daemon = con->daemon; mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (con->tid) ); /* Here, we need to bi-directionally forward until the application tells us that it is done with the socket; */ if ( (0 != (daemon->options & MHD_USE_TLS)) && MHD_D_IS_USING_SELECT_ (daemon)) { while ( (0 != urh->in_buffer_size) || (0 != urh->out_buffer_size) || (0 != urh->in_buffer_used) || (0 != urh->out_buffer_used) ) { /* use select */ fd_set rs; fd_set ws; fd_set es; MHD_socket max_fd; int num_ready; bool result; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); max_fd = MHD_INVALID_SOCKET; result = urh_to_fdset (urh, &rs, &ws, &es, &max_fd, FD_SETSIZE); if (! result) { #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error preparing select.\n")); #endif break; } /* FIXME: does this check really needed? */ if (MHD_INVALID_SOCKET != max_fd) { struct timeval *tvp; struct timeval tv; if (((con->tls_read_ready) && (urh->in_buffer_used < urh->in_buffer_size)) || (daemon->shutdown)) { /* No need to wait if incoming data is already pending in TLS buffers. */ tv.tv_sec = 0; tv.tv_usec = 0; tvp = &tv; } else tvp = NULL; num_ready = MHD_SYS_select_ (max_fd + 1, &rs, &ws, &es, tvp); } else num_ready = 0; if (num_ready < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during select (%d): `%s'\n"), err, MHD_socket_strerr_ (err)); #endif break; } urh_from_fdset (urh, &rs, &ws, &es, (int) FD_SETSIZE); process_urh (urh); } } #ifdef HAVE_POLL else if (0 != (daemon->options & MHD_USE_TLS)) { /* use poll() */ struct pollfd p[2]; memset (p, 0, sizeof (p)); p[0].fd = urh->connection->socket_fd; p[1].fd = urh->mhd.socket; while ( (0 != urh->in_buffer_size) || (0 != urh->out_buffer_size) || (0 != urh->in_buffer_used) || (0 != urh->out_buffer_used) ) { int timeout; urh_update_pollfd (urh, p); if (((con->tls_read_ready) && (urh->in_buffer_used < urh->in_buffer_size)) || (daemon->shutdown)) timeout = 0; /* No need to wait if incoming data is already pending in TLS buffers. */ else timeout = -1; if (MHD_sys_poll_ (p, 2, timeout) < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during poll: `%s'\n"), MHD_socket_strerr_ (err)); #endif break; } urh_from_pollfd (urh, p); process_urh (urh); } } /* end POLL */ #endif /* end HTTPS */ #endif /* HTTPS_SUPPORT */ /* TLS forwarding was finished. Cleanup socketpair. */ MHD_connection_finish_forward_ (con); /* Do not set 'urh->clean_ready' yet as 'urh' will be used * in connection thread for a little while. */ } #endif /* UPGRADE_SUPPORT */ /** * Get maximum wait period for the connection (the amount of time left before * connection time out) * @param c the connection to check * @return the maximum number of millisecond before the connection must be * processed again. */ static uint64_t connection_get_wait (struct MHD_Connection *c) { const uint64_t now = MHD_monotonic_msec_counter (); const uint64_t since_actv = now - c->last_activity; const uint64_t timeout = c->connection_timeout_ms; uint64_t mseconds_left; mhd_assert (0 != timeout); /* Keep the next lines in sync with #connection_check_timedout() to avoid * undesired side-effects like busy-waiting. */ if (timeout < since_actv) { if (UINT64_MAX / 2 < since_actv) { const uint64_t jump_back = c->last_activity - now; /* Very unlikely that it is more than quarter-million years pause. * More likely that system clock jumps back. */ if (5000 >= jump_back) { /* Jump back is less than 5 seconds, try to recover. */ return 100; /* Set wait time to 0.1 seconds */ } /* Too large jump back */ } return 0; /* Connection has timed out */ } else if (since_actv == timeout) { /* Exact match for timeout and time from last activity. * Maybe this is just a precise match or this happens because the timer * resolution is too low. * Set wait time to 0.1 seconds to avoid busy-waiting with low * timer resolution as connection is not timed-out yet. */ return 100; } mseconds_left = timeout - since_actv; return mseconds_left; } /** * Complete the resume of a connection that has its own thread. * * This is the thread-per-connection counterpart of * resume_suspended_connections(): the connection's own thread does the * bookkeeping for itself instead of waiting for the daemon's thread to * do it. That is what makes the wake-up reliable -- the notification * is sent to the connection's own ITC and is acted upon by the only * thread that reads it, so it can neither be consumed by the daemon's * thread nor be missed between the check of @e resuming and the wait. * * @param connection the suspended connection that is to be resumed, * must have @e resuming set */ static void resume_connection_own_thread_ (struct MHD_Connection *connection) { struct MHD_Daemon *const daemon = connection->daemon; mhd_assert (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)); mhd_assert (! MHD_D_IS_USING_EPOLL_ (daemon)); #ifdef UPGRADE_SUPPORT mhd_assert (NULL == connection->urh); #endif /* UPGRADE_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif mhd_assert (connection->suspended); mhd_assert (connection->resuming); DLL_remove (daemon->suspended_connections_head, daemon->suspended_connections_tail, connection); connection->suspended = false; DLL_insert (daemon->connections_head, daemon->connections_tail, connection); connection->resuming = false; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif /* Drop the notification that led here, as well as any notification left over from a resume that was undone by a suspend before this thread got to see it. */ MHD_itc_clear_ (connection->resume_itc); } /** * Main function of the thread that handles an individual * connection when #MHD_USE_THREAD_PER_CONNECTION is set. * * @param data the `struct MHD_Connection` this thread will handle * @return always 0 */ static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ thread_main_handle_connection (void *data) { struct MHD_Connection *con = data; struct MHD_Daemon *daemon = con->daemon; int num_ready; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; #ifdef WINDOWS #ifdef HAVE_POLL unsigned int extra_slot; #endif /* HAVE_POLL */ #define EXTRA_SLOTS 1 #else /* !WINDOWS */ #define EXTRA_SLOTS 0 #endif /* !WINDOWS */ #ifdef HAVE_POLL struct pollfd p[1 + EXTRA_SLOTS]; #endif #undef EXTRA_SLOTS #ifdef HAVE_POLL const bool use_poll = MHD_D_IS_USING_POLL_ (daemon); #else /* ! HAVE_POLL */ const bool use_poll = 0; #endif /* ! HAVE_POLL */ bool was_suspended = false; MHD_thread_handle_ID_set_current_thread_ID_ (&(con->tid)); while ( (! daemon->shutdown) && (MHD_CONNECTION_CLOSED != con->state) ) { bool use_zero_timeout; #ifdef UPGRADE_SUPPORT struct MHD_UpgradeResponseHandle *const urh = con->urh; #else /* ! UPGRADE_SUPPORT */ static const void *const urh = NULL; #endif /* ! UPGRADE_SUPPORT */ if ( (con->suspended) && (NULL == urh) ) { /* Connection was suspended, wait for resume. */ was_suspended = true; if (con->resuming) { /* The application resumed this connection. Complete the resume right here: this thread is the only one that handles this connection, and doing it here is what keeps the wake-up below free of lost-notification races. */ resume_connection_own_thread_ (con); continue; } mhd_assert (MHD_ITC_IS_VALID_ (con->resume_itc)); if (! use_poll) { FD_ZERO (&rs); if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (con->resume_itc), &rs, NULL, FD_SETSIZE)) { #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Failed to add FD to fd_set.\n")); #endif goto exit; } if (0 > MHD_SYS_select_ (MHD_itc_r_fd_ (con->resume_itc) + 1, &rs, NULL, NULL, NULL)) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during select (%d): `%s'\n"), err, MHD_socket_strerr_ (err)); #endif break; } } #ifdef HAVE_POLL else /* use_poll */ { p[0].events = POLLIN; p[0].fd = MHD_itc_r_fd_ (con->resume_itc); p[0].revents = 0; if (0 > MHD_sys_poll_ (p, 1, -1)) { if (MHD_SCKT_LAST_ERR_IS_ (MHD_SCKT_EINTR_)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during poll: `%s'\n"), MHD_socket_last_strerr_ ()); #endif break; } } #endif /* HAVE_POLL */ MHD_itc_clear_ (con->resume_itc); continue; /* Check again for resume. */ } /* End of "suspended" branch. */ if (was_suspended) { MHD_update_last_activity_ (con); /* Reset timeout timer. */ /* Process response queued during suspend and update states. */ MHD_connection_handle_idle (con); was_suspended = false; } use_zero_timeout = (0 != (MHD_EVENT_LOOP_INFO_PROCESS & con->event_loop_info) #ifdef HTTPS_SUPPORT || ( (con->tls_read_ready) && (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) ) #endif /* HTTPS_SUPPORT */ ); if (! use_poll) { /* use select */ bool err_state = false; struct timeval tv; struct timeval *tvp; if (use_zero_timeout) { tv.tv_sec = 0; tv.tv_usec = 0; tvp = &tv; } else if (con->connection_timeout_ms > 0) { const uint64_t mseconds_left = connection_get_wait (con); #if (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC if (mseconds_left / 1000 > TIMEVAL_TV_SEC_MAX) tv.tv_sec = TIMEVAL_TV_SEC_MAX; else #endif /* (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC */ tv.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) mseconds_left / 1000; tv.tv_usec = ((uint16_t) (mseconds_left % 1000)) * ((int32_t) 1000); tvp = &tv; } else tvp = NULL; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); maxsock = MHD_INVALID_SOCKET; switch (con->event_loop_info) { case MHD_EVENT_LOOP_INFO_READ: case MHD_EVENT_LOOP_INFO_PROCESS_READ: if (! MHD_add_to_fd_set_ (con->socket_fd, &rs, &maxsock, FD_SETSIZE)) err_state = true; break; case MHD_EVENT_LOOP_INFO_WRITE: if (! MHD_add_to_fd_set_ (con->socket_fd, &ws, &maxsock, FD_SETSIZE)) err_state = true; break; case MHD_EVENT_LOOP_INFO_PROCESS: if (! MHD_add_to_fd_set_ (con->socket_fd, &es, &maxsock, FD_SETSIZE)) err_state = true; break; case MHD_EVENT_LOOP_INFO_CLEANUP: /* how did we get here!? */ goto exit; } #ifdef WINDOWS if (MHD_ITC_IS_VALID_ (daemon->itc) ) { if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc), &rs, &maxsock, FD_SETSIZE)) err_state = 1; } #endif if (err_state) { #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Failed to add FD to fd_set.\n")); #endif goto exit; } num_ready = MHD_SYS_select_ (maxsock + 1, &rs, &ws, &es, tvp); if (num_ready < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during select (%d): `%s'\n"), err, MHD_socket_strerr_ (err)); #endif break; } #ifdef WINDOWS /* Clear ITC before other processing so additional * signals will trigger select() again */ if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (FD_ISSET (MHD_itc_r_fd_ (daemon->itc), &rs)) ) MHD_itc_clear_ (daemon->itc); #endif if (MHD_NO == call_handlers (con, FD_ISSET (con->socket_fd, &rs), FD_ISSET (con->socket_fd, &ws), FD_ISSET (con->socket_fd, &es)) ) goto exit; } #ifdef HAVE_POLL else { int timeout_val; /* use poll */ if (use_zero_timeout) timeout_val = 0; else if (con->connection_timeout_ms > 0) { const uint64_t mseconds_left = connection_get_wait (con); #if SIZEOF_UINT64_T >= SIZEOF_INT if (mseconds_left >= INT_MAX) timeout_val = INT_MAX; else #endif /* SIZEOF_UINT64_T >= SIZEOF_INT */ timeout_val = (int) mseconds_left; } else timeout_val = -1; memset (&p, 0, sizeof (p)); p[0].fd = con->socket_fd; switch (con->event_loop_info) { case MHD_EVENT_LOOP_INFO_READ: case MHD_EVENT_LOOP_INFO_PROCESS_READ: p[0].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_WRITE: p[0].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_PROCESS: p[0].events |= MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_CLEANUP: /* how did we get here!? */ goto exit; } #ifdef WINDOWS extra_slot = 0; if (MHD_ITC_IS_VALID_ (daemon->itc)) { p[1].events |= POLLIN; p[1].fd = MHD_itc_r_fd_ (daemon->itc); p[1].revents = 0; extra_slot = 1; } #endif if (MHD_sys_poll_ (p, #ifdef WINDOWS 1 + extra_slot, #else 1, #endif timeout_val) < 0) { if (MHD_SCKT_LAST_ERR_IS_ (MHD_SCKT_EINTR_)) continue; #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Error during poll: `%s'\n"), MHD_socket_last_strerr_ ()); #endif break; } #ifdef WINDOWS /* Clear ITC before other processing so additional * signals will trigger poll() again */ if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (0 != (p[1].revents & (POLLERR | POLLHUP | POLLIN))) ) MHD_itc_clear_ (daemon->itc); #endif if (MHD_NO == call_handlers (con, (0 != (p[0].revents & POLLIN)), (0 != (p[0].revents & POLLOUT)), (0 != (p[0].revents & MHD_POLL_REVENTS_ERR_DISC)) )) goto exit; } #endif #ifdef UPGRADE_SUPPORT if (MHD_CONNECTION_UPGRADE == con->state) { /* Normal HTTP processing is finished, * notify application. */ if ( (NULL != daemon->notify_completed) && (con->rq.client_aware) ) daemon->notify_completed (daemon->notify_completed_cls, con, &con->rq.client_context, MHD_REQUEST_TERMINATED_COMPLETED_OK); con->rq.client_aware = false; thread_main_connection_upgrade (con); /* MHD_connection_finish_forward_() was called by thread_main_connection_upgrade(). */ /* "Upgraded" data will not be used in this thread from this point. */ con->urh->clean_ready = true; /* If 'urh->was_closed' set to true, connection will be * moved immediately to cleanup list. Otherwise connection * will stay in suspended list until 'urh' will be marked * with 'was_closed' by application. */ MHD_resume_connection (con); /* skip usual clean up */ return (MHD_THRD_RTRN_TYPE_) 0; } #endif /* UPGRADE_SUPPORT */ } #if _MHD_DEBUG_CLOSE #ifdef HAVE_MESSAGES MHD_DLOG (con->daemon, _ ("Processing thread terminating. Closing connection.\n")); #endif #endif if (MHD_CONNECTION_CLOSED != con->state) MHD_connection_close_ (con, (daemon->shutdown) ? MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN : MHD_REQUEST_TERMINATED_WITH_ERROR); MHD_connection_handle_idle (con); exit: if (NULL != con->rp.response) { MHD_destroy_response (con->rp.response); con->rp.response = NULL; } if (MHD_INVALID_SOCKET != con->socket_fd) { shutdown (con->socket_fd, SHUT_WR); /* 'socket_fd' can be used in other thread to signal shutdown. * To avoid data races, do not close socket here. Daemon will * use more connections only after cleanup anyway. */ } if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "t")) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal thread termination via inter-thread " \ "communication channel.\n")); #endif } return (MHD_THRD_RTRN_TYPE_) 0; } #endif /** * Free resources associated with all closed connections. * (destroy responses, free buffers, etc.). All closed * connections are kept in the "cleanup" doubly-linked list. * * @param daemon daemon to clean up */ static void MHD_cleanup_connections (struct MHD_Daemon *daemon); #if defined(HTTPS_SUPPORT) #if defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) && \ defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) && \ ! defined(MHD_socket_nosignal_) && \ (GNUTLS_VERSION_NUMBER + 0 < 0x030402) && defined(MSG_NOSIGNAL) /** * Older version of GnuTLS do not support suppressing of SIGPIPE signal. * Use push function replacement with suppressing SIGPIPE signal where necessary * and if possible. */ #define MHD_TLSLIB_NEED_PUSH_FUNC 1 #endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED && MHD_SEND_SPIPE_SUPPRESS_POSSIBLE && ! MHD_socket_nosignal_ && (GNUTLS_VERSION_NUMBER+0 < 0x030402) && MSG_NOSIGNAL */ #ifdef MHD_TLSLIB_NEED_PUSH_FUNC /** * Data push function replacement with suppressing SIGPIPE signal * for TLS library. */ static ssize_t MHD_tls_push_func_ (gnutls_transport_ptr_t trnsp, const void *data, size_t data_size) { #if (MHD_SCKT_SEND_MAX_SIZE_ < SSIZE_MAX) || (0 == SSIZE_MAX) if (data_size > MHD_SCKT_SEND_MAX_SIZE_) data_size = MHD_SCKT_SEND_MAX_SIZE_; #endif /* (MHD_SCKT_SEND_MAX_SIZE_ < SSIZE_MAX) || (0 == SSIZE_MAX) */ return MHD_send_ ((MHD_socket) (intptr_t) (trnsp), data, data_size); } #endif /* MHD_TLSLIB_DONT_SUPPRESS_SIGPIPE */ /** * The shortest pre-shared key #MHD_OPTION_GNUTLS_PSK_CRED_HANDLER may * hand back, in bytes. RFC 4279 section 7.1 requires at least 16 bytes * of entropy in a PSK and recommends the length of the hash of the * negotiated cipher suite; anything shorter is brute-forceable offline * from a single recorded handshake, so MHD refuses it rather than let * the application weaken the connection by accident. */ #define MHD_PSK_MIN_SIZE 16 /** * Function called by GNUtls to obtain the PSK for a given session. * * @param session the session to lookup PSK for * @param username username to lookup PSK for * @param[out] key where to write PSK * @return 0 on success, -1 on error */ static int psk_gnutls_adapter (gnutls_session_t session, const char *username, gnutls_datum_t *key) { struct MHD_Connection *connection; struct MHD_Daemon *daemon; #if GNUTLS_VERSION_MAJOR >= 3 void *app_psk; size_t app_psk_size; #endif /* GNUTLS_VERSION_MAJOR >= 3 */ connection = gnutls_session_get_ptr (session); if (NULL == connection) { #ifdef HAVE_MESSAGES /* Cannot use our logger, we don't even have "daemon" */ MHD_PANIC (_ ("Internal server error. This should be impossible.\n")); #endif return -1; } daemon = connection->daemon; #if GNUTLS_VERSION_MAJOR >= 3 if (NULL == daemon->cred_callback) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("PSK not supported by this server.\n")); #endif return -1; } if (0 != daemon->cred_callback (daemon->cred_callback_cls, connection, username, &app_psk, &app_psk_size)) return -1; if (MHD_PSK_MIN_SIZE > app_psk_size) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("PSK authentication failed: PSK too short.\n")); #endif free (app_psk); return -1; } if (UINT_MAX < app_psk_size) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("PSK authentication failed: PSK too long.\n")); #endif free (app_psk); return -1; } /* @a app_psk_size is at least MHD_PSK_MIN_SIZE here, so this is never gnutls_malloc(0) -- whose result is implementation defined and would be reported below as an allocation failure. */ if (NULL == (key->data = gnutls_malloc (app_psk_size))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("PSK authentication failed: gnutls_malloc failed to " \ "allocate memory.\n")); #endif free (app_psk); return -1; } key->size = (unsigned int) app_psk_size; memcpy (key->data, app_psk, app_psk_size); free (app_psk); return 0; #else (void) username; (void) key; /* Mute compiler warning */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("PSK not supported by this server.\n")); #endif return -1; #endif } #endif /* HTTPS_SUPPORT */ /** * Do basic preparation work on the new incoming connection. * * This function do all preparation that is possible outside main daemon * thread. * @remark Could be called from any thread. * * @param daemon daemon that manages the connection * @param client_socket socket to manage (MHD will expect * to receive an HTTP request from this socket next). * @param addr IP address of the client * @param addrlen number of bytes in @a addr * @param external_add indicate that socket has been added externally * @param non_blck indicate that socket in non-blocking mode * @param sk_spipe_supprs indicate that the @a client_socket has * set SIGPIPE suppression * @param sk_is_nonip _MHD_YES if this is not a TCP/IP socket * @return pointer to the connection on success, NULL if this daemon could * not handle the connection (i.e. malloc failed, etc). * The socket will be closed in case of error; 'errno' is * set to indicate further details about the error. */ static struct MHD_Connection * new_connection_prepare_ (struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr_storage *addr, socklen_t addrlen, bool external_add, bool non_blck, bool sk_spipe_supprs, enum MHD_tristate sk_is_nonip) { struct MHD_Connection *connection; int eno = 0; #ifdef HAVE_MESSAGES #if _MHD_DEBUG_CONNECT MHD_DLOG (daemon, _ ("Accepted connection on socket %d.\n"), client_socket); #endif #endif if ( (daemon->connections == daemon->connection_limit) || (MHD_NO == MHD_ip_limit_add (daemon, addr, addrlen)) ) { /* above connection limit - reject */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Server reached connection limit. " \ "Closing inbound connection.\n")); #endif MHD_socket_close_chk_ (client_socket); #if defined(ENFILE) && (ENFILE + 0 != 0) errno = ENFILE; #endif return NULL; } /* apply connection acceptance policy if present */ if ( (NULL != daemon->apc) && (MHD_NO == daemon->apc (daemon->apc_cls, (const struct sockaddr *) addr, addrlen)) ) { #if _MHD_DEBUG_CLOSE #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Connection rejected by application. Closing connection.\n")); #endif #endif MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); #if defined(EACCESS) && (EACCESS + 0 != 0) errno = EACCESS; #endif return NULL; } if (NULL == (connection = MHD_calloc_ (1, sizeof (struct MHD_Connection)))) { eno = errno; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error allocating memory: %s\n"), MHD_strerror_ (errno)); #endif MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); errno = eno; return NULL; } if (! external_add) { connection->sk_corked = _MHD_OFF; connection->sk_nodelay = _MHD_OFF; } else { connection->sk_corked = _MHD_UNKNOWN; connection->sk_nodelay = _MHD_UNKNOWN; } if (0 < addrlen) { if (NULL == (connection->addr = malloc ((size_t) addrlen))) { eno = errno; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error allocating memory: %s\n"), MHD_strerror_ (errno)); #endif MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); free (connection); errno = eno; return NULL; } memcpy (connection->addr, addr, (size_t) addrlen); } else connection->addr = NULL; connection->addr_len = addrlen; connection->socket_fd = client_socket; connection->sk_nonblck = non_blck; connection->is_nonip = sk_is_nonip; connection->sk_spipe_suppress = sk_spipe_supprs; #ifdef MHD_USE_THREADS MHD_thread_handle_ID_set_invalid_ (&connection->tid); #endif /* MHD_USE_THREADS */ connection->daemon = daemon; connection->connection_timeout_ms = daemon->connection_timeout_ms; connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; if (0 != connection->connection_timeout_ms) connection->last_activity = MHD_monotonic_msec_counter (); MHD_itc_set_invalid_ (connection->resume_itc); if ( (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) && (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && (! MHD_itc_init_ (connection->resume_itc)) ) { eno = errno; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to create inter-thread communication channel " \ "for the connection: %s\n"), MHD_itc_last_strerror_ ()); #endif MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); if (NULL != connection->addr) free (connection->addr); free (connection); errno = eno; return NULL; } if (0 == (daemon->options & MHD_USE_TLS)) { /* set default connection handlers */ MHD_set_http_callbacks_ (connection); } else { #ifdef HTTPS_SUPPORT #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030500) gnutls_init_flags_t #else unsigned int #endif flags; flags = GNUTLS_SERVER; #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030402) flags |= GNUTLS_NO_SIGNAL; #endif /* GNUTLS_VERSION_NUMBER >= 0x030402 */ #if GNUTLS_VERSION_MAJOR >= 3 flags |= GNUTLS_NONBLOCK; #endif /* GNUTLS_VERSION_MAJOR >= 3*/ #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030603) if (0 != (daemon->options & MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT)) flags |= GNUTLS_POST_HANDSHAKE_AUTH; #endif #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030605) if (0 != (daemon->options & MHD_USE_INSECURE_TLS_EARLY_DATA)) flags |= GNUTLS_ENABLE_EARLY_DATA; #endif connection->tls_state = MHD_TLS_CONN_INIT; MHD_set_https_callbacks (connection); if ((GNUTLS_E_SUCCESS != gnutls_init (&connection->tls_session, flags)) || (GNUTLS_E_SUCCESS != gnutls_priority_set (connection->tls_session, daemon->priority_cache))) { if (NULL != connection->tls_session) gnutls_deinit (connection->tls_session); MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); if (NULL != connection->addr) free (connection->addr); free (connection); #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise TLS session.\n")); #endif #if defined(EPROTO) && (EPROTO + 0 != 0) errno = EPROTO; #endif return NULL; } #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030200) if (! daemon->disable_alpn) { static const char prt1[] = "http/1.1"; /* Registered code for HTTP/1.1 */ static const char prt2[] = "http/1.0"; /* Registered code for HTTP/1.0 */ static const gnutls_datum_t prts[2] = { {_MHD_DROP_CONST (prt1), MHD_STATICSTR_LEN_ (prt1)}, {_MHD_DROP_CONST (prt2), MHD_STATICSTR_LEN_ (prt2)} }; if (GNUTLS_E_SUCCESS != gnutls_alpn_set_protocols (connection->tls_session, prts, sizeof(prts) / sizeof(prts[0]), 0 /* | GNUTLS_ALPN_SERVER_PRECEDENCE */)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set ALPN protocols.\n")); #else /* ! HAVE_MESSAGES */ (void) 0; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ } } #endif /* GNUTLS_VERSION_NUMBER >= 0x030200 */ gnutls_session_set_ptr (connection->tls_session, connection); switch (daemon->cred_type) { /* set needed credentials for certificate authentication. */ case GNUTLS_CRD_CERTIFICATE: gnutls_credentials_set (connection->tls_session, GNUTLS_CRD_CERTIFICATE, daemon->x509_cred); break; case GNUTLS_CRD_PSK: gnutls_credentials_set (connection->tls_session, GNUTLS_CRD_PSK, daemon->psk_cred); gnutls_psk_set_server_credentials_function (daemon->psk_cred, &psk_gnutls_adapter); break; case GNUTLS_CRD_ANON: case GNUTLS_CRD_SRP: case GNUTLS_CRD_IA: default: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to setup TLS credentials: " \ "unknown credential type %d.\n"), daemon->cred_type); #endif gnutls_deinit (connection->tls_session); MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); if (NULL != connection->addr) free (connection->addr); free (connection); MHD_PANIC (_ ("Unknown credential type.\n")); #if defined(EINVAL) && (EINVAL + 0 != 0) errno = EINVAL; #endif return NULL; } #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64) gnutls_transport_set_int (connection->tls_session, (int) (client_socket)); #else /* GnuTLS before 3.1.9 or Win x64 */ gnutls_transport_set_ptr (connection->tls_session, (gnutls_transport_ptr_t) \ (intptr_t) client_socket); #endif /* GnuTLS before 3.1.9 or Win x64 */ #ifdef MHD_TLSLIB_NEED_PUSH_FUNC gnutls_transport_set_push_function (connection->tls_session, MHD_tls_push_func_); #endif /* MHD_TLSLIB_NEED_PUSH_FUNC */ if (daemon->https_mem_trust) gnutls_certificate_server_set_request (connection->tls_session, GNUTLS_CERT_REQUEST); #else /* ! HTTPS_SUPPORT */ MHD_socket_close_chk_ (client_socket); MHD_ip_limit_del (daemon, addr, addrlen); free (connection->addr); free (connection); MHD_PANIC (_ ("TLS connection on non-TLS daemon.\n")); #if 0 /* Unreachable code */ eno = EINVAL; return NULL; #endif #endif /* ! HTTPS_SUPPORT */ } return connection; } #ifdef MHD_USE_THREADS /** * Close prepared, but not yet processed connection. * @param daemon the daemon * @param connection the connection to close */ static void new_connection_close_ (struct MHD_Daemon *daemon, struct MHD_Connection *connection) { mhd_assert (connection->daemon == daemon); mhd_assert (! connection->in_cleanup); mhd_assert (NULL == connection->next); mhd_assert (NULL == connection->nextX); #ifdef EPOLL_SUPPORT mhd_assert (NULL == connection->nextE); #endif /* EPOLL_SUPPORT */ #ifdef HTTPS_SUPPORT if (NULL != connection->tls_session) { mhd_assert (0 != (daemon->options & MHD_USE_TLS)); gnutls_deinit (connection->tls_session); } #endif /* HTTPS_SUPPORT */ MHD_socket_close_chk_ (connection->socket_fd); if (MHD_ITC_IS_VALID_ (connection->resume_itc)) MHD_itc_destroy_chk_ (connection->resume_itc); MHD_ip_limit_del (daemon, connection->addr, connection->addr_len); if (NULL != connection->addr) free (connection->addr); free (connection); } #endif /* MHD_USE_THREADS */ /** * Finally insert the new connection to the list of connections * served by the daemon and start processing. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon that manages the connection * @param connection the newly created connection * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result new_connection_process_ (struct MHD_Daemon *daemon, struct MHD_Connection *connection) { int eno = 0; mhd_assert (connection->daemon == daemon); #ifdef MHD_USE_THREADS /* Function manipulate connection and timeout DL-lists, * must be called only within daemon thread. */ mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ /* Allocate memory pool in the processing thread so * intensively used memory area is allocated in "good" * (for the thread) memory region. It is important with * NUMA and/or complex cache hierarchy. */ connection->pool = MHD_pool_create (daemon->pool_size); if (NULL == connection->pool) { /* 'pool' creation failed */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error allocating memory: %s\n"), MHD_strerror_ (errno)); #endif #if defined(ENOMEM) && (ENOMEM + 0 != 0) eno = ENOMEM; #endif (void) 0; /* Mute possible compiler warning */ } else { /* 'pool' creation succeed */ MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); /* Firm check under lock. */ if (daemon->connections >= daemon->connection_limit) { /* Connections limit */ MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Server reached connection limit. " "Closing inbound connection.\n")); #endif #if defined(ENFILE) && (ENFILE + 0 != 0) eno = ENFILE; #endif (void) 0; /* Mute possible compiler warning */ } else { /* Have space for new connection */ daemon->connections++; DLL_insert (daemon->connections_head, daemon->connections_tail, connection); if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { XDLL_insert (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); } MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); MHD_connection_set_initial_state_ (connection); if (NULL != daemon->notify_connection) daemon->notify_connection (daemon->notify_connection_cls, connection, &connection->socket_context, MHD_CONNECTION_NOTIFY_STARTED); #ifdef MHD_USE_THREADS if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { mhd_assert (! MHD_D_IS_USING_EPOLL_ (daemon)); if (! MHD_create_named_thread_ (&connection->tid, "MHD-connection", daemon->thread_stack_size, &thread_main_handle_connection, connection)) { eno = errno; #ifdef HAVE_MESSAGES #ifdef EAGAIN if (EAGAIN == eno) MHD_DLOG (daemon, _ ("Failed to create a new thread because it would " "have exceeded the system limit on the number of " "threads or no system resources available.\n")); else #endif /* EAGAIN */ MHD_DLOG (daemon, _ ("Failed to create a thread: %s\n"), MHD_strerror_ (eno)); #endif /* HAVE_MESSAGES */ } else /* New thread has been created successfully */ return MHD_YES; /* *** Function success exit point *** */ } else #else /* ! MHD_USE_THREADS */ if (1) #endif /* ! MHD_USE_THREADS */ { /* No 'thread-per-connection' */ #ifdef MHD_USE_THREADS connection->tid = daemon->tid; #endif /* MHD_USE_THREADS */ #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { if (0 == (daemon->options & MHD_USE_TURBO)) { struct epoll_event event; event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET | EPOLLRDHUP; event.data.ptr = connection; if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, connection->socket_fd, &event)) { eno = errno; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif } else { /* 'socket_fd' has been added to 'epool' */ connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET; return MHD_YES; /* *** Function success exit point *** */ } } else { connection->epoll_state |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY | MHD_EPOLL_STATE_IN_EREADY_EDLL; EDLL_insert (daemon->eready_head, daemon->eready_tail, connection); return MHD_YES; /* *** Function success exit point *** */ } } else /* No 'epoll' */ #endif /* EPOLL_SUPPORT */ return MHD_YES; /* *** Function success exit point *** */ } /* ** Below is a cleanup path ** */ if (NULL != daemon->notify_connection) daemon->notify_connection (daemon->notify_connection_cls, connection, &connection->socket_context, MHD_CONNECTION_NOTIFY_CLOSED); MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); } DLL_remove (daemon->connections_head, daemon->connections_tail, connection); daemon->connections--; MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); } MHD_pool_destroy (connection->pool); } /* Free resources allocated before the call of this functions */ #ifdef HTTPS_SUPPORT if (NULL != connection->tls_session) gnutls_deinit (connection->tls_session); #endif /* HTTPS_SUPPORT */ MHD_ip_limit_del (daemon, connection->addr, connection->addr_len); if (NULL != connection->addr) free (connection->addr); MHD_socket_close_chk_ (connection->socket_fd); free (connection); if (0 != eno) errno = eno; #ifdef EINVAL else errno = EINVAL; #endif /* EINVAL */ return MHD_NO; /* *** Function failure exit point *** */ } /** * Add another client connection to the set of connections * managed by MHD. This API is usually not needed (since * MHD will accept inbound connections on the server socket). * Use this API in special cases, for example if your HTTP * server is behind NAT and needs to connect out to the * HTTP client. * * The given client socket will be managed (and closed!) by MHD after * this call and must no longer be used directly by the application * afterwards. * * @param daemon daemon that manages the connection * @param client_socket socket to manage (MHD will expect * to receive an HTTP request from this socket next). * @param addr IP address of the client * @param addrlen number of bytes in @a addr * @param external_add perform additional operations needed due * to the application calling us directly * @param non_blck indicate that socket in non-blocking mode * @param sk_spipe_supprs indicate that the @a client_socket has * set SIGPIPE suppression * @param sk_is_nonip _MHD_YES if this is not a TCP/IP socket * @return #MHD_YES on success, #MHD_NO if this daemon could * not handle the connection (i.e. malloc failed, etc). * The socket will be closed in any case; 'errno' is * set to indicate further details about the error. */ static enum MHD_Result internal_add_connection (struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr_storage *addr, socklen_t addrlen, bool external_add, bool non_blck, bool sk_spipe_supprs, enum MHD_tristate sk_is_nonip) { struct MHD_Connection *connection; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /* Direct add to master daemon could never happen. */ mhd_assert (NULL == daemon->worker_pool); #endif if (MHD_D_IS_USING_SELECT_ (daemon) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (client_socket, daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("New connection socket descriptor (%d) is not less " \ "than FD_SETSIZE (%d).\n"), (int) client_socket, (int) MHD_D_GET_FD_SETSIZE_ (daemon)); #endif MHD_socket_close_chk_ (client_socket); #if defined(ENFILE) && (ENFILE + 0 != 0) errno = ENFILE; #endif return MHD_NO; } if (MHD_D_IS_USING_EPOLL_ (daemon) && (! non_blck) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Epoll mode supports only non-blocking sockets\n")); #endif MHD_socket_close_chk_ (client_socket); #if defined(EINVAL) && (EINVAL + 0 != 0) errno = EINVAL; #endif return MHD_NO; } connection = new_connection_prepare_ (daemon, client_socket, addr, addrlen, external_add, non_blck, sk_spipe_supprs, sk_is_nonip); if (NULL == connection) return MHD_NO; if ((external_add) && MHD_D_IS_THREAD_SAFE_ (daemon)) { /* Connection is added externally and MHD is thread safe mode. */ MHD_mutex_lock_chk_ (&daemon->new_connections_mutex); DLL_insert (daemon->new_connections_head, daemon->new_connections_tail, connection); daemon->have_new = true; MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex); /* The rest of connection processing must be handled in * the daemon thread. */ if ((MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "n"))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal new connection via inter-thread " \ "communication channel.\n")); #endif } return MHD_YES; } return new_connection_process_ (daemon, connection); } static void new_connections_list_process_ (struct MHD_Daemon *daemon) { struct MHD_Connection *local_head; struct MHD_Connection *local_tail; mhd_assert (daemon->have_new); mhd_assert (MHD_D_IS_THREAD_SAFE_ (daemon)); /* Detach DL-list of new connections from the daemon for * following local processing. */ MHD_mutex_lock_chk_ (&daemon->new_connections_mutex); mhd_assert (NULL != daemon->new_connections_head); local_head = daemon->new_connections_head; local_tail = daemon->new_connections_tail; daemon->new_connections_head = NULL; daemon->new_connections_tail = NULL; daemon->have_new = false; MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex); (void) local_head; /* Mute compiler warning */ /* Process new connections in FIFO order. */ do { struct MHD_Connection *c; /**< Currently processed connection */ c = local_tail; DLL_remove (local_head, local_tail, c); mhd_assert (daemon == c->daemon); if (MHD_NO == new_connection_process_ (daemon, c)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to start serving new connection.\n")); #endif (void) 0; } } while (NULL != local_tail); } /** * Internal version of ::MHD_suspend_connection(). * * @remark In thread-per-connection mode: can be called from any thread, * in any other mode: to be called only from thread that process * daemon's select()/poll()/etc. * * @param connection the connection to suspend */ void internal_suspend_connection_ (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; mhd_assert (NULL == daemon->worker_pool); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif if (connection->resuming) { /* suspending again while we didn't even complete resuming yet */ connection->resuming = false; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif return; } if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { if (connection->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); else XDLL_remove (daemon->manual_timeout_head, daemon->manual_timeout_tail, connection); } DLL_remove (daemon->connections_head, daemon->connections_tail, connection); mhd_assert (! connection->suspended); DLL_insert (daemon->suspended_connections_head, daemon->suspended_connections_tail, connection); connection->suspended = true; #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) { EDLL_remove (daemon->eready_head, daemon->eready_tail, connection); connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL); } if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) { if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, connection->socket_fd, NULL)) MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EPOLL_SET); } connection->epoll_state |= MHD_EPOLL_STATE_SUSPENDED; } #endif #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif } /** * Suspend handling of network data for a given connection. * This can be used to dequeue a connection from MHD's event loop * (not applicable to thread-per-connection!) for a while. * * If you use this API in conjunction with an "internal" socket polling, * you must set the option #MHD_USE_ITC to ensure that a resumed * connection is immediately processed by MHD. * * Suspended connections continue to count against the total number of * connections allowed (per daemon, as well as per IP, if such limits * are set). Suspended connections will NOT time out; timeouts will * restart when the connection handling is resumed. While a * connection is suspended, MHD will not detect disconnects by the * client. * * The only safe way to call this function is to call it from the * #MHD_AccessHandlerCallback or #MHD_ContentReaderCallback. * * Finally, it is an API violation to call #MHD_stop_daemon while * having suspended connections (this will at least create memory and * socket leaks or lead to undefined behavior). You must explicitly * resume all connections before stopping the daemon. * * @param connection the connection to suspend * * @sa #MHD_AccessHandlerCallback */ _MHD_EXTERN void MHD_suspend_connection (struct MHD_Connection *connection) { struct MHD_Daemon *const daemon = connection->daemon; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); #endif /* MHD_USE_THREADS */ if (0 == (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) MHD_PANIC (_ ("Cannot suspend connections without " \ "enabling MHD_ALLOW_SUSPEND_RESUME!\n")); #ifdef UPGRADE_SUPPORT if (NULL != connection->urh) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error: connection scheduled for \"upgrade\" cannot " \ "be suspended.\n")); #endif /* HAVE_MESSAGES */ return; } #endif /* UPGRADE_SUPPORT */ internal_suspend_connection_ (connection); } /** * Resume handling of network data for suspended connection. It is * safe to resume a suspended connection at any time. Calling this * function on a connection that was not previously suspended will * result in undefined behavior. * * If you are using this function in "external" sockets polling mode, you must * make sure to run #MHD_run() and #MHD_get_timeout() afterwards (before * again calling #MHD_get_fdset()), as otherwise the change may not be * reflected in the set returned by #MHD_get_fdset() and you may end up * with a connection that is stuck until the next network activity. * * @param connection the connection to resume */ _MHD_EXTERN void MHD_resume_connection (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; bool own_thread; /**< The connection's own thread completes the resume */ #if defined(MHD_USE_THREADS) mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ if (0 == (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) MHD_PANIC (_ ("Cannot resume connections without enabling " \ "MHD_ALLOW_SUSPEND_RESUME!\n")); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif connection->resuming = true; /* An "upgraded" connection is resumed only to be moved to the cleanup list, which is the daemon thread's job even with a thread per connection. */ own_thread = MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) #ifdef UPGRADE_SUPPORT && (NULL == connection->urh) #endif /* UPGRADE_SUPPORT */ ; if (! own_thread) daemon->resuming = true; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif if (own_thread) { /* Wake the connection's own thread. See the description of @e resume_itc for why the daemon-wide ITC will not do. */ mhd_assert (MHD_ITC_IS_VALID_ (connection->resume_itc)); if (! MHD_itc_activate_ (connection->resume_itc, "r")) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal resume via the connection's " \ "inter-thread communication channel.\n")); #endif } } else if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "r")) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal resume via inter-thread " \ "communication channel.\n")); #endif } } #ifdef UPGRADE_SUPPORT /** * Mark upgraded connection as closed by application. * * The @a connection pointer must not be used after call of this function * as it may be freed in other thread immediately. * @param connection the upgraded connection to mark as closed by application */ void MHD_upgraded_connection_mark_app_closed_ (struct MHD_Connection *connection) { /* Cache 'daemon' here to avoid data races */ struct MHD_Daemon *const daemon = connection->daemon; #if defined(MHD_USE_THREADS) mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ mhd_assert (NULL != connection->urh); mhd_assert (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)); MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); connection->urh->was_closed = true; connection->resuming = true; daemon->resuming = true; MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "r")) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal resume via " \ "inter-thread communication channel.\n")); #endif } } #endif /* UPGRADE_SUPPORT */ /** * Run through the suspended connections and move any that are no * longer suspended back to the active state. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon context * @return #MHD_YES if a connection was actually resumed */ static enum MHD_Result resume_suspended_connections (struct MHD_Daemon *daemon) { struct MHD_Connection *pos; struct MHD_Connection *prev = NULL; enum MHD_Result ret; const bool used_thr_p_c = (0 != (daemon->options & MHD_USE_THREAD_PER_CONNECTION)); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) mhd_assert (NULL == daemon->worker_pool); mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); #endif ret = MHD_NO; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif if (daemon->resuming) { prev = daemon->suspended_connections_tail; /* During shutdown check for resuming is forced. */ mhd_assert ((NULL != prev) || (daemon->shutdown) || \ (0 != (daemon->options & MHD_ALLOW_UPGRADE))); } daemon->resuming = false; while (NULL != (pos = prev)) { #ifdef UPGRADE_SUPPORT struct MHD_UpgradeResponseHandle *const urh = pos->urh; #else /* ! UPGRADE_SUPPORT */ static const void *const urh = NULL; #endif /* ! UPGRADE_SUPPORT */ prev = pos->prev; if ( (! pos->resuming) #ifdef UPGRADE_SUPPORT || ( (NULL != urh) && ( (! urh->was_closed) || (! urh->clean_ready) ) ) #endif /* UPGRADE_SUPPORT */ ) continue; ret = MHD_YES; mhd_assert (pos->suspended); DLL_remove (daemon->suspended_connections_head, daemon->suspended_connections_tail, pos); pos->suspended = false; if (NULL == urh) { DLL_insert (daemon->connections_head, daemon->connections_tail, pos); if (! used_thr_p_c) { /* The states of a suspended connection are not updated, so they are stale now that it is running again. Updating them here would mean running the state machine under the cleanup mutex, which is what 0ecf4f26e4c1a4c03d66e1d04bf4cae62bd236a0 backed out of; flag the connection instead and let call_handlers() update it before it acts on @e event_loop_info. Thread-per- connection does the same for itself, in thread_main_handle_connection(). */ pos->resumed = true; /* Reset timeout timer on resume. */ if (0 != pos->connection_timeout_ms) pos->last_activity = MHD_monotonic_msec_counter (); if (pos->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_insert (daemon->normal_timeout_head, daemon->normal_timeout_tail, pos); else XDLL_insert (daemon->manual_timeout_head, daemon->manual_timeout_tail, pos); } #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) MHD_PANIC ("Resumed connection was already in EREADY set.\n"); /* we always mark resumed connections as ready, as we might have missed the edge poll event during suspension */ EDLL_insert (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL \ | MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_SUSPENDED); } #endif } #ifdef UPGRADE_SUPPORT else { /* Data forwarding was finished (for TLS connections) AND * application was closed upgraded connection. * Insert connection into cleanup list. */ if ( (NULL != daemon->notify_completed) && (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) && (pos->rq.client_aware) ) { daemon->notify_completed (daemon->notify_completed_cls, pos, &pos->rq.client_context, MHD_REQUEST_TERMINATED_COMPLETED_OK); pos->rq.client_aware = false; } DLL_insert (daemon->cleanup_head, daemon->cleanup_tail, pos); daemon->data_already_pending = true; } #endif /* UPGRADE_SUPPORT */ pos->resuming = false; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif if ( (used_thr_p_c) && (MHD_NO != ret) ) { /* Wake up suspended connections. */ if (! MHD_itc_activate_ (daemon->itc, "w")) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal resume of connection via " \ "inter-thread communication channel.\n")); #endif } } return ret; } /** * Add another client connection to the set of connections managed by * MHD. This API is usually not needed (since MHD will accept inbound * connections on the server socket). Use this API in special cases, * for example if your HTTP server is behind NAT and needs to connect * out to the HTTP client, or if you are building a proxy. * * If you use this API in conjunction with a internal select or a * thread pool, you must set the option * #MHD_USE_ITC to ensure that the freshly added * connection is immediately processed by MHD. * * The given client socket will be managed (and closed!) by MHD after * this call and must no longer be used directly by the application * afterwards. * * @param daemon daemon that manages the connection * @param client_socket socket to manage (MHD will expect * to receive an HTTP request from this socket next). * @param addr IP address of the client * @param addrlen number of bytes in @a addr * @return #MHD_YES on success, #MHD_NO if this daemon could * not handle the connection (i.e. malloc() failed, etc). * The socket will be closed in any case; `errno` is * set to indicate further details about the error. * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_add_connection (struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr *addr, socklen_t addrlen) { bool sk_nonbl; bool sk_spipe_supprs; struct sockaddr_storage addrstorage; /* TODO: fix atomic value reading */ if ((! MHD_D_IS_THREAD_SAFE_ (daemon)) && (daemon->connection_limit <= daemon->connections)) MHD_cleanup_connections (daemon); #ifdef HAVE_MESSAGES if (MHD_D_IS_USING_THREADS_ (daemon) && (0 == (daemon->options & MHD_USE_ITC))) { MHD_DLOG (daemon, _ ("MHD_add_connection() has been called for daemon started" " without MHD_USE_ITC flag.\nDaemon will not process newly" " added connection until any activity occurs in already" " added sockets.\n")); } #endif /* HAVE_MESSAGES */ if (0 != addrlen) { if (AF_INET == addr->sa_family) { if (sizeof(struct sockaddr_in) > (size_t) addrlen) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_add_connection() has been called with " "incorrect 'addrlen' value.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if ((0 != addr->sa_len) && (sizeof(struct sockaddr_in) > (size_t) addr->sa_len) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_add_connection() has been called with " \ "non-zero value of 'sa_len' member of " \ "'struct sockaddr' which does not match 'sa_family'.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ } #ifdef HAVE_INET6 if (AF_INET6 == addr->sa_family) { if (sizeof(struct sockaddr_in6) > (size_t) addrlen) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_add_connection() has been called with " "incorrect 'addrlen' value.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if ((0 != addr->sa_len) && (sizeof(struct sockaddr_in6) > (size_t) addr->sa_len) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_add_connection() has been called with " \ "non-zero value of 'sa_len' member of " \ "'struct sockaddr' which does not match 'sa_family'.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if ((0 != addr->sa_len) && (addrlen > addr->sa_len)) addrlen = (socklen_t) addr->sa_len; /* Use safest value */ #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ #endif /* HAVE_INET6 */ } if (! MHD_socket_nonblocking_ (client_socket)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set nonblocking mode on new client socket: %s\n"), MHD_socket_last_strerr_ ()); #endif sk_nonbl = false; } else sk_nonbl = true; #ifndef MHD_WINSOCK_SOCKETS sk_spipe_supprs = false; #else /* MHD_WINSOCK_SOCKETS */ sk_spipe_supprs = true; /* Nothing to suppress on W32 */ #endif /* MHD_WINSOCK_SOCKETS */ #if defined(MHD_socket_nosignal_) if (! sk_spipe_supprs) sk_spipe_supprs = MHD_socket_nosignal_ (client_socket); if (! sk_spipe_supprs) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to suppress SIGPIPE on new client socket: %s\n"), MHD_socket_last_strerr_ ()); #else /* ! HAVE_MESSAGES */ (void) 0; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ #ifndef MSG_NOSIGNAL /* Application expects that SIGPIPE will be suppressed, * but suppression failed and SIGPIPE cannot be suppressed with send(). */ if (! daemon->sigpipe_blocked) { int err = MHD_socket_get_error_ (); MHD_socket_close_ (client_socket); MHD_socket_fset_error_ (err); return MHD_NO; } #endif /* MSG_NOSIGNAL */ } #endif /* MHD_socket_nosignal_ */ if ( (0 != (daemon->options & MHD_USE_TURBO)) && (! MHD_socket_noninheritable_ (client_socket)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set noninheritable mode on new client socket.\n")); #endif } /* Copy to sockaddr_storage structure to avoid alignment problems */ if (0 < addrlen) memcpy (&addrstorage, addr, (size_t) addrlen); #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN addrstorage.ss_len = addrlen; /* Force set the right length */ #endif /* HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != daemon->worker_pool) { unsigned int i; /* have a pool, try to find a pool with capacity; we use the socket as the initial offset into the pool for load balancing */ for (i = 0; i < daemon->worker_pool_size; ++i) { struct MHD_Daemon *const worker = &daemon->worker_pool[(i + (unsigned int) client_socket) % daemon->worker_pool_size]; if (worker->connections < worker->connection_limit) return internal_add_connection (worker, client_socket, &addrstorage, addrlen, true, sk_nonbl, sk_spipe_supprs, _MHD_UNKNOWN); } /* all pools are at their connection limit, must refuse */ MHD_socket_close_chk_ (client_socket); #if defined(ENFILE) && (ENFILE + 0 != 0) errno = ENFILE; #endif return MHD_NO; } #endif /* MHD_USE_POSIX_THREADS || MHD_USE_W32_THREADS */ return internal_add_connection (daemon, client_socket, &addrstorage, addrlen, true, sk_nonbl, sk_spipe_supprs, _MHD_UNKNOWN); } /** * Accept an incoming connection and create the MHD_Connection object for * it. This function also enforces policy by way of checking with the * accept policy callback. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon handle with the listen socket * @return #MHD_YES on success (connections denied by policy or due * to 'out of memory' and similar errors) are still considered * successful as far as #MHD_accept_connection() is concerned); * a return code of #MHD_NO only refers to the actual * accept() system call. */ static enum MHD_Result MHD_accept_connection (struct MHD_Daemon *daemon) { struct sockaddr_storage addrstorage; socklen_t addrlen; MHD_socket s; MHD_socket fd; bool sk_nonbl; bool sk_spipe_supprs; bool sk_cloexec; enum MHD_tristate sk_non_ip; #if defined(_DEBUG) && defined (USE_ACCEPT4) const bool use_accept4 = ! daemon->avoid_accept4; #elif defined (USE_ACCEPT4) static const bool use_accept4 = true; #else /* ! USE_ACCEPT4 && ! _DEBUG */ static const bool use_accept4 = false; #endif /* ! USE_ACCEPT4 && ! _DEBUG */ #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ if ( (MHD_INVALID_SOCKET == (fd = daemon->listen_fd)) || (daemon->was_quiesced) ) return MHD_NO; addrlen = (socklen_t) sizeof (addrstorage); memset (&addrstorage, 0, (size_t) addrlen); #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN addrstorage.ss_len = addrlen; #endif /* HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */ /* Initialise with default values to avoid compiler warnings */ sk_nonbl = false; sk_spipe_supprs = false; sk_cloexec = false; s = MHD_INVALID_SOCKET; #ifdef USE_ACCEPT4 if (use_accept4 && (MHD_INVALID_SOCKET != (s = accept4 (fd, (struct sockaddr *) &addrstorage, &addrlen, SOCK_CLOEXEC_OR_ZERO | SOCK_NONBLOCK_OR_ZERO | SOCK_NOSIGPIPE_OR_ZERO)))) { sk_nonbl = (SOCK_NONBLOCK_OR_ZERO != 0); #ifndef MHD_WINSOCK_SOCKETS sk_spipe_supprs = (SOCK_NOSIGPIPE_OR_ZERO != 0); #else /* MHD_WINSOCK_SOCKETS */ sk_spipe_supprs = true; /* Nothing to suppress on W32 */ #endif /* MHD_WINSOCK_SOCKETS */ sk_cloexec = (SOCK_CLOEXEC_OR_ZERO != 0); } #endif /* USE_ACCEPT4 */ #if defined(_DEBUG) || ! defined(USE_ACCEPT4) if (! use_accept4 && (MHD_INVALID_SOCKET != (s = accept (fd, (struct sockaddr *) &addrstorage, &addrlen)))) { #ifdef MHD_ACCEPT_INHERIT_NONBLOCK sk_nonbl = daemon->listen_nonblk; #else /* ! MHD_ACCEPT_INHERIT_NONBLOCK */ sk_nonbl = false; #endif /* ! MHD_ACCEPT_INHERIT_NONBLOCK */ #ifndef MHD_WINSOCK_SOCKETS sk_spipe_supprs = false; #else /* MHD_WINSOCK_SOCKETS */ sk_spipe_supprs = true; /* Nothing to suppress on W32 */ #endif /* MHD_WINSOCK_SOCKETS */ sk_cloexec = false; } #endif /* _DEBUG || !USE_ACCEPT4 */ if (MHD_INVALID_SOCKET == s) { const int err = MHD_socket_get_error_ (); /* This could be a common occurrence with multiple worker threads */ if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_)) return MHD_NO; /* can happen during shutdown */ if (MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_ (err)) return MHD_NO; /* do not print error if client just disconnected early */ #ifdef HAVE_MESSAGES if (! MHD_SCKT_ERR_IS_EAGAIN_ (err) ) MHD_DLOG (daemon, _ ("Error accepting connection: %s\n"), MHD_socket_strerr_ (err)); #endif if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err) ) { /* system/process out of resources */ if (0 == daemon->connections) { #ifdef HAVE_MESSAGES /* Not setting 'at_limit' flag, as there is no way it would ever be cleared. Instead trying to produce bit fat ugly warning. */ MHD_DLOG (daemon, _ ("Hit process or system resource limit at FIRST " \ "connection. This is really bad as there is no sane " \ "way to proceed. Will try busy waiting for system " \ "resources to become magically available.\n")); #endif } else { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif daemon->at_limit = true; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Hit process or system resource limit at %u " \ "connections, temporarily suspending accept(). " \ "Consider setting a lower MHD_OPTION_CONNECTION_LIMIT.\n"), (unsigned int) daemon->connections); #endif } } return MHD_NO; } sk_non_ip = daemon->listen_is_unix; if (0 >= addrlen) { #ifdef HAVE_MESSAGES if (_MHD_NO != daemon->listen_is_unix) MHD_DLOG (daemon, _ ("Accepted socket has zero-length address. " "Processing the new socket as a socket with " \ "unknown type.\n")); #endif addrlen = 0; sk_non_ip = _MHD_YES; /* IP-type addresses have non-zero length */ } if (((socklen_t) sizeof (addrstorage)) < addrlen) { /* Should not happen as 'sockaddr_storage' must be large enough to * store any address supported by the system. */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Accepted socket address is larger than expected by " \ "system headers. Processing the new socket as a socket with " \ "unknown type.\n")); #endif addrlen = 0; sk_non_ip = _MHD_YES; /* IP-type addresses must fit */ } if (! sk_nonbl && ! MHD_socket_nonblocking_ (s)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set nonblocking mode on incoming connection " \ "socket: %s\n"), MHD_socket_last_strerr_ ()); #else /* ! HAVE_MESSAGES */ (void) 0; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ } else sk_nonbl = true; if (! sk_cloexec && ! MHD_socket_noninheritable_ (s)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set noninheritable mode on incoming connection " \ "socket.\n")); #else /* ! HAVE_MESSAGES */ (void) 0; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ } #if defined(MHD_socket_nosignal_) if (! sk_spipe_supprs && ! MHD_socket_nosignal_ (s)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to suppress SIGPIPE on incoming connection " \ "socket: %s\n"), MHD_socket_last_strerr_ ()); #else /* ! HAVE_MESSAGES */ (void) 0; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ #ifndef MSG_NOSIGNAL /* Application expects that SIGPIPE will be suppressed, * but suppression failed and SIGPIPE cannot be suppressed with send(). */ if (! daemon->sigpipe_blocked) { (void) MHD_socket_close_ (s); return MHD_NO; } #endif /* MSG_NOSIGNAL */ } else sk_spipe_supprs = true; #endif /* MHD_socket_nosignal_ */ #ifdef HAVE_MESSAGES #if _MHD_DEBUG_CONNECT MHD_DLOG (daemon, _ ("Accepted connection on socket %d\n"), s); #endif #endif (void) internal_add_connection (daemon, s, &addrstorage, addrlen, false, sk_nonbl, sk_spipe_supprs, sk_non_ip); return MHD_YES; } /** * Free resources associated with all closed connections. * (destroy responses, free buffers, etc.). All closed * connections are kept in the "cleanup" doubly-linked list. * @remark To be called only from thread that * process daemon's select()/poll()/etc. * * @param daemon daemon to clean up */ static void MHD_cleanup_connections (struct MHD_Daemon *daemon) { struct MHD_Connection *pos; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); mhd_assert (NULL == daemon->worker_pool); MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif while (NULL != (pos = daemon->cleanup_tail)) { DLL_remove (daemon->cleanup_head, daemon->cleanup_tail, pos); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && (! pos->thread_joined) && (! MHD_thread_handle_ID_join_thread_ (pos->tid)) ) MHD_PANIC (_ ("Failed to join a thread.\n")); #endif #ifdef UPGRADE_SUPPORT cleanup_upgraded_connection (pos); #endif /* UPGRADE_SUPPORT */ MHD_pool_destroy (pos->pool); #ifdef HTTPS_SUPPORT if (NULL != pos->tls_session) gnutls_deinit (pos->tls_session); #endif /* HTTPS_SUPPORT */ /* clean up the connection */ if (NULL != daemon->notify_connection) daemon->notify_connection (daemon->notify_connection_cls, pos, &pos->socket_context, MHD_CONNECTION_NOTIFY_CLOSED); MHD_ip_limit_del (daemon, pos->addr, pos->addr_len); #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) { EDLL_remove (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL); } if ( (-1 != daemon->epoll_fd) && (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) ) { /* epoll documentation suggests that closing a FD automatically removes it from the epoll set; however, this is not true as if we fail to do manually remove it, we are still seeing an event for this fd in epoll, causing grief (use-after-free...) --- at least on my system. */ if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, pos->socket_fd, NULL)) MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EPOLL_SET); } } #endif if (NULL != pos->rp.response) { MHD_destroy_response (pos->rp.response); pos->rp.response = NULL; } if (MHD_INVALID_SOCKET != pos->socket_fd) MHD_socket_close_chk_ (pos->socket_fd); if (MHD_ITC_IS_VALID_ (pos->resume_itc)) MHD_itc_destroy_chk_ (pos->resume_itc); if (NULL != pos->addr) free (pos->addr); free (pos); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif daemon->connections--; daemon->at_limit = false; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif } /** * Obtain timeout value for polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function. Smaller timeout values can be used for * polling function if it is required for any reason, but using larger * timeout value or no timeout (indefinite timeout) when this function * return #MHD_YES will break MHD processing logic and result in "hung" * connections with data pending in network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout64(), * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select()) * must be called right after return from polling function, regardless of * the states of MHD FDs. * * In practice, if #MHD_YES is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than @a timeout * millisecond even if no activity is detected on sockets by sockets * polling function. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon to query for timeout * @param[out] timeout set to the timeout (in milliseconds) * @return #MHD_YES on success, #MHD_NO if timeouts are * not used and no data processing is pending. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_timeout (struct MHD_Daemon *daemon, MHD_UNSIGNED_LONG_LONG *timeout) { uint64_t t64; if (MHD_NO == MHD_get_timeout64 (daemon, &t64)) return MHD_NO; #if SIZEOF_UINT64_T > SIZEOF_UNSIGNED_LONG_LONG if (ULLONG_MAX <= t64) *timeout = ULLONG_MAX; else #endif /* SIZEOF_UINT64_T > SIZEOF_UNSIGNED_LONG_LONG */ *timeout = (MHD_UNSIGNED_LONG_LONG) t64; return MHD_YES; } /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function. Smaller timeout values can be used for * polling function if it is required for any reason, but using larger * timeout value or no timeout (indefinite timeout) when this function * return #MHD_YES will break MHD processing logic and result in "hung" * connections with data pending in network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select()) * must be called right after return from polling function, regardless of * the states of MHD FDs. * * In practice, if #MHD_YES is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than @a timeout * millisecond even if no activity is detected on sockets by sockets * polling function. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon to query for timeout * @param[out] timeout64 the pointer to the variable to be set to the * timeout (in milliseconds) * @return #MHD_YES if timeout value has been set, * #MHD_NO if timeouts are not used and no data processing is pending. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_get_timeout64 (struct MHD_Daemon *daemon, uint64_t *timeout64) { uint64_t earliest_deadline; struct MHD_Connection *pos; struct MHD_Connection *earliest_tmot_conn; /**< the connection with earliest timeout */ bool resuming; /**< the copy of @a daemon->resuming, read under the lock */ #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); #endif /* MHD_USE_THREADS */ if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Illegal call to MHD_get_timeout.\n")); #endif return MHD_NO; } /* Unlike the other flags checked below, which are touched only by the thread that processes this daemon's polling, 'resuming' is set by #MHD_resume_connection(), which the application may legally call from any thread. It is guarded by 'cleanup_connection_mutex' everywhere. */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif resuming = daemon->resuming; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif if (daemon->data_already_pending || (NULL != daemon->cleanup_head) || resuming || daemon->have_new || daemon->shutdown) { /* Some data or connection statuses already waiting to be processed. */ *timeout64 = 0; return MHD_YES; } #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && ((NULL != daemon->eready_head) #if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT) || (NULL != daemon->eready_urh_head) #endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */ ) ) { /* Some connection(s) already have some data pending. */ *timeout64 = 0; return MHD_YES; } #endif /* EPOLL_SUPPORT */ earliest_tmot_conn = NULL; earliest_deadline = 0; /* mute compiler warning */ /* normal timeouts are sorted, so we only need to look at the 'tail' (oldest) */ pos = daemon->normal_timeout_tail; if ( (NULL != pos) && (0 != pos->connection_timeout_ms) ) { earliest_tmot_conn = pos; earliest_deadline = pos->last_activity + pos->connection_timeout_ms; } for (pos = daemon->manual_timeout_tail; NULL != pos; pos = pos->prevX) { if (0 != pos->connection_timeout_ms) { if ( (NULL == earliest_tmot_conn) || (earliest_deadline > pos->last_activity + pos->connection_timeout_ms) ) { earliest_tmot_conn = pos; earliest_deadline = pos->last_activity + pos->connection_timeout_ms; } } } if (NULL != earliest_tmot_conn) { *timeout64 = connection_get_wait (earliest_tmot_conn); return MHD_YES; } return MHD_NO; } #if defined(HAVE_POLL) || defined(EPOLL_SUPPORT) /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function (if returned value is non-negative). * Smaller timeout values can be used for polling function if it is required * for any reason, but using larger timeout value or no timeout (indefinite * timeout) when this function returns non-negative value will break MHD * processing logic and result in "hung" connections with data pending in * network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64(), #MHD_get_timeout_i() functions) when "external" * polling is used. * If this function returns non-negative value then #MHD_run() (or * #MHD_run_from_select()) must be called right after return from polling * function, regardless of the states of MHD FDs. * * In practice, if zero or positive value is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than returned amount of * millisecond even if no activity is detected on sockets by sockets * polling function. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon the daemon to query for timeout * @return -1 if connections' timeouts are not set and no data processing * is pending, so external polling function may wait for sockets * activity for indefinite amount of time, * otherwise returned value is the the maximum amount of millisecond * that external polling function must wait for the activity of FDs. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN int64_t MHD_get_timeout64s (struct MHD_Daemon *daemon) { uint64_t utimeout; if (MHD_NO == MHD_get_timeout64 (daemon, &utimeout)) return -1; if (INT64_MAX < utimeout) return INT64_MAX; return (int64_t) utimeout; } /** * Obtain timeout value for external polling function for this daemon. * * This function set value to the amount of milliseconds for which polling * function (`select()`, `poll()` or epoll) should at most block, not the * timeout value set for connections. * * Any "external" sockets polling function must be called with the timeout * value provided by this function (if returned value is non-negative). * Smaller timeout values can be used for polling function if it is required * for any reason, but using larger timeout value or no timeout (indefinite * timeout) when this function returns non-negative value will break MHD * processing logic and result in "hung" connections with data pending in * network buffers and other problems. * * It is important to always use this function (or #MHD_get_timeout(), * #MHD_get_timeout64(), #MHD_get_timeout64s() functions) when "external" * polling is used. * If this function returns non-negative value then #MHD_run() (or * #MHD_run_from_select()) must be called right after return from polling * function, regardless of the states of MHD FDs. * * In practice, if zero or positive value is returned then #MHD_run() (or * #MHD_run_from_select()) must be called not later than returned amount of * millisecond even if no activity is detected on sockets by sockets * polling function. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon the daemon to query for timeout * @return -1 if connections' timeouts are not set and no data processing * is pending, so external polling function may wait for sockets * activity for indefinite amount of time, * otherwise returned value is the the maximum amount of millisecond * (capped at INT_MAX) that external polling function must wait * for the activity of FDs. * @note Available since #MHD_VERSION 0x00097701 * @ingroup event */ _MHD_EXTERN int MHD_get_timeout_i (struct MHD_Daemon *daemon) { #if SIZEOF_INT >= SIZEOF_INT64_T return MHD_get_timeout64s (daemon); #else /* SIZEOF_INT < SIZEOF_INT64_T */ const int64_t to64 = MHD_get_timeout64s (daemon); if (INT_MAX >= to64) return (int) to64; return INT_MAX; #endif /* SIZEOF_INT < SIZEOF_INT64_T */ } /** * Obtain timeout value for polling function for this daemon. * @remark To be called only from the thread that processes * daemon's select()/poll()/etc. * * @param daemon the daemon to query for timeout * @param max_timeout the maximum return value (in milliseconds), * ignored if set to '-1' * @return timeout value in milliseconds or -1 if no timeout is expected. */ static int64_t get_timeout_millisec_ (struct MHD_Daemon *daemon, int32_t max_timeout) { uint64_t d_timeout; mhd_assert (0 <= max_timeout || -1 == max_timeout); if (0 == max_timeout) return 0; if (MHD_NO == MHD_get_timeout64 (daemon, &d_timeout)) return max_timeout; if ((0 < max_timeout) && ((uint64_t) max_timeout < d_timeout)) return max_timeout; if (INT64_MAX <= d_timeout) return INT64_MAX; return (int64_t) d_timeout; } /** * Obtain timeout value for polling function for this daemon. * @remark To be called only from the thread that processes * daemon's select()/poll()/etc. * * @param daemon the daemon to query for timeout * @param max_timeout the maximum return value (in milliseconds), * ignored if set to '-1' * @return timeout value in milliseconds, capped to INT_MAX, or * -1 if no timeout is expected. */ static int get_timeout_millisec_int (struct MHD_Daemon *daemon, int32_t max_timeout) { int64_t res; res = get_timeout_millisec_ (daemon, max_timeout); #if SIZEOF_INT < SIZEOF_INT64_T if (INT_MAX <= res) return INT_MAX; #endif /* SIZEOF_INT < SIZEOF_INT64_T */ return (int) res; } #endif /* HAVE_POLL || EPOLL_SUPPORT */ /** * Internal version of #MHD_run_from_select(). * * @param daemon daemon to run select loop for * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @param fd_setsize value of FD_SETSIZE used when fd_sets were created * @return #MHD_NO on serious errors, #MHD_YES on success * @ingroup event */ static enum MHD_Result internal_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set, int fd_setsize) { MHD_socket ds; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) struct MHD_UpgradeResponseHandle *urh; struct MHD_UpgradeResponseHandle *urhn; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_current_thread_ (daemon->tid))); mhd_assert (0 < fd_setsize); (void) fd_setsize; /* Mute compiler warning */ #ifndef HAS_FD_SETSIZE_OVERRIDABLE (void) fd_setsize; /* Mute compiler warning */ mhd_assert (((int) FD_SETSIZE) <= fd_setsize); fd_setsize = FD_SETSIZE; /* Help compiler to optimise */ #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ /* Clear ITC to avoid spinning select */ /* Do it before any other processing so new signals will trigger select again and will be processed */ if (MHD_ITC_IS_VALID_ (daemon->itc)) { /* Have ITC */ bool need_to_clear_itc = true; /* ITC is always non-blocking, it is safe to clear even if ITC not activated */ if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (MHD_itc_r_fd_ (daemon->itc), NULL, fd_setsize)) need_to_clear_itc = FD_ISSET (MHD_itc_r_fd_ (daemon->itc), \ (fd_set *) _MHD_DROP_CONST (read_fd_set)); /* Skip clearing, if not needed */ if (need_to_clear_itc) MHD_itc_clear_ (daemon->itc); } /* Reset. New value will be set when connections are processed. */ /* Note: no-op for thread-per-connection as it is always false in that mode. */ daemon->data_already_pending = false; /* Process externally added connection if any */ if (daemon->have_new) new_connections_list_process_ (daemon); /* select connection thread handling type */ ds = daemon->listen_fd; if ( (MHD_INVALID_SOCKET != ds) && (! daemon->was_quiesced) ) { bool need_to_accept; if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (ds, NULL, fd_setsize)) need_to_accept = FD_ISSET (ds, (fd_set *) _MHD_DROP_CONST (read_fd_set)); else /* Cannot check whether new connection are pending */ need_to_accept = daemon->listen_nonblk; /* Try to accept if non-blocking */ if (need_to_accept) (void) MHD_accept_connection (daemon); } if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { /* do not have a thread per connection, process all connections now */ struct MHD_Connection *pos; struct MHD_Connection *prev; for (pos = daemon->connections_tail; NULL != pos; pos = prev) { MHD_socket cs; bool r_ready; bool w_ready; bool has_err; prev = pos->prev; cs = pos->socket_fd; if (MHD_INVALID_SOCKET == cs) continue; if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (cs, NULL, fd_setsize)) { r_ready = FD_ISSET (cs, (fd_set *) _MHD_DROP_CONST (read_fd_set)); w_ready = FD_ISSET (cs, (fd_set *) _MHD_DROP_CONST (write_fd_set)); has_err = (NULL != except_fd_set) && FD_ISSET (cs, (fd_set *) _MHD_DROP_CONST (except_fd_set)); } else { /* Cannot check the real readiness */ r_ready = pos->sk_nonblck; w_ready = r_ready; has_err = false; } call_handlers (pos, r_ready, w_ready, has_err); } } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /* handle upgraded HTTPS connections */ for (urh = daemon->urh_tail; NULL != urh; urh = urhn) { urhn = urh->prev; /* update urh state based on select() output */ urh_from_fdset (urh, read_fd_set, write_fd_set, except_fd_set, fd_setsize); /* call generic forwarding function for passing data */ process_urh (urh); /* Finished forwarding? */ if ( (0 == urh->in_buffer_size) && (0 == urh->out_buffer_size) && (0 == urh->in_buffer_used) && (0 == urh->out_buffer_used) ) { MHD_connection_finish_forward_ (urh->connection); urh->clean_ready = true; /* Resuming will move connection to cleanup list. */ MHD_resume_connection (urh->connection); } } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ MHD_cleanup_connections (daemon); return MHD_YES; } #undef MHD_run_from_select /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * This function specifies FD_SETSIZE used when provided fd_sets were * created. It is important on platforms where FD_SETSIZE can be * overridden. * * You can use this function instead of #MHD_run if you called * 'select()' on the result from #MHD_get_fdset2(). File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run() is more efficient as MHD will * not have to call 'select()' again to determine which operations are * ready. * * If #MHD_get_timeout() returned #MHD_YES, than this function must be * called right after 'select()' returns regardless of detected activity * on the daemon's FDs. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon the daemon to run select loop for * @param read_fd_set the read set * @param write_fd_set the write set * @param except_fd_set the except set * @param fd_setsize the value of FD_SETSIZE * @return #MHD_NO on serious errors, #MHD_YES on success * @sa #MHD_get_fdset2(), #MHD_OPTION_APP_FD_SETSIZE * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_from_select2 (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set, unsigned int fd_setsize) { if (MHD_D_IS_USING_POLL_ (daemon) || MHD_D_IS_USING_THREADS_ (daemon)) return MHD_NO; if ((NULL == read_fd_set) || (NULL == write_fd_set)) return MHD_NO; #ifdef HAVE_MESSAGES if (NULL == except_fd_set) { MHD_DLOG (daemon, _ ("MHD_run_from_select() called with except_fd_set " "set to NULL. Such behavior is deprecated.\n")); } #endif /* HAVE_MESSAGES */ #ifdef HAS_FD_SETSIZE_OVERRIDABLE if (0 == fd_setsize) return MHD_NO; else if (((unsigned int) INT_MAX) < fd_setsize) fd_setsize = (unsigned int) INT_MAX; #ifdef HAVE_MESSAGES else if (daemon->fdset_size > ((int) fd_setsize)) { if (daemon->fdset_size_set_by_app) { MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than value set by MHD_OPTION_APP_FD_SETSIZE (%d). " \ "Some socket FDs may be not processed. " \ "Use MHD_OPTION_APP_FD_SETSIZE with the correct value.\n"), "MHD_run_from_select2", fd_setsize, daemon->fdset_size); } else { MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than FD_SETSIZE used by MHD (%d). " \ "Some socket FDs may be not processed. " \ "Consider using MHD_OPTION_APP_FD_SETSIZE option.\n"), "MHD_run_from_select2", fd_setsize, daemon->fdset_size); } } #endif /* HAVE_MESSAGES */ #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (((unsigned int) FD_SETSIZE) > fd_setsize) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("%s() called with fd_setsize (%u) " \ "less than fixed FD_SETSIZE value (%d) used on the " \ "platform.\n"), "MHD_run_from_select2", fd_setsize, (int) FD_SETSIZE); #endif /* HAVE_MESSAGES */ return MHD_NO; } #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ if (MHD_D_IS_USING_EPOLL_ (daemon)) { #ifdef EPOLL_SUPPORT enum MHD_Result ret = MHD_epoll (daemon, 0); MHD_cleanup_connections (daemon); return ret; #else /* ! EPOLL_SUPPORT */ return MHD_NO; #endif /* ! EPOLL_SUPPORT */ } /* Resuming external connections when using an extern mainloop */ if (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) resume_suspended_connections (daemon); return internal_run_from_select (daemon, read_fd_set, write_fd_set, except_fd_set, (int) fd_setsize); } /** * Run webserver operations. This method should be called by clients * in combination with #MHD_get_fdset and #MHD_get_timeout() if the * client-controlled select method is used. * * You can use this function instead of #MHD_run if you called * `select()` on the result from #MHD_get_fdset. File descriptors in * the sets that are not controlled by MHD will be ignored. Calling * this function instead of #MHD_run is more efficient as MHD will * not have to call `select()` again to determine which operations are * ready. * * If #MHD_get_timeout() returned #MHD_YES, than this function must be * called right after `select()` returns regardless of detected activity * on the daemon's FDs. * * This function cannot be used with daemon started with * #MHD_USE_INTERNAL_POLLING_THREAD flag. * * @param daemon daemon to run select loop for * @param read_fd_set read set * @param write_fd_set write set * @param except_fd_set except set * @return #MHD_NO on serious errors, #MHD_YES on success * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set) { return MHD_run_from_select2 (daemon, read_fd_set, write_fd_set, except_fd_set, #ifdef HAS_FD_SETSIZE_OVERRIDABLE daemon->fdset_size_set_by_app ? ((unsigned int) daemon->fdset_size) : ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ ); } /** * Main internal select() call. Will compute select sets, call select() * and then #internal_run_from_select with the result. * * @param daemon daemon to run select() loop for * @param millisec the maximum time in milliseconds to wait for events, * set to '0' for non-blocking processing, * set to '-1' to wait indefinitely. * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_select (struct MHD_Daemon *daemon, int32_t millisec) { int num_ready; fd_set rs; fd_set ws; fd_set es; MHD_socket maxsock; struct timeval timeout; struct timeval *tv; int err_state; MHD_socket ls; timeout.tv_sec = 0; timeout.tv_usec = 0; if (daemon->shutdown) return MHD_NO; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); maxsock = MHD_INVALID_SOCKET; err_state = MHD_NO; if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && (MHD_NO != resume_suspended_connections (daemon)) && (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) ) millisec = 0; if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { /* single-threaded, go over everything */ if (MHD_NO == internal_get_fdset2 (daemon, &rs, &ws, &es, &maxsock, (int) FD_SETSIZE)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Could not obtain daemon fdsets.\n")); #endif err_state = MHD_YES; } } else { bool itc_added; /* accept only, have one thread per connection */ itc_added = false; if (MHD_ITC_IS_VALID_ (daemon->itc)) { itc_added = MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc), &rs, &maxsock, (int) FD_SETSIZE); if (! itc_added) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Could not add control inter-thread " \ "communication channel FD to fdset.\n")); #endif err_state = MHD_YES; } } if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && (! daemon->was_quiesced) ) { /* Stop listening if we are at the configured connection limit */ /* If we're at the connection limit, no point in really accepting new connections; however, make sure we do not miss the shutdown OR the termination of an existing connection; so only do this optimisation if we have a signaling ITC in place. */ if (! itc_added || ((daemon->connections < daemon->connection_limit) && ! daemon->at_limit)) { if (! MHD_add_to_fd_set_ (ls, &rs, &maxsock, (int) FD_SETSIZE)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Could not add listen socket to fdset.\n")); #endif err_state = MHD_YES; } } } } if (MHD_NO != err_state) millisec = 0; if (0 == millisec) { timeout.tv_usec = 0; timeout.tv_sec = 0; tv = &timeout; } else { uint64_t mhd_tmo; uint64_t select_tmo; if ( (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) && (MHD_NO != MHD_get_timeout64 (daemon, &mhd_tmo)) ) { if ( (0 < millisec) && (mhd_tmo > (uint64_t) millisec) ) select_tmo = (uint64_t) millisec; else select_tmo = mhd_tmo; tv = &timeout; /* have timeout value */ } else if (0 < millisec) { select_tmo = (uint64_t) millisec; tv = &timeout; /* have timeout value */ } else { select_tmo = 0; /* Not actually used, silent compiler warning */ tv = NULL; } if (NULL != tv) { /* have timeout value */ #if (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC if (select_tmo / 1000 > TIMEVAL_TV_SEC_MAX) timeout.tv_sec = TIMEVAL_TV_SEC_MAX; else #endif /* (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC */ timeout.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) (select_tmo / 1000); timeout.tv_usec = ((uint16_t) (select_tmo % 1000)) * ((int32_t) 1000); } } num_ready = MHD_SYS_select_ (maxsock + 1, &rs, &ws, &es, tv); if (daemon->shutdown) return MHD_NO; if (num_ready < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) return (MHD_NO == err_state) ? MHD_YES : MHD_NO; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("select failed: %s\n"), MHD_socket_strerr_ (err)); #endif return MHD_NO; } if (MHD_NO != internal_run_from_select (daemon, &rs, &ws, &es, (int) FD_SETSIZE)) return (MHD_NO == err_state) ? MHD_YES : MHD_NO; return MHD_NO; } #ifdef HAVE_POLL /** * Process all of our connections and possibly the server * socket using poll(). * * @param daemon daemon to run poll loop for * @param millisec the maximum time in milliseconds to wait for events, * set to '0' for non-blocking processing, * set to '-1' to wait indefinitely. * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_poll_all (struct MHD_Daemon *daemon, int32_t millisec) { unsigned int num_connections; struct MHD_Connection *pos; struct MHD_Connection *prev; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) struct MHD_UpgradeResponseHandle *urh; struct MHD_UpgradeResponseHandle *urhn; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_current_thread_ (daemon->tid))); if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && (MHD_NO != resume_suspended_connections (daemon)) ) millisec = 0; /* count number of connections and thus determine poll set size */ num_connections = 0; for (pos = daemon->connections_head; NULL != pos; pos = pos->next) num_connections++; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) for (urh = daemon->urh_head; NULL != urh; urh = urh->next) num_connections += 2; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ { unsigned int i; int timeout; unsigned int poll_server; int poll_listen; int poll_itc_idx; struct pollfd *p; MHD_socket ls; p = MHD_calloc_ ((2 + (size_t) num_connections), sizeof (struct pollfd)); if (NULL == p) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error allocating memory: %s\n"), MHD_strerror_ (errno)); #endif return MHD_NO; } poll_server = 0; poll_listen = -1; if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && (! daemon->was_quiesced) && (daemon->connections < daemon->connection_limit) && (! daemon->at_limit) ) { /* only listen if we are not at the connection limit */ p[poll_server].fd = ls; p[poll_server].events = POLLIN; p[poll_server].revents = 0; poll_listen = (int) poll_server; poll_server++; } poll_itc_idx = -1; if (MHD_ITC_IS_VALID_ (daemon->itc)) { p[poll_server].fd = MHD_itc_r_fd_ (daemon->itc); p[poll_server].events = POLLIN; p[poll_server].revents = 0; poll_itc_idx = (int) poll_server; poll_server++; } timeout = get_timeout_millisec_int (daemon, millisec); i = 0; for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev) { p[poll_server + i].fd = pos->socket_fd; switch (pos->event_loop_info) { case MHD_EVENT_LOOP_INFO_READ: case MHD_EVENT_LOOP_INFO_PROCESS_READ: p[poll_server + i].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_WRITE: p[poll_server + i].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_PROCESS: p[poll_server + i].events |= MHD_POLL_EVENTS_ERR_DISC; break; case MHD_EVENT_LOOP_INFO_CLEANUP: timeout = 0; /* clean up "pos" immediately */ break; } i++; } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev) { urh_to_pollfd (urh, &(p[poll_server + i])); i += 2; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ if (0 == poll_server + num_connections) { free (p); return MHD_YES; } if (MHD_sys_poll_ (p, poll_server + num_connections, timeout) < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) { free (p); return MHD_YES; } #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("poll failed: %s\n"), MHD_socket_strerr_ (err)); #endif free (p); return MHD_NO; } /* handle ITC FD */ /* do it before any other processing so new signals will be processed in next loop */ if ( (-1 != poll_itc_idx) && (0 != (p[poll_itc_idx].revents & POLLIN)) ) MHD_itc_clear_ (daemon->itc); /* handle shutdown */ if (daemon->shutdown) { free (p); return MHD_NO; } /* Process externally added connection if any */ if (daemon->have_new) new_connections_list_process_ (daemon); /* handle 'listen' FD */ if ( (-1 != poll_listen) && (0 != (p[poll_listen].revents & POLLIN)) ) (void) MHD_accept_connection (daemon); /* Reset. New value will be set when connections are processed. */ daemon->data_already_pending = false; i = 0; prev = daemon->connections_tail; while (NULL != (pos = prev)) { prev = pos->prev; /* first, sanity checks */ if (i >= num_connections) break; /* connection list changed somehow, retry later ... */ if (p[poll_server + i].fd != pos->socket_fd) continue; /* fd mismatch, something else happened, retry later ... */ call_handlers (pos, 0 != (p[poll_server + i].revents & POLLIN), 0 != (p[poll_server + i].revents & POLLOUT), 0 != (p[poll_server + i].revents & MHD_POLL_REVENTS_ERR_DISC)); i++; } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) for (urh = daemon->urh_tail; NULL != urh; urh = urhn) { if (i >= num_connections) break; /* connection list changed somehow, retry later ... */ /* Get next connection here as connection can be removed * from 'daemon->urh_head' list. */ urhn = urh->prev; /* Check for fd mismatch. FIXME: required for safety? */ if ((p[poll_server + i].fd != urh->connection->socket_fd) || (p[poll_server + i + 1].fd != urh->mhd.socket)) break; urh_from_pollfd (urh, &p[poll_server + i]); i += 2; process_urh (urh); /* Finished forwarding? */ if ( (0 == urh->in_buffer_size) && (0 == urh->out_buffer_size) && (0 == urh->in_buffer_used) && (0 == urh->out_buffer_used) ) { /* MHD_connection_finish_forward_() will remove connection from * 'daemon->urh_head' list. */ MHD_connection_finish_forward_ (urh->connection); urh->clean_ready = true; /* If 'urh->was_closed' already was set to true, connection will be * moved immediately to cleanup list. Otherwise connection * will stay in suspended list until 'urh' will be marked * with 'was_closed' by application. */ MHD_resume_connection (urh->connection); } } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ free (p); } return MHD_YES; } /** * Process only the listen socket using poll(). * * @param daemon daemon to run poll loop for * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_poll_listen_socket (struct MHD_Daemon *daemon, int may_block) { struct pollfd p[2]; int timeout; unsigned int poll_count; int poll_listen; int poll_itc_idx; MHD_socket ls; mhd_assert (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid)); mhd_assert (MHD_thread_handle_ID_is_current_thread_ (daemon->tid)); memset (&p, 0, sizeof (p)); poll_count = 0; poll_listen = -1; poll_itc_idx = -1; if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && (! daemon->was_quiesced) ) { p[poll_count].fd = ls; p[poll_count].events = POLLIN; p[poll_count].revents = 0; poll_listen = (int) poll_count; poll_count++; } if (MHD_ITC_IS_VALID_ (daemon->itc)) { p[poll_count].fd = MHD_itc_r_fd_ (daemon->itc); p[poll_count].events = POLLIN; p[poll_count].revents = 0; poll_itc_idx = (int) poll_count; poll_count++; } if (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) (void) resume_suspended_connections (daemon); if (MHD_NO == may_block) timeout = 0; else timeout = -1; if (0 == poll_count) return MHD_YES; if (MHD_sys_poll_ (p, poll_count, timeout) < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_YES; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("poll failed: %s\n"), MHD_socket_strerr_ (err)); #endif return MHD_NO; } if ( (0 <= poll_itc_idx) && (0 != (p[poll_itc_idx].revents & POLLIN)) ) MHD_itc_clear_ (daemon->itc); /* handle shutdown */ if (daemon->shutdown) return MHD_NO; /* Process externally added connection if any */ if (daemon->have_new) new_connections_list_process_ (daemon); if ( (0 <= poll_listen) && (0 != (p[poll_listen].revents & POLLIN)) ) (void) MHD_accept_connection (daemon); return MHD_YES; } #endif #ifdef HAVE_POLL /** * Do poll()-based processing. * * @param daemon daemon to run poll()-loop for * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_poll (struct MHD_Daemon *daemon, int may_block) { if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) return MHD_poll_all (daemon, may_block ? -1 : 0); return MHD_poll_listen_socket (daemon, may_block); } #endif /* HAVE_POLL */ #ifdef EPOLL_SUPPORT /** * How many events to we process at most per epoll() call? Trade-off * between required stack-size and number of system calls we have to * make; 128 should be way enough to avoid more than one system call * for most scenarios, and still be moderate in stack size * consumption. Embedded systems might want to choose a smaller value * --- but why use epoll() on such a system in the first place? */ #define MAX_EVENTS 128 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /** * Checks whether @a urh has some data to process. * * @param urh upgrade handler to analyse * @return 'true' if @a urh has some data to process, * 'false' otherwise */ static bool is_urh_ready (struct MHD_UpgradeResponseHandle *const urh) { const struct MHD_Connection *const connection = urh->connection; if ( (0 == urh->in_buffer_size) && (0 == urh->out_buffer_size) && (0 == urh->in_buffer_used) && (0 == urh->out_buffer_used) ) return false; if (connection->daemon->shutdown) return true; if ( ( (0 != ((MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_ERROR) & urh->app.celi)) || (connection->tls_read_ready) ) && (urh->in_buffer_used < urh->in_buffer_size) ) return true; if ( ( (0 != ((MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_ERROR) & urh->mhd.celi)) || urh->was_closed) && (urh->out_buffer_used < urh->out_buffer_size) ) return true; if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) && (urh->out_buffer_used > 0) ) return true; if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) && (urh->in_buffer_used > 0) ) return true; return false; } /** * Do epoll()-based processing for TLS connections that have been * upgraded. This requires a separate epoll() invocation as we * cannot use the `struct MHD_Connection` data structures for * the `union epoll_data` in this case. * @remark To be called only from thread that process * daemon's select()/poll()/etc. */ static enum MHD_Result run_epoll_for_upgrade (struct MHD_Daemon *daemon) { struct epoll_event events[MAX_EVENTS]; int num_events; struct MHD_UpgradeResponseHandle *pos; struct MHD_UpgradeResponseHandle *prev; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); #endif /* MHD_USE_THREADS */ num_events = MAX_EVENTS; while (0 != num_events) { unsigned int i; /* update event masks */ num_events = epoll_wait (daemon->epoll_upgrade_fd, events, MAX_EVENTS, 0); if (-1 == num_events) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_YES; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_wait failed: %s\n"), MHD_socket_strerr_ (err)); #endif return MHD_NO; } for (i = 0; i < (unsigned int) num_events; i++) { struct UpgradeEpollHandle *const ueh = events[i].data.ptr; struct MHD_UpgradeResponseHandle *const urh = ueh->urh; bool new_err_state = false; if (urh->clean_ready) continue; /* Update ueh state based on what is ready according to epoll() */ if (0 != (events[i].events & EPOLLIN)) { ueh->celi |= MHD_EPOLL_STATE_READ_READY; } if (0 != (events[i].events & EPOLLOUT)) { ueh->celi |= MHD_EPOLL_STATE_WRITE_READY; } if (0 != (events[i].events & EPOLLHUP)) { ueh->celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; } if ( (0 == (ueh->celi & MHD_EPOLL_STATE_ERROR)) && (0 != (events[i].events & (EPOLLERR | EPOLLPRI))) ) { /* Process new error state only one time and avoid continuously * marking this connection as 'ready'. */ ueh->celi |= MHD_EPOLL_STATE_ERROR; new_err_state = true; } if (! urh->in_eready_list) { if (new_err_state || is_urh_ready (urh)) { EDLL_insert (daemon->eready_urh_head, daemon->eready_urh_tail, urh); urh->in_eready_list = true; } } } } prev = daemon->eready_urh_tail; while (NULL != (pos = prev)) { prev = pos->prevE; process_urh (pos); if (! is_urh_ready (pos)) { EDLL_remove (daemon->eready_urh_head, daemon->eready_urh_tail, pos); pos->in_eready_list = false; } /* Finished forwarding? */ if ( (0 == pos->in_buffer_size) && (0 == pos->out_buffer_size) && (0 == pos->in_buffer_used) && (0 == pos->out_buffer_used) ) { MHD_connection_finish_forward_ (pos->connection); pos->clean_ready = true; /* If 'pos->was_closed' already was set to true, connection * will be moved immediately to cleanup list. Otherwise * connection will stay in suspended list until 'pos' will * be marked with 'was_closed' by application. */ MHD_resume_connection (pos->connection); } } return MHD_YES; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ /** * Pointer-marker to distinguish ITC slot in epoll sets. */ static const char *const epoll_itc_marker = "itc_marker"; /** * Do epoll()-based processing. * * @param daemon daemon to run poll loop for * @param millisec the maximum time in milliseconds to wait for events, * set to '0' for non-blocking processing, * set to '-1' to wait indefinitely. * @return #MHD_NO on serious errors, #MHD_YES on success */ static enum MHD_Result MHD_epoll (struct MHD_Daemon *daemon, int32_t millisec) { #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) static const char *const upgrade_marker = "upgrade_ptr"; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ struct MHD_Connection *pos; struct MHD_Connection *prev; struct epoll_event events[MAX_EVENTS]; struct epoll_event event; int timeout_ms; int num_events; unsigned int i; MHD_socket ls; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) bool run_upgraded = false; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ bool need_to_accept; mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (MHD_thread_handle_ID_is_current_thread_ (daemon->tid))); if (-1 == daemon->epoll_fd) return MHD_NO; /* we're down! */ if (daemon->shutdown) return MHD_NO; /* 'listen_socket_in_epoll', 'was_quiesced' and the epoll set itself are shared with MHD_quiesce_daemon(), which runs on the application's thread. Testing them and acting on the result has to be one atomic step. */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->epoll_listen_mutex); #endif if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && (! daemon->was_quiesced) && (daemon->connections < daemon->connection_limit) && (! daemon->listen_socket_in_epoll) && (! daemon->at_limit) ) { event.events = EPOLLIN | EPOLLRDHUP; event.data.ptr = daemon; if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, ls, &event)) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex); #endif #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif return MHD_NO; } daemon->listen_socket_in_epoll = true; } if ( (daemon->was_quiesced) && (daemon->listen_socket_in_epoll) ) { if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, ls, NULL)) MHD_PANIC ("Failed to remove listen FD from epoll set.\n"); daemon->listen_socket_in_epoll = false; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex); #endif #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if ( ( (! daemon->upgrade_fd_in_epoll) && (-1 != daemon->epoll_upgrade_fd) ) ) { event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP; event.data.ptr = _MHD_DROP_CONST (upgrade_marker); if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, daemon->epoll_upgrade_fd, &event)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif return MHD_NO; } daemon->upgrade_fd_in_epoll = true; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->epoll_listen_mutex); #endif if ( (daemon->listen_socket_in_epoll) && ( (daemon->connections == daemon->connection_limit) || (daemon->at_limit) || (daemon->was_quiesced) ) ) { /* we're at the connection limit, disable listen socket for event loop for now */ if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, ls, NULL)) MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n")); daemon->listen_socket_in_epoll = false; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex); #endif if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && (MHD_NO != resume_suspended_connections (daemon)) ) millisec = 0; timeout_ms = get_timeout_millisec_int (daemon, millisec); /* Reset. New value will be set when connections are processed. */ /* Note: Used mostly for uniformity here as same situation is * signaled in epoll mode by non-empty eready DLL. */ daemon->data_already_pending = false; need_to_accept = false; /* drain 'epoll' event queue; need to iterate as we get at most MAX_EVENTS in one system call here; in practice this should pretty much mean only one round, but better an extra loop here than unfair behavior... */ num_events = MAX_EVENTS; while (MAX_EVENTS == num_events) { /* update event masks */ num_events = epoll_wait (daemon->epoll_fd, events, MAX_EVENTS, timeout_ms); if (-1 == num_events) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_YES; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_wait failed: %s\n"), MHD_socket_strerr_ (err)); #endif return MHD_NO; } for (i = 0; i < (unsigned int) num_events; i++) { /* First, check for the values of `ptr` that would indicate that this event is not about a normal connection. */ if (NULL == events[i].data.ptr) continue; /* shutdown signal! */ #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (upgrade_marker == events[i].data.ptr) { /* activity on an upgraded connection, we process those in a separate epoll() */ run_upgraded = true; continue; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ if (epoll_itc_marker == events[i].data.ptr) { /* It's OK to clear ITC here as all external conditions will be processed later. */ MHD_itc_clear_ (daemon->itc); continue; } if (daemon == events[i].data.ptr) { /* Check for error conditions on listen socket. */ /* FIXME: Initiate MHD_quiesce_daemon() to prevent busy waiting? */ if (0 == (events[i].events & (EPOLLERR | EPOLLHUP))) need_to_accept = true; continue; } /* this is an event relating to a 'normal' connection, remember the event and if appropriate mark the connection as 'eready'. */ pos = events[i].data.ptr; /* normal processing: update read/write data */ if (0 != (events[i].events & (EPOLLPRI | EPOLLERR | EPOLLHUP))) { pos->epoll_state |= MHD_EPOLL_STATE_ERROR; if (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) { EDLL_insert (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; } } else { if (0 != (events[i].events & EPOLLIN)) { pos->epoll_state |= MHD_EPOLL_STATE_READ_READY; if ( ( (0 != (MHD_EVENT_LOOP_INFO_READ & pos->event_loop_info)) || (pos->read_buffer_size > pos->read_buffer_offset) ) && (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) ) { EDLL_insert (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; } } if (0 != (events[i].events & EPOLLOUT)) { pos->epoll_state |= MHD_EPOLL_STATE_WRITE_READY; if ( (MHD_EVENT_LOOP_INFO_WRITE == pos->event_loop_info) && (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) ) { EDLL_insert (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; } } } } } /* Process externally added connection if any */ if (daemon->have_new) new_connections_list_process_ (daemon); if (need_to_accept) { unsigned int series_length = 0; /* Run 'accept' until it fails or daemon at limit of connections. * Do not accept more then 10 connections at once. The rest will * be accepted on next turn (level trigger is used for listen * socket). */ while ( (MHD_NO != MHD_accept_connection (daemon)) && (series_length < 10) && (daemon->connections < daemon->connection_limit) && (! daemon->at_limit) ) series_length++; } /* Handle timed-out connections; we need to do this here as the epoll mechanism won't call the 'MHD_connection_handle_idle()' on everything, as the other event loops do. As timeouts do not get an explicit event, we need to find those connections that might have timed out here. Connections with custom timeouts must all be looked at, as we do not bother to sort that (presumably very short) list. */ prev = daemon->manual_timeout_tail; while (NULL != (pos = prev)) { prev = pos->prevX; MHD_connection_handle_idle (pos); } /* Connections with the default timeout are sorted by prepending them to the head of the list whenever we touch the connection; thus it suffices to iterate from the tail until the first connection is NOT timed out */ prev = daemon->normal_timeout_tail; while (NULL != (pos = prev)) { prev = pos->prevX; MHD_connection_handle_idle (pos); if (MHD_CONNECTION_CLOSED != pos->state) break; /* sorted by timeout, no need to visit the rest! */ } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (run_upgraded || (NULL != daemon->eready_urh_head)) run_epoll_for_upgrade (daemon); #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ /* process events for connections */ prev = daemon->eready_tail; while (NULL != (pos = prev)) { prev = pos->prevE; call_handlers (pos, 0 != (pos->epoll_state & MHD_EPOLL_STATE_READ_READY), 0 != (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY), 0 != (pos->epoll_state & MHD_EPOLL_STATE_ERROR)); if (MHD_EPOLL_STATE_IN_EREADY_EDLL == (pos->epoll_state & (MHD_EPOLL_STATE_SUSPENDED | MHD_EPOLL_STATE_IN_EREADY_EDLL))) { if ( ((MHD_EVENT_LOOP_INFO_READ == pos->event_loop_info) && (0 == (pos->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) || ((MHD_EVENT_LOOP_INFO_WRITE == pos->event_loop_info) && (0 == (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY)) ) || (MHD_EVENT_LOOP_INFO_CLEANUP == pos->event_loop_info) ) { EDLL_remove (daemon->eready_head, daemon->eready_tail, pos); pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL); } } } return MHD_YES; } #endif /** * Run webserver operations (without blocking unless in client callbacks). * * This method should be called by clients in combination with * #MHD_get_fdset() (or #MHD_get_daemon_info() with MHD_DAEMON_INFO_EPOLL_FD * if epoll is used) and #MHD_get_timeout() if the client-controlled * connection polling method is used (i.e. daemon was started without * #MHD_USE_INTERNAL_POLLING_THREAD flag). * * This function is a convenience method, which is useful if the * fd_sets from #MHD_get_fdset were not directly passed to `select()`; * with this function, MHD will internally do the appropriate `select()` * call itself again. While it is acceptable to call #MHD_run (if * #MHD_USE_INTERNAL_POLLING_THREAD is not set) at any moment, you should * call #MHD_run_from_select() if performance is important (as it saves an * expensive call to `select()`). * * If #MHD_get_timeout() returned #MHD_YES, than this function must be called * right after polling function returns regardless of detected activity on * the daemon's FDs. * * @param daemon daemon to run * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call. * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run (struct MHD_Daemon *daemon) { if ( (daemon->shutdown) || MHD_D_IS_USING_THREADS_ (daemon) ) return MHD_NO; (void) MHD_run_wait (daemon, 0); return MHD_YES; } /** * Run webserver operation with possible blocking. * * This function does the following: waits for any network event not more than * specified number of milliseconds, processes all incoming and outgoing data, * processes new connections, processes any timed-out connection, and does * other things required to run webserver. * Once all connections are processed, function returns. * * This function is useful for quick and simple (lazy) webserver implementation * if application needs to run a single thread only and does not have any other * network activity. * * This function calls MHD_get_timeout() internally and use returned value as * maximum wait time if it less than value of @a millisec parameter. * * It is expected that the "external" socket polling function is not used in * conjunction with this function unless the @a millisec is set to zero. * * @param daemon the daemon to run * @param millisec the maximum time in milliseconds to wait for network and * other events. Note: there is no guarantee that function * blocks for the specified amount of time. The real processing * time can be shorter (if some data or connection timeout * comes earlier) or longer (if data processing requires more * time, especially in user callbacks). * If set to '0' then function does not block and processes * only already available data (if any). * If set to '-1' then function waits for events * indefinitely (blocks until next network activity or * connection timeout). * @return #MHD_YES on success, #MHD_NO if this * daemon was not started with the right * options for this call or some serious * unrecoverable error occurs. * @note Available since #MHD_VERSION 0x00097206 * @ingroup event */ _MHD_EXTERN enum MHD_Result MHD_run_wait (struct MHD_Daemon *daemon, int32_t millisec) { enum MHD_Result res; if ( (daemon->shutdown) || MHD_D_IS_USING_THREADS_ (daemon) ) return MHD_NO; mhd_assert (! MHD_thread_handle_ID_is_valid_handle_ (daemon->tid)); if (0 > millisec) millisec = -1; #ifdef HAVE_POLL if (MHD_D_IS_USING_POLL_ (daemon)) { res = MHD_poll_all (daemon, millisec); MHD_cleanup_connections (daemon); } else #endif /* HAVE_POLL */ #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) { res = MHD_epoll (daemon, millisec); MHD_cleanup_connections (daemon); } else #endif if (1) { mhd_assert (MHD_D_IS_USING_SELECT_ (daemon)); #ifdef HAS_FD_SETSIZE_OVERRIDABLE #ifdef HAVE_MESSAGES if (daemon->fdset_size_set_by_app && (((int) FD_SETSIZE) < daemon->fdset_size)) { MHD_DLOG (daemon, _ ("MHD_run()/MHD_run_wait() called for daemon started with " \ "MHD_OPTION_APP_FD_SETSIZE option (%d). " \ "The library was compiled with smaller FD_SETSIZE (%d). " \ "Some socket FDs may be not processed. " \ "Use MHD_run_from_select2() instead of MHD_run() or " \ "do not use MHD_OPTION_APP_FD_SETSIZE option.\n"), daemon->fdset_size, (int) FD_SETSIZE); } #endif /* HAVE_MESSAGES */ #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ res = MHD_select (daemon, millisec); /* MHD_select does MHD_cleanup_connections already */ } return res; } /** * Close the given connection, remove it from all of its * DLLs and move it into the cleanup queue. * @remark To be called only from thread that * process daemon's select()/poll()/etc. * * @param pos connection to move to cleanup */ static void close_connection (struct MHD_Connection *pos) { struct MHD_Daemon *daemon = pos->daemon; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { MHD_connection_mark_closed_ (pos); return; /* must let thread to do the rest */ } MHD_connection_close_ (pos, MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif mhd_assert (! pos->suspended); mhd_assert (! pos->resuming); if (pos->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, pos); else XDLL_remove (daemon->manual_timeout_head, daemon->manual_timeout_tail, pos); DLL_remove (daemon->connections_head, daemon->connections_tail, pos); DLL_insert (daemon->cleanup_head, daemon->cleanup_tail, pos); daemon->data_already_pending = true; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Thread that runs the polling loop until the daemon * is explicitly shut down. * * @param cls `struct MHD_Deamon` to run select loop in a thread for * @return always 0 (on shutdown) */ static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ MHD_polling_thread (void *cls) { struct MHD_Daemon *daemon = cls; #ifdef HAVE_PTHREAD_SIGMASK sigset_t s_mask; int err; #endif /* HAVE_PTHREAD_SIGMASK */ MHD_thread_handle_ID_set_current_thread_ID_ (&(daemon->tid)); #ifdef HAVE_PTHREAD_SIGMASK if ((0 == sigemptyset (&s_mask)) && (0 == sigaddset (&s_mask, SIGPIPE))) { err = pthread_sigmask (SIG_BLOCK, &s_mask, NULL); } else err = errno; if (0 == err) daemon->sigpipe_blocked = true; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("Failed to block SIGPIPE on daemon thread: %s\n"), MHD_strerror_ (errno)); #endif /* HAVE_MESSAGES */ #endif /* HAVE_PTHREAD_SIGMASK */ while (! daemon->shutdown) { #ifdef HAVE_POLL if (MHD_D_IS_USING_POLL_ (daemon)) MHD_poll (daemon, MHD_YES); else #endif /* HAVE_POLL */ #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon)) MHD_epoll (daemon, -1); else #endif MHD_select (daemon, -1); MHD_cleanup_connections (daemon); } /* Resume any pending for resume connections, join * all connection's threads (if any) and finally cleanup * everything. */ if (0 != (MHD_TEST_ALLOW_SUSPEND_RESUME & daemon->options)) resume_suspended_connections (daemon); close_all_connections (daemon); return (MHD_THRD_RTRN_TYPE_) 0; } #endif /** * Process escape sequences ('%HH') Updates val in place; the * result cannot be larger than the input. * The result must also still be 0-terminated. * * @param cls closure (use NULL) * @param connection handle to connection, not used * @param val value to unescape (modified in the process) * @return length of the resulting val (strlen(val) maybe * shorter afterwards due to elimination of escape sequences) */ static size_t unescape_wrapper (void *cls, struct MHD_Connection *connection, char *val) { bool broken; size_t res; (void) cls; /* Mute compiler warning. */ /* TODO: add individual parameter */ if (0 <= connection->daemon->client_discipline) return MHD_str_pct_decode_in_place_strict_ (val); res = MHD_str_pct_decode_in_place_lenient_ (val, &broken); #ifdef HAVE_MESSAGES if (broken) { MHD_DLOG (connection->daemon, _ ("The URL encoding is broken.\n")); } #endif /* HAVE_MESSAGES */ return res; } /** * Start a webserver on the given port. Variadic version of * #MHD_start_daemon_va. * * @param flags combination of `enum MHD_FLAG` values * @param port port to bind to (in host byte order), * use '0' to bind to random free port, * ignored if #MHD_OPTION_SOCK_ADDR or * #MHD_OPTION_LISTEN_SOCKET is provided * or #MHD_USE_NO_LISTEN_SOCKET is specified * @param apc callback to call to check which clients * will be allowed to connect; you can pass NULL * in which case connections from any IP will be * accepted * @param apc_cls extra argument to @a apc * @param dh handler called for all requests (repeatedly) * @param dh_cls extra argument to @a dh * @return NULL on error, handle to daemon on success * @ingroup event */ _MHD_EXTERN struct MHD_Daemon * MHD_start_daemon (unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, ...) { struct MHD_Daemon *daemon; va_list ap; va_start (ap, dh_cls); daemon = MHD_start_daemon_va (flags, port, apc, apc_cls, dh, dh_cls, ap); va_end (ap); return daemon; } /** * Stop accepting connections from the listening socket. Allows * clients to continue processing, but stops accepting new * connections. Note that the caller is responsible for closing the * returned socket; however, if MHD is run using threads (anything but * external select mode), socket will be removed from existing threads * with some delay and it must not be closed while it's in use. To make * sure that the socket is not used anymore, call #MHD_stop_daemon. * * Note that some thread modes require the caller to have passed * #MHD_USE_ITC when using this API. If this daemon is * in one of those modes and this option was not given to * #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET. * * @param daemon daemon to stop accepting new connections for * @return old listen socket on success, #MHD_INVALID_SOCKET if * the daemon was already not listening anymore * @ingroup specialized */ _MHD_EXTERN MHD_socket MHD_quiesce_daemon (struct MHD_Daemon *daemon) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) unsigned int i; #endif MHD_socket ret; ret = daemon->listen_fd; if ((MHD_INVALID_SOCKET == ret) || daemon->was_quiesced) return MHD_INVALID_SOCKET; if ( (0 == (daemon->options & (MHD_USE_ITC))) && MHD_D_IS_USING_THREADS_ (daemon) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Using MHD_quiesce_daemon in this mode " \ "requires MHD_USE_ITC.\n")); #endif return MHD_INVALID_SOCKET; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != daemon->worker_pool) for (i = 0; i < daemon->worker_pool_size; i++) { /* Each worker is an independent daemon with its own epoll set and its own lock; they are taken one at a time and never nested, so there is no ordering to get wrong. Holding the worker's lock is what stops it removing the same descriptor concurrently from its own MHD_epoll(). */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->worker_pool[i].epoll_listen_mutex); #endif daemon->worker_pool[i].was_quiesced = true; #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && (-1 != daemon->worker_pool[i].epoll_fd) && (daemon->worker_pool[i].listen_socket_in_epoll) ) { if (0 != epoll_ctl (daemon->worker_pool[i].epoll_fd, EPOLL_CTL_DEL, ret, NULL)) MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n")); daemon->worker_pool[i].listen_socket_in_epoll = false; } else #endif if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc)) { if (! MHD_itc_activate_ (daemon->worker_pool[i].itc, "q")) MHD_PANIC (_ ("Failed to signal quiesce via inter-thread " \ "communication channel.\n")); } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->worker_pool[i].epoll_listen_mutex); #endif } #endif #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->epoll_listen_mutex); #endif daemon->was_quiesced = true; #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && (-1 != daemon->epoll_fd) && (daemon->listen_socket_in_epoll) ) { if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, ret, NULL)) MHD_PANIC ("Failed to remove listen FD from epoll set.\n"); daemon->listen_socket_in_epoll = false; } #endif #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex); #endif if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "q")) ) MHD_PANIC (_ ("failed to signal quiesce via inter-thread " \ "communication channel.\n")); return ret; } /** * Temporal location of the application-provided parameters/options. * Used when options are decoded from #MHD_start_deamon() parameters, but * not yet processed/applied. */ struct MHD_InterimParams_ { /** * The total number of all user options used. * * Contains number only of meaningful options, i.e. #MHD_OPTION_END and * #MHD_OPTION_ARRAY themselves are not counted, while options inside * #MHD_OPTION_ARRAY are counted. */ size_t num_opts; /** * Set to 'true' if @a fdset_size is set by application. */ bool fdset_size_set; /** * The value for #MHD_OPTION_APP_FD_SETSIZE set by application. */ int fdset_size; /** * Set to 'true' if @a listen_fd is set by application. */ bool listen_fd_set; /** * Application-provided listen socket. */ MHD_socket listen_fd; /** * Set to 'true' if @a server_addr is set by application. */ bool pserver_addr_set; /** * Application-provided struct sockaddr to bind server to. */ const struct sockaddr *pserver_addr; /** * Set to 'true' if @a server_addr_len is set by application. */ bool server_addr_len_set; /** * Applicaiton-provided the size of the memory pointed by @a server_addr. */ socklen_t server_addr_len; }; /** * Signature of the MHD custom logger function. * * @param cls closure * @param format format string * @param va arguments to the format string (fprintf-style) */ typedef void (*VfprintfFunctionPointerType)(void *cls, const char *format, va_list va); /** * Parse a list of options given as varargs. * * @param daemon the daemon to initialize * @param servaddr where to store the server's listen address * @param params the interim parameters to be assigned to * @param ap the options * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result parse_options_va (struct MHD_Daemon *daemon, struct MHD_InterimParams_ *params, va_list ap); /** * Parse a list of options given as varargs. * * @param daemon the daemon to initialize * @param servaddr where to store the server's listen address * @param params the interim parameters to be assigned to * @param ... the options * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result parse_options (struct MHD_Daemon *daemon, struct MHD_InterimParams_ *params, ...) { va_list ap; enum MHD_Result ret; va_start (ap, params); ret = parse_options_va (daemon, params, ap); va_end (ap); return ret; } #ifdef HTTPS_SUPPORT /** * Type of GnuTLS priorities base string */ enum MHD_TlsPrioritiesBaseType { MHD_TLS_PRIO_BASE_LIBMHD = 0, /**< @c "@LIBMICROHTTPD" */ MHD_TLS_PRIO_BASE_SYSTEM = 1, /**< @c "@SYSTEM" */ #if GNUTLS_VERSION_NUMBER >= 0x030300 MHD_TLS_PRIO_BASE_DEFAULT, /**< Default priorities string */ #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ MHD_TLS_PRIO_BASE_NORMAL /**< @c "NORMAL */ }; static const struct _MHD_cstr_w_len MHD_TlsBasePriotities[] = { _MHD_S_STR_W_LEN ("@LIBMICROHTTPD"), _MHD_S_STR_W_LEN ("@SYSTEM"), #if GNUTLS_VERSION_NUMBER >= 0x030300 {NULL, 0}, #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ _MHD_S_STR_W_LEN ("NORMAL") }; /** * Initialise TLS priorities with default settings * @param daemon the daemon to initialise TLS priorities * @return true on success, false on error */ static bool daemon_tls_priorities_init_default (struct MHD_Daemon *daemon) { unsigned int p; int res; mhd_assert (0 != (((unsigned int) daemon->options) & MHD_USE_TLS)); mhd_assert (NULL == daemon->priority_cache); mhd_assert (MHD_TLS_PRIO_BASE_NORMAL + 1 == \ sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0])); res = GNUTLS_E_SUCCESS; /* Mute compiler warning */ for (p = 0; p < sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]); ++p) { res = gnutls_priority_init (&daemon->priority_cache, MHD_TlsBasePriotities[p].str, NULL); if (GNUTLS_E_SUCCESS == res) { #ifdef _DEBUG #ifdef HAVE_MESSAGES switch ((enum MHD_TlsPrioritiesBaseType) p) { case MHD_TLS_PRIO_BASE_LIBMHD: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "@LIBMICROHTTPD application-specific system-wide " \ "configuration.\n") ); break; case MHD_TLS_PRIO_BASE_SYSTEM: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "@SYSTEM system-wide configuration.\n") ); break; #if GNUTLS_VERSION_NUMBER >= 0x030300 case MHD_TLS_PRIO_BASE_DEFAULT: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "GnuTLS default configuration.\n") ); break; #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ case MHD_TLS_PRIO_BASE_NORMAL: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "NORMAL configuration.\n") ); break; default: mhd_assert (0); } #endif /* HAVE_MESSAGES */ #endif /* _DEBUG */ return true; } } #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set GnuTLS priorities. Last error: %s\n"), gnutls_strerror (res)); #endif /* HAVE_MESSAGES */ return false; } /** * The inner helper function for #daemon_tls_priorities_init_app(). * @param daemon the daemon to use * @param prio the appication-specified appendix for default priorities * @param prio_len the length of @a prio * @param buf the temporal buffer for string manipulations * @param buf_size the size of the @a buf * @return true on success, false on error */ static bool daemon_tls_priorities_init_append_inner_ (struct MHD_Daemon *daemon, const char *prio, size_t prio_len, char *buf, const size_t buf_size) { unsigned int p; int res; const char *err_pos; (void) buf_size; /* Mute compiler warning for non-Debug builds */ mhd_assert (0 != (((unsigned int) daemon->options) & MHD_USE_TLS)); mhd_assert (NULL == daemon->priority_cache); mhd_assert (MHD_TLS_PRIO_BASE_NORMAL + 1 == \ sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0])); res = GNUTLS_E_SUCCESS; /* Mute compiler warning */ for (p = 0; p < sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]); ++p) { #if GNUTLS_VERSION_NUMBER >= 0x030300 #if GNUTLS_VERSION_NUMBER >= 0x030603 if (NULL == MHD_TlsBasePriotities[p].str) res = gnutls_priority_init2 (&daemon->priority_cache, prio, &err_pos, GNUTLS_PRIORITY_INIT_DEF_APPEND); else #else /* 0x030300 <= GNUTLS_VERSION_NUMBER && GNUTLS_VERSION_NUMBER < 0x030603 */ if (NULL == MHD_TlsBasePriotities[p].str) continue; /* Skip the value, no way to append priorities to the default string */ else #endif /* GNUTLS_VERSION_NUMBER < 0x030603 */ #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ if (1) { size_t buf_pos; mhd_assert (NULL != MHD_TlsBasePriotities[p].str); buf_pos = 0; memcpy (buf + buf_pos, MHD_TlsBasePriotities[p].str, MHD_TlsBasePriotities[p].len); buf_pos += MHD_TlsBasePriotities[p].len; buf[buf_pos++] = ':'; memcpy (buf + buf_pos, prio, prio_len + 1); #ifdef _DEBUG buf_pos += prio_len + 1; mhd_assert (buf_size >= buf_pos); #endif /* _DEBUG */ res = gnutls_priority_init (&daemon->priority_cache, buf, &err_pos); } if (GNUTLS_E_SUCCESS == res) { #ifdef _DEBUG #ifdef HAVE_MESSAGES switch ((enum MHD_TlsPrioritiesBaseType) p) { case MHD_TLS_PRIO_BASE_LIBMHD: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "priorities specified by application appended to " \ "@LIBMICROHTTPD application-specific system-wide " \ "configuration.\n") ); break; case MHD_TLS_PRIO_BASE_SYSTEM: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "priorities specified by application appended to " \ "@SYSTEM system-wide configuration.\n") ); break; #if GNUTLS_VERSION_NUMBER >= 0x030300 case MHD_TLS_PRIO_BASE_DEFAULT: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "priorities specified by application appended to " \ "GnuTLS default configuration.\n") ); break; #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ case MHD_TLS_PRIO_BASE_NORMAL: MHD_DLOG (daemon, _ ("GnuTLS priorities have been initialised with " \ "priorities specified by application appended to " \ "NORMAL configuration.\n") ); break; default: mhd_assert (0); } #endif /* HAVE_MESSAGES */ #endif /* _DEBUG */ return true; } } #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set GnuTLS priorities. Last error: %s. " \ "The problematic part starts at: %s\n"), gnutls_strerror (res), err_pos); #endif /* HAVE_MESSAGES */ return false; } #define LOCAL_BUFF_SIZE 128 /** * Initialise TLS priorities with default settings with application-specified * appended string. * @param daemon the daemon to initialise TLS priorities * @param prio the application specified priorities to be appended to * the GnuTLS standard priorities string * @return true on success, false on error */ static bool daemon_tls_priorities_init_append (struct MHD_Daemon *daemon, const char *prio) { static const size_t longest_base_prio = MHD_STATICSTR_LEN_ ("@LIBMICROHTTPD"); bool ret; size_t prio_len; size_t buf_size_needed; if (NULL == prio) return daemon_tls_priorities_init_default (daemon); if (':' == prio[0]) ++prio; prio_len = strlen (prio); buf_size_needed = longest_base_prio + 1 + prio_len + 1; if (LOCAL_BUFF_SIZE >= buf_size_needed) { char local_buffer[LOCAL_BUFF_SIZE]; ret = daemon_tls_priorities_init_append_inner_ (daemon, prio, prio_len, local_buffer, LOCAL_BUFF_SIZE); } else { char *allocated_buffer; allocated_buffer = (char *) malloc (buf_size_needed); if (NULL == allocated_buffer) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error allocating memory: %s\n"), MHD_strerror_ (errno)); #endif return false; } ret = daemon_tls_priorities_init_append_inner_ (daemon, prio, prio_len, allocated_buffer, buf_size_needed); free (allocated_buffer); } return ret; } #endif /* HTTPS_SUPPORT */ /** * Parse a list of options given as varargs. * * @param[in,out] daemon the daemon to initialize * @param[out] params the interim parameters to be assigned to * @param ap the options * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result parse_options_va (struct MHD_Daemon *daemon, struct MHD_InterimParams_ *params, va_list ap) { enum MHD_OPTION opt; struct MHD_OptionItem *oa; unsigned int i; unsigned int uv; #ifdef HTTPS_SUPPORT const char *pstr; #if GNUTLS_VERSION_MAJOR >= 3 gnutls_certificate_retrieve_function2 * pgcrf; #endif #if GNUTLS_VERSION_NUMBER >= 0x030603 gnutls_certificate_retrieve_function3 * pgcrf2; #endif #endif /* HTTPS_SUPPORT */ while (MHD_OPTION_END != (opt = (enum MHD_OPTION) va_arg (ap, int))) { /* Increase counter at start, so resulting value is number of * processed options, including any failed ones. */ params->num_opts++; switch (opt) { case MHD_OPTION_CONNECTION_MEMORY_LIMIT: if (1) { size_t val; val = va_arg (ap, size_t); if (0 != val) { daemon->pool_size = val; if (64 > daemon->pool_size) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Warning: specified " \ "MHD_OPTION_CONNECTION_MEMORY_LIMIT " \ "value is too small and rounded up to 64.\n")); #endif /* HAVE_MESSAGES */ daemon->pool_size = 64; } if (daemon->pool_size / 4 < daemon->pool_increment) daemon->pool_increment = daemon->pool_size / 4; } } break; case MHD_OPTION_CONNECTION_MEMORY_INCREMENT: if (1) { size_t val; val = va_arg (ap, size_t); if (0 != val) { daemon->pool_increment = val; if (daemon->pool_size / 4 < daemon->pool_increment) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Warning: specified " \ "MHD_OPTION_CONNECTION_MEMORY_INCREMENT value is " \ "too large and rounded down to 1/4 of " \ "MHD_OPTION_CONNECTION_MEMORY_LIMIT.\n")); #endif /* HAVE_MESSAGES */ daemon->pool_increment = daemon->pool_size / 4; } } } break; case MHD_OPTION_CONNECTION_LIMIT: daemon->connection_limit = va_arg (ap, unsigned int); break; case MHD_OPTION_CONNECTION_TIMEOUT: uv = va_arg (ap, unsigned int); #if (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT if ((UINT64_MAX / 4000 - 1) < uv) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The specified connection timeout (%u) is too large. " \ "Maximum allowed value (%" PRIu64 ") will be used " \ "instead.\n"), uv, (UINT64_MAX / 4000 - 1)); #endif uv = UINT64_MAX / 4000 - 1; } #endif /* (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT */ daemon->connection_timeout_ms = ((uint64_t) uv) * 1000; break; case MHD_OPTION_NOTIFY_COMPLETED: daemon->notify_completed = va_arg (ap, MHD_RequestCompletedCallback); daemon->notify_completed_cls = va_arg (ap, void *); break; case MHD_OPTION_NOTIFY_CONNECTION: daemon->notify_connection = va_arg (ap, MHD_NotifyConnectionCallback); daemon->notify_connection_cls = va_arg (ap, void *); break; case MHD_OPTION_PER_IP_CONNECTION_LIMIT: daemon->per_ip_connection_limit = va_arg (ap, unsigned int); break; case MHD_OPTION_SOCK_ADDR_LEN: params->server_addr_len = va_arg (ap, socklen_t); params->server_addr_len_set = true; params->pserver_addr = va_arg (ap, const struct sockaddr *); params->pserver_addr_set = true; break; case MHD_OPTION_SOCK_ADDR: params->server_addr_len_set = false; params->pserver_addr = va_arg (ap, const struct sockaddr *); params->pserver_addr_set = true; break; case MHD_OPTION_URI_LOG_CALLBACK: daemon->uri_log_callback = va_arg (ap, LogCallback); daemon->uri_log_callback_cls = va_arg (ap, void *); break; case MHD_OPTION_SERVER_INSANITY: daemon->insanity_level = (enum MHD_DisableSanityCheck) va_arg (ap, unsigned int); break; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) case MHD_OPTION_THREAD_POOL_SIZE: daemon->worker_pool_size = va_arg (ap, unsigned int); if (0 == daemon->worker_pool_size) { (void) 0; /* MHD_OPTION_THREAD_POOL_SIZE ignored, do nothing */ } else if (1 == daemon->worker_pool_size) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Warning: value \"1\", specified as the thread pool " \ "size, is ignored. Thread pool is not used.\n")); #endif daemon->worker_pool_size = 0; } #if SIZEOF_UNSIGNED_INT >= (SIZEOF_SIZE_T - 2) /* Next comparison could be always false on some platforms and whole branch will * be optimized out on these platforms. On others it will be compiled into real * check. */ else if (daemon->worker_pool_size >= (SIZE_MAX / sizeof (struct MHD_Daemon))) /* Compiler may warn on some platforms, ignore warning. */ { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Specified thread pool size (%u) too big.\n"), daemon->worker_pool_size); #endif return MHD_NO; } #endif /* SIZEOF_UNSIGNED_INT >= (SIZEOF_SIZE_T - 2) */ else { if (! MHD_D_IS_USING_THREADS_ (daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_OPTION_THREAD_POOL_SIZE option is specified but " "MHD_USE_INTERNAL_POLLING_THREAD flag is not specified.\n")); #endif return MHD_NO; } if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Both MHD_OPTION_THREAD_POOL_SIZE option and " "MHD_USE_THREAD_PER_CONNECTION flag are specified.\n")); #endif return MHD_NO; } } break; #endif #ifdef HTTPS_SUPPORT case MHD_OPTION_HTTPS_MEM_KEY: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->https_mem_key = pstr; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_KEY_PASSWORD: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->https_key_password = pstr; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_MEM_CERT: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->https_mem_cert = pstr; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_MEM_TRUST: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->https_mem_trust = pstr; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_CRED_TYPE: daemon->cred_type = (gnutls_credentials_type_t) va_arg (ap, int); break; case MHD_OPTION_HTTPS_MEM_DHPARAMS: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) { gnutls_datum_t dhpar; size_t pstr_len; if (gnutls_dh_params_init (&daemon->https_mem_dhparams) < 0) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Error initializing DH parameters.\n")); #endif return MHD_NO; } dhpar.data = (unsigned char *) _MHD_DROP_CONST (pstr); pstr_len = strlen (pstr); if (UINT_MAX < pstr_len) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Diffie-Hellman parameters string too long.\n")); #endif return MHD_NO; } dhpar.size = (unsigned int) pstr_len; if (gnutls_dh_params_import_pkcs3 (daemon->https_mem_dhparams, &dhpar, GNUTLS_X509_FMT_PEM) < 0) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Bad Diffie-Hellman parameters format.\n")); #endif gnutls_dh_params_deinit (daemon->https_mem_dhparams); return MHD_NO; } daemon->have_dhparams = true; } #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_PRIORITIES: case MHD_OPTION_HTTPS_PRIORITIES_APPEND: pstr = va_arg (ap, const char *); if (0 != (daemon->options & MHD_USE_TLS)) { if (NULL != daemon->priority_cache) gnutls_priority_deinit (daemon->priority_cache); if (MHD_OPTION_HTTPS_PRIORITIES == opt) { int init_res; const char *err_pos; init_res = gnutls_priority_init (&daemon->priority_cache, pstr, &err_pos); if (GNUTLS_E_SUCCESS != init_res) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Setting priorities to '%s' failed: %s " \ "The problematic part starts at: %s\n"), pstr, gnutls_strerror (init_res), err_pos); #endif daemon->priority_cache = NULL; return MHD_NO; } } else { /* The cache has been deinited */ daemon->priority_cache = NULL; if (! daemon_tls_priorities_init_append (daemon, pstr)) return MHD_NO; } } #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif break; case MHD_OPTION_HTTPS_CERT_CALLBACK: #if GNUTLS_VERSION_MAJOR < 3 #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_OPTION_HTTPS_CERT_CALLBACK requires building " \ "MHD with GnuTLS >= 3.0.\n")); #endif return MHD_NO; #else pgcrf = va_arg (ap, gnutls_certificate_retrieve_function2 *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->cert_callback = pgcrf; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif /* HAVE_MESSAGES */ break; #endif case MHD_OPTION_HTTPS_CERT_CALLBACK2: #if GNUTLS_VERSION_NUMBER < 0x030603 #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_OPTION_HTTPS_CERT_CALLBACK2 requires building " \ "MHD with GnuTLS >= 3.6.3.\n")); #endif return MHD_NO; #else pgcrf2 = va_arg (ap, gnutls_certificate_retrieve_function3 *); if (0 != (daemon->options & MHD_USE_TLS)) daemon->cert_callback2 = pgcrf2; #ifdef HAVE_MESSAGES else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD but " \ "MHD_USE_TLS not set.\n"), opt); #endif /* HAVE_MESSAGES */ break; #endif #endif /* HTTPS_SUPPORT */ #ifdef DAUTH_SUPPORT case MHD_OPTION_DIGEST_AUTH_RANDOM: case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY: daemon->digest_auth_rand_size = va_arg (ap, size_t); daemon->digest_auth_random = va_arg (ap, const char *); if (MHD_OPTION_DIGEST_AUTH_RANDOM_COPY == opt) /* Set to some non-NULL value just to indicate that copy is required. */ daemon->digest_auth_random_copy = daemon; else daemon->digest_auth_random_copy = NULL; break; case MHD_OPTION_NONCE_NC_SIZE: daemon->nonce_nc_size = va_arg (ap, unsigned int); break; case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE: daemon->dauth_bind_type = va_arg (ap, unsigned int); if (0 != (daemon->dauth_bind_type & MHD_DAUTH_BIND_NONCE_URI_PARAMS)) daemon->dauth_bind_type |= MHD_DAUTH_BIND_NONCE_URI; break; case MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT: if (1) { unsigned int val; val = va_arg (ap, unsigned int); if (0 != val) daemon->dauth_def_nonce_timeout = val; } break; case MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC: if (1) { uint32_t val; val = va_arg (ap, uint32_t); if (0 != val) daemon->dauth_def_max_nc = val; } break; #else /* ! DAUTH_SUPPORT */ case MHD_OPTION_DIGEST_AUTH_RANDOM: case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY: case MHD_OPTION_NONCE_NC_SIZE: case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE: case MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT: case MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Digest Auth is disabled for this build " \ "of GNU libmicrohttpd.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; #endif /* ! DAUTH_SUPPORT */ case MHD_OPTION_LISTEN_SOCKET: params->listen_fd = va_arg (ap, MHD_socket); params->listen_fd_set = true; break; case MHD_OPTION_EXTERNAL_LOGGER: #ifdef HAVE_MESSAGES daemon->custom_error_log = va_arg (ap, VfprintfFunctionPointerType); daemon->custom_error_log_cls = va_arg (ap, void *); if (1 != params->num_opts) MHD_DLOG (daemon, _ ("MHD_OPTION_EXTERNAL_LOGGER is not the first option " "specified for the daemon. Some messages may be " "printed by the standard MHD logger.\n")); #else (void) va_arg (ap, VfprintfFunctionPointerType); (void) va_arg (ap, void *); #endif break; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) case MHD_OPTION_THREAD_STACK_SIZE: daemon->thread_stack_size = va_arg (ap, size_t); break; #endif case MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE: #ifdef TCP_FASTOPEN daemon->fastopen_queue_size = va_arg (ap, unsigned int); break; #else /* ! TCP_FASTOPEN */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("TCP fastopen is not supported on this platform.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; #endif /* ! TCP_FASTOPEN */ case MHD_OPTION_LISTENING_ADDRESS_REUSE: daemon->listening_address_reuse = va_arg (ap, unsigned int) ? 1 : -1; break; case MHD_OPTION_LISTEN_BACKLOG_SIZE: daemon->listen_backlog_size = va_arg (ap, unsigned int); break; case MHD_OPTION_STRICT_FOR_CLIENT: daemon->client_discipline = va_arg (ap, int); /* Temporal assignment */ /* Map to correct value */ if (-1 >= daemon->client_discipline) daemon->client_discipline = -3; else if (1 <= daemon->client_discipline) daemon->client_discipline = 1; #ifdef HAVE_MESSAGES if ( (0 != (daemon->options & MHD_USE_PEDANTIC_CHECKS)) && (1 != daemon->client_discipline) ) { MHD_DLOG (daemon, _ ("Flag MHD_USE_PEDANTIC_CHECKS is ignored because " "another behaviour is specified by " "MHD_OPTION_STRICT_CLIENT.\n")); } #endif /* HAVE_MESSAGES */ break; case MHD_OPTION_CLIENT_DISCIPLINE_LVL: daemon->client_discipline = va_arg (ap, int); #ifdef HAVE_MESSAGES if ( (0 != (daemon->options & MHD_USE_PEDANTIC_CHECKS)) && (1 != daemon->client_discipline) ) { MHD_DLOG (daemon, _ ("Flag MHD_USE_PEDANTIC_CHECKS is ignored because " "another behaviour is specified by " "MHD_OPTION_CLIENT_DISCIPLINE_LVL.\n")); } #endif /* HAVE_MESSAGES */ break; case MHD_OPTION_ALLOW_BIN_ZERO_IN_URI_PATH: daemon->allow_bzero_in_url = va_arg (ap, int); if ((0 > daemon->allow_bzero_in_url) || (2 < daemon->allow_bzero_in_url)) daemon->allow_bzero_in_url = 1; break; case MHD_OPTION_ARRAY: params->num_opts--; /* Do not count MHD_OPTION_ARRAY */ oa = va_arg (ap, struct MHD_OptionItem *); i = 0; while (MHD_OPTION_END != (opt = oa[i].option)) { switch (opt) { /* all options taking 'size_t' */ case MHD_OPTION_CONNECTION_MEMORY_LIMIT: case MHD_OPTION_CONNECTION_MEMORY_INCREMENT: case MHD_OPTION_THREAD_STACK_SIZE: if (MHD_NO == parse_options (daemon, params, opt, (size_t) oa[i].value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking 'unsigned int' */ case MHD_OPTION_NONCE_NC_SIZE: case MHD_OPTION_CONNECTION_LIMIT: case MHD_OPTION_CONNECTION_TIMEOUT: case MHD_OPTION_PER_IP_CONNECTION_LIMIT: case MHD_OPTION_THREAD_POOL_SIZE: case MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE: case MHD_OPTION_LISTENING_ADDRESS_REUSE: case MHD_OPTION_LISTEN_BACKLOG_SIZE: case MHD_OPTION_SERVER_INSANITY: case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE: case MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT: if (MHD_NO == parse_options (daemon, params, opt, (unsigned int) oa[i].value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking 'enum' */ case MHD_OPTION_HTTPS_CRED_TYPE: #ifdef HTTPS_SUPPORT if (MHD_NO == parse_options (daemon, params, opt, (gnutls_credentials_type_t) oa[i].value, MHD_OPTION_END)) #endif /* HTTPS_SUPPORT */ return MHD_NO; break; /* all options taking 'MHD_socket' */ case MHD_OPTION_LISTEN_SOCKET: if (MHD_NO == parse_options (daemon, params, opt, (MHD_socket) oa[i].value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking 'int' */ case MHD_OPTION_STRICT_FOR_CLIENT: case MHD_OPTION_CLIENT_DISCIPLINE_LVL: case MHD_OPTION_SIGPIPE_HANDLED_BY_APP: case MHD_OPTION_TLS_NO_ALPN: case MHD_OPTION_APP_FD_SETSIZE: case MHD_OPTION_ALLOW_BIN_ZERO_IN_URI_PATH: if (MHD_NO == parse_options (daemon, params, opt, (int) oa[i].value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking 'uint32_t' */ case MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC: if (MHD_NO == parse_options (daemon, params, opt, (uint32_t) oa[i].value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking one pointer */ case MHD_OPTION_SOCK_ADDR: case MHD_OPTION_HTTPS_MEM_KEY: case MHD_OPTION_HTTPS_KEY_PASSWORD: case MHD_OPTION_HTTPS_MEM_CERT: case MHD_OPTION_HTTPS_MEM_TRUST: case MHD_OPTION_HTTPS_MEM_DHPARAMS: case MHD_OPTION_HTTPS_PRIORITIES: case MHD_OPTION_HTTPS_PRIORITIES_APPEND: case MHD_OPTION_ARRAY: case MHD_OPTION_HTTPS_CERT_CALLBACK: case MHD_OPTION_HTTPS_CERT_CALLBACK2: if (MHD_NO == parse_options (daemon, params, opt, oa[i].ptr_value, MHD_OPTION_END)) return MHD_NO; break; /* all options taking two pointers */ case MHD_OPTION_NOTIFY_COMPLETED: case MHD_OPTION_NOTIFY_CONNECTION: case MHD_OPTION_URI_LOG_CALLBACK: case MHD_OPTION_EXTERNAL_LOGGER: case MHD_OPTION_UNESCAPE_CALLBACK: case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER: if (MHD_NO == parse_options (daemon, params, opt, (void *) oa[i].value, oa[i].ptr_value, MHD_OPTION_END)) return MHD_NO; break; /* options taking size_t-number followed by pointer */ case MHD_OPTION_DIGEST_AUTH_RANDOM: case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY: if (MHD_NO == parse_options (daemon, params, opt, (size_t) oa[i].value, oa[i].ptr_value, MHD_OPTION_END)) return MHD_NO; break; /* options taking socklen_t-number followed by pointer */ case MHD_OPTION_SOCK_ADDR_LEN: if (MHD_NO == parse_options (daemon, params, opt, (socklen_t) oa[i].value, oa[i].ptr_value, MHD_OPTION_END)) return MHD_NO; break; case MHD_OPTION_END: /* Not possible */ default: return MHD_NO; } i++; } break; case MHD_OPTION_UNESCAPE_CALLBACK: daemon->unescape_callback = va_arg (ap, UnescapeCallback); daemon->unescape_callback_cls = va_arg (ap, void *); break; #ifdef HTTPS_SUPPORT case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER: #if GNUTLS_VERSION_MAJOR >= 3 daemon->cred_callback = va_arg (ap, MHD_PskServerCredentialsCallback); daemon->cred_callback_cls = va_arg (ap, void *); break; #else MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD compiled " \ "without GNUtls >= 3.\n"), opt); return MHD_NO; #endif #endif /* HTTPS_SUPPORT */ case MHD_OPTION_SIGPIPE_HANDLED_BY_APP: if (! MHD_D_IS_USING_THREADS_ (daemon)) daemon->sigpipe_blocked = ( (va_arg (ap, int)) != 0); else { (void) va_arg (ap, int); } break; case MHD_OPTION_TLS_NO_ALPN: #ifdef HTTPS_SUPPORT daemon->disable_alpn = (va_arg (ap, int) != 0); #else /* ! HTTPS_SUPPORT */ (void) va_arg (ap, int); #endif /* ! HTTPS_SUPPORT */ #ifdef HAVE_MESSAGES if (0 == (daemon->options & MHD_USE_TLS)) MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD " \ "but MHD_USE_TLS not set.\n"), (int) opt); #endif /* HAVE_MESSAGES */ break; case MHD_OPTION_APP_FD_SETSIZE: params->fdset_size_set = true; params->fdset_size = va_arg (ap, int); break; #ifndef HTTPS_SUPPORT case MHD_OPTION_HTTPS_MEM_KEY: case MHD_OPTION_HTTPS_MEM_CERT: case MHD_OPTION_HTTPS_CRED_TYPE: case MHD_OPTION_HTTPS_PRIORITIES: case MHD_OPTION_HTTPS_PRIORITIES_APPEND: case MHD_OPTION_HTTPS_MEM_TRUST: case MHD_OPTION_HTTPS_CERT_CALLBACK: case MHD_OPTION_HTTPS_MEM_DHPARAMS: case MHD_OPTION_HTTPS_KEY_PASSWORD: case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER: case MHD_OPTION_HTTPS_CERT_CALLBACK2: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD HTTPS option %d passed to MHD " "compiled without HTTPS support.\n"), opt); #endif return MHD_NO; #endif /* HTTPS_SUPPORT */ case MHD_OPTION_END: /* Not possible */ default: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Invalid option %d! (Did you terminate " "the list with MHD_OPTION_END?).\n"), opt); #endif return MHD_NO; } } return MHD_YES; } #ifdef EPOLL_SUPPORT static int setup_epoll_fd (struct MHD_Daemon *daemon) { int fd; #ifndef HAVE_MESSAGES (void) daemon; /* Mute compiler warning. */ #endif /* ! HAVE_MESSAGES */ #ifdef USE_EPOLL_CREATE1 fd = epoll_create1 (EPOLL_CLOEXEC); #else /* ! USE_EPOLL_CREATE1 */ fd = epoll_create (MAX_EVENTS); #endif /* ! USE_EPOLL_CREATE1 */ if (MHD_INVALID_SOCKET == fd) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_create1 failed: %s\n"), MHD_socket_last_strerr_ ()); #endif return MHD_INVALID_SOCKET; } #if ! defined(USE_EPOLL_CREATE1) if (! MHD_socket_noninheritable_ (fd)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set noninheritable mode on epoll FD.\n")); #endif } #endif /* ! USE_EPOLL_CREATE1 */ return fd; } /** * Setup epoll() FD for the daemon and initialize it to listen * on the listen FD. * @remark To be called only from MHD_start_daemon_va() * * @param daemon daemon to initialize for epoll() * @return #MHD_YES on success, #MHD_NO on failure */ static enum MHD_Result setup_epoll_to_listen (struct MHD_Daemon *daemon) { struct epoll_event event; MHD_socket ls; mhd_assert (MHD_D_IS_USING_EPOLL_ (daemon)); mhd_assert (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION)); mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) || \ MHD_ITC_IS_VALID_ (daemon->itc) ); daemon->epoll_fd = setup_epoll_fd (daemon); if (! MHD_D_IS_USING_THREADS_ (daemon) && (0 != (daemon->options & MHD_USE_AUTO))) { /* Application requested "MHD_USE_AUTO", probably MHD_get_fdset() will be used. Make sure that epoll FD is suitable for fd_set. Actually, MHD_get_fdset() is allowed for MHD_USE_EPOLL direct, but most probably direct requirement for MHD_USE_EPOLL means that epoll FD will be used directly. This logic is fuzzy, but better than nothing with current MHD API. */ if (! MHD_D_DOES_SCKT_FIT_FDSET_ (daemon->epoll_fd, daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The epoll FD is too large to be used with fd_set.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } } if (-1 == daemon->epoll_fd) return MHD_NO; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (0 != (MHD_ALLOW_UPGRADE & daemon->options)) { daemon->epoll_upgrade_fd = setup_epoll_fd (daemon); if (MHD_INVALID_SOCKET == daemon->epoll_upgrade_fd) return MHD_NO; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && (! daemon->was_quiesced) ) { event.events = EPOLLIN | EPOLLRDHUP; event.data.ptr = daemon; if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, ls, &event)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif return MHD_NO; } daemon->listen_socket_in_epoll = true; } if (MHD_ITC_IS_VALID_ (daemon->itc)) { event.events = EPOLLIN | EPOLLRDHUP; event.data.ptr = _MHD_DROP_CONST (epoll_itc_marker); if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, MHD_itc_r_fd_ (daemon->itc), &event)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif return MHD_NO; } } return MHD_YES; } #endif /** * Apply interim parameters * @param[in,out] d the daemon to use * @param[out] ppsockaddr the pointer to store the pointer to 'struct sockaddr' * if provided by application * @param[out] psockaddr_len the size memory area pointed by 'struct sockaddr' * if provided by application * @param[in,out] params the interim parameters to process * @return true in case of success, * false in case of critical error (the daemon must be closed). */ static bool process_interim_params (struct MHD_Daemon *d, const struct sockaddr **ppsockaddr, socklen_t *psockaddr_len, struct MHD_InterimParams_ *params) { if (params->fdset_size_set) { if (0 >= params->fdset_size) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_APP_FD_SETSIZE value (%d) is not positive.\n"), params->fdset_size); #endif /* HAVE_MESSAGES */ return false; } if (MHD_D_IS_USING_THREADS_ (d)) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_APP_FD_SETSIZE is ignored for daemon started " \ "with MHD_USE_INTERNAL_POLLING_THREAD.\n")); #endif /* HAVE_MESSAGES */ (void) 0; } else if (MHD_D_IS_USING_POLL_ (d)) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_APP_FD_SETSIZE is ignored for daemon started " \ "with MHD_USE_POLL.\n")); #endif /* HAVE_MESSAGES */ (void) 0; } else { /* The daemon without internal threads, external sockets polling */ #ifndef HAS_FD_SETSIZE_OVERRIDABLE if (((int) FD_SETSIZE) != params->fdset_size) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_APP_FD_SETSIZE value (%d) does not match " \ "the platform FD_SETSIZE value (%d) and this platform " \ "does not support overriding of FD_SETSIZE.\n"), params->fdset_size, (int) FD_SETSIZE); #endif /* HAVE_MESSAGES */ return false; } #else /* HAS_FD_SETSIZE_OVERRIDABLE */ d->fdset_size = params->fdset_size; d->fdset_size_set_by_app = true; #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ } } if (params->listen_fd_set) { if (MHD_INVALID_SOCKET == params->listen_fd) { (void) 0; /* Use MHD-created socket */ } #ifdef HAS_SIGNED_SOCKET else if (0 > params->listen_fd) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("The value provided for MHD_OPTION_LISTEN_SOCKET " \ "is invalid.\n")); #endif /* HAVE_MESSAGES */ return false; } #endif /* HAS_SIGNED_SOCKET */ else if (0 != (d->options & MHD_USE_NO_LISTEN_SOCKET)) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_LISTEN_SOCKET specified for daemon " "with MHD_USE_NO_LISTEN_SOCKET flag set.\n")); #endif /* HAVE_MESSAGES */ (void) MHD_socket_close_ (params->listen_fd); return false; } else { d->listen_fd = params->listen_fd; d->listen_is_unix = _MHD_UNKNOWN; #ifdef MHD_USE_GETSOCKNAME d->port = 0; /* Force use of autodetection */ #endif /* MHD_USE_GETSOCKNAME */ } } mhd_assert (! params->server_addr_len_set || params->pserver_addr_set); if (params->pserver_addr_set) { if (NULL == params->pserver_addr) { /* The size must be zero if set */ if (params->server_addr_len_set && (0 != params->server_addr_len)) return false; /* Ignore parameter if it is NULL */ } else if (MHD_INVALID_SOCKET != d->listen_fd) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_LISTEN_SOCKET cannot be used together with " \ "MHD_OPTION_SOCK_ADDR_LEN or MHD_OPTION_SOCK_ADDR.\n")); #endif /* HAVE_MESSAGES */ return false; } else if (0 != (d->options & MHD_USE_NO_LISTEN_SOCKET)) { #ifdef HAVE_MESSAGES MHD_DLOG (d, _ ("MHD_OPTION_SOCK_ADDR_LEN or MHD_OPTION_SOCK_ADDR " \ "specified for daemon with MHD_USE_NO_LISTEN_SOCKET " \ "flag set.\n")); #endif /* HAVE_MESSAGES */ if (MHD_INVALID_SOCKET != d->listen_fd) { (void) MHD_socket_close_ (params->listen_fd); params->listen_fd = MHD_INVALID_SOCKET; } return false; } else { *ppsockaddr = params->pserver_addr; if (params->server_addr_len_set) { /* The size must be non-zero if set */ if (0 == params->server_addr_len) return false; *psockaddr_len = params->server_addr_len; } else *psockaddr_len = 0; } } return true; } /** * Start a webserver on the given port. * * @param flags combination of `enum MHD_FLAG` values * @param port port to bind to (in host byte order), * use '0' to bind to random free port, * ignored if #MHD_OPTION_SOCK_ADDR or * #MHD_OPTION_LISTEN_SOCKET is provided * or #MHD_USE_NO_LISTEN_SOCKET is specified * @param apc callback to call to check which clients * will be allowed to connect; you can pass NULL * in which case connections from any IP will be * accepted * @param apc_cls extra argument to @a apc * @param dh handler called for all requests (repeatedly) * @param dh_cls extra argument to @a dh * @param ap list of options (type-value pairs, * terminated with #MHD_OPTION_END). * @return NULL on error, handle to daemon on success * @ingroup event */ _MHD_EXTERN struct MHD_Daemon * MHD_start_daemon_va (unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, va_list ap) { const MHD_SCKT_OPT_BOOL_ on = 1; struct MHD_Daemon *daemon; const struct sockaddr *pservaddr = NULL; socklen_t addrlen; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) unsigned int i; #endif enum MHD_FLAG eflags; /* same type as in MHD_Daemon */ enum MHD_FLAG *pflags; struct MHD_InterimParams_ *interim_params; MHD_check_global_init_ (); eflags = (enum MHD_FLAG) flags; pflags = &eflags; if (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION)) *pflags |= MHD_USE_INTERNAL_POLLING_THREAD; /* Force enable, log warning later if needed */ #ifndef HAVE_INET6 if (0 != (*pflags & MHD_USE_IPv6)) return NULL; #endif #ifndef HAVE_POLL if (0 != (*pflags & MHD_USE_POLL)) return NULL; #endif #ifndef EPOLL_SUPPORT if (0 != (*pflags & MHD_USE_EPOLL)) return NULL; #endif /* ! EPOLL_SUPPORT */ #ifndef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) return NULL; #endif /* ! HTTPS_SUPPORT */ #ifndef TCP_FASTOPEN if (0 != (*pflags & MHD_USE_TCP_FASTOPEN)) return NULL; #endif if (0 != (*pflags & MHD_ALLOW_UPGRADE)) { #ifdef UPGRADE_SUPPORT *pflags |= MHD_ALLOW_SUSPEND_RESUME; #else /* ! UPGRADE_SUPPORT */ return NULL; #endif /* ! UPGRADE_SUPPORT */ } #ifdef MHD_USE_THREADS if ((MHD_USE_NO_THREAD_SAFETY | MHD_USE_INTERNAL_POLLING_THREAD) == ((MHD_USE_NO_THREAD_SAFETY | MHD_USE_INTERNAL_POLLING_THREAD) & *pflags)) return NULL; /* Cannot be thread-unsafe with multiple threads */ #else /* ! MHD_USE_THREADS */ if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) return NULL; #endif /* ! MHD_USE_THREADS */ if (NULL == dh) return NULL; /* Check for invalid combinations of flags. */ if ((0 != (*pflags & MHD_USE_POLL)) && (0 != (*pflags & MHD_USE_EPOLL))) return NULL; if ((0 != (*pflags & MHD_USE_EPOLL)) && (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION))) return NULL; if ((0 != (*pflags & MHD_USE_POLL)) && (0 == (*pflags & (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION)))) return NULL; if ((0 != (*pflags & MHD_USE_AUTO)) && (0 != (*pflags & (MHD_USE_POLL | MHD_USE_EPOLL)))) return NULL; if (0 != (*pflags & MHD_USE_AUTO)) { #if defined(EPOLL_SUPPORT) && defined(HAVE_POLL) if (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION)) *pflags |= MHD_USE_POLL; else *pflags |= MHD_USE_EPOLL; /* Including "external select" mode */ #elif defined(HAVE_POLL) if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) *pflags |= MHD_USE_POLL; /* Including thread-per-connection */ #elif defined(EPOLL_SUPPORT) if (0 == (*pflags & MHD_USE_THREAD_PER_CONNECTION)) *pflags |= MHD_USE_EPOLL; /* Including "external select" mode */ #else /* No choice: use select() for any mode - do not modify flags */ #endif } if (0 != (*pflags & MHD_USE_NO_THREAD_SAFETY)) *pflags = (*pflags & ~((enum MHD_FLAG) MHD_USE_ITC)); /* useless in single-threaded environment */ else if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) { #ifdef HAVE_LISTEN_SHUTDOWN if (0 != (*pflags & MHD_USE_NO_LISTEN_SOCKET)) #endif *pflags |= MHD_USE_ITC; /* yes, must use ITC to signal thread */ } if (NULL == (daemon = MHD_calloc_ (1, sizeof (struct MHD_Daemon)))) return NULL; interim_params = (struct MHD_InterimParams_ *) \ MHD_calloc_ (1, sizeof (struct MHD_InterimParams_)); if (NULL == interim_params) { int err_num = errno; free (daemon); errno = err_num; return NULL; } #ifdef EPOLL_SUPPORT daemon->epoll_fd = -1; #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) daemon->epoll_upgrade_fd = -1; #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #endif /* try to open listen socket */ #ifdef HTTPS_SUPPORT daemon->priority_cache = NULL; #endif /* HTTPS_SUPPORT */ daemon->listen_fd = MHD_INVALID_SOCKET; daemon->listen_is_unix = _MHD_NO; daemon->listening_address_reuse = 0; daemon->options = *pflags; pflags = &daemon->options; daemon->client_discipline = (0 != (*pflags & MHD_USE_PEDANTIC_CHECKS)) ? 1 : 0; daemon->port = port; daemon->apc = apc; daemon->apc_cls = apc_cls; daemon->default_handler = dh; daemon->default_handler_cls = dh_cls; daemon->connections = 0; daemon->connection_limit = MHD_MAX_CONNECTIONS_DEFAULT; daemon->pool_size = MHD_POOL_SIZE_DEFAULT; daemon->pool_increment = MHD_BUF_INC_SIZE; daemon->unescape_callback = &unescape_wrapper; daemon->connection_timeout_ms = 0; /* no timeout */ MHD_itc_set_invalid_ (daemon->itc); #ifdef MHD_USE_THREADS MHD_thread_handle_ID_set_invalid_ (&daemon->tid); #endif /* MHD_USE_THREADS */ #ifdef SOMAXCONN daemon->listen_backlog_size = SOMAXCONN; #else /* !SOMAXCONN */ daemon->listen_backlog_size = 511; /* should be safe value */ #endif /* !SOMAXCONN */ #ifdef HAVE_MESSAGES daemon->custom_error_log = &MHD_default_logger_; daemon->custom_error_log_cls = stderr; #endif #ifndef MHD_WINSOCK_SOCKETS daemon->sigpipe_blocked = false; #else /* MHD_WINSOCK_SOCKETS */ /* There is no SIGPIPE on W32, nothing to block. */ daemon->sigpipe_blocked = true; #endif /* _WIN32 && ! __CYGWIN__ */ #if defined(_DEBUG) && defined(HAVE_ACCEPT4) daemon->avoid_accept4 = false; #endif /* _DEBUG */ #ifdef HAS_FD_SETSIZE_OVERRIDABLE daemon->fdset_size = (int) FD_SETSIZE; daemon->fdset_size_set_by_app = false; #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ #ifdef DAUTH_SUPPORT daemon->digest_auth_rand_size = 0; daemon->digest_auth_random = NULL; daemon->nonce_nc_size = 4; /* tiny */ daemon->dauth_def_nonce_timeout = MHD_DAUTH_DEF_TIMEOUT_; daemon->dauth_def_max_nc = MHD_DAUTH_DEF_MAX_NC_; #endif #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) { daemon->cred_type = GNUTLS_CRD_CERTIFICATE; } #endif /* HTTPS_SUPPORT */ interim_params->num_opts = 0; interim_params->fdset_size_set = false; interim_params->fdset_size = 0; interim_params->listen_fd_set = false; interim_params->listen_fd = MHD_INVALID_SOCKET; interim_params->pserver_addr_set = false; interim_params->pserver_addr = NULL; interim_params->server_addr_len_set = false; interim_params->server_addr_len = 0; if (MHD_NO == parse_options_va (daemon, interim_params, ap)) { #ifdef HTTPS_SUPPORT tls_cleanup_failed_start (daemon); #endif /* HTTPS_SUPPORT */ free (interim_params); free (daemon); return NULL; } if (! process_interim_params (daemon, &pservaddr, &addrlen, interim_params)) { #ifdef HTTPS_SUPPORT tls_cleanup_failed_start (daemon); #endif /* HTTPS_SUPPORT */ free (interim_params); free (daemon); return NULL; } free (interim_params); interim_params = NULL; #ifdef HTTPS_SUPPORT if ((0 != (*pflags & MHD_USE_TLS)) && (NULL == daemon->priority_cache) && ! daemon_tls_priorities_init_default (daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise GnuTLS priorities.\n")); #endif /* HAVE_MESSAGES */ tls_cleanup_failed_start (daemon); free (daemon); return NULL; } #endif /* HTTPS_SUPPORT */ #ifdef HAVE_MESSAGES if ( (0 != (flags & MHD_USE_THREAD_PER_CONNECTION)) && (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD)) ) { MHD_DLOG (daemon, _ ("Warning: MHD_USE_THREAD_PER_CONNECTION must be used " \ "only with MHD_USE_INTERNAL_POLLING_THREAD. " \ "Flag MHD_USE_INTERNAL_POLLING_THREAD was added. " \ "Consider setting MHD_USE_INTERNAL_POLLING_THREAD " \ "explicitly.\n")); } #endif if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && ((NULL != daemon->notify_completed) || (NULL != daemon->notify_connection)) ) *pflags |= MHD_USE_ITC; /* requires ITC */ #ifdef _DEBUG #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Using debug build of libmicrohttpd.\n") ); #endif /* HAVE_MESSAGES */ #endif /* _DEBUG */ if ( (0 != (*pflags & MHD_USE_ITC)) #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) && (0 == daemon->worker_pool_size) #endif ) { if (! MHD_itc_init_ (daemon->itc)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to create inter-thread communication channel: %s\n"), MHD_itc_last_strerror_ ()); #endif #ifdef HTTPS_SUPPORT if (NULL != daemon->priority_cache) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon); return NULL; } if (MHD_D_IS_USING_SELECT_ (daemon) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (MHD_itc_r_fd_ (daemon->itc), daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("file descriptor for inter-thread communication " \ "channel exceeds maximum value.\n")); #endif MHD_itc_destroy_chk_ (daemon->itc); #ifdef HTTPS_SUPPORT if (NULL != daemon->priority_cache) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon); return NULL; } } #ifdef DAUTH_SUPPORT if (NULL != daemon->digest_auth_random_copy) { mhd_assert (daemon == daemon->digest_auth_random_copy); daemon->digest_auth_random_copy = malloc (daemon->digest_auth_rand_size); if (NULL == daemon->digest_auth_random_copy) { #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon); return NULL; } memcpy (daemon->digest_auth_random_copy, daemon->digest_auth_random, daemon->digest_auth_rand_size); daemon->digest_auth_random = daemon->digest_auth_random_copy; } if (daemon->nonce_nc_size > 0) { if ( ( (size_t) (daemon->nonce_nc_size * sizeof (struct MHD_NonceNc))) / sizeof(struct MHD_NonceNc) != daemon->nonce_nc_size) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Specified value for NC_SIZE too large.\n")); #endif #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon->digest_auth_random_copy); free (daemon); return NULL; } daemon->nnc = MHD_calloc_ (daemon->nonce_nc_size, sizeof (struct MHD_NonceNc)); if (NULL == daemon->nnc) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to allocate memory for nonce-nc map: %s\n"), MHD_strerror_ (errno)); #endif #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon->digest_auth_random_copy); free (daemon); return NULL; } } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (! MHD_mutex_init_ (&daemon->nnc_lock)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD failed to initialize nonce-nc mutex.\n")); #endif #ifdef HTTPS_SUPPORT if (0 != (*pflags & MHD_USE_TLS)) gnutls_priority_deinit (daemon->priority_cache); #endif /* HTTPS_SUPPORT */ free (daemon->digest_auth_random_copy); free (daemon->nnc); free (daemon); return NULL; } #endif #endif /* Thread polling currently works only with internal select thread mode */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if ( (! MHD_D_IS_USING_THREADS_ (daemon)) && (daemon->worker_pool_size > 0) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD thread polling only works with " \ "MHD_USE_INTERNAL_POLLING_THREAD.\n")); #endif goto free_and_fail; } #endif if ( (MHD_INVALID_SOCKET == daemon->listen_fd) && (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)) ) { /* try to open listen socket */ struct sockaddr_in servaddr4; #ifdef HAVE_INET6 struct sockaddr_in6 servaddr6; const bool use_ipv6 = (0 != (*pflags & MHD_USE_IPv6)); #else /* ! HAVE_INET6 */ const bool use_ipv6 = false; #endif /* ! HAVE_INET6 */ int domain; if (NULL != pservaddr) { #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN const socklen_t sa_len = pservaddr->sa_len; #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ #ifdef HAVE_INET6 if (use_ipv6 && (AF_INET6 != pservaddr->sa_family)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD_USE_IPv6 is enabled, but 'struct sockaddr *' " \ "specified for MHD_OPTION_SOCK_ADDR_LEN or " \ "MHD_OPTION_SOCK_ADDR is not IPv6 address.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } #endif /* HAVE_INET6 */ switch (pservaddr->sa_family) { case AF_INET: if (1) { struct sockaddr_in sa4; uint16_t sa4_port; if ((0 != addrlen) && (((socklen_t) sizeof(sa4)) > addrlen)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The size specified for MHD_OPTION_SOCK_ADDR_LEN " \ "option is wrong.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if (0 != sa_len) { if (((socklen_t) sizeof(sa4)) > sa_len) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The value of 'struct sockaddr.sa_len' provided " \ "via MHD_OPTION_SOCK_ADDR_LEN option is not zero " \ "and does not match 'sa_family' value of the " \ "same structure.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } if ((0 == addrlen) || (sa_len < addrlen)) addrlen = sa_len; /* Use smaller value for safety */ } #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ if (0 == addrlen) addrlen = sizeof(sa4); memcpy (&sa4, pservaddr, sizeof(sa4)); /* Required due to stronger alignment */ sa4_port = (uint16_t) ntohs (sa4.sin_port); #ifndef MHD_USE_GETSOCKNAME if (0 != sa4_port) #endif /* ! MHD_USE_GETSOCKNAME */ daemon->port = sa4_port; domain = PF_INET; } break; #ifdef HAVE_INET6 case AF_INET6: if (1) { struct sockaddr_in6 sa6; uint16_t sa6_port; if ((0 != addrlen) && (((socklen_t) sizeof(sa6)) > addrlen)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The size specified for MHD_OPTION_SOCK_ADDR_LEN " \ "option is wrong.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if (0 != sa_len) { if (((socklen_t) sizeof(sa6)) > sa_len) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The value of 'struct sockaddr.sa_len' provided " \ "via MHD_OPTION_SOCK_ADDR_LEN option is not zero " \ "and does not match 'sa_family' value of the " \ "same structure.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } if ((0 == addrlen) || (sa_len < addrlen)) addrlen = sa_len; /* Use smaller value for safety */ } #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ if (0 == addrlen) addrlen = sizeof(sa6); memcpy (&sa6, pservaddr, sizeof(sa6)); /* Required due to stronger alignment */ sa6_port = (uint16_t) ntohs (sa6.sin6_port); #ifndef MHD_USE_GETSOCKNAME if (0 != sa6_port) #endif /* ! MHD_USE_GETSOCKNAME */ daemon->port = sa6_port; domain = PF_INET6; *pflags |= ((enum MHD_FLAG) MHD_USE_IPv6); } break; #endif /* HAVE_INET6 */ #ifdef AF_UNIX case AF_UNIX: #endif /* AF_UNIX */ default: #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN if (0 == addrlen) addrlen = sa_len; else if ((0 != sa_len) && (sa_len < addrlen)) addrlen = sa_len; /* Use smaller value for safety */ #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ if (0 >= addrlen) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("The 'sa_family' of the 'struct sockaddr' provided " \ "via MHD_OPTION_SOCK_ADDR option is not supported.\n")); #endif /* HAVE_MESSAGES */ goto free_and_fail; } #ifdef AF_UNIX if (AF_UNIX == pservaddr->sa_family) { daemon->port = 0; /* special value for UNIX domain sockets */ daemon->listen_is_unix = _MHD_YES; #ifdef PF_UNIX domain = PF_UNIX; #else /* ! PF_UNIX */ domain = AF_UNIX; #endif /* ! PF_UNIX */ } else /* combined with the next 'if' */ #endif /* AF_UNIX */ if (1) { daemon->port = 0; /* ugh */ daemon->listen_is_unix = _MHD_UNKNOWN; /* Assumed the same values for AF_* and PF_* */ domain = pservaddr->sa_family; } break; } } else { if (! use_ipv6) { memset (&servaddr4, 0, sizeof (struct sockaddr_in)); servaddr4.sin_family = AF_INET; servaddr4.sin_port = htons (port); if (0 != INADDR_ANY) servaddr4.sin_addr.s_addr = htonl (INADDR_ANY); #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN servaddr4.sin_len = sizeof (struct sockaddr_in); #endif pservaddr = (struct sockaddr *) &servaddr4; addrlen = (socklen_t) sizeof(servaddr4); daemon->listen_is_unix = _MHD_NO; domain = PF_INET; } #ifdef HAVE_INET6 else { #ifdef IN6ADDR_ANY_INIT static const struct in6_addr static_in6any = IN6ADDR_ANY_INIT; #endif memset (&servaddr6, 0, sizeof (struct sockaddr_in6)); servaddr6.sin6_family = AF_INET6; servaddr6.sin6_port = htons (port); #ifdef IN6ADDR_ANY_INIT servaddr6.sin6_addr = static_in6any; #endif #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN servaddr6.sin6_len = sizeof (struct sockaddr_in6); #endif pservaddr = (struct sockaddr *) &servaddr6; addrlen = (socklen_t) sizeof (servaddr6); daemon->listen_is_unix = _MHD_NO; domain = PF_INET6; } #endif /* HAVE_INET6 */ } daemon->listen_fd = MHD_socket_create_listen_ (domain); if (MHD_INVALID_SOCKET == daemon->listen_fd) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to create socket for listening: %s\n"), MHD_socket_last_strerr_ ()); #endif goto free_and_fail; } if (MHD_D_IS_USING_SELECT_ (daemon) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (daemon->listen_fd, daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Listen socket descriptor (%d) is not " \ "less than daemon FD_SETSIZE value (%d).\n"), (int) daemon->listen_fd, (int) MHD_D_GET_FD_SETSIZE_ (daemon)); #endif goto free_and_fail; } /* Apply the socket options according to listening_address_reuse. */ if (0 == daemon->listening_address_reuse) { #ifndef MHD_WINSOCK_SOCKETS /* No user requirement, use "traditional" default SO_REUSEADDR * on non-W32 platforms, and do not fail if it doesn't work. * Don't use it on W32, because on W32 it will allow multiple * bind to the same address:port, like SO_REUSEPORT on others. */ if (0 > setsockopt (daemon->listen_fd, SOL_SOCKET, SO_REUSEADDR, (const void *) &on, sizeof (on))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif } #endif /* ! MHD_WINSOCK_SOCKETS */ } else if (daemon->listening_address_reuse > 0) { /* User requested to allow reusing listening address:port. */ #ifndef MHD_WINSOCK_SOCKETS /* Use SO_REUSEADDR on non-W32 platforms, and do not fail if * it doesn't work. */ if (0 > setsockopt (daemon->listen_fd, SOL_SOCKET, SO_REUSEADDR, (const void *) &on, sizeof (on))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif } #endif /* ! MHD_WINSOCK_SOCKETS */ /* Use SO_REUSEADDR on Windows and SO_REUSEPORT on most platforms. * Fail if SO_REUSEPORT is not defined or setsockopt fails. */ /* SO_REUSEADDR on W32 has the same semantics as SO_REUSEPORT on BSD/Linux */ #if defined(MHD_WINSOCK_SOCKETS) || defined(SO_REUSEPORT) if (0 > setsockopt (daemon->listen_fd, SOL_SOCKET, #ifndef MHD_WINSOCK_SOCKETS SO_REUSEPORT, #else /* MHD_WINSOCK_SOCKETS */ SO_REUSEADDR, #endif /* MHD_WINSOCK_SOCKETS */ (const void *) &on, sizeof (on))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif goto free_and_fail; } #else /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */ /* we're supposed to allow address:port re-use, but on this platform we cannot; fail hard */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Cannot allow listening address reuse: " \ "SO_REUSEPORT not defined.\n")); #endif goto free_and_fail; #endif /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */ } else /* if (daemon->listening_address_reuse < 0) */ { /* User requested to disallow reusing listening address:port. * Do nothing except for Windows where SO_EXCLUSIVEADDRUSE * is used and Solaris with SO_EXCLBIND. * Fail if MHD was compiled for W32 without SO_EXCLUSIVEADDRUSE * or setsockopt fails. */ #if (defined(MHD_WINSOCK_SOCKETS) && defined(SO_EXCLUSIVEADDRUSE)) || \ (defined(__sun) && defined(SO_EXCLBIND)) if (0 > setsockopt (daemon->listen_fd, SOL_SOCKET, #ifdef SO_EXCLUSIVEADDRUSE SO_EXCLUSIVEADDRUSE, #else /* SO_EXCLBIND */ SO_EXCLBIND, #endif /* SO_EXCLBIND */ (const void *) &on, sizeof (on))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif goto free_and_fail; } #elif defined(MHD_WINSOCK_SOCKETS) /* SO_EXCLUSIVEADDRUSE not defined on W32? */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Cannot disallow listening address reuse: " \ "SO_EXCLUSIVEADDRUSE not defined.\n")); #endif goto free_and_fail; #endif /* MHD_WINSOCK_SOCKETS */ } /* check for user supplied sockaddr */ if (0 != (*pflags & MHD_USE_IPv6)) { #ifdef IPPROTO_IPV6 #ifdef IPV6_V6ONLY /* Note: "IPV6_V6ONLY" is declared by Windows Vista ff., see "IPPROTO_IPV6 Socket Options" (http://msdn.microsoft.com/en-us/library/ms738574%28v=VS.85%29.aspx); and may also be missing on older POSIX systems; good luck if you have any of those, your IPv6 socket may then also bind against IPv4 anyway... */ const MHD_SCKT_OPT_BOOL_ v6_only = (MHD_USE_DUAL_STACK != (*pflags & MHD_USE_DUAL_STACK)); if (0 > setsockopt (daemon->listen_fd, IPPROTO_IPV6, IPV6_V6ONLY, (const void *) &v6_only, sizeof (v6_only))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif } #endif #endif } if (0 != bind (daemon->listen_fd, pservaddr, addrlen)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to bind to port %u: %s\n"), (unsigned int) port, MHD_socket_last_strerr_ ()); #endif goto free_and_fail; } #ifdef TCP_FASTOPEN if (0 != (*pflags & MHD_USE_TCP_FASTOPEN)) { if (0 == daemon->fastopen_queue_size) daemon->fastopen_queue_size = MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT; if (0 != setsockopt (daemon->listen_fd, IPPROTO_TCP, TCP_FASTOPEN, (const void *) &daemon->fastopen_queue_size, sizeof (daemon->fastopen_queue_size))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("setsockopt failed: %s\n"), MHD_socket_last_strerr_ ()); #endif } } #endif if (0 != listen (daemon->listen_fd, (int) daemon->listen_backlog_size)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to listen for connections: %s\n"), MHD_socket_last_strerr_ ()); #endif goto free_and_fail; } } else { if (MHD_D_IS_USING_SELECT_ (daemon) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (daemon->listen_fd, daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Listen socket descriptor (%d) is not " \ "less than daemon FD_SETSIZE value (%d).\n"), (int) daemon->listen_fd, (int) MHD_D_GET_FD_SETSIZE_ (daemon)); #endif goto free_and_fail; } else { #if defined(SOL_SOCKET) && (defined(SO_DOMAIN) || defined(SO_PROTOCOL_INFOW)) int af; int opt_name; void *poptval; socklen_t optval_size; #ifdef SO_DOMAIN opt_name = SO_DOMAIN; poptval = ⁡ optval_size = (socklen_t) sizeof (af); #else /* SO_PROTOCOL_INFOW */ WSAPROTOCOL_INFOW prot_info; opt_name = SO_PROTOCOL_INFOW; poptval = &prot_info; optval_size = (socklen_t) sizeof (prot_info); #endif /* SO_PROTOCOL_INFOW */ if (0 == getsockopt (daemon->listen_fd, SOL_SOCKET, opt_name, poptval, &optval_size)) { #ifndef SO_DOMAIN af = prot_info.iAddressFamily; #endif /* SO_DOMAIN */ switch (af) { case AF_INET: daemon->listen_is_unix = _MHD_NO; break; #ifdef HAVE_INET6 case AF_INET6: *pflags |= MHD_USE_IPv6; daemon->listen_is_unix = _MHD_NO; break; #endif /* HAVE_INET6 */ #ifdef AF_UNIX case AF_UNIX: daemon->port = 0; /* special value for UNIX domain sockets */ daemon->listen_is_unix = _MHD_YES; break; #endif /* AF_UNIX */ default: daemon->port = 0; /* ugh */ daemon->listen_is_unix = _MHD_UNKNOWN; break; } } else #endif /* SOL_SOCKET && (SO_DOMAIN || SO_PROTOCOL_INFOW)) */ daemon->listen_is_unix = _MHD_UNKNOWN; } #ifdef MHD_USE_GETSOCKNAME daemon->port = 0; /* Force use of autodetection */ #endif /* MHD_USE_GETSOCKNAME */ } #ifdef MHD_USE_GETSOCKNAME if ( (0 == daemon->port) && (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)) && (_MHD_YES != daemon->listen_is_unix) ) { /* Get port number. */ struct sockaddr_storage bindaddr; memset (&bindaddr, 0, sizeof (struct sockaddr_storage)); addrlen = sizeof (struct sockaddr_storage); #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN bindaddr.ss_len = (socklen_t) addrlen; #endif if (0 != getsockname (daemon->listen_fd, (struct sockaddr *) &bindaddr, &addrlen)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to get listen port number: %s\n"), MHD_socket_last_strerr_ ()); #endif /* HAVE_MESSAGES */ } #ifdef MHD_POSIX_SOCKETS else if (sizeof (bindaddr) < addrlen) { /* should be impossible with `struct sockaddr_storage` */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to get listen port number " \ "(`struct sockaddr_storage` too small!?).\n")); #endif /* HAVE_MESSAGES */ } #ifndef __linux__ else if (0 == addrlen) { /* Many non-Linux-based platforms return zero addrlen * for AF_UNIX sockets */ daemon->port = 0; /* special value for UNIX domain sockets */ if (_MHD_UNKNOWN == daemon->listen_is_unix) daemon->listen_is_unix = _MHD_YES; } #endif /* __linux__ */ #endif /* MHD_POSIX_SOCKETS */ else { switch (bindaddr.ss_family) { case AF_INET: { struct sockaddr_in *s4 = (struct sockaddr_in *) &bindaddr; daemon->port = ntohs (s4->sin_port); daemon->listen_is_unix = _MHD_NO; break; } #ifdef HAVE_INET6 case AF_INET6: { struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) &bindaddr; daemon->port = ntohs (s6->sin6_port); daemon->listen_is_unix = _MHD_NO; mhd_assert (0 != (*pflags & MHD_USE_IPv6)); break; } #endif /* HAVE_INET6 */ #ifdef AF_UNIX case AF_UNIX: daemon->port = 0; /* special value for UNIX domain sockets */ daemon->listen_is_unix = _MHD_YES; break; #endif default: #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Listen socket has unknown address family!\n")); #endif daemon->port = 0; /* ugh */ daemon->listen_is_unix = _MHD_UNKNOWN; break; } } } #endif /* MHD_USE_GETSOCKNAME */ if (MHD_INVALID_SOCKET != daemon->listen_fd) { mhd_assert (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)); if (! MHD_socket_nonblocking_ (daemon->listen_fd)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set nonblocking mode on listening socket: %s\n"), MHD_socket_last_strerr_ ()); #endif if (MHD_D_IS_USING_EPOLL_ (daemon) #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) || (daemon->worker_pool_size > 0) #endif ) { /* Accept must be non-blocking. Multiple children may wake up * to handle a new connection, but only one will win the race. * The others must immediately return. */ goto free_and_fail; } daemon->listen_nonblk = false; } else daemon->listen_nonblk = true; } else { mhd_assert (0 != (*pflags & MHD_USE_NO_LISTEN_SOCKET)); daemon->listen_nonblk = false; /* Actually listen socket does not exist */ } #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) && (0 == daemon->worker_pool_size) #endif ) { if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Combining MHD_USE_THREAD_PER_CONNECTION and " \ "MHD_USE_EPOLL is not supported.\n")); #endif goto free_and_fail; } if (MHD_NO == setup_epoll_to_listen (daemon)) goto free_and_fail; } #endif /* EPOLL_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (! MHD_mutex_init_ (&daemon->per_ip_connection_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("MHD failed to initialize IP connection limit mutex.\n")); #endif goto free_and_fail; } #endif #ifdef HTTPS_SUPPORT /* initialize HTTPS daemon certificate aspects & send / recv functions */ if ( (0 != (*pflags & MHD_USE_TLS)) && (0 != MHD_TLS_init (daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialize TLS support.\n")); #endif #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); #endif goto free_and_fail; } #endif /* HTTPS_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /* Start threads if requested by parameters */ if (MHD_D_IS_USING_THREADS_ (daemon)) { /* Internal thread (or threads) is used. * Make sure that MHD will be able to communicate with threads. */ /* If using a thread pool ITC will be initialised later * for each individual worker thread. */ #ifdef HAVE_LISTEN_SHUTDOWN mhd_assert ((1 < daemon->worker_pool_size) || \ (MHD_ITC_IS_VALID_ (daemon->itc)) || \ (MHD_INVALID_SOCKET != daemon->listen_fd)); #else /* ! HAVE_LISTEN_SHUTDOWN */ mhd_assert ((1 < daemon->worker_pool_size) || \ (MHD_ITC_IS_VALID_ (daemon->itc))); #endif /* ! HAVE_LISTEN_SHUTDOWN */ if (0 == daemon->worker_pool_size) { if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise internal lists mutex.\n")); #endif MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); goto free_and_fail; } if (! MHD_mutex_init_ (&daemon->new_connections_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise mutex.\n")); #endif MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); goto free_and_fail; } if (! MHD_mutex_init_ (&daemon->epoll_listen_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise mutex.\n")); #endif MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex); MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); goto free_and_fail; } if (! MHD_create_named_thread_ (&daemon->tid, MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) ? "MHD-listen" : "MHD-single", daemon->thread_stack_size, &MHD_polling_thread, daemon) ) { #ifdef HAVE_MESSAGES #ifdef EAGAIN if (EAGAIN == errno) MHD_DLOG (daemon, _ ("Failed to create a new thread because it would have " \ "exceeded the system limit on the number of threads or " \ "no system resources available.\n")); else #endif /* EAGAIN */ MHD_DLOG (daemon, _ ("Failed to create listen thread: %s\n"), MHD_strerror_ (errno)); #endif /* HAVE_MESSAGES */ MHD_mutex_destroy_chk_ (&daemon->epoll_listen_mutex); MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex); MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); goto free_and_fail; } } else /* 0 < daemon->worker_pool_size */ { /* Coarse-grained count of connections per thread (note error * due to integer division). Also keep track of how many * connections are leftover after an equal split. */ unsigned int conns_per_thread = daemon->connection_limit / daemon->worker_pool_size; unsigned int leftover_conns = daemon->connection_limit % daemon->worker_pool_size; mhd_assert (2 <= daemon->worker_pool_size); i = 0; /* we need this in case fcntl or malloc fails */ /* Allocate memory for pooled objects */ daemon->worker_pool = malloc (sizeof (struct MHD_Daemon) * daemon->worker_pool_size); if (NULL == daemon->worker_pool) goto thread_failed; /* Start the workers in the pool */ for (i = 0; i < daemon->worker_pool_size; ++i) { /* Create copy of the Daemon object for each worker */ struct MHD_Daemon *d = &daemon->worker_pool[i]; memcpy (d, daemon, sizeof (struct MHD_Daemon)); /* Adjust polling params for worker daemons; note that memcpy() has already copied MHD_USE_INTERNAL_POLLING_THREAD thread mode into the worker threads. */ d->master = daemon; d->worker_pool_size = 0; d->worker_pool = NULL; if (! MHD_mutex_init_ (&d->cleanup_connection_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise internal lists mutex.\n")); #endif goto thread_failed; } if (! MHD_mutex_init_ (&d->new_connections_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise mutex.\n")); #endif MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); goto thread_failed; } if (! MHD_mutex_init_ (&d->epoll_listen_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise mutex.\n")); #endif MHD_mutex_destroy_chk_ (&d->new_connections_mutex); MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); goto free_and_fail; } if (0 != (*pflags & MHD_USE_ITC)) { if (! MHD_itc_init_ (d->itc)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to create worker inter-thread " \ "communication channel: %s\n"), MHD_itc_last_strerror_ () ); #endif MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex); MHD_mutex_destroy_chk_ (&d->new_connections_mutex); MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); goto thread_failed; } if (MHD_D_IS_USING_SELECT_ (d) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (MHD_itc_r_fd_ (d->itc), daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("File descriptor for worker inter-thread " \ "communication channel exceeds maximum value.\n")); #endif MHD_itc_destroy_chk_ (d->itc); MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex); MHD_mutex_destroy_chk_ (&d->new_connections_mutex); MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); goto thread_failed; } } else MHD_itc_set_invalid_ (d->itc); #ifdef HAVE_LISTEN_SHUTDOWN mhd_assert ((MHD_ITC_IS_VALID_ (d->itc)) || \ (MHD_INVALID_SOCKET != d->listen_fd)); #else /* ! HAVE_LISTEN_SHUTDOWN */ mhd_assert (MHD_ITC_IS_VALID_ (d->itc)); #endif /* ! HAVE_LISTEN_SHUTDOWN */ /* Divide available connections evenly amongst the threads. * Thread indexes in [0, leftover_conns) each get one of the * leftover connections. */ d->connection_limit = conns_per_thread; if (i < leftover_conns) ++d->connection_limit; #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (d) && (MHD_NO == setup_epoll_to_listen (d)) ) { if (MHD_ITC_IS_VALID_ (d->itc)) MHD_itc_destroy_chk_ (d->itc); MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex); MHD_mutex_destroy_chk_ (&d->new_connections_mutex); MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); goto thread_failed; } #endif /* Some members must be used only in master daemon */ #if defined(MHD_USE_THREADS) memset (&d->per_ip_connection_mutex, 0x7F, sizeof(d->per_ip_connection_mutex)); #endif /* MHD_USE_THREADS */ #ifdef DAUTH_SUPPORT d->nnc = NULL; d->nonce_nc_size = 0; d->digest_auth_random_copy = NULL; #if defined(MHD_USE_THREADS) memset (&d->nnc_lock, 0x7F, sizeof(d->nnc_lock)); #endif /* MHD_USE_THREADS */ #endif /* DAUTH_SUPPORT */ /* Spawn the worker thread */ if (! MHD_create_named_thread_ (&d->tid, "MHD-worker", daemon->thread_stack_size, &MHD_polling_thread, d)) { #ifdef HAVE_MESSAGES #ifdef EAGAIN if (EAGAIN == errno) MHD_DLOG (daemon, _ ("Failed to create a new pool thread because it would " \ "have exceeded the system limit on the number of " \ "threads or no system resources available.\n")); else #endif /* EAGAIN */ MHD_DLOG (daemon, _ ("Failed to create pool thread: %s\n"), MHD_strerror_ (errno)); #endif /* Free memory for this worker; cleanup below handles * all previously-created workers. */ if (MHD_ITC_IS_VALID_ (d->itc)) MHD_itc_destroy_chk_ (d->itc); MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex); MHD_mutex_destroy_chk_ (&d->new_connections_mutex); MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); goto thread_failed; } } } } else { /* Daemon without internal threads */ if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise internal lists mutex.\n")); #endif MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); goto free_and_fail; } if (! MHD_mutex_init_ (&daemon->new_connections_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise mutex.\n")); #endif MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); goto free_and_fail; } if (! MHD_mutex_init_ (&daemon->epoll_listen_mutex)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to initialise mutex.\n")); #endif MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex); MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); goto free_and_fail; } } #endif #ifdef HTTPS_SUPPORT /* API promises to never use the password after initialization, so we additionally NULL it here to not deref a dangling pointer. */ daemon->https_key_password = NULL; #endif /* HTTPS_SUPPORT */ return daemon; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) thread_failed: /* If no worker threads created, then shut down normally. Calling MHD_stop_daemon (as we do below) doesn't work here since it assumes a 0-sized thread pool means we had been in the default MHD_USE_INTERNAL_POLLING_THREAD mode. */ if (0 == i) { MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); if (NULL != daemon->worker_pool) free (daemon->worker_pool); goto free_and_fail; } /* Shutdown worker threads we've already created. Pretend as though we had fully initialized our daemon, but with a smaller number of threads than had been requested. */ daemon->worker_pool_size = i; MHD_stop_daemon (daemon); return NULL; #endif free_and_fail: /* clean up basic memory state in 'daemon' and return NULL to indicate failure */ #ifdef EPOLL_SUPPORT #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (daemon->upgrade_fd_in_epoll) { if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_DEL, daemon->epoll_upgrade_fd, NULL)) MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); daemon->upgrade_fd_in_epoll = false; } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ if (-1 != daemon->epoll_fd) close (daemon->epoll_fd); #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (-1 != daemon->epoll_upgrade_fd) close (daemon->epoll_upgrade_fd); #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #endif /* EPOLL_SUPPORT */ #ifdef DAUTH_SUPPORT free (daemon->digest_auth_random_copy); free (daemon->nnc); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_destroy_chk_ (&daemon->nnc_lock); #endif #endif #ifdef HTTPS_SUPPORT tls_cleanup_failed_start (daemon); #endif /* HTTPS_SUPPORT */ if (MHD_ITC_IS_VALID_ (daemon->itc)) MHD_itc_destroy_chk_ (daemon->itc); if (MHD_INVALID_SOCKET != daemon->listen_fd) (void) MHD_socket_close_ (daemon->listen_fd); free (daemon); return NULL; } /** * Close all connections for the daemon. * Must only be called when MHD_Daemon::shutdown was set to true. * @remark To be called only from thread that process * daemon's select()/poll()/etc. * * @param daemon daemon to close down */ static void close_all_connections (struct MHD_Daemon *daemon) { struct MHD_Connection *pos; const bool used_thr_p_c = MHD_D_IS_USING_THREAD_PER_CONN_ (daemon); #ifdef UPGRADE_SUPPORT const bool upg_allowed = (0 != (daemon->options & MHD_ALLOW_UPGRADE)); #endif /* UPGRADE_SUPPORT */ #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) struct MHD_UpgradeResponseHandle *urh; struct MHD_UpgradeResponseHandle *urhn; const bool used_tls = (0 != (daemon->options & MHD_USE_TLS)); #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ mhd_assert (daemon->shutdown); #ifdef MHD_USE_THREADS /* Remove new connections that MHD_add_connection() queued and that were * never processed. This is not limited to daemons with an internal * polling thread: internal_add_connection() queues whenever the daemon * is thread-safe, which is every daemon that was not started with * MHD_USE_NO_THREAD_SAFETY, and new_connections_list_process_() * asserts the same condition. An application driving an external * event loop can therefore call MHD_add_connection() and then * MHD_stop_daemon() before the next MHD_run(), and this list is what * holds the connection at that point. */ MHD_mutex_lock_chk_ (&daemon->new_connections_mutex); while (NULL != (pos = daemon->new_connections_tail)) { mhd_assert (MHD_D_IS_THREAD_SAFE_ (daemon)); DLL_remove (daemon->new_connections_head, daemon->new_connections_tail, pos); new_connection_close_ (daemon, pos); } MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex); #endif /* MHD_USE_THREADS */ #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /* give upgraded HTTPS connections a chance to finish */ /* 'daemon->urh_head' is not used in thread-per-connection mode. */ for (urh = daemon->urh_tail; NULL != urh; urh = urhn) { mhd_assert (! used_thr_p_c); urhn = urh->prev; /* call generic forwarding function for passing data with chance to detect that application is done. */ process_urh (urh); MHD_connection_finish_forward_ (urh->connection); urh->clean_ready = true; /* Resuming will move connection to cleanup list. */ MHD_resume_connection (urh->connection); } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ /* Give suspended connections a chance to resume to avoid running into the check for there not being any suspended connections left in case of a tight race with a recently resumed connection. */ if (0 != (MHD_TEST_ALLOW_SUSPEND_RESUME & daemon->options)) { daemon->resuming = true; /* Force check for pending resume. */ resume_suspended_connections (daemon); } /* first, make sure all threads are aware of shutdown; need to traverse DLLs in peace... */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif #ifdef UPGRADE_SUPPORT if (upg_allowed) { struct MHD_Connection *susp; susp = daemon->suspended_connections_tail; while (NULL != susp) { if (NULL == susp->urh) /* "Upgraded" connection? */ MHD_PANIC (_ ("MHD_stop_daemon() called while we have " \ "suspended connections.\n")); #ifdef HTTPS_SUPPORT else if (used_tls && used_thr_p_c && (! susp->urh->clean_ready) ) shutdown (susp->urh->app.socket, SHUT_RDWR); /* Wake thread by shutdown of app socket. */ #endif /* HTTPS_SUPPORT */ else { #ifdef HAVE_MESSAGES if (! susp->urh->was_closed) MHD_DLOG (daemon, _ ("Initiated daemon shutdown while \"upgraded\" " \ "connection was not closed.\n")); #endif susp->urh->was_closed = true; /* If thread-per-connection is used, connection's thread * may still processing "upgrade" (exiting). */ if (! used_thr_p_c) MHD_connection_finish_forward_ (susp); /* Do not use MHD_resume_connection() as mutex is * already locked. */ susp->resuming = true; daemon->resuming = true; } susp = susp->prev; } } else /* This 'else' is combined with next 'if' */ #endif /* UPGRADE_SUPPORT */ if (NULL != daemon->suspended_connections_head) MHD_PANIC (_ ("MHD_stop_daemon() called while we have " \ "suspended connections.\n")); #if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT) #ifdef MHD_USE_THREADS if (upg_allowed && used_tls && used_thr_p_c) { /* "Upgraded" threads may be running in parallel. Connection will not be * moved to the "cleanup list" until connection's thread finishes. * We must ensure that all "upgraded" connections are finished otherwise * connection may stay in "suspended" list and will not be cleaned. */ for (pos = daemon->suspended_connections_tail; NULL != pos; pos = pos->prev) { /* Any connection found here is "upgraded" connection, normal suspended * connections are already removed from this list. */ mhd_assert (NULL != pos->urh); if (! pos->thread_joined) { /* While "cleanup" list is not manipulated by "upgraded" * connection, "cleanup" mutex is required for call of * MHD_resume_connection() during finishing of "upgraded" * thread. */ MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); if (! MHD_thread_handle_ID_join_thread_ (pos->tid)) MHD_PANIC (_ ("Failed to join a thread.\n")); pos->thread_joined = true; MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); } } } #endif /* MHD_USE_THREADS */ #endif for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev) { shutdown (pos->socket_fd, SHUT_RDWR); #ifdef MHD_WINSOCK_SOCKETS if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "e")) ) MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \ "communication channel.\n")); #endif } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /* now, collect per-connection threads */ if (used_thr_p_c) { pos = daemon->connections_tail; while (NULL != pos) { if (! pos->thread_joined) { MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); if (! MHD_thread_handle_ID_join_thread_ (pos->tid)) MHD_PANIC (_ ("Failed to join a thread.\n")); MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); pos->thread_joined = true; /* The thread may have concurrently modified the DLL, need to restart from the beginning */ pos = daemon->connections_tail; continue; } pos = pos->prev; } } MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif #ifdef UPGRADE_SUPPORT /* Finished threads with "upgraded" connections need to be moved * to cleanup list by resume_suspended_connections(). */ /* "Upgraded" connections that were not closed explicitly by * application should be moved to cleanup list too. */ if (upg_allowed) { daemon->resuming = true; /* Force check for pending resume. */ resume_suspended_connections (daemon); } #endif /* UPGRADE_SUPPORT */ mhd_assert (NULL == daemon->suspended_connections_head); /* now that we're alone, move everyone to cleanup */ while (NULL != (pos = daemon->connections_tail)) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && (! pos->thread_joined) ) MHD_PANIC (_ ("Failed to join a thread.\n")); #endif close_connection (pos); } MHD_cleanup_connections (daemon); } /** * Shutdown an HTTP daemon. * * @param daemon daemon to stop * @ingroup event */ _MHD_EXTERN void MHD_stop_daemon (struct MHD_Daemon *daemon) { MHD_socket fd; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) unsigned int i; #endif if (NULL == daemon) return; if ( (daemon->shutdown) && (NULL == daemon->master) ) MHD_PANIC (_ ("MHD_stop_daemon() was called twice.")); mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (NULL != daemon->worker_pool) || \ (MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); mhd_assert (((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) && (NULL == daemon->worker_pool)) || \ (! MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); /* Slave daemons must be stopped by master daemon. */ mhd_assert ( (NULL == daemon->master) || (daemon->shutdown) ); daemon->shutdown = true; if (daemon->was_quiesced) fd = MHD_INVALID_SOCKET; /* Do not use FD if daemon was quiesced */ else fd = daemon->listen_fd; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != daemon->worker_pool) { /* Master daemon with worker pool. */ mhd_assert (1 < daemon->worker_pool_size); mhd_assert (MHD_D_IS_USING_THREADS_ (daemon)); /* Let workers shutdown in parallel. */ for (i = 0; i < daemon->worker_pool_size; ++i) { daemon->worker_pool[i].shutdown = true; if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc)) { if (! MHD_itc_activate_ (daemon->worker_pool[i].itc, "e")) MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \ "communication channel.\n")); } else mhd_assert (MHD_INVALID_SOCKET != fd); } #ifdef HAVE_LISTEN_SHUTDOWN if (MHD_INVALID_SOCKET != fd) { (void) shutdown (fd, SHUT_RDWR); } #endif /* HAVE_LISTEN_SHUTDOWN */ for (i = 0; i < daemon->worker_pool_size; ++i) { MHD_stop_daemon (&daemon->worker_pool[i]); } free (daemon->worker_pool); mhd_assert (MHD_ITC_IS_INVALID_ (daemon->itc)); #ifdef EPOLL_SUPPORT mhd_assert (-1 == daemon->epoll_fd); #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) mhd_assert (-1 == daemon->epoll_upgrade_fd); #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #endif /* EPOLL_SUPPORT */ } else #endif { /* Worker daemon or single daemon. */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (MHD_D_IS_USING_THREADS_ (daemon)) { /* Worker daemon or single daemon with internal thread(s). */ mhd_assert (0 == daemon->worker_pool_size); /* Separate thread(s) is used for polling sockets. */ if (MHD_ITC_IS_VALID_ (daemon->itc)) { if (! MHD_itc_activate_ (daemon->itc, "e")) MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \ "communication channel.\n")); } else { #ifdef HAVE_LISTEN_SHUTDOWN if (MHD_INVALID_SOCKET != fd) { if (NULL == daemon->master) (void) shutdown (fd, SHUT_RDWR); } else #endif /* HAVE_LISTEN_SHUTDOWN */ mhd_assert (false); /* Should never happen */ } if (! MHD_thread_handle_ID_join_thread_ (daemon->tid)) { MHD_PANIC (_ ("Failed to join a thread.\n")); } /* close_all_connections() was called in daemon thread. */ } else #endif { /* No internal threads are used for polling sockets. */ close_all_connections (daemon); } mhd_assert (NULL == daemon->connections_head); mhd_assert (NULL == daemon->cleanup_head); mhd_assert (NULL == daemon->suspended_connections_head); mhd_assert (NULL == daemon->new_connections_head); #if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT) mhd_assert (NULL == daemon->urh_head); #endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */ if (MHD_ITC_IS_VALID_ (daemon->itc)) MHD_itc_destroy_chk_ (daemon->itc); #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && (-1 != daemon->epoll_fd) ) MHD_socket_close_chk_ (daemon->epoll_fd); #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) if (MHD_D_IS_USING_EPOLL_ (daemon) && (-1 != daemon->epoll_upgrade_fd) ) MHD_socket_close_chk_ (daemon->epoll_upgrade_fd); #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ #endif /* EPOLL_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); MHD_mutex_destroy_chk_ (&daemon->epoll_listen_mutex); MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex); #endif } if (NULL == daemon->master) { /* Cleanup that should be done only one time in master/single daemon. * Do not perform this cleanup in worker daemons. */ if (MHD_INVALID_SOCKET != fd) MHD_socket_close_chk_ (fd); /* TLS clean up */ #ifdef HTTPS_SUPPORT if (daemon->have_dhparams) { gnutls_dh_params_deinit (daemon->https_mem_dhparams); daemon->have_dhparams = false; } if (0 != (daemon->options & MHD_USE_TLS)) { gnutls_priority_deinit (daemon->priority_cache); if (daemon->x509_cred) gnutls_certificate_free_credentials (daemon->x509_cred); if (daemon->psk_cred) gnutls_psk_free_server_credentials (daemon->psk_cred); } #endif /* HTTPS_SUPPORT */ #ifdef DAUTH_SUPPORT free (daemon->digest_auth_random_copy); free (daemon->nnc); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_destroy_chk_ (&daemon->nnc_lock); #endif #endif #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); #endif free (daemon); } } /** * Obtain information about the given daemon. * The returned pointer is invalidated with the next call of this function or * when the daemon is stopped. * * @param daemon what daemon to get information about * @param info_type what information is desired? * @param ... depends on @a info_type * @return NULL if this information is not available * (or if the @a info_type is unknown) * @ingroup specialized */ _MHD_EXTERN const union MHD_DaemonInfo * MHD_get_daemon_info (struct MHD_Daemon *daemon, enum MHD_DaemonInfoType info_type, ...) { if (NULL == daemon) return NULL; mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ (NULL != daemon->worker_pool) || \ (MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); mhd_assert (((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) && (NULL == daemon->worker_pool)) || \ (! MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); switch (info_type) { case MHD_DAEMON_INFO_KEY_SIZE: return NULL; /* no longer supported */ case MHD_DAEMON_INFO_MAC_KEY_SIZE: return NULL; /* no longer supported */ case MHD_DAEMON_INFO_LISTEN_FD: daemon->daemon_info_dummy_listen_fd.listen_fd = daemon->listen_fd; return &daemon->daemon_info_dummy_listen_fd; case MHD_DAEMON_INFO_EPOLL_FD: #ifdef EPOLL_SUPPORT daemon->daemon_info_dummy_epoll_fd.epoll_fd = daemon->epoll_fd; return &daemon->daemon_info_dummy_epoll_fd; #else /* ! EPOLL_SUPPORT */ return NULL; #endif /* ! EPOLL_SUPPORT */ case MHD_DAEMON_INFO_CURRENT_CONNECTIONS: if (! MHD_D_IS_THREAD_SAFE_ (daemon)) MHD_cleanup_connections (daemon); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) else if (daemon->worker_pool) { unsigned int i; /* Collect the connection information stored in the workers. */ daemon->connections = 0; for (i = 0; i < daemon->worker_pool_size; i++) { /* FIXME: next line is thread-safe only if read is atomic. */ daemon->connections += daemon->worker_pool[i].connections; } } #endif daemon->daemon_info_dummy_num_connections.num_connections = daemon->connections; return &daemon->daemon_info_dummy_num_connections; case MHD_DAEMON_INFO_FLAGS: daemon->daemon_info_dummy_flags.flags = daemon->options; return &daemon->daemon_info_dummy_flags; case MHD_DAEMON_INFO_BIND_PORT: daemon->daemon_info_dummy_port.port = daemon->port; return &daemon->daemon_info_dummy_port; default: return NULL; } } /** * Obtain the version of this library * * @return static version string, e.g. "0.9.9" * @ingroup specialized */ _MHD_EXTERN const char * MHD_get_version (void) { #ifdef PACKAGE_VERSION return PACKAGE_VERSION; #else /* !PACKAGE_VERSION */ static char ver[12] = "\0\0\0\0\0\0\0\0\0\0\0"; if (0 == ver[0]) { int res = MHD_snprintf_ (ver, sizeof(ver), "%x.%x.%x", (int) (((uint32_t) MHD_VERSION >> 24) & 0xFF), (int) (((uint32_t) MHD_VERSION >> 16) & 0xFF), (int) (((uint32_t) MHD_VERSION >> 8) & 0xFF)); if ((0 >= res) || (sizeof(ver) <= res)) return "0.0.0"; /* Can't return real version */ } return ver; #endif /* !PACKAGE_VERSION */ } /** * Obtain the version of this library as a binary value. * * @return version binary value, e.g. "0x00090900" (#MHD_VERSION of * compiled MHD binary) * @note Available since #MHD_VERSION 0x00097601 * @ingroup specialized */ _MHD_EXTERN uint32_t MHD_get_version_bin (void) { return (uint32_t) MHD_VERSION; } /** * Get information about supported MHD features. * Indicate that MHD was compiled with or without support for * particular feature. Some features require additional support * by kernel. Kernel support is not checked by this function. * * @param feature type of requested information * @return #MHD_YES if feature is supported by MHD, #MHD_NO if * feature is not supported or feature is unknown. * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_is_feature_supported (enum MHD_FEATURE feature) { switch (feature) { case MHD_FEATURE_MESSAGES: #ifdef HAVE_MESSAGES return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_TLS: #ifdef HTTPS_SUPPORT return MHD_YES; #else /* ! HTTPS_SUPPORT */ return MHD_NO; #endif /* ! HTTPS_SUPPORT */ case MHD_FEATURE_HTTPS_CERT_CALLBACK: #if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_MAJOR >= 3 return MHD_YES; #else /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */ return MHD_NO; #endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */ case MHD_FEATURE_HTTPS_CERT_CALLBACK2: #if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030603 return MHD_YES; #else /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030603 */ return MHD_NO; #endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030603 */ case MHD_FEATURE_IPv6: #ifdef HAVE_INET6 return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_IPv6_ONLY: #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_POLL: #ifdef HAVE_POLL return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_EPOLL: #ifdef EPOLL_SUPPORT return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET: #ifdef HAVE_LISTEN_SHUTDOWN return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_SOCKETPAIR: #ifdef _MHD_ITC_SOCKETPAIR return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_TCP_FASTOPEN: #ifdef TCP_FASTOPEN return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_BASIC_AUTH: #ifdef BAUTH_SUPPORT return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH: #ifdef DAUTH_SUPPORT return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_POSTPROCESSOR: #ifdef HAVE_POSTPROCESSOR return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_HTTPS_KEY_PASSWORD: #if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030111 return MHD_YES; #else /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */ return MHD_NO; #endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */ case MHD_FEATURE_LARGE_FILE: #if defined(HAVE_PREAD64) || defined(_WIN32) return MHD_YES; #elif defined(HAVE_PREAD) return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES; #elif defined(HAVE_LSEEK64) return MHD_YES; #else return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES; #endif case MHD_FEATURE_THREAD_NAMES: #if defined(MHD_USE_THREAD_NAME_) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_UPGRADE: #if defined(UPGRADE_SUPPORT) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_RESPONSES_SHARED_FD: #if defined(HAVE_PREAD64) || defined(HAVE_PREAD) || defined(_WIN32) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_AUTODETECT_BIND_PORT: #ifdef MHD_USE_GETSOCKNAME return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_AUTOSUPPRESS_SIGPIPE: #if defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) || \ ! defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_SENDFILE: #ifdef _MHD_HAVE_SENDFILE return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_THREADS: #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_COOKIE_PARSING: #if defined(COOKIE_SUPPORT) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_RFC2069: #ifdef DAUTH_SUPPORT return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_MD5: #if defined(DAUTH_SUPPORT) && defined(MHD_MD5_SUPPORT) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_SHA256: #if defined(DAUTH_SUPPORT) && defined(MHD_SHA256_SUPPORT) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_SHA512_256: #if defined(DAUTH_SUPPORT) && defined(MHD_SHA512_256_SUPPORT) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_AUTH_INT: #ifdef DAUTH_SUPPORT return MHD_NO; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_ALGO_SESSION: #ifdef DAUTH_SUPPORT return MHD_NO; #else return MHD_NO; #endif case MHD_FEATURE_DIGEST_AUTH_USERHASH: #ifdef DAUTH_SUPPORT return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_EXTERN_HASH: #if defined(MHD_MD5_TLSLIB) || defined(MHD_SHA256_TLSLIB) return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_DEBUG_BUILD: #ifdef _DEBUG return MHD_YES; #else return MHD_NO; #endif case MHD_FEATURE_FLEXIBLE_FD_SETSIZE: #ifdef HAS_FD_SETSIZE_OVERRIDABLE return MHD_YES; #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ return MHD_NO; #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ default: break; } return MHD_NO; } #ifdef MHD_HTTPS_REQUIRE_GCRYPT #if defined(HTTPS_SUPPORT) && GCRYPT_VERSION_NUMBER < 0x010600 #if defined(MHD_USE_POSIX_THREADS) GCRY_THREAD_OPTION_PTHREAD_IMPL; #elif defined(MHD_W32_MUTEX_) static int gcry_w32_mutex_init (void **ppmtx) { *ppmtx = malloc (sizeof (MHD_mutex_)); if (NULL == *ppmtx) return ENOMEM; if (! MHD_mutex_init_ ((MHD_mutex_ *) *ppmtx)) { free (*ppmtx); *ppmtx = NULL; return EPERM; } return 0; } static int gcry_w32_mutex_destroy (void **ppmtx) { int res = (MHD_mutex_destroy_ ((MHD_mutex_ *) *ppmtx)) ? 0 : EINVAL; free (*ppmtx); return res; } static int gcry_w32_mutex_lock (void **ppmtx) { return MHD_mutex_lock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL; } static int gcry_w32_mutex_unlock (void **ppmtx) { return MHD_mutex_unlock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL; } static struct gcry_thread_cbs gcry_threads_w32 = { (GCRY_THREAD_OPTION_USER | (GCRY_THREAD_OPTION_VERSION << 8)), NULL, gcry_w32_mutex_init, gcry_w32_mutex_destroy, gcry_w32_mutex_lock, gcry_w32_mutex_unlock, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; #endif /* defined(MHD_W32_MUTEX_) */ #endif /* HTTPS_SUPPORT && GCRYPT_VERSION_NUMBER < 0x010600 */ #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ /** * Initialize do setup work. */ void MHD_init (void) { #if defined(MHD_WINSOCK_SOCKETS) WSADATA wsd; #endif /* MHD_WINSOCK_SOCKETS */ MHD_set_panic_func (NULL, NULL); #if defined(MHD_WINSOCK_SOCKETS) if (0 != WSAStartup (MAKEWORD (2, 2), &wsd)) MHD_PANIC (_ ("Failed to initialize winsock.\n")); if ((2 != LOBYTE (wsd.wVersion)) && (2 != HIBYTE (wsd.wVersion))) MHD_PANIC (_ ("Winsock version 2.2 is not available.\n")); #endif /* MHD_WINSOCK_SOCKETS */ #ifdef HTTPS_SUPPORT #ifdef MHD_HTTPS_REQUIRE_GCRYPT #if GCRYPT_VERSION_NUMBER < 0x010600 #if GNUTLS_VERSION_NUMBER <= 0x020b00 #if defined(MHD_USE_POSIX_THREADS) if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)) MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n")); #elif defined(MHD_W32_MUTEX_) if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_w32)) MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n")); #endif /* defined(MHD_W32_MUTEX_) */ #endif /* GNUTLS_VERSION_NUMBER <= 0x020b00 */ gcry_check_version (NULL); #else if (NULL == gcry_check_version ("1.6.0")) MHD_PANIC (_ ("libgcrypt is too old. MHD was compiled for " \ "libgcrypt 1.6.0 or newer.\n")); #endif #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ gnutls_global_init (); #endif /* HTTPS_SUPPORT */ MHD_monotonic_sec_counter_init (); MHD_send_init_static_vars_ (); MHD_init_mem_pools_ (); /* Check whether sizes were correctly detected by configure */ #ifdef _DEBUG if (1) { struct timeval tv; mhd_assert (sizeof(tv.tv_sec) == SIZEOF_STRUCT_TIMEVAL_TV_SEC); } #endif /* _DEBUG */ mhd_assert (sizeof(uint64_t) == SIZEOF_UINT64_T); } void MHD_fini (void) { #ifdef HTTPS_SUPPORT gnutls_global_deinit (); #endif /* HTTPS_SUPPORT */ #if defined(MHD_WINSOCK_SOCKETS) WSACleanup (); #endif /* MHD_WINSOCK_SOCKETS */ MHD_monotonic_sec_counter_finish (); } #ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED _SET_INIT_AND_DEINIT_FUNCS (MHD_init, MHD_fini); #endif /* _AUTOINIT_FUNCS_ARE_SUPPORTED */ /* end of daemon.c */ libmicrohttpd-1.0.10/src/microhttpd/mhd_itc_types.h0000644000175000017500000000455215035214301016066 /* This file is part of libmicrohttpd Copyright (C) 2016-2020 Karlson2k (Evgeny Grin), Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_itc_types.h * @brief Types for platform-independent inter-thread communication * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff * * Provides basic types for inter-thread communication. * Designed to be included by other headers. */ #ifndef MHD_ITC_TYPES_H #define MHD_ITC_TYPES_H 1 #include "mhd_options.h" /* Force socketpair on native W32 */ #if defined(_WIN32) && ! defined(__CYGWIN__) && ! defined(_MHD_ITC_SOCKETPAIR) #error _MHD_ITC_SOCKETPAIR is not defined on naitive W32 platform #endif /* _WIN32 && !__CYGWIN__ && !_MHD_ITC_SOCKETPAIR */ #if defined(_MHD_ITC_EVENTFD) /* **************** Optimized GNU/Linux ITC implementation by eventfd ********** */ /** * Data type for a MHD ITC. */ struct MHD_itc_ { int fd; }; /** * Static initialiser for struct MHD_itc_ */ #define MHD_ITC_STATIC_INIT_INVALID { -1 } #elif defined(_MHD_ITC_PIPE) /* **************** Standard UNIX ITC implementation by pipe ********** */ /** * Data type for a MHD ITC. */ struct MHD_itc_ { int fd[2]; }; /** * Static initialiser for struct MHD_itc_ */ #define MHD_ITC_STATIC_INIT_INVALID { { -1, -1 } } #elif defined(_MHD_ITC_SOCKETPAIR) /* **************** ITC implementation by socket pair ********** */ #include "mhd_sockets.h" /** * Data type for a MHD ITC. */ struct MHD_itc_ { MHD_socket sk[2]; }; /** * Static initialiser for struct MHD_itc_ */ #define MHD_ITC_STATIC_INIT_INVALID \ { { MHD_INVALID_SOCKET, MHD_INVALID_SOCKET } } #endif /* _MHD_ITC_SOCKETPAIR */ #endif /* ! MHD_ITC_TYPES_H */ libmicrohttpd-1.0.10/src/microhttpd/mhd_opt_matrix.h0000664000175000017500000003060115232103064016247 /* This file is part of GNU libmicrohttpd Copyright (C) 2026 Christian Grothoff GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/mhd_opt_matrix.h * @brief The environment-driven daemon option matrix shared by the tests * @author Christian Grothoff * * This header must be included *after* "platform.h" and . * * ## What this is * * Almost every test in this directory starts its daemon with one hard-coded * set of options, so the whole test suite only ever exercises a single point * of a large configuration space. This helper turns that space into a small * table of named *profiles* and lets the profile be selected from the * environment, so that an already built test binary can be re-run across the * whole matrix without recompiling anything (see contrib/run-option-matrix.sh). * * The dimensions of the matrix are: * * * #MHD_OPTION_CONNECTION_MEMORY_LIMIT in * {64, 128, 256, 512, 1024, 2048, 3072, 4096, library default}. 64 is the * smallest value MHD accepts (anything below is rounded up to 64, see * daemon.c). Everything up to 2048 keeps the read buffer below * #MHD_BUF_INC_SIZE (1500) resp. small enough to unlock the read-buffer * "shift back" path fixed by commit 29eaa56b, 3072 and 4096 do not, so both * sides of that boundary are in the sweep; * * #MHD_OPTION_CLIENT_DISCIPLINE_LVL in {-3 ... 3}; * * #MHD_OPTION_STRICT_FOR_CLIENT, the older two-valued form of the same * knob, so that its translation code is covered as well. Beware: that * option maps *every* value of -1 or below to client discipline level -3, * the most permissive one (daemon.c:7102-7106), so an application asking * for "slightly lenient" in fact selects the most lenient mode; * * the threading mode: external polling, internal polling thread, * thread-per-connection and thread pool; * * the polling backend: select(), poll() and epoll. Profiles asking for a * backend that this build does not provide are reported as unsupported by * mhd_opt_matrix_profile_supported(). * * #MHD_OPTION_SERVER_INSANITY is deliberately *not* a dimension: in this MHD * version `enum MHD_DisableSanityCheck` has exactly one member, * #MHD_DSC_SANE (zero), so the option cannot disable anything. * * ## Environment variables * * * #MHD_OPT_MATRIX_PROFILE_ENV ("MHD_TEST_PROFILE") - the profile to use, * given either by name ("mem-512") or by index ("4"). The special value * "list" is not handled here; contrib/run-option-matrix.sh knows the names. * * #MHD_OPT_MATRIX_MEM_ENV ("MHD_TEST_MEM_LIMIT") - override the connection * memory limit of the selected profile. "0" or "default" selects the * library default. * * #MHD_OPT_MATRIX_DISCP_ENV ("MHD_TEST_DISCIPLINE") - override the client * discipline level (-3 ... 3) and use #MHD_OPTION_CLIENT_DISCIPLINE_LVL. * * #MHD_OPT_MATRIX_STRICT_ENV ("MHD_TEST_STRICT_FOR_CLIENT") - override the * same knob but use the deprecated #MHD_OPTION_STRICT_FOR_CLIENT instead. * * #MHD_OPT_MATRIX_THREADING_ENV ("MHD_TEST_THREADING") - one of * "external", "internal", "per-connection", "pool". * * #MHD_OPT_MATRIX_POLL_ENV ("MHD_TEST_POLL") - one of "select", "poll", * "epoll". * * If *none* of these variables is set, mhd_opt_matrix_from_env() * returns NULL and every test keeps its previous, hard-coded behaviour. This * is what a stock "make check" does, so nothing regresses. */ #ifndef MHD_OPT_MATRIX_H #define MHD_OPT_MATRIX_H 1 #include #include /** * The name of the environment variable selecting the profile. */ #define MHD_OPT_MATRIX_PROFILE_ENV "MHD_TEST_PROFILE" /** * The name of the environment variable overriding the memory limit. */ #define MHD_OPT_MATRIX_MEM_ENV "MHD_TEST_MEM_LIMIT" /** * The name of the environment variable overriding the discipline level. */ #define MHD_OPT_MATRIX_DISCP_ENV "MHD_TEST_DISCIPLINE" /** * The name of the environment variable overriding the discipline level via * the deprecated #MHD_OPTION_STRICT_FOR_CLIENT option. */ #define MHD_OPT_MATRIX_STRICT_ENV "MHD_TEST_STRICT_FOR_CLIENT" /** * The name of the environment variable overriding the threading mode. */ #define MHD_OPT_MATRIX_THREADING_ENV "MHD_TEST_THREADING" /** * The name of the environment variable overriding the polling backend. */ #define MHD_OPT_MATRIX_POLL_ENV "MHD_TEST_POLL" /** * The threading mode of a profile. */ enum MHD_OptMatrixThreading { /** * External polling: the application drives the daemon with MHD_run(). */ MHD_OPT_MATRIX_THR_EXTERNAL = 0, /** * One internal polling thread for all connections. */ MHD_OPT_MATRIX_THR_INTERNAL = 1, /** * One internal thread per connection. */ MHD_OPT_MATRIX_THR_PER_CONNECTION = 2, /** * A pool of internal polling threads. */ MHD_OPT_MATRIX_THR_POOL = 3 }; /** * The polling backend of a profile. */ enum MHD_OptMatrixPoll { /** * Use select(). */ MHD_OPT_MATRIX_POLL_SELECT = 0, /** * Use poll(), needs #MHD_FEATURE_POLL. */ MHD_OPT_MATRIX_POLL_POLL = 1, /** * Use epoll, needs #MHD_FEATURE_EPOLL. */ MHD_OPT_MATRIX_POLL_EPOLL = 2 }; /** * One point of the daemon option matrix. * * A caller may copy the structure and modify the copy, e.g. with * mhd_opt_matrix_raise_mem_limit(); the tables returned by * mhd_opt_matrix_profile() must not be modified. */ struct MHD_OptMatrixProfile { /** * Human readable name of the profile, used for logging and for * #MHD_OPT_MATRIX_PROFILE_ENV. */ const char *name; /** * The value for #MHD_OPTION_CONNECTION_MEMORY_LIMIT. * Zero means "keep the MHD default". */ size_t mem_limit; /** * The value for #MHD_OPTION_CLIENT_DISCIPLINE_LVL or, when * @a use_legacy_strict is set, for #MHD_OPTION_STRICT_FOR_CLIENT. * Zero means "keep the MHD default" and adds no option at all. */ int discipline_lvl; /** * If non-zero, the deprecated #MHD_OPTION_STRICT_FOR_CLIENT option is used * instead of #MHD_OPTION_CLIENT_DISCIPLINE_LVL, so that the legacy option * translation code is exercised as well. */ int use_legacy_strict; /** * The threading mode. */ enum MHD_OptMatrixThreading threading; /** * The polling backend. */ enum MHD_OptMatrixPoll poll_backend; /** * The number of worker threads, only used with * #MHD_OPT_MATRIX_THR_POOL. */ unsigned int thread_pool_size; }; /** * The number of built-in profiles. */ unsigned int mhd_opt_matrix_num_profiles (void); /** * Get the built-in profile number @a idx. * * Profile zero is the "default" profile: the library defaults for every * dimension plus one internal polling thread, i.e. the configuration the * tests of this directory used before the matrix was introduced. * * @param idx the index of the profile, wraps around * @return the profile, never NULL */ const struct MHD_OptMatrixProfile * mhd_opt_matrix_profile (unsigned int idx); /** * Look up a profile by name or by decimal index. * * @param name_or_idx the name ("mem-512") or the index ("4") * @return the profile, or NULL if @a name_or_idx matches nothing */ const struct MHD_OptMatrixProfile * mhd_opt_matrix_lookup (const char *name_or_idx); /** * Get the profile selected by the environment. * * @return NULL if the environment selects nothing, in which case the caller * must keep its own, previous configuration; otherwise a pointer to * a static profile that stays valid until the next call */ const struct MHD_OptMatrixProfile * mhd_opt_matrix_from_env (void); /** * Get the client discipline level that MHD will *really* use for @a prof. * * This is not always @a prof->discipline_lvl: #MHD_OPTION_STRICT_FOR_CLIENT * only has two settings, and daemon.c:7102-7106 maps every value of -1 or * below to level -3 (the most permissive one) and every value of 1 or above * to level 1. A caller that decides what a request must do therefore has to * ask for the effective level, not for the configured one - a test that * believes it asked for "slightly lenient" in fact runs at -3. * * @param prof the profile to inspect, may be NULL (0 is returned then) * @return the client discipline level in effect */ int mhd_opt_matrix_effective_discipline (const struct MHD_OptMatrixProfile *prof); /** * Check whether @a prof can be used by this build at run time. * * @param prof the profile to check * @return non-zero if the profile is usable, zero if the required threading * support or polling backend is missing */ int mhd_opt_matrix_profile_supported (const struct MHD_OptMatrixProfile *prof); /** * Render a one-line, human readable description of @a prof. * * @param prof the profile to describe * @param[out] buf the buffer to write to * @param buf_size the size of @a buf * @return @a buf */ const char * mhd_opt_matrix_describe (const struct MHD_OptMatrixProfile *prof, char *buf, size_t buf_size); /** * Fill @a ops with the options of @a prof. * * The array is terminated with an #MHD_OPTION_END element, so it can be * passed to MHD_start_daemon() as * * MHD_start_daemon (flags, port, NULL, NULL, ahc, cls, * MHD_OPTION_ARRAY, ops, * ... other options ..., * MHD_OPTION_END); * * which works for a varargs call just as well as for a call that already * uses #MHD_OPTION_ARRAY. * * @param prof the profile to apply, may be NULL (only #MHD_OPTION_END is * stored then) * @param[out] ops the array to fill * @param max_ops the number of elements of @a ops, at least 4 * @return the number of elements used, including the terminating * #MHD_OPTION_END; zero if @a ops is too small */ unsigned int mhd_opt_matrix_fill_options (const struct MHD_OptMatrixProfile *prof, struct MHD_OptionItem *ops, unsigned int max_ops); /** * Combine the daemon flags required by @a prof with @a base_flags. * * @param prof the profile to apply, may be NULL (@a base_flags is returned) * @param base_flags the flags the caller wants in any case, e.g. * #MHD_USE_ERROR_LOG * @param allow_external if zero, a profile that asks for external polling is * served with an internal polling thread instead; use * this in tests whose client cannot call MHD_run() * @return the flags for MHD_start_daemon() */ unsigned int mhd_opt_matrix_daemon_flags (const struct MHD_OptMatrixProfile *prof, unsigned int base_flags, int allow_external); /** * Check whether @a prof needs the application to drive MHD_run(). * * @param prof the profile to check, may be NULL * @return non-zero if the daemon has no internal thread */ int mhd_opt_matrix_is_external (const struct MHD_OptMatrixProfile *prof); /** * Raise the connection memory limit of @a prof to at least @a min_limit. * * Tests that cannot work with a tiny connection pool (because the requests * they must send do not fit into it) use this to keep the other dimensions of * the matrix while staying functional. The change must be reported in the * test output so that the log stays truthful. * * @param[in,out] prof the profile to adjust, must be a caller-owned copy * @param min_limit the smallest acceptable limit, zero does nothing * @return non-zero if the limit was actually raised */ int mhd_opt_matrix_raise_mem_limit (struct MHD_OptMatrixProfile *prof, size_t min_limit); /** * Print the one-line notice naming the profile in use and, if a profile is * selected, the profile. * * @param test_name the name of the calling test, used as the line prefix */ void mhd_opt_matrix_print_notice (const char *test_name); #endif /* MHD_OPT_MATRIX_H */ libmicrohttpd-1.0.10/src/microhttpd/test_start_stop.c0000664000175000017500000001144215232103064016467 /* This file is part of libmicrohttpd Copyright (C) 2011 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_start_stop.c * @brief test for #1901 (start+stop) * @author Christian Grothoff */ #include "mhd_options.h" #include "platform.h" #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif static enum MHD_Result ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; (void) connection; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ return MHD_NO; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) static unsigned int testInternalGet (unsigned int poll_flag) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | poll_flag, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 1; MHD_stop_daemon (d); return 0; } static unsigned int testMultithreadedGet (unsigned int poll_flag) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | poll_flag, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (d == NULL) return 2; MHD_stop_daemon (d); return 0; } static unsigned int testMultithreadedPoolGet (unsigned int poll_flag) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG | poll_flag, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_THREAD_POOL_SIZE, MHD_CPU_COUNT, MHD_OPTION_END); if (d == NULL) return 4; MHD_stop_daemon (d); return 0; } static unsigned int testExternalGet (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_ERROR_LOG, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 8; MHD_stop_daemon (d); return 0; } #endif static unsigned int testExternalGetSingleThread (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_NO_THREAD_SAFETY, 0, NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); if (NULL == d) return 8; MHD_stop_daemon (d); return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silence compiler warning. */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) errorCount += testInternalGet (0); errorCount += testMultithreadedGet (0); errorCount += testMultithreadedPoolGet (0); errorCount += testExternalGet (); #endif errorCount += testExternalGetSingleThread (); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { errorCount += testInternalGet (MHD_USE_POLL); errorCount += testMultithreadedGet (MHD_USE_POLL); errorCount += testMultithreadedPoolGet (MHD_USE_POLL); } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { errorCount += testInternalGet (MHD_USE_EPOLL); errorCount += testMultithreadedPoolGet (MHD_USE_EPOLL); } #endif if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/microhttpd/sha256.c0000664000175000017500000006026215223423441014246 /* This file is part of libmicrohttpd Copyright (C) 2019-2023 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha256.c * @brief Calculation of SHA-256 digest as defined in FIPS PUB 180-4 (2015) * @author Karlson2k (Evgeny Grin) */ #include "sha256.h" #include #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #include "mhd_bithelpers.h" #include "mhd_assert.h" /** * Initialise structure for SHA256 calculation. * * @param ctx must be a `struct Sha256Ctx *` */ void MHD_SHA256_init (struct Sha256Ctx *ctx) { /* Initial hash values, see FIPS PUB 180-4 paragraph 5.3.3 */ /* First thirty-two bits of the fractional parts of the square * roots of the first eight prime numbers: 2, 3, 5, 7, 11, 13, * 17, 19." */ ctx->H[0] = UINT32_C (0x6a09e667); ctx->H[1] = UINT32_C (0xbb67ae85); ctx->H[2] = UINT32_C (0x3c6ef372); ctx->H[3] = UINT32_C (0xa54ff53a); ctx->H[4] = UINT32_C (0x510e527f); ctx->H[5] = UINT32_C (0x9b05688c); ctx->H[6] = UINT32_C (0x1f83d9ab); ctx->H[7] = UINT32_C (0x5be0cd19); /* Initialise number of bytes. */ ctx->count = 0; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /** * Base of SHA-256 transformation. * Gets full 64 bytes block of data and updates hash values; * @param H hash values * @param data data, must be exactly 64 bytes long */ static void sha256_transform (uint32_t H[SHA256_DIGEST_SIZE_WORDS], const void *data) { /* Working variables, see FIPS PUB 180-4 paragraph 6.2. */ uint32_t a = H[0]; uint32_t b = H[1]; uint32_t c = H[2]; uint32_t d = H[3]; uint32_t e = H[4]; uint32_t f = H[5]; uint32_t g = H[6]; uint32_t h = H[7]; /* Data buffer, used as cyclic buffer. See FIPS PUB 180-4 paragraphs 5.2.1, 6.2. */ uint32_t W[16]; #ifndef _MHD_GET_32BIT_BE_UNALIGNED if (0 != (((uintptr_t) data) % _MHD_UINT32_ALIGN)) { /* Copy the unaligned input data to the aligned buffer */ memcpy (W, data, SHA256_BLOCK_SIZE); /* The W[] buffer itself will be used as the source of the data, * but data will be reloaded in correct bytes order during * the next steps */ data = (const void *) W; } #endif /* _MHD_GET_32BIT_BE_UNALIGNED */ /* 'Ch' and 'Maj' macro functions are defined with widely-used optimization. See FIPS PUB 180-4 formulae 4.2, 4.3. */ #define Ch(x,y,z) ( (z) ^ ((x) & ((y) ^ (z))) ) #define Maj(x,y,z) ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) ) /* Unoptimized (original) versions: */ /* #define Ch(x,y,z) ( ( (x) & (y) ) ^ ( ~(x) & (z) ) ) */ /* #define Maj(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */ /* Four 'Sigma' macro functions. See FIPS PUB 180-4 formulae 4.4, 4.5, 4.6, 4.7. */ #define SIG0(x) (_MHD_ROTR32 ((x), 2) ^ _MHD_ROTR32 ((x), 13) ^ \ _MHD_ROTR32 ((x), 22) ) #define SIG1(x) (_MHD_ROTR32 ((x), 6) ^ _MHD_ROTR32 ((x), 11) ^ \ _MHD_ROTR32 ((x), 25) ) #define sig0(x) (_MHD_ROTR32 ((x), 7) ^ _MHD_ROTR32 ((x), 18) ^ \ ((x) >> 3) ) #define sig1(x) (_MHD_ROTR32 ((x), 17) ^ _MHD_ROTR32 ((x),19) ^ \ ((x) >> 10) ) /* One step of SHA-256 computation, see FIPS PUB 180-4 paragraph 6.2.2 step 3. * Note: this macro updates working variables in-place, without rotation. * Note: first (vH += SIG1(vE) + Ch(vE,vF,vG) + kt + wt) equals T1 in FIPS PUB 180-4 paragraph 6.2.2 step 3. second (vH += SIG0(vA) + Maj(vE,vF,vC) equals T1 + T2 in FIPS PUB 180-4 paragraph 6.2.2 step 3. * Note: 'wt' must be used exactly one time in this macro as it change other data as well every time when used. */ #define SHA2STEP32(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do { \ (vD) += ((vH) += SIG1 ((vE)) + Ch ((vE),(vF),(vG)) + (kt) + (wt)); \ (vH) += SIG0 ((vA)) + Maj ((vA),(vB),(vC)); } while (0) /* Get value of W(t) from input data buffer, See FIPS PUB 180-4 paragraph 6.2. Input data must be read in big-endian bytes order, see FIPS PUB 180-4 paragraph 3.1.2. */ /* Use cast to (const void*) to mute compiler alignment warning, * data was already aligned in previous step */ #define GET_W_FROM_DATA(buf,t) \ _MHD_GET_32BIT_BE ((const void*)(((const uint8_t*) (buf)) + \ (t) * SHA256_BYTES_IN_WORD)) /* 'W' generation and assignment for 16 <= t <= 63. See FIPS PUB 180-4 paragraph 6.2.2. As only last 16 'W' are used in calculations, it is possible to use 16 elements array of W as cyclic buffer. * Note: ((t-16)&0xf) have same value as (t&0xf) */ #define Wgen(w,t) ( (w)[(t - 16) & 0xf] + sig1 ((w)[((t) - 2) & 0xf]) \ + (w)[((t) - 7) & 0xf] + sig0 ((w)[((t) - 15) & 0xf]) ) #ifndef MHD_FAVOR_SMALL_CODE /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 paragraph 4.2.2 for K values. */ /* Note: instead of reassigning all working variables on each step, variables are rotated for each step: SHA2STEP32(a, b, c, d, e, f, g, h, K[0], data[0]); SHA2STEP32(h, a, b, c, d, e, f, g, K[1], data[1]); so current 'vD' will be used as 'vE' on next step, current 'vH' will be used as 'vA' on next step. */ #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN if ((const void *) W == data) { /* The input data is already in the cyclic data buffer W[] in correct bytes order. */ SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x428a2f98), W[0]); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x71374491), W[1]); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xb5c0fbcf), W[2]); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xe9b5dba5), W[3]); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x3956c25b), W[4]); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x59f111f1), W[5]); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x923f82a4), W[6]); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xab1c5ed5), W[7]); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xd807aa98), W[8]); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x12835b01), W[9]); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x243185be), W[10]); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x550c7dc3), W[11]); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x72be5d74), W[12]); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x80deb1fe), W[13]); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x9bdc06a7), W[14]); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xc19bf174), W[15]); } else /* Combined with the next 'if' */ #endif /* _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */ if (1) { /* During first 16 steps, before making any calculations on each step, the W element is read from input data buffer as big-endian value and stored in array of W elements. */ SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x428a2f98), W[0] = \ GET_W_FROM_DATA (data, 0)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x71374491), W[1] = \ GET_W_FROM_DATA (data, 1)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xb5c0fbcf), W[2] = \ GET_W_FROM_DATA (data, 2)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xe9b5dba5), W[3] = \ GET_W_FROM_DATA (data, 3)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x3956c25b), W[4] = \ GET_W_FROM_DATA (data, 4)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x59f111f1), W[5] = \ GET_W_FROM_DATA (data, 5)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x923f82a4), W[6] = \ GET_W_FROM_DATA (data, 6)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xab1c5ed5), W[7] = \ GET_W_FROM_DATA (data, 7)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xd807aa98), W[8] = \ GET_W_FROM_DATA (data, 8)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x12835b01), W[9] = \ GET_W_FROM_DATA (data, 9)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x243185be), W[10] = \ GET_W_FROM_DATA (data, 10)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x550c7dc3), W[11] = \ GET_W_FROM_DATA (data, 11)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x72be5d74), W[12] = \ GET_W_FROM_DATA (data, 12)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x80deb1fe), W[13] = \ GET_W_FROM_DATA (data, 13)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x9bdc06a7), W[14] = \ GET_W_FROM_DATA (data, 14)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xc19bf174), W[15] = \ GET_W_FROM_DATA (data, 15)); } /* During last 48 steps, before making any calculations on each step, current W element is generated from other W elements of the cyclic buffer and the generated value is stored back in the cyclic buffer. */ /* Note: instead of using K constants as array, all K values are specified individually for each step, see FIPS PUB 180-4 paragraph 4.2.2 for K values. */ SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xe49b69c1), W[16 & 0xf] = \ Wgen (W,16)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0xefbe4786), W[17 & 0xf] = \ Wgen (W,17)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x0fc19dc6), W[18 & 0xf] = \ Wgen (W,18)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x240ca1cc), W[19 & 0xf] = \ Wgen (W,19)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x2de92c6f), W[20 & 0xf] = \ Wgen (W,20)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x4a7484aa), W[21 & 0xf] = \ Wgen (W,21)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x5cb0a9dc), W[22 & 0xf] = \ Wgen (W,22)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x76f988da), W[23 & 0xf] = \ Wgen (W,23)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x983e5152), W[24 & 0xf] = \ Wgen (W,24)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0xa831c66d), W[25 & 0xf] = \ Wgen (W,25)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xb00327c8), W[26 & 0xf] = \ Wgen (W,26)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xbf597fc7), W[27 & 0xf] = \ Wgen (W,27)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0xc6e00bf3), W[28 & 0xf] = \ Wgen (W,28)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0xd5a79147), W[29 & 0xf] = \ Wgen (W,29)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x06ca6351), W[30 & 0xf] = \ Wgen (W,30)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x14292967), W[31 & 0xf] = \ Wgen (W,31)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x27b70a85), W[32 & 0xf] = \ Wgen (W,32)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x2e1b2138), W[33 & 0xf] = \ Wgen (W,33)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x4d2c6dfc), W[34 & 0xf] = \ Wgen (W,34)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x53380d13), W[35 & 0xf] = \ Wgen (W,35)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x650a7354), W[36 & 0xf] = \ Wgen (W,36)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x766a0abb), W[37 & 0xf] = \ Wgen (W,37)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x81c2c92e), W[38 & 0xf] = \ Wgen (W,38)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x92722c85), W[39 & 0xf] = \ Wgen (W,39)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0xa2bfe8a1), W[40 & 0xf] = \ Wgen (W,40)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0xa81a664b), W[41 & 0xf] = \ Wgen (W,41)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0xc24b8b70), W[42 & 0xf] = \ Wgen (W,42)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0xc76c51a3), W[43 & 0xf] = \ Wgen (W,43)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0xd192e819), W[44 & 0xf] = \ Wgen (W,44)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0xd6990624), W[45 & 0xf] = \ Wgen (W,45)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0xf40e3585), W[46 & 0xf] = \ Wgen (W,46)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x106aa070), W[47 & 0xf] = \ Wgen (W,47)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x19a4c116), W[48 & 0xf] = \ Wgen (W,48)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x1e376c08), W[49 & 0xf] = \ Wgen (W,49)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x2748774c), W[50 & 0xf] = \ Wgen (W,50)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x34b0bcb5), W[51 & 0xf] = \ Wgen (W,51)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x391c0cb3), W[52 & 0xf] = \ Wgen (W,52)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0x4ed8aa4a), W[53 & 0xf] = \ Wgen (W,53)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0x5b9cca4f), W[54 & 0xf] = \ Wgen (W,54)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0x682e6ff3), W[55 & 0xf] = \ Wgen (W,55)); SHA2STEP32 (a, b, c, d, e, f, g, h, UINT32_C (0x748f82ee), W[56 & 0xf] = \ Wgen (W,56)); SHA2STEP32 (h, a, b, c, d, e, f, g, UINT32_C (0x78a5636f), W[57 & 0xf] = \ Wgen (W,57)); SHA2STEP32 (g, h, a, b, c, d, e, f, UINT32_C (0x84c87814), W[58 & 0xf] = \ Wgen (W,58)); SHA2STEP32 (f, g, h, a, b, c, d, e, UINT32_C (0x8cc70208), W[59 & 0xf] = \ Wgen (W,59)); SHA2STEP32 (e, f, g, h, a, b, c, d, UINT32_C (0x90befffa), W[60 & 0xf] = \ Wgen (W,60)); SHA2STEP32 (d, e, f, g, h, a, b, c, UINT32_C (0xa4506ceb), W[61 & 0xf] = \ Wgen (W,61)); SHA2STEP32 (c, d, e, f, g, h, a, b, UINT32_C (0xbef9a3f7), W[62 & 0xf] = \ Wgen (W,62)); SHA2STEP32 (b, c, d, e, f, g, h, a, UINT32_C (0xc67178f2), W[63 & 0xf] = \ Wgen (W,63)); #else /* ! MHD_FAVOR_SMALL_CODE */ if (1) { unsigned int t; /* K constants array. See FIPS PUB 180-4 paragraph 4.2.2 for K values. */ static const uint32_t K[64] = { UINT32_C (0x428a2f98), UINT32_C (0x71374491), UINT32_C (0xb5c0fbcf), UINT32_C (0xe9b5dba5), UINT32_C (0x3956c25b), UINT32_C (0x59f111f1), UINT32_C (0x923f82a4), UINT32_C (0xab1c5ed5), UINT32_C (0xd807aa98), UINT32_C (0x12835b01), UINT32_C (0x243185be), UINT32_C (0x550c7dc3), UINT32_C (0x72be5d74), UINT32_C (0x80deb1fe), UINT32_C (0x9bdc06a7), UINT32_C (0xc19bf174), UINT32_C (0xe49b69c1), UINT32_C (0xefbe4786), UINT32_C (0x0fc19dc6), UINT32_C (0x240ca1cc), UINT32_C (0x2de92c6f), UINT32_C (0x4a7484aa), UINT32_C (0x5cb0a9dc), UINT32_C (0x76f988da), UINT32_C (0x983e5152), UINT32_C (0xa831c66d), UINT32_C (0xb00327c8), UINT32_C (0xbf597fc7), UINT32_C (0xc6e00bf3), UINT32_C (0xd5a79147), UINT32_C (0x06ca6351), UINT32_C (0x14292967), UINT32_C (0x27b70a85), UINT32_C (0x2e1b2138), UINT32_C (0x4d2c6dfc), UINT32_C (0x53380d13), UINT32_C (0x650a7354), UINT32_C (0x766a0abb), UINT32_C (0x81c2c92e), UINT32_C (0x92722c85), UINT32_C (0xa2bfe8a1), UINT32_C (0xa81a664b), UINT32_C (0xc24b8b70), UINT32_C (0xc76c51a3), UINT32_C (0xd192e819), UINT32_C (0xd6990624), UINT32_C (0xf40e3585), UINT32_C (0x106aa070), UINT32_C (0x19a4c116), UINT32_C (0x1e376c08), UINT32_C (0x2748774c), UINT32_C (0x34b0bcb5), UINT32_C (0x391c0cb3), UINT32_C (0x4ed8aa4a), UINT32_C (0x5b9cca4f), UINT32_C (0x682e6ff3), UINT32_C (0x748f82ee), UINT32_C (0x78a5636f), UINT32_C (0x84c87814), UINT32_C (0x8cc70208), UINT32_C (0x90befffa), UINT32_C (0xa4506ceb), UINT32_C (0xbef9a3f7), UINT32_C (0xc67178f2) }; /* One step of SHA-256 computation with working variables rotation, see FIPS PUB 180-4 paragraph 6.2.2 step 3. * Note: this version of macro reassign all working variable on each step. */ #define SHA2STEP32RV(vA,vB,vC,vD,vE,vF,vG,vH,kt,wt) do { \ uint32_t tmp_h_ = (vH); \ SHA2STEP32((vA),(vB),(vC),(vD),(vE),(vF),(vG),tmp_h_,(kt),(wt)); \ (vH) = (vG); \ (vG) = (vF); \ (vF) = (vE); \ (vE) = (vD); \ (vD) = (vC); \ (vC) = (vB); \ (vB) = (vA); \ (vA) = tmp_h_; } while (0) /* During first 16 steps, before making any calculations on each step, the W element is read from input data buffer as big-endian value and stored in array of W elements. */ for (t = 0; t < 16; ++t) { SHA2STEP32RV (a, b, c, d, e, f, g, h, K[t], \ W[t] = GET_W_FROM_DATA (data, t)); } /* During last 48 steps, before making any calculations on each step, current W element is generated from other W elements of the cyclic buffer and the generated value is stored back in the cyclic buffer. */ for (t = 16; t < 64; ++t) { SHA2STEP32RV (a, b, c, d, e, f, g, h, K[t], W[t & 15] = Wgen (W,t)); } } #endif /* ! MHD_FAVOR_SMALL_CODE */ /* Compute intermediate hash. See FIPS PUB 180-4 paragraph 6.2.2 step 4. */ H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h; } /** * Process portion of bytes. * * @param ctx_ must be a `struct Sha256Ctx *` * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA256_update (struct Sha256Ctx *ctx, const uint8_t *data, size_t length) { unsigned bytes_have; /**< Number of bytes in buffer */ mhd_assert ((data != NULL) || (length == 0)); #ifndef MHD_FAVOR_SMALL_CODE if (0 == length) return; /* Shortcut, do nothing */ #endif /* MHD_FAVOR_SMALL_CODE */ /* Note: (count & (SHA256_BLOCK_SIZE-1)) equals (count % SHA256_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned) (ctx->count & (SHA256_BLOCK_SIZE - 1)); ctx->count += length; if (0 != bytes_have) { unsigned bytes_left = SHA256_BLOCK_SIZE - bytes_have; if (length >= bytes_left) { /* Combine new data with data in the buffer and process full block. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, bytes_left); data += bytes_left; length -= bytes_left; sha256_transform (ctx->H, ctx->buffer); bytes_have = 0; } } while (SHA256_BLOCK_SIZE <= length) { /* Process any full blocks of new data directly, without copying to the buffer. */ sha256_transform (ctx->H, data); data += SHA256_BLOCK_SIZE; length -= SHA256_BLOCK_SIZE; } if (0 != length) { /* Copy incomplete block of new data (if any) to the buffer. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, length); } } /** * Size of "length" padding addition in bytes. * See FIPS PUB 180-4 paragraph 5.1.1. */ #define SHA256_SIZE_OF_LEN_ADD (64 / 8) /** * Finalise SHA256 calculation, return digest. * * @param ctx must be a `struct Sha256Ctx *` * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes */ void MHD_SHA256_finish (struct Sha256Ctx *ctx, uint8_t digest[SHA256_DIGEST_SIZE]) { uint64_t num_bits; /**< Number of processed bits */ unsigned bytes_have; /**< Number of bytes in buffer */ num_bits = ctx->count << 3; /* Note: (count & (SHA256_BLOCK_SIZE-1)) equal (count % SHA256_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned) (ctx->count & (SHA256_BLOCK_SIZE - 1)); /* Input data must be padded with a single bit "1", then with zeros and the finally the length of data in bits must be added as the final bytes of the last block. See FIPS PUB 180-4 paragraph 5.1.1. */ /* Data is always processed in form of bytes (not by individual bits), therefore position of first padding bit in byte is always predefined (0x80). */ /* Buffer always have space at least for one byte (as full buffers are processed immediately). */ ((uint8_t *) ctx->buffer)[bytes_have++] = 0x80; if (SHA256_BLOCK_SIZE - bytes_have < SHA256_SIZE_OF_LEN_ADD) { /* No space in current block to put total length of message. Pad current block with zeros and process it. */ if (bytes_have < SHA256_BLOCK_SIZE) memset (((uint8_t *) ctx->buffer) + bytes_have, 0, SHA256_BLOCK_SIZE - bytes_have); /* Process full block. */ sha256_transform (ctx->H, ctx->buffer); /* Start new block. */ bytes_have = 0; } /* Pad the rest of the buffer with zeros. */ memset (((uint8_t *) ctx->buffer) + bytes_have, 0, SHA256_BLOCK_SIZE - SHA256_SIZE_OF_LEN_ADD - bytes_have); /* Put the number of bits in processed message as big-endian value. */ _MHD_PUT_64BIT_BE_SAFE (ctx->buffer + SHA256_BLOCK_SIZE_WORDS - 2, num_bits); /* Process full final block. */ sha256_transform (ctx->H, ctx->buffer); /* Put final hash/digest in BE mode */ #ifndef _MHD_PUT_32BIT_BE_UNALIGNED if (1 #ifndef MHD_FAVOR_SMALL_CODE && (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN) #endif /* MHD_FAVOR_SMALL_CODE */ ) { /* If storing of the final result requires aligned address and the destination address is not aligned or compact code is used, store the final digest in aligned temporary buffer first, then copy it to the destination. */ uint32_t alig_dgst[SHA256_DIGEST_SIZE_WORDS]; _MHD_PUT_32BIT_BE (alig_dgst + 0, ctx->H[0]); _MHD_PUT_32BIT_BE (alig_dgst + 1, ctx->H[1]); _MHD_PUT_32BIT_BE (alig_dgst + 2, ctx->H[2]); _MHD_PUT_32BIT_BE (alig_dgst + 3, ctx->H[3]); _MHD_PUT_32BIT_BE (alig_dgst + 4, ctx->H[4]); _MHD_PUT_32BIT_BE (alig_dgst + 5, ctx->H[5]); _MHD_PUT_32BIT_BE (alig_dgst + 6, ctx->H[6]); _MHD_PUT_32BIT_BE (alig_dgst + 7, ctx->H[7]); /* Copy result to unaligned destination address */ memcpy (digest, alig_dgst, SHA256_DIGEST_SIZE); } #ifndef MHD_FAVOR_SMALL_CODE else /* Combined with the next 'if' */ #endif /* MHD_FAVOR_SMALL_CODE */ #endif /* ! _MHD_PUT_32BIT_BE_UNALIGNED */ #if ! defined(MHD_FAVOR_SMALL_CODE) || defined(_MHD_PUT_32BIT_BE_UNALIGNED) if (1) { /* Use cast to (void*) here to mute compiler alignment warnings. * Compilers are not smart enough to see that alignment has been checked. */ _MHD_PUT_32BIT_BE ((void *) (digest + 0 * SHA256_BYTES_IN_WORD), ctx->H[0]); _MHD_PUT_32BIT_BE ((void *) (digest + 1 * SHA256_BYTES_IN_WORD), ctx->H[1]); _MHD_PUT_32BIT_BE ((void *) (digest + 2 * SHA256_BYTES_IN_WORD), ctx->H[2]); _MHD_PUT_32BIT_BE ((void *) (digest + 3 * SHA256_BYTES_IN_WORD), ctx->H[3]); _MHD_PUT_32BIT_BE ((void *) (digest + 4 * SHA256_BYTES_IN_WORD), ctx->H[4]); _MHD_PUT_32BIT_BE ((void *) (digest + 5 * SHA256_BYTES_IN_WORD), ctx->H[5]); _MHD_PUT_32BIT_BE ((void *) (digest + 6 * SHA256_BYTES_IN_WORD), ctx->H[6]); _MHD_PUT_32BIT_BE ((void *) (digest + 7 * SHA256_BYTES_IN_WORD), ctx->H[7]); } #endif /* ! MHD_FAVOR_SMALL_CODE || _MHD_PUT_32BIT_BE_UNALIGNED */ /* Erase potentially sensitive data. */ memset (ctx, 0, sizeof(struct Sha256Ctx)); } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ libmicrohttpd-1.0.10/src/microhttpd/sha512_256.h0000664000175000017500000000711115223423441014634 /* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha512_256.h * @brief Calculation of SHA-512/256 digest * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA512_256_H #define MHD_SHA512_256_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * Number of bits in single SHA-512/256 word. */ #define SHA512_256_WORD_SIZE_BITS 64 /** * Number of bytes in single SHA-512/256 word. */ #define SHA512_256_BYTES_IN_WORD (SHA512_256_WORD_SIZE_BITS / 8) /** * Hash is kept internally as 8 64-bit words. * This is intermediate hash size, used during computing the final digest. */ #define SHA512_256_HASH_SIZE_WORDS 8 /** * Size of SHA-512/256 resulting digest in words. * This is the final digest size, not intermediate hash. */ #define SHA512_256_DIGEST_SIZE_WORDS (SHA512_256_HASH_SIZE_WORDS / 2) /** * Size of SHA-512/256 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define SHA512_256_DIGEST_SIZE \ (SHA512_256_DIGEST_SIZE_WORDS * SHA512_256_BYTES_IN_WORD) /** * Size of SHA-512/256 digest string in chars including termination NUL. */ #define SHA512_256_DIGEST_STRING_SIZE ((SHA512_256_DIGEST_SIZE) * 2 + 1) /** * Size of SHA-512/256 single processing block in bits. */ #define SHA512_256_BLOCK_SIZE_BITS 1024 /** * Size of SHA-512/256 single processing block in bytes. */ #define SHA512_256_BLOCK_SIZE (SHA512_256_BLOCK_SIZE_BITS / 8) /** * Size of SHA-512/256 single processing block in words. */ #define SHA512_256_BLOCK_SIZE_WORDS \ (SHA512_256_BLOCK_SIZE_BITS / SHA512_256_WORD_SIZE_BITS) /** * SHA-512/256 calculation context */ struct Sha512_256Ctx { uint64_t H[SHA512_256_HASH_SIZE_WORDS]; /**< Intermediate hash value */ uint64_t buffer[SHA512_256_BLOCK_SIZE_WORDS]; /**< SHA512_256 input data buffer */ /** * The number of bytes, lower part */ uint64_t count; /** * The number of bits, high part. * Unlike lower part, this counts the number of bits, not bytes. */ uint64_t count_bits_hi; }; /** * Initialise structure for SHA-512/256 calculation. * * @param ctx the calculation context */ void MHD_SHA512_256_init (struct Sha512_256Ctx *ctx); /** * Process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA512_256_update (struct Sha512_256Ctx *ctx, const uint8_t *data, size_t length); /** * Finalise SHA-512/256 calculation, return digest. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #SHA512_256_DIGEST_SIZE bytes */ void MHD_SHA512_256_finish (struct Sha512_256Ctx *ctx, uint8_t digest[SHA512_256_DIGEST_SIZE]); #endif /* MHD_SHA512_256_H */ libmicrohttpd-1.0.10/src/microhttpd/test_raw_requests.c0000664000175000017500000020353415232103064017016 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_raw_requests.c * @brief Data-driven raw HTTP request corpus, replayed at every possible * TCP stream split point and under a sweep of connection memory * limits. * @author Christian Grothoff * * ## Why this test exists * * The MHD request parser is *incremental*: it is re-entered every time more * bytes arrive from the network and has to decide, at each entry, whether it * already holds a complete line / chunk header / chunk / body. Off-by-N * errors, misplaced `break; /_* need more data *_/` statements and * state-machine desynchronisations live exactly in that logic and they are * invisible when the whole request arrives in a single `read()`. * * This test therefore takes every corpus entry and replays it over a fresh TCP * connection once per possible split offset, forcing the server to re-enter * the parser at that offset. The parse result (method, URL, version, upload * body, headers, GET arguments, footers, number of complete requests, response * status, connection re-use) must be *identical* for every split offset. Any * divergence is a bug, no matter what the declared expectations say. * * The whole corpus is additionally replayed for a sweep of * #MHD_OPTION_CONNECTION_MEMORY_LIMIT values. Values below #MHD_BUF_INC_SIZE * (1500) unlock the read-buffer "shift back" and buffer-grow code paths that * are never reached with the default pool size. * * ## How to add a corpus entry * * Add exactly one initialiser to the @a corpus[] table below. Nothing else * has to be touched. The fields are: * * * `.name` - short identifier, printed on failure; * * `.desc` - one line saying which behaviour the entry pins down; * * `.raw` - the raw request byte stream (may contain several pipelined * requests); `.raw_len` may stay 0, then `strlen()` is used; * * `.n_req` - how many complete requests MHD *must* parse out of `.raw` * (this is the request-smuggling / desync detector: a stream * that must yield 2 requests may never yield 1 or 3); * * `.reqs[]`- the per-request expectations. `.hdrs`, `.args` and `.foot` * are newline separated `key=value` lists in the order in which * MHD reports them; a NULL value (what a query argument without * '=' produces) is written as ``; * * `.n_resp`- how many HTTP responses the client must see; * * `.status`- expected status code of the *first* response, 0 for "any * well-formed response"; * * `.alive` - 1 if the connection must stay alive afterwards, 0 if MHD must * close it; * * `.deep` - non-zero to additionally run the (much slower) three-way split * pass over this entry. * * The escaping used by the observation format has to be applied to the * expectation strings as well: every byte outside the printable ASCII range * appears as `\\xNN` (so a TAB inside a header value is written as `\\x09`). * * If the entry does not fit into the connection memory pool of the current * sweep step, MHD answers 431/413/414/500 without ever invoking the request * handler, or it cannot even build the reply header and closes the connection * without an answer, or it serves only the first of several pipelined * requests. All three are legitimate resource limitations; the test detects * them and falls back to the relaxed check "every request that MHD did parse * matches the expectation for its index, and MHD never parses more requests * than the stream contains". A 400 Bad Request is never accepted as a * resource limitation. * * ## The daemon option matrix * * The test honours the matrix of mhd_opt_matrix.h: when one of the MHD_TEST_* * environment variables selects a profile, the built-in memory limit sweep is * replaced by the single memory limit of the profile and the threading mode, * the polling backend and the client discipline level of the profile are * applied. Without those variables nothing changes, so a stock "make check" * runs exactly the sweep described above. * * The declared expectations of a corpus entry are only valid for a range of * client discipline levels - the levels are precisely the knob that switches * the parser leniency the entries pin down. Every entry whose expectation * depends on the level is therefore listed in @a discp_limits[] with the * range in which it is meaningful, and is skipped outside of it. At the * default level 0 nothing is ever skipped. * * ## Command line * * * `-v` - report the memory limit sweep and degraded entries; * * `-v -v` - additionally print the MHD error log; * * `--entry=NAME` - restrict the run to a single corpus entry (`NAME` may * also be given as a bare argument). * * Exit codes: 0 = pass, 77 = skip, 99 = hard setup error, 1 = test failure. */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #include #include "mhd_sockets.h" /* only macros used */ #include "mhd_opt_matrix.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /** * Convenience shorthand used all over the corpus table. */ #define CRLF "\r\n" /** * Maximum number of pipelined requests a single corpus entry may contain. */ #define MAX_REQS 4 /** * Size of the textual observation buffers. */ #define OBS_SIZE 8192 /** * Size of the client receive buffer. */ #define RX_SIZE 16384 /** * Milliseconds to wait between two parts of a split request so that the * server really gets to process the partial input. */ #define SPLIT_DELAY_MS 2 /** * Hard upper bound (ms) for reading the complete server answer. */ #define READ_DEADLINE_MS 400 /** * Silence (ms) after the expected number of responses that is accepted as * "the server is done and keeps the connection alive". Only used for the * unsplit reference run. */ #define READ_GRACE_MS 12 /** * Milliseconds to wait for the server side to finish tearing down the * connection (and thus for the observations to become stable). */ #define CLOSE_WAIT_MS 2000 /** * Split offsets 1 .. SPLIT_DENSE_LIMIT are all exercised, beyond that only * every SPLIT_STRIDE-th offset is used. */ #define SPLIT_DENSE_LIMIT 512 /** * Stride for sampling split offsets of long requests. */ #define SPLIT_STRIDE 7 /** * Maximum number of three-way split combinations per entry and pool size. */ #define DEEP_SPLIT_MAX 24 /** * Give up after that many reported failures. */ #define MAX_FAILURES 10 #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #endif /* Forward declaration, needed by the error exit helpers. */ static void print_context (FILE *out); _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ print_context (stderr); fflush (stderr); exit (99); } /** * Pause execution for specified number of milliseconds. * @param ms the number of milliseconds to sleep */ static void _MHD_sleep (uint32_t ms) { #if defined(_WIN32) Sleep (ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp = {(time_t) (ms / 1000), (long) ((ms % 1000) * 1000000)}; struct timespec rmn; int num_retries = 0; while (0 != nanosleep (&slp, &rmn)) { if (EINTR != errno) externalErrorExit (); if (num_retries++ > 8) break; slp = rmn; } #elif defined(HAVE_USLEEP) uint64_t us = ms * 1000; do { uint64_t this_sleep; if (999999 < us) this_sleep = 999999; else this_sleep = us; /* Ignore return value as it could be void */ usleep ((useconds_t) this_sleep); us -= this_sleep; } while (us > 0); #else externalErrorExitDesc ("No sleep function available on this system"); #endif } /** * Monotonic-ish millisecond clock. */ static uint64_t now_ms (void) { #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) struct timespec ts; if (0 == clock_gettime (CLOCK_MONOTONIC, &ts)) return ((uint64_t) ts.tv_sec) * 1000 + (uint64_t) (ts.tv_nsec / 1000000); #endif /* HAVE_CLOCK_GETTIME && CLOCK_MONOTONIC */ return ((uint64_t) time (NULL)) * 1000; } /* ------------------------------------------------------------------ */ /* Textual observation buffers */ /* ------------------------------------------------------------------ */ /** * A bounded, always NUL-terminated text accumulator. All observations * (expected as well as actual) are rendered into such a buffer and the * comparison is a plain strcmp(), which also gives readable diagnostics. */ struct obs_buf { char d[OBS_SIZE]; size_t len; int overflow; }; static void obs_reset (struct obs_buf *b) { b->len = 0; b->overflow = 0; b->d[0] = 0; } static void obs_addf (struct obs_buf *b, const char *fmt, ...) { va_list ap; int r; size_t space; if (b->len >= sizeof(b->d) - 1) { b->overflow = 1; return; } space = sizeof(b->d) - b->len; va_start (ap, fmt); r = vsnprintf (b->d + b->len, space, fmt, ap); va_end (ap); if (0 > r) { b->overflow = 1; return; } if ((size_t) r >= space) { b->len = sizeof(b->d) - 1; b->overflow = 1; return; } b->len += (size_t) r; } /** * Append @a data with all non-printable bytes escaped as \\xNN. */ static void obs_add_escaped (struct obs_buf *b, const char *data, size_t size) { size_t i; for (i = 0; i < size; ++i) { const unsigned char c = (unsigned char) data[i]; if ((0x20 <= c) && (0x7e >= c) && ('\\' != c)) obs_addf (b, "%c", (char) c); else if ('\\' == c) obs_addf (b, "\\\\"); else obs_addf (b, "\\x%02x", (unsigned int) c); } } /* ------------------------------------------------------------------ */ /* The corpus */ /* ------------------------------------------------------------------ */ /** * Expectations for a single (possibly pipelined) request inside a stream. */ struct exp_req { const char *method; const char *url; const char *version; /** * Expected upload body, NULL for "no body at all". */ const char *body; /** * Length of @a body, 0 means strlen(). */ size_t body_len; /** * Newline separated list of expected #MHD_HEADER_KIND elements. */ const char *hdrs; /** * Newline separated list of expected #MHD_GET_ARGUMENT_KIND elements. */ const char *args; /** * Newline separated list of expected #MHD_FOOTER_KIND elements. */ const char *foot; }; struct corpus_entry { const char *name; const char *desc; const char *raw; size_t raw_len; /**< 0 -> strlen (raw) */ unsigned int n_req; /**< complete requests MHD must parse */ unsigned int n_resp; /**< responses the client must see */ int status; /**< first response status, 0 = any */ int alive; /**< 1: keep-alive, 0: MHD must close */ int deep; /**< also run three-way splits */ struct exp_req reqs[MAX_REQS]; }; #define H_LOCAL "Host: localhost" CRLF #define E_HOST "Host=localhost" static const struct corpus_entry corpus[] = { /* ---- request line basics -------------------------------------- */ { "get_11_host", "baseline: request line + one header, incremental line assembly", "GET / HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 1, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST, "", "" } } }, { "get_10_nohost", "HTTP/1.0 without Host: no header lines at all, must not keep alive", "GET / HTTP/1.0" CRLF CRLF, 0, 1, 1, 200, 0, 1, { { "GET", "/", "HTTP/1.0", NULL, 0, "", "", "" } } }, { "head_11", "HEAD: reply must carry no body, parser path is the same", "HEAD / HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "HEAD", "/", "HTTP/1.1", NULL, 0, E_HOST, "", "" } } }, /* ---- query string handling ------------------------------------ */ { "q_bare", "single query argument without '=' -> NULL value", "GET /?a HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST, "a=", "" } } }, { "q_two_bare", "two arguments, both without '='", "GET /?a&b HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST, "a=\nb=", "" } } }, { "q_mixed", "'=' in the first argument only", "GET /?a=1&b HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST, "a=1\nb=", "" } } }, { "q_empty_val", "'a=' must give an empty (not NULL) value", "GET /?a= HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST, "a=", "" } } }, { "q_trailing_amp", "trailing '&' must not create a second, empty argument", "GET /?a& HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST, "a=", "" } } }, { "q_no_key", "'=v' must give an empty key with value 'v'", "GET /?=v HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST, "=v", "" } } }, { "q_pct", "percent decoding of both key and value happens in place", "GET /?a%20b=c%26d HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST, "a b=c&d", "" } } }, { "q_frag", "'#' is not special for a server: it stays part of the argument", "GET /?a#frag HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST, "a#frag=", "" } } }, { "q_plus", "'+' is decoded to a space in query arguments", "GET /?a+b=c+d HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST, "a b=c d", "" } } }, { "q_pct_url", "percent decoding of the path part", "GET /a%2Fb%20c HTTP/1.1" CRLF H_LOCAL CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/a/b c", "HTTP/1.1", NULL, 0, E_HOST, "", "" } } }, /* The next two entries have *no* header line at all, so the last parsed element is a query argument with a NULL value. With a connection memory limit below MHD_BUF_INC_SIZE this is the precondition of the read buffer "shift back" underflow fixed in 29eaa56b. */ { "q_only_10_nohdr", "no headers at all + trailing arg without '=': read-buffer shift back", "GET /x?a HTTP/1.0" CRLF CRLF, 0, 1, 1, 200, 0, 1, { { "GET", "/x", "HTTP/1.0", NULL, 0, "", "a=", "" } } }, { "q_only_10_nohdr2", "same, but two NULL-valued args (tail element is the second one)", "GET /y?a&b HTTP/1.0" CRLF CRLF, 0, 1, 1, 200, 0, 1, { { "GET", "/y", "HTTP/1.0", NULL, 0, "", "a=\nb=", "" } } }, { "q_only_10_nohdr_val", "control case: no headers but a trailing arg *with* '='", "GET /z?a=1 HTTP/1.0" CRLF CRLF, 0, 1, 1, 200, 0, 0, { { "GET", "/z", "HTTP/1.0", NULL, 0, "", "a=1", "" } } }, /* ---- Content-Length bodies ------------------------------------ */ { "cl_exact", "Content-Length body, delivered incrementally to the handler", "POST /p HTTP/1.1" CRLF H_LOCAL "Content-Length: 5" CRLF CRLF "Hello", 0, 1, 1, 200, 1, 1, { { "POST", "/p", "HTTP/1.1", "Hello", 0, E_HOST "\nContent-Length=5", "", "" } } }, { "cl_zero", "Content-Length: 0 must not wait for body bytes", "POST /p HTTP/1.1" CRLF H_LOCAL "Content-Length: 0" CRLF CRLF, 0, 1, 1, 200, 1, 0, { { "POST", "/p", "HTTP/1.1", "", 0, E_HOST "\nContent-Length=0", "", "" } } }, { "cl_long", "longer Content-Length body, forces several read-buffer rounds", "POST /p HTTP/1.1" CRLF H_LOCAL "Content-Length: 40" CRLF CRLF "0123456789abcdefghijklmnopqrstuvwxyz+-*/", 0, 1, 1, 200, 1, 0, { { "POST", "/p", "HTTP/1.1", "0123456789abcdefghijklmnopqrstuvwxyz+-*/", 0, E_HOST "\nContent-Length=40", "", "" } } }, /* ---- chunked bodies ------------------------------------------- */ { "chunk_plain", "plain chunked body without extensions", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5" CRLF "Hello" CRLF "0" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, /* The chunk-extension entries pin down that the CRLF that terminates the chunk size line is consumed *together with* the extension. Failing to do so (bug fixed in c13f4c64) shifts the whole chunk body by two bytes and desynchronises the stream -> request smuggling. */ { "chunk_ext_val", "chunk extension 'ext=val': CRLF after the extension must be consumed", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5;ext=val" CRLF "Hello" CRLF "0" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, { "chunk_ext_noval", "chunk extension without a value", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5;ext" CRLF "Hello" CRLF "0" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, { "chunk_ext_quoted", "quoted chunk extension value containing ';'", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5;ext=\"quoted;value\"" CRLF "Hello" CRLF "0" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, { "chunk_ext_bws", "'bad whitespace' between chunk size and ';' (lenient mode)", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5 ;ext=val" CRLF "Hello" CRLF "0" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, { "chunk_ext_last", "chunk extension on the terminating chunk", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5;a=b" CRLF "Hello" CRLF "0;z=y" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, { "chunk_multi", "several chunks are concatenated into one upload body", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "3" CRLF "abc" CRLF "2" CRLF "de" CRLF "1" CRLF "f" CRLF "0" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "abcdef", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, { "chunk_lead_zeros", "chunk size with leading zeros", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "0005" CRLF "Hello" CRLF "000" CRLF CRLF, 0, 1, 1, 200, 1, 0, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, { "chunk_trailers", "trailer (footer) fields after the terminating chunk", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5" CRLF "Hello" CRLF "0" CRLF "X-Trailer: v" CRLF "X-T2: w" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "X-Trailer=v\nX-T2=w" } } }, { "chunk_fold_trailer", "obs-fold continuation inside a trailer field", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5" CRLF "Hello" CRLF "0" CRLF "X-T: a" CRLF " b" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "X-T=a b" } } }, { "chunk_ext_trailers", "chunk extension *and* trailers in the same message", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5;ext=val" CRLF "Hello" CRLF "0" CRLF "X-Trailer: v" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "X-Trailer=v" } } }, { "chunk_empty", "only the terminating chunk: empty upload body", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "0" CRLF CRLF, 0, 1, 1, 200, 1, 0, { { "POST", "/c", "HTTP/1.1", "", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, /* MHD keeps room for a chunk "header" of MHD_CHUNK_HEADER_REASONABLE_LEN (24) bytes in the read buffer; a longer chunk extension forces the buffer-grow path in the middle of the chunk size line. */ { "chunk_ext_long", "chunk extension longer than the reserved chunk header space", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5;ext=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" CRLF "Hello" CRLF "0" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, { "chunk_multi_ext", "a chunk extension on every single chunk", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "3;a=1" CRLF "abc" CRLF "2;b=2" CRLF "de" CRLF "1;c" CRLF "f" CRLF "0;d=4" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "abcdef", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" } } }, /* ---- pipelining / desynchronisation --------------------------- */ { "pipe2", "two pipelined requests must yield exactly two parsed requests", "GET /1 HTTP/1.1" CRLF H_LOCAL CRLF "GET /2 HTTP/1.1" CRLF H_LOCAL CRLF, 0, 2, 2, 200, 1, 1, { { "GET", "/1", "HTTP/1.1", NULL, 0, E_HOST, "", "" }, { "GET", "/2", "HTTP/1.1", NULL, 0, E_HOST, "", "" } } }, { "pipe3", "three pipelined requests, never two and never four", "GET /1 HTTP/1.1" CRLF H_LOCAL CRLF "GET /2?x=1 HTTP/1.1" CRLF H_LOCAL CRLF "GET /3 HTTP/1.1" CRLF H_LOCAL CRLF, 0, 3, 3, 200, 1, 0, { { "GET", "/1", "HTTP/1.1", NULL, 0, E_HOST, "", "" }, { "GET", "/2", "HTTP/1.1", NULL, 0, E_HOST, "x=1", "" }, { "GET", "/3", "HTTP/1.1", NULL, 0, E_HOST, "", "" } } }, { "pipe_chunk_get", "chunked POST followed by a GET: the smuggling detector", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5" CRLF "Hello" CRLF "0" CRLF CRLF "GET /after HTTP/1.1" CRLF H_LOCAL CRLF, 0, 2, 2, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" }, { "GET", "/after", "HTTP/1.1", NULL, 0, E_HOST, "", "" } } }, { "pipe_chunkext_get", "chunk *extension* + pipelined GET: smuggling detector for c13f4c64", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5;ext=val" CRLF "Hello" CRLF "0" CRLF CRLF "GET /after HTTP/1.1" CRLF H_LOCAL CRLF, 0, 2, 2, 200, 1, 1, { { "POST", "/c", "HTTP/1.1", "Hello", 0, E_HOST "\nTransfer-Encoding=chunked", "", "" }, { "GET", "/after", "HTTP/1.1", NULL, 0, E_HOST, "", "" } } }, { "pipe_cl_get", "Content-Length POST followed by a GET", "POST /p HTTP/1.1" CRLF H_LOCAL "Content-Length: 5" CRLF CRLF "Hello" "GET /after HTTP/1.1" CRLF H_LOCAL CRLF, 0, 2, 2, 200, 1, 0, { { "POST", "/p", "HTTP/1.1", "Hello", 0, E_HOST "\nContent-Length=5", "", "" }, { "GET", "/after", "HTTP/1.1", NULL, 0, E_HOST, "", "" } } }, /* ---- header line edge cases ----------------------------------- */ { "hdr_obs_fold", "obs-fold continuation: CR, LF and the fold space each become one space", "GET / HTTP/1.1" CRLF H_LOCAL "X-Fold: one" CRLF " two" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST "\nX-Fold=one two", "", "" } } }, /* Note: the CR and the LF of the folded line are each replaced by a space and the leading whitespace of the continuation line is kept verbatim, so a TAB survives as a TAB. */ { "hdr_fold_multi", "two consecutive obs-fold continuation lines, second one folded with TAB", "GET / HTTP/1.1" CRLF H_LOCAL "X-F: one" CRLF " two" CRLF "\ttree" CRLF CRLF, 0, 1, 1, 200, 1, 1, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST "\nX-F=one two \\x09tree", "", "" } } }, { "hdr_empty_val", "header with an empty value", "GET / HTTP/1.1" CRLF H_LOCAL "X-Empty:" CRLF CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST "\nX-Empty=", "", "" } } }, { "hdr_dup", "duplicated header names are reported twice, in order", "GET / HTTP/1.1" CRLF H_LOCAL "X-Dup: 1" CRLF "X-Dup: 2" CRLF CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST "\nX-Dup=1\nX-Dup=2", "", "" } } }, { "hdr_bare_lf", "bare LF line terminators (lenient mode) must parse identically", "GET / HTTP/1.1\n" H_LOCAL "X-B: v\n\n", 0, 1, 1, 200, 1, 1, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST "\nX-B=v", "", "" } } }, { "hdr_bare_cr", "a bare CR inside a header value is rejected with 400 at the default " "client discipline level", "GET / HTTP/1.1" CRLF H_LOCAL "X-Cr: a\rb" CRLF CRLF, 0, 0, 1, 400, 0, 1, { { NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL } } }, { "hdr_trail_ws", "trailing whitespace in a header value must be stripped", "GET / HTTP/1.1" CRLF H_LOCAL "X-Ws: val " CRLF CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST "\nX-Ws=val", "", "" } } }, { "hdr_lead_ws", "several spaces after the colon are not part of the value", "GET / HTTP/1.1" CRLF H_LOCAL "X-Lw: val" CRLF CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST "\nX-Lw=val", "", "" } } }, { "hdr_many", "many small headers: exercises pool allocation and buffer growth", "GET / HTTP/1.1" CRLF H_LOCAL "A: 1" CRLF "B: 2" CRLF "C: 3" CRLF "D: 4" CRLF "E: 5" CRLF "F: 6" CRLF "G: 7" CRLF "H: 8" CRLF CRLF, 0, 1, 1, 200, 1, 0, { { "GET", "/", "HTTP/1.1", NULL, 0, E_HOST "\nA=1\nB=2\nC=3\nD=4\nE=5\nF=6\nG=7\nH=8", "", "" } } }, /* Bare LF is accepted as a line terminator in the request header but NOT inside the chunked framing (process_request_body() requires discipline level < -2 for that), so this must be a clean 400 - and it must be a 400 no matter where the stream is cut. */ { "hdr_bare_lf_chunk", "bare LF inside the chunked framing is rejected with 400", "POST /c HTTP/1.1\n" H_LOCAL "Transfer-Encoding: chunked\n\n" "5;ext=val\nHello\n0\n\n", 0, 0, 1, 400, 0, 1, { { NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL } } } }; #define CORPUS_SIZE (sizeof(corpus) / sizeof(corpus[0])) /** * Sweep of #MHD_OPTION_CONNECTION_MEMORY_LIMIT values; 0 means "use the MHD * default". Everything below #MHD_BUF_INC_SIZE (1500) unlocks read-buffer * code paths that are otherwise never taken. */ static const size_t mem_limits[] = { 256, 512, 1024, 1499, 4096, 0 }; #define MEM_LIMITS_SIZE (sizeof(mem_limits) / sizeof(mem_limits[0])) /** * The range of client discipline levels in which the declared expectation of * a corpus entry holds. * * Every entry that is not listed here is level independent. The bounds * follow the predicates of connection.c directly: * * * a bare LF is a line terminator only while `MHD_ALLOW_BARE_LF_AS_CRLF_` * (0 >= level) holds, and an obs-fold continuation only while * `allow_folded` (0 >= level) holds, so both are meaningless above 0; * * `allow_bws` is (2 > level), so the "bad whitespace" chunk-size line is * meaningless above 1; * * a bare CR is turned into a space by `bare_cr_as_sp` (-1 >= level) and * kept by `bare_cr_keep` (-3 >= level), so the entry that expects a 400 * only holds from level 0 upwards; * * inside the chunked framing `bare_lf_as_crlf` is (-2 > level), so the * entry that expects a 400 for a bare LF there only holds from -2 upwards. */ struct entry_discp_limit { const char *name; int min_discp; int max_discp; }; static const struct entry_discp_limit discp_limits[] = { { "hdr_bare_lf", -3, 0 }, { "hdr_obs_fold", -3, 0 }, { "hdr_fold_multi", -3, 0 }, { "chunk_fold_trailer", -3, 0 }, { "chunk_ext_bws", -3, 1 }, { "hdr_bare_cr", 0, 3 }, { "hdr_bare_lf_chunk", -2, 3 } }; #define DISCP_LIMITS_SIZE \ (sizeof(discp_limits) / sizeof(discp_limits[0])) /** * The profile selected by the environment, NULL if the built-in sweep is * used (which is the case for a stock "make check"). */ static const struct MHD_OptMatrixProfile *test_prof; /** * The (possibly adjusted) copy of the profile @a test_prof points to. */ static struct MHD_OptMatrixProfile test_prof_copy; /** * The client discipline level really in effect, see * mhd_opt_matrix_effective_discipline(). */ static int test_discp; /** * Check whether the declared expectation of @a name holds at the client * discipline level currently in effect. * * @param name the name of the corpus entry * @return non-zero if the entry may be run */ static int entry_in_discp_range (const char *name) { size_t i; for (i = 0; i < DISCP_LIMITS_SIZE; ++i) { if (0 == strcmp (name, discp_limits[i].name)) return ((test_discp >= discp_limits[i].min_discp) && (test_discp <= discp_limits[i].max_discp)) ? 1 : 0; } return 1; } /* ------------------------------------------------------------------ */ /* Global state */ /* ------------------------------------------------------------------ */ static int verbose; /** Current corpus entry under test (the test is strictly serialised). */ static const struct corpus_entry *cur_entry; /** Human readable description of the current split. */ static char cur_split[128]; /** Current connection memory limit. */ static size_t cur_mem_limit; /** Non-zero while the (slow) three-way split pass is enabled. */ static int deep_enabled; static uint16_t global_port; /** Server side observations of the connection currently under test. */ static struct obs_buf srv_obs; /** Number of completed requests seen by the request handler. */ static volatile unsigned int srv_n_req; /** Set if the handler noticed something structurally impossible. */ static volatile unsigned int srv_error; static volatile unsigned int conn_started; static volatile unsigned int conn_closed; /** Total number of (entry x split x memory limit) combinations executed. */ static unsigned long combos; /** Number of combinations that could not fit into the memory pool. */ static unsigned long combos_pool_limited; /** Number of failures found. */ static unsigned long failures; static void print_context (FILE *out) { fprintf (out, " context: entry='%s' split=%s mem_limit=", (NULL != cur_entry) ? cur_entry->name : "(none)", cur_split); if (0 == cur_mem_limit) fprintf (out, "default\n"); else fprintf (out, "%u\n", (unsigned int) cur_mem_limit); if (NULL != cur_entry) fprintf (out, " entry purpose: %s\n", cur_entry->desc); } #if defined(HAVE_SIGNAL_H) && defined(SIGABRT) /** * Report the corpus entry and split offset when the library aborts (e.g. * from an internal assertion), instead of dying anonymously. */ static void abort_handler (int sig) { (void) sig; fprintf (stderr, "\nFATAL: the library aborted while running a corpus entry.\n"); print_context (stderr); fflush (stderr); _exit (1); } #endif /* HAVE_SIGNAL_H && SIGABRT */ /** * Panic callback: a library panic must be reported as a test failure that * names the corpus entry and split offset. */ static void test_panic (void *cls, const char *file, unsigned int line, const char *reason) { (void) cls; fprintf (stderr, "\nFATAL: MHD panic at %s:%u: %s\n", (NULL != file) ? file : "(unknown)", line, (NULL != reason) ? reason : "(no reason given)"); print_context (stderr); fflush (stderr); _exit (1); } /* ------------------------------------------------------------------ */ /* Request handler: records the observations */ /* ------------------------------------------------------------------ */ struct req_state { int marker; unsigned int idx; struct obs_buf body; }; struct iter_ctx { struct obs_buf *out; unsigned int num; }; static enum MHD_Result value_iterator (void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct iter_ctx *const ctx = (struct iter_ctx *) cls; (void) kind; if (0 != ctx->num) obs_addf (ctx->out, "\n"); ctx->num++; if (NULL != key) obs_add_escaped (ctx->out, key, key_size); else obs_addf (ctx->out, ""); obs_addf (ctx->out, "="); if (NULL == value) obs_addf (ctx->out, ""); else obs_add_escaped (ctx->out, value, value_size); return MHD_YES; } static void dump_values (struct MHD_Connection *c, enum MHD_ValueKind kind, const char *label, struct obs_buf *out) { struct iter_ctx ctx; ctx.out = out; ctx.num = 0; obs_addf (out, " %s=[", label); MHD_get_connection_values_n (c, kind, &value_iterator, &ctx); obs_addf (out, "]\n"); } static enum MHD_Result ahc_record (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { /* The reply body is intentionally empty: that makes the reply of a HEAD request byte-identical to the reply of a GET request and keeps the client side response framing trivial. */ static const char rp_data[] = ""; struct req_state *rs; struct MHD_Response *response; enum MHD_Result ret; (void) cls; if (NULL == *req_cls) { rs = (struct req_state *) malloc (sizeof (struct req_state)); if (NULL == rs) externalErrorExitDesc ("malloc() failed"); rs->marker = 1; rs->idx = srv_n_req; obs_reset (&rs->body); *req_cls = rs; return MHD_YES; } rs = (struct req_state *) *req_cls; if (0 != *upload_data_size) { obs_add_escaped (&rs->body, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } /* The request is complete: record everything we can observe. */ obs_addf (&srv_obs, "REQ %u\n", rs->idx); obs_addf (&srv_obs, " method=%s\n", (NULL != method) ? method : "(null)"); obs_addf (&srv_obs, " url="); if (NULL != url) obs_add_escaped (&srv_obs, url, strlen (url)); else obs_addf (&srv_obs, "(null)"); obs_addf (&srv_obs, "\n"); obs_addf (&srv_obs, " version=%s\n", (NULL != version) ? version : "(null)"); obs_addf (&srv_obs, " body=[%s]\n", rs->body.d); dump_values (connection, MHD_HEADER_KIND, "hdr", &srv_obs); dump_values (connection, MHD_GET_ARGUMENT_KIND, "arg", &srv_obs); dump_values (connection, MHD_FOOTER_KIND, "foot", &srv_obs); free (rs); *req_cls = NULL; srv_n_req++; response = MHD_create_response_from_buffer (MHD_STATICSTR_LEN_ (rp_data), (void *) rp_data, MHD_RESPMEM_PERSISTENT); if (NULL == response) { srv_error++; return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) srv_error++; return ret; } /** * MHD is started with #MHD_USE_ERROR_LOG so that library complaints are * available, but they are only printed with '-v -v' to keep the (very * repetitive) output of the sweep readable. */ static void test_log (void *cls, const char *fmt, va_list ap) { (void) cls; if (1 < verbose) { vfprintf (stderr, fmt, ap); fflush (stderr); } } static void conn_notify (void *cls, struct MHD_Connection *c, void **socket_context, enum MHD_ConnectionNotificationCode toe) { (void) cls; (void) c; (void) socket_context; if (MHD_CONNECTION_NOTIFY_STARTED == toe) conn_started++; else if (MHD_CONNECTION_NOTIFY_CLOSED == toe) conn_closed++; } static void req_completed (void *cls, struct MHD_Connection *c, void **req_cls, enum MHD_RequestTerminationCode term_code) { (void) cls; (void) c; (void) term_code; if ((NULL != req_cls) && (NULL != *req_cls)) { free (*req_cls); *req_cls = NULL; } } /* ------------------------------------------------------------------ */ /* Raw client */ /* ------------------------------------------------------------------ */ struct client_result { unsigned int n_resp; int first_status; int peer_closed; int timed_out; size_t rx_len; char rx[RX_SIZE]; }; /** * Case-insensitive comparison of @a size bytes (ASCII only). */ static int mem_equal_ci (const char *a, const char *b, size_t size) { size_t i; for (i = 0; i < size; ++i) { char ca = a[i]; char cb = b[i]; if (('A' <= ca) && ('Z' >= ca)) ca = (char) (ca - 'A' + 'a'); if (('A' <= cb) && ('Z' >= cb)) cb = (char) (cb - 'A' + 'a'); if (ca != cb) return 0; } return 1; } /** * Count the number of complete HTTP responses in @a buf. * * @param buf the received bytes * @param len the number of bytes in @a buf * @param[out] first_status set to the status code of the first response * @return the number of *complete* responses found */ static unsigned int count_responses (const char *buf, size_t len, int *first_status) { size_t pos = 0; unsigned int num = 0; *first_status = 0; while (pos < len) { const char *hdr_end; const char *cl; size_t hdr_len; size_t body_len = 0; int status; size_t i; if (7 > len - pos) break; if (0 != memcmp (buf + pos, "HTTP/1.", 7)) break; /* Not a well-formed response */ hdr_end = NULL; for (i = pos; i + 3 < len; ++i) { if (('\r' == buf[i]) && ('\n' == buf[i + 1]) && ('\r' == buf[i + 2]) && ('\n' == buf[i + 3])) { hdr_end = buf + i + 4; break; } } if (NULL == hdr_end) break; /* Incomplete header */ hdr_len = (size_t) (hdr_end - (buf + pos)); status = 0; if ((pos + 12 <= len) && ('0' <= buf[pos + 9]) && ('9' >= buf[pos + 9])) status = (buf[pos + 9] - '0') * 100 + (buf[pos + 10] - '0') * 10 + (buf[pos + 11] - '0'); if (0 == num) *first_status = status; /* Find "Content-Length:" inside this response header. */ cl = NULL; for (i = pos; i + 15 <= pos + hdr_len; ++i) { if (mem_equal_ci (buf + i, "content-length:", 15)) { cl = buf + i + 15; break; } } if (NULL != cl) { while ((cl < buf + pos + hdr_len) && (' ' == *cl)) cl++; body_len = 0; while ((cl < buf + pos + hdr_len) && ('0' <= *cl) && ('9' >= *cl)) { body_len = body_len * 10 + (size_t) (*cl - '0'); cl++; } } if (pos + hdr_len + body_len > len) break; /* Body incomplete */ pos += hdr_len + body_len; num++; } return num; } static MHD_socket client_connect (void) { MHD_socket sk; struct sockaddr_in sa; const MHD_SCKT_OPT_BOOL_ on_val = 1; sk = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == sk) externalErrorExitDesc ("Cannot create the client socket"); #ifdef MHD_socket_nosignal_ if (! MHD_socket_nosignal_ (sk)) externalErrorExitDesc ("Cannot suppress SIGPIPE on the client socket"); #endif /* MHD_socket_nosignal_ */ if (0 != setsockopt (sk, IPPROTO_TCP, TCP_NODELAY, (const void *) &on_val, sizeof (on_val))) externalErrorExitDesc ("Cannot set TCP_NODELAY option"); memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (global_port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != connect (sk, (struct sockaddr *) &sa, sizeof (sa))) externalErrorExitDesc ("Cannot connect() to the daemon"); return sk; } static int client_send_all (MHD_socket sk, const char *data, size_t size) { size_t off = 0; while (off < size) { ssize_t s = MHD_send_ (sk, data + off, size - off); if (0 > s) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err) || MHD_SCKT_ERR_IS_EAGAIN_ (err)) continue; return 0; /* Server closed the connection early, that is an observation */ } off += (size_t) s; } return 1; } /** * Wait for a socket to become readable. * * @return 1 readable, 0 timeout, -1 error */ static int wait_readable (MHD_socket sk, unsigned int timeout_ms) { fd_set rs; struct timeval tv; int r; FD_ZERO (&rs); FD_SET (sk, &rs); tv.tv_sec = (time_t) (timeout_ms / 1000); tv.tv_usec = (long) ((timeout_ms % 1000) * 1000); r = select ((int) sk + 1, &rs, NULL, NULL, &tv); if (0 > r) { if (EINTR == errno) return 0; return -1; } return (0 == r) ? 0 : 1; } /** * Read the server answer. * * @param sk the socket to read from * @param[out] r the result * @param min_resp stop once that many complete responses have been read * @param want_close keep reading until the peer closes the connection * @param grace_ms extra silence to wait for after @a min_resp responses */ static void client_read (MHD_socket sk, struct client_result *r, unsigned int min_resp, int want_close, unsigned int grace_ms) { const uint64_t start = now_ms (); memset (r, 0, sizeof (*r)); while (1) { const uint64_t el = now_ms () - start; unsigned int tmo; int wr; ssize_t got; if (el >= READ_DEADLINE_MS) { r->timed_out = 1; break; } r->n_resp = count_responses (r->rx, r->rx_len, &r->first_status); if ((r->n_resp >= min_resp) && (! want_close)) tmo = grace_ms; else tmo = (unsigned int) (READ_DEADLINE_MS - el); wr = wait_readable (sk, tmo); if (0 > wr) { r->peer_closed = 1; break; } if (0 == wr) { if ((r->n_resp >= min_resp) && (! want_close)) break; /* Done, connection stays alive */ r->timed_out = 1; break; } if (r->rx_len >= sizeof (r->rx)) break; /* Way too much data, will be reported as a mismatch */ got = MHD_recv_ (sk, r->rx + r->rx_len, sizeof (r->rx) - r->rx_len); if (0 > got) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EINTR_ (err) || MHD_SCKT_ERR_IS_EAGAIN_ (err)) continue; r->peer_closed = 1; /* Connection reset counts as "closed" */ break; } if (0 == got) { r->peer_closed = 1; break; } r->rx_len += (size_t) got; } r->n_resp = count_responses (r->rx, r->rx_len, &r->first_status); } /** * Wait until the daemon has finished tearing down all connections, so that * the server side observations are stable. * * @return 1 on success, 0 on timeout */ static int wait_conns_closed (void) { const uint64_t start = now_ms (); unsigned int spin = 0; while (conn_closed != conn_started) { if (1000 > spin) spin++; else _MHD_sleep (1); if (now_ms () - start > CLOSE_WAIT_MS) return 0; } return 1; } /* ------------------------------------------------------------------ */ /* One replay of one corpus entry */ /* ------------------------------------------------------------------ */ /** * Send @a e over a fresh connection, cut into @a n_cuts + 1 pieces at the * offsets given in @a cuts, and render all observations into @a out. */ static void run_stream (const struct corpus_entry *e, const size_t *cuts, unsigned int n_cuts, unsigned int min_resp, int want_close, unsigned int grace_ms, struct obs_buf *out) { const size_t len = (0 != e->raw_len) ? e->raw_len : strlen (e->raw); struct client_result cr; MHD_socket sk; size_t off = 0; unsigned int i; int send_ok = 1; obs_reset (&srv_obs); srv_n_req = 0; srv_error = 0; sk = client_connect (); for (i = 0; i <= n_cuts; ++i) { const size_t end = (i < n_cuts) ? cuts[i] : len; if (end > off) { if (! client_send_all (sk, e->raw + off, end - off)) { send_ok = 0; break; } off = end; } if (i < n_cuts) _MHD_sleep (SPLIT_DELAY_MS); } client_read (sk, &cr, min_resp, want_close, grace_ms); (void) MHD_socket_close_ (sk); if (! wait_conns_closed ()) { fprintf (stderr, "WARNING: timeout waiting for connection teardown.\n"); print_context (stderr); } obs_reset (out); obs_addf (out, "%s", srv_obs.d); obs_addf (out, "nreq=%u\n", srv_n_req); obs_addf (out, "nresp=%u status=%d closed=%d\n", cr.n_resp, cr.first_status, cr.peer_closed); if (cr.timed_out) obs_addf (out, "TIMED_OUT\n"); /* Note: whether the *client* managed to push out the rest of the request before MHD closed the connection is inherently racy, so it must not be part of the compared observation; 'closed=' already carries the relevant information. It is only reported in verbose mode. */ if ((! send_ok) && (1 < verbose)) { printf (" (send aborted by the server for entry '%s' split %s)\n", e->name, cur_split); fflush (stdout); } if (0 != srv_error) obs_addf (out, "SERVER_ERROR=%u\n", srv_error); if (srv_obs.overflow || out->overflow) obs_addf (out, "OBS_OVERFLOW\n"); } /** * Render the declared expectations of @a e into the very same format that * run_stream() produces, so that a single strcmp() does the whole check. */ static void build_expected (const struct corpus_entry *e, struct obs_buf *out) { unsigned int i; obs_reset (out); for (i = 0; i < e->n_req; ++i) { const struct exp_req *const r = &e->reqs[i]; size_t bl; obs_addf (out, "REQ %u\n", i); obs_addf (out, " method=%s\n", r->method); obs_addf (out, " url="); obs_add_escaped (out, r->url, strlen (r->url)); obs_addf (out, "\n"); obs_addf (out, " version=%s\n", r->version); obs_addf (out, " body=["); if (NULL != r->body) { bl = (0 != r->body_len) ? r->body_len : strlen (r->body); obs_add_escaped (out, r->body, bl); } obs_addf (out, "]\n"); obs_addf (out, " hdr=[%s]\n", r->hdrs); obs_addf (out, " arg=[%s]\n", r->args); obs_addf (out, " foot=[%s]\n", r->foot); } obs_addf (out, "nreq=%u\n", e->n_req); obs_addf (out, "nresp=%u status=%d closed=%d\n", e->n_resp, e->status, e->alive ? 0 : 1); } static void hexdump (FILE *out, const char *data, size_t size) { size_t i; for (i = 0; i < size; i += 16) { size_t j; fprintf (out, " %04x ", (unsigned int) i); for (j = 0; j < 16; ++j) { if (i + j < size) fprintf (out, "%02x ", (unsigned char) data[i + j]); else fprintf (out, " "); } fprintf (out, " |"); for (j = 0; (j < 16) && (i + j < size); ++j) { const unsigned char c = (unsigned char) data[i + j]; fprintf (out, "%c", ((0x20 <= c) && (0x7e >= c)) ? (char) c : '.'); } fprintf (out, "|\n"); } } static void report_failure (const struct corpus_entry *e, const char *what, const char *expected, const char *actual) { const size_t len = (0 != e->raw_len) ? e->raw_len : strlen (e->raw); failures++; fprintf (stderr, "\n==== FAILURE: %s ====\n", what); fprintf (stderr, " entry: %s (%s)\n", e->name, e->desc); fprintf (stderr, " split: %s\n", cur_split); fprintf (stderr, " mem_limit: "); if (0 == cur_mem_limit) fprintf (stderr, "default\n"); else fprintf (stderr, "%u\n", (unsigned int) cur_mem_limit); fprintf (stderr, " --- expected ---\n%s", expected); fprintf (stderr, " --- observed ---\n%s", actual); fprintf (stderr, " --- raw request (%u bytes) ---\n", (unsigned int) len); hexdump (stderr, e->raw, len); fflush (stderr); } /** * Length of the leading "REQ ..." section of an observation, i.e. everything * that describes the requests that MHD actually parsed. */ static size_t obs_reqs_len (const struct obs_buf *o) { const char *const p = strstr (o->d, "nreq="); return (NULL != p) ? (size_t) (p - o->d) : o->len; } /** * Read an unsigned decimal number that follows @a key in the observation. */ static unsigned int obs_get_uint (const struct obs_buf *o, const char *key) { const char *const p = strstr (o->d, key); if (NULL == p) return 0; return (unsigned int) strtoul (p + strlen (key), NULL, 10); } /** * Decide whether a deviation from the declared expectations is a legitimate * *resource* limitation of an artificially small connection memory pool * rather than a parser problem. * * Only these three signatures are accepted, and only when a non-default * #MHD_OPTION_CONNECTION_MEMORY_LIMIT is configured: * - 431/413/414/500 without a single completed request (the request header * does not fit into the pool), * - no reply at all and MHD closed the connection (it could not even build * the reply header), * - fewer requests than the stream contains but a successful reply (a * pipelined stream that was only served partially). * * In particular a 400 Bad Request is *never* accepted as a resource * limitation: a well-formed corpus entry that suddenly becomes malformed is * exactly the kind of parser bug this test hunts for. */ static int is_resource_degradation (const struct obs_buf *o, const struct corpus_entry *e) { const unsigned int nreq = obs_get_uint (o, "nreq="); const unsigned int nresp = obs_get_uint (o, "nresp="); const unsigned int status = obs_get_uint (o, "status="); if (0 == cur_mem_limit) return 0; if (NULL != strstr (o->d, "TIMED_OUT")) return 0; if ((0 == nreq) && ((431 == status) || (413 == status) || (414 == status) || (500 == status))) return 1; if ((0 == nresp) && (0 == status)) return 1; if ((nreq < e->n_req) && ((200 == status) || (0 == status))) return 1; return 0; } /** * Status codes that a run under memory pressure may legitimately show. * * 0 means "no reply at all" (MHD could not build the reply header), 200 is * the normal answer, the 4xx/5xx codes are the resource errors. A 400 is * deliberately *not* in this set: a well-formed corpus entry that MHD * suddenly considers malformed is a parser bug, not a resource problem. */ static int status_acceptable_degraded (const struct obs_buf *o, const struct corpus_entry *e) { const unsigned int status = obs_get_uint (o, "status="); if ((unsigned int) e->status == status) return 1; switch (status) { case 0: case 200: case 413: case 414: case 431: case 500: return 1; default: break; } return 0; } /** * Relaxed check used when the connection memory pool is too small for the * corpus entry. * * Under memory pressure MHD may legitimately stop early: it may answer * 431/413, it may fail to build a reply header, or it may serve only the * first of several pipelined requests. What may *never* happen is that a * request which MHD does parse is parsed differently, or that MHD conjures up * more requests than the byte stream contains (that would be smuggling). * * So the requests that were parsed must form an exact prefix of the declared * expectations. * * @return 1 if acceptable, 0 on a real mismatch */ static int check_relaxed (const struct obs_buf *exp, const struct obs_buf *got) { const size_t gl = obs_reqs_len (got); const size_t el = obs_reqs_len (exp); if (gl > el) return 0; /* More requests parsed than the stream contains */ return 0 == memcmp (exp->d, got->d, gl); } /** * Build the list of split offsets that will be exercised for a request of * @a len bytes. * * @return the number of offsets stored in @a offs */ static unsigned int build_split_offsets (size_t len, size_t *offs, unsigned int max_offs) { unsigned int n = 0; size_t s; for (s = 1; (s < len) && (n < max_offs); ++s) { if ((s <= SPLIT_DENSE_LIMIT) || (0 == (s % SPLIT_STRIDE))) offs[n++] = s; } return n; } /* ------------------------------------------------------------------ */ /* Main test driver */ /* ------------------------------------------------------------------ */ static struct MHD_Daemon * start_daemon_with_limit (size_t limit) { struct MHD_Daemon *d; struct MHD_OptMatrixProfile prof; struct MHD_OptionItem ops[8]; unsigned int flags; /* The profile (if any) supplies the discipline level, the threading mode and the polling backend; the memory limit is the one of the sweep, which the caller has already taken from the profile. */ if (NULL != test_prof) prof = *test_prof; else { memset (&prof, 0, sizeof (prof)); prof.name = "built-in"; prof.threading = MHD_OPT_MATRIX_THR_INTERNAL; prof.poll_backend = MHD_OPT_MATRIX_POLL_SELECT; } prof.mem_limit = limit; if (0 == mhd_opt_matrix_fill_options (&prof, ops, (unsigned int) (sizeof (ops) / sizeof (ops[0])))) externalErrorExitDesc ("The daemon option array is too small"); /* The client of this test is a plain blocking socket client, so external polling is served with an internal polling thread instead. */ flags = mhd_opt_matrix_daemon_flags (&prof, MHD_USE_ERROR_LOG, 0); d = MHD_start_daemon (flags, 0, NULL, NULL, &ahc_record, NULL, MHD_OPTION_ARRAY, ops, MHD_OPTION_EXTERNAL_LOGGER, &test_log, NULL, MHD_OPTION_NOTIFY_CONNECTION, &conn_notify, NULL, MHD_OPTION_NOTIFY_COMPLETED, &req_completed, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 8, MHD_OPTION_END); return d; } /** * Run one corpus entry through the full split sweep at the current memory * limit. */ static void run_entry (const struct corpus_entry *e, unsigned long *split_counter) { const size_t len = (0 != e->raw_len) ? e->raw_len : strlen (e->raw); struct obs_buf expected; struct obs_buf ref; struct obs_buf got; size_t *offs; unsigned int n_offs; unsigned int i; unsigned int stride; int degraded; int ref_bad = 0; const struct obs_buf *cmp; unsigned int ref_resp; unsigned int min_resp; int want_close; cur_entry = e; build_expected (e, &expected); /* 1) Unsplit reference run. */ snprintf (cur_split, sizeof (cur_split), "none (unsplit)"); run_stream (e, NULL, 0, e->n_resp, ! e->alive, READ_GRACE_MS, &ref); combos++; (*split_counter)++; degraded = (0 != strcmp (expected.d, ref.d)) && is_resource_degradation (&ref, e); if ((0 != strcmp (expected.d, ref.d)) && (! degraded)) { /* Either the default connection memory pool is in use, or the deviation does not look like a resource limitation: in both cases the corpus entry must match its declared expectations exactly. */ report_failure (e, "unsplit run does not match the expectations", expected.d, ref.d); /* The reference is useless as a comparison base now; keep checking the split runs against the declared expectations so that the report names the concrete split offsets that are affected. */ ref_bad = 1; } else if (degraded) { combos_pool_limited++; if (! check_relaxed (&expected, &ref)) { report_failure (e, "unsplit run with a small memory pool parsed a request " "differently than expected", expected.d, ref.d); return; } if (verbose) { printf (" %-22s degraded by the memory pool, relaxed checking\n", e->name); fflush (stdout); } } /* Derive the read strategy for the split runs from the reference run, so that the split runs never have to wait for a timeout. */ ref_resp = 0; if (1) { const char *p = strstr (ref.d, "nresp="); if (NULL != p) ref_resp = (unsigned int) strtoul (p + 6, NULL, 10); } if (! degraded) { const char *p = strstr (ref.d, "closed="); min_resp = ref_resp; want_close = (NULL != p) ? ('0' != p[7]) : 0; stride = 1; } else { /* The client side numbers are not reproducible under memory pressure; stop as soon as the first reply is complete (or as soon as MHD closes the connection if it does not reply at all) and only compare the server side observations. */ min_resp = (0 != ref_resp) ? 1 : 0; want_close = (0 != ref_resp) ? 0 : 1; stride = 3; /* Sample: these runs are slower and less informative */ } cmp = ref_bad ? &expected : &ref; /* 2) Two-way splits. */ offs = (size_t *) malloc (sizeof (size_t) * (len + 1)); if (NULL == offs) externalErrorExitDesc ("malloc() failed"); n_offs = build_split_offsets (len, offs, (unsigned int) len + 1); for (i = 0; i < n_offs; i += stride) { snprintf (cur_split, sizeof (cur_split), "%u", (unsigned int) offs[i]); run_stream (e, offs + i, 1, min_resp, want_close, 0, &got); combos++; (*split_counter)++; if (degraded) { combos_pool_limited++; if ((! check_relaxed (&expected, &got)) || (! status_acceptable_degraded (&got, e)) || (NULL != strstr (got.d, "TIMED_OUT"))) report_failure (e, "split point with a small memory pool parsed a " "request differently than expected", expected.d, got.d); } else if (0 != strcmp (cmp->d, got.d)) report_failure (e, ref_bad ? "split point does not match the expectations" : "split point yields a different parse than the " "unsplit run", cmp->d, got.d); if (MAX_FAILURES < failures) { free (offs); return; } } /* 3) Three-way splits for the marked entries. */ if (e->deep && deep_enabled && (! degraded) && (2 < len)) { unsigned int done = 0; unsigned int a; const unsigned int step = (unsigned int) (((len * len) / (2 * DEEP_SPLIT_MAX)) + 1); unsigned int ctr = 0; for (a = 1; (a + 1 < (unsigned int) len) && (done < DEEP_SPLIT_MAX); ++a) { unsigned int b; for (b = a + 1; (b < (unsigned int) len) && (done < DEEP_SPLIT_MAX); ++b) { size_t two[2]; if (0 != (ctr++ % step)) continue; two[0] = a; two[1] = b; snprintf (cur_split, sizeof (cur_split), "%u+%u", a, b); run_stream (e, two, 2, min_resp, want_close, 0, &got); combos++; (*split_counter)++; done++; if (0 != strcmp (cmp->d, got.d)) report_failure (e, ref_bad ? "three-way split does not match the expectations" : "three-way split yields a different parse than " "the unsplit run", cmp->d, got.d); if (MAX_FAILURES < failures) { free (offs); return; } } } } free (offs); } int main (int argc, char *const *argv) { const uint64_t t_start = now_ms (); unsigned int mi; int i; const char *only = NULL; unsigned long total_splits = 0; size_t sweep[MEM_LIMITS_SIZE]; unsigned int sweep_size; unsigned long entries_skipped = 0; for (i = 1; i < argc; ++i) { if ((0 == strcmp (argv[i], "-v")) || (0 == strcmp (argv[i], "--verbose"))) verbose++; else if (0 == strncmp (argv[i], "--entry=", 8)) only = argv[i] + 8; else if ('-' != argv[i][0]) only = argv[i]; } strcpy (cur_split, "(not started)"); #if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE)) { if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) externalErrorExitDesc ("Error suppressing SIGPIPE signal"); } #endif /* HAVE_SIGNAL_H && SIGPIPE */ #if defined(HAVE_SIGNAL_H) && defined(SIGABRT) (void) signal (SIGABRT, &abort_handler); #endif /* HAVE_SIGNAL_H && SIGABRT */ /* Deliberately NOT mhd_panic_tripwire.h: this test installs its own panic and SIGABRT handlers, which print the failing input and the daemon options along with the diagnostic. That context is worth more here than the generic tripwire, and the two would collide (whichever runs last wins). See TESTING.md, P5. */ MHD_set_panic_func (&test_panic, NULL); mhd_opt_matrix_print_notice ("test_raw_requests"); test_prof = mhd_opt_matrix_from_env (); if (NULL != test_prof) { char desc[256]; test_prof_copy = *test_prof; test_prof = &test_prof_copy; if (! mhd_opt_matrix_profile_supported (test_prof)) { printf ("test_raw_requests: the selected profile %s is not supported " "by this build, the test is skipped.\n", mhd_opt_matrix_describe (test_prof, desc, sizeof (desc))); return 77; } /* One profile pins one memory limit; the built-in sweep is replaced. */ sweep[0] = test_prof_copy.mem_limit; sweep_size = 1; } else { for (mi = 0; mi < MEM_LIMITS_SIZE; ++mi) sweep[mi] = mem_limits[mi]; sweep_size = (unsigned int) MEM_LIMITS_SIZE; } test_discp = mhd_opt_matrix_effective_discipline (test_prof); for (mi = 0; mi < sweep_size; ++mi) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; size_t ci; cur_mem_limit = sweep[mi]; /* The three-way split pass is expensive; run it for the smallest pool size that is not permanently degraded and for the default pool. */ deep_enabled = ((1 == sweep_size) || (1 == mi) || (sweep_size - 1 == mi)); conn_started = 0; conn_closed = 0; d = start_daemon_with_limit (cur_mem_limit); if (NULL == d) { fprintf (stderr, "Failed to start the daemon with memory limit %u.\n", (unsigned int) cur_mem_limit); return 99; } dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port)) { MHD_stop_daemon (d); fprintf (stderr, "Cannot get the daemon port.\n"); return 99; } global_port = dinfo->port; if (verbose) { printf ("--- connection memory limit: "); if (0 == cur_mem_limit) printf ("default ---\n"); else printf ("%u ---\n", (unsigned int) cur_mem_limit); fflush (stdout); } for (ci = 0; ci < CORPUS_SIZE; ++ci) { unsigned long before = total_splits; if ((NULL != only) && (0 != strcmp (only, corpus[ci].name))) continue; if (! entry_in_discp_range (corpus[ci].name)) { entries_skipped++; if (verbose) printf (" %-22s skipped: its expectation is only valid for a " "different client discipline level\n", corpus[ci].name); continue; } run_entry (&corpus[ci], &total_splits); if (1 < verbose) { printf (" %-22s %lu runs\n", corpus[ci].name, total_splits - before); fflush (stdout); } if (MAX_FAILURES < failures) break; } MHD_stop_daemon (d); cur_entry = NULL; if (MAX_FAILURES < failures) break; } printf ("\ntest_raw_requests: %u corpus entries, %u memory limits, " "%lu combinations executed (%lu pool-limited, %lu entry runs " "skipped as out of the discipline range), %.1f s\n", (unsigned int) ((NULL == only) ? CORPUS_SIZE : 1), sweep_size, combos, combos_pool_limited, entries_skipped, (double) (now_ms () - t_start) / 1000.0); if (0 != failures) { printf ("test_raw_requests: FAILED (%lu failure(s))\n", failures); fflush (stdout); return 1; } printf ("test_raw_requests: PASSED\n"); fflush (stdout); return 0; } libmicrohttpd-1.0.10/src/microhttpd/test_sha1.c0000664000175000017500000003775015232103064015133 /* This file is part of libmicrohttpd Copyright (C) 2019-2021 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_sha1.h * @brief Unit tests for SHA-1 functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "sha1.h" #include "test_helpers.h" #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static int verbose = 0; /* verbose level (0-1)*/ struct str_with_len { const char *const str; const size_t len; }; #define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1} struct data_unit1 { const struct str_with_len str_l; const uint8_t digest[SHA1_DIGEST_SIZE]; }; static const struct data_unit1 data_units1[] = { {D_STR_W_LEN ("abc"), {0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D}}, {D_STR_W_LEN ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), {0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE, 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1}}, {D_STR_W_LEN (""), {0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09}}, {D_STR_W_LEN ("The quick brown fox jumps over the lazy dog"), {0x2f, 0xd4, 0xe1, 0xc6, 0x7a, 0x2d, 0x28, 0xfc, 0xed, 0x84, 0x9e, 0xe1, 0xbb, 0x76, 0xe7, 0x39, 0x1b, 0x93, 0xeb, 0x12}}, {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), {0xa7, 0x08, 0x9e, 0x3d, 0xe1, 0x6b, 0x63, 0xa3, 0x2a, 0x43, 0xa5, 0xe7, 0xf3, 0xb5, 0x4f, 0x80, 0x6a, 0xc8, 0x4f, 0x53}}, {D_STR_W_LEN ("Simple string."), {0x6c, 0x6c, 0x9c, 0xef, 0x53, 0xff, 0x22, 0x39, 0x0c, 0x54, 0xc7, 0xba, 0x6d, 0x98, 0xe0, 0xd5, 0x6c, 0x24, 0x0d, 0x55}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), {0x32, 0xd1, 0x0c, 0x7b, 0x8c, 0xf9, 0x65, 0x70, 0xca, 0x04, 0xce, 0x37, 0xf2, 0xa1, 0x9d, 0x84, 0x24, 0x0d, 0x3a, 0x89}}, {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"), {0x59, 0x0f, 0xc8, 0xea, 0xde, 0xa2, 0x78, 0x65, 0x5a, 0xf2, 0xa1, 0xe5, 0xb4, 0xc9, 0x61, 0xa4, 0x3a, 0xc3, 0x6a, 0x83}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"), {0xa7, 0x87, 0x4c, 0x16, 0xc0, 0x4e, 0xd6, 0x24, 0x5f, 0x25, 0xbe, 0x06, 0x7b, 0x1b, 0x6b, 0xaf, 0xf4, 0x0e, 0x74, 0x0b}}, }; static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]); struct bin_with_len { const uint8_t bin[512]; const size_t len; }; struct data_unit2 { const struct bin_with_len bin_l; const uint8_t digest[SHA1_DIGEST_SIZE]; }; /* Size must be less than 512 bytes! */ static const struct data_unit2 data_units2[] = { { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */ {0x32, 0xd1, 0x0c, 0x7b, 0x8c, 0xf9, 0x65, 0x70, 0xca, 0x04, 0xce, 0x37, 0xf2, 0xa1, 0x9d, 0x84, 0x24, 0x0d, 0x3a, 0x89}}, { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65}, 72 }, /* 'A' x 72 times */ {0x41, 0xf9, 0x07, 0x05, 0x04, 0xf9, 0xc8, 0x1a, 0xbf, 0xbb, 0x61, 0x4d, 0xaa, 0xec, 0x3b, 0x26, 0xa2, 0xf9, 0x23, 0x7e}}, { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,43, 44, 45, 46, 47, 48, 49, 50, 51, 52,53, 54, 55, 56, 57, 58, 59, 60,61, 62, 63, 64, 65, 66, 67,68, 69, 70, 71, 72, 73}, 55}, /* 19..73 sequence */ {0xf2, 0x50, 0xb2, 0x79, 0x62, 0xcc, 0xff, 0x4b, 0x1b, 0x61, 0x4a, 0x6f, 0x80, 0xec, 0x9b, 0x4d, 0xd0, 0xc0, 0xfb, 0x7b}}, { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,32, 33, 34, 35, 36, 37, 38, 39, 40, 41,42, 43, 44, 45, 46, 47, 48, 49,50, 51, 52, 53, 54, 55, 56,57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */ {0xf0, 0xa3, 0xfc, 0x4b, 0x90, 0x6f, 0x1b, 0x41, 0x68, 0xc8, 0x3e, 0x05, 0xb0, 0xc5, 0xac, 0xb7, 0x3d, 0xcd, 0x6b, 0x0f}}, { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,62, 63, 64, 65, 66, 67, 68, 69, 70, 71,72, 73, 74, 75, 76, 77, 78, 79,80, 81, 82, 83, 84, 85, 86,87, 88, 89, 90, 91, 92}, 55}, /* 38..92 sequence */ {0x93, 0xa4, 0x9c, 0x5f, 0xda, 0x22, 0x63, 0x73, 0x85, 0xeb, 0x70, 0xd2, 0x00, 0x52, 0x0c, 0xb0, 0x2e, 0x86, 0x9b, 0xa0 }}, { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,37, 38, 39, 40, 41, 42, 43, 44, 45,46, 47, 48, 49, 50, 51, 52,53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,71, 72},72}, /* 1..72 sequence */ {0x8b, 0x30, 0xd3, 0x41, 0x89, 0xb6, 0x1b, 0x66, 0x5a, 0x1a, 0x9a, 0x51, 0x64, 0x93, 0xab, 0x5e, 0x78, 0x81, 0x52, 0xb5}}, { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140,141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154,155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167,168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180,181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220,221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234,235, 236, 237, 238, 239, 240,241, 242, 243, 244, 245, 246, 247,248, 249, 250, 251, 252, 253, 254, 255}, 256}, /* 0..255 sequence */ {0x49, 0x16, 0xd6, 0xbd, 0xb7, 0xf7, 0x8e, 0x68, 0x03, 0x69, 0x8c, 0xab, 0x32, 0xd1, 0x58, 0x6e, 0xa4, 0x57, 0xdf, 0xc8}}, { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186,185, 184, 183, 182, 181, 180,179, 178, 177, 176, 175, 174, 173,172, 171, 170, 169, 168, 167, 166,165, 164, 163, 162, 161, 160,159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146,145, 144, 143, 142, 141, 140,139}, 61}, /* 199..139 sequence */ {0xb3, 0xec, 0x61, 0x3c, 0xf7, 0x36, 0x57, 0x94, 0x61, 0xdb, 0xb2, 0x16, 0x75, 0xfe, 0x34, 0x60, 0x99, 0x94, 0xb5, 0xfc}}, { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255}, /* 255..1 sequence */ {0x99, 0x1d, 0xc6, 0x95, 0xe1, 0xaa, 0xcc, 0xc9, 0x35, 0x60, 0xbe, 0xe3, 0xe2, 0x41, 0x2b, 0xa7, 0xab, 0x49, 0x32, 0xf7}}, { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233, 235, 179, 166, 219, 60, 135, 12, 62, 153, 36, 94, 13, 28, 6, 183, 71, 222, 179, 18, 77, 200, 67, 187, 139, 166, 31, 3, 90, 125, 9, 56, 37, 31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28, 219, 174, 50, 32, 154, 80, 238, 64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220, 173, 79, 20, 242, 68, 64, 102, 208, 107, 196, 48, 183, 50, 59, 161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202, 153, 2, 185, 114, 157, 73, 44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191, 103, 214, 191, 20, 214, 126, 45, 220, 142, 102, 131, 239, 87, 73, 97, 255, 105, 143, 97, 205, 209, 30, 157, 156, 22, 114, 114, 230, 29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51, 116, 158, 12, 244, 213, 212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244, 204, 207, 211, 144, 45, 72, 211, 143, 117, 230, 217, 29, 42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212, 97, 141, 190, 123, 5, 21, 7, 59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62, 105, 21, 248, 70, 106, 4, 150, 115, 14, 217, 22, 47, 103, 104, 212, 247, 74, 74, 208, 87, 104}, 255}, /* pseudo-random data */ {0x9e, 0xb6, 0xce, 0x48, 0xf4, 0x6e, 0x9c, 0xf4, 0x1b, 0x4f, 0x9f, 0x66, 0xdd, 0xe8, 0x41, 0x01, 0x71, 0xf6, 0xf5, 0xd6}} }; static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]); /* * Helper functions */ /** * Print bin as hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0')); } *hex = 0; } static int check_result (const char *test_name, unsigned int check_num, const uint8_t calculated[SHA1_DIGEST_SIZE], const uint8_t expected[SHA1_DIGEST_SIZE]) { int failed = memcmp (calculated, expected, SHA1_DIGEST_SIZE); check_num++; /* Print 1-based numbers */ if (failed) { char calc_str[SHA1_DIGEST_STRING_SIZE]; char expc_str[SHA1_DIGEST_STRING_SIZE]; bin2hex (calculated, SHA1_DIGEST_SIZE, calc_str); bin2hex (expected, SHA1_DIGEST_SIZE, expc_str); fprintf (stderr, "FAILED: %s check %u: calculated digest %s, expected digest %s.\n", test_name, check_num, calc_str, expc_str); fflush (stderr); } else if (verbose) { char calc_str[SHA1_DIGEST_STRING_SIZE]; bin2hex (calculated, SHA1_DIGEST_SIZE, calc_str); printf ("PASSED: %s check %u: calculated digest %s matches " \ "expected digest.\n", test_name, check_num, calc_str); fflush (stdout); } return failed ? 1 : 0; } /* * Tests */ /* Calculated SHA-256 as one pass for whole data */ static int test1_str (void) { int num_failed = 0; unsigned int i; for (i = 0; i < units1_num; i++) { struct sha1_ctx ctx; uint8_t digest[SHA1_DIGEST_SIZE]; MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, data_units1[i].str_l.len); MHD_SHA1_finish (&ctx, digest); num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } return num_failed; } static int test1_bin (void) { int num_failed = 0; unsigned int i; for (i = 0; i < units2_num; i++) { struct sha1_ctx ctx; uint8_t digest[SHA1_DIGEST_SIZE]; MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, data_units2[i].bin_l.bin, data_units2[i].bin_l.len); MHD_SHA1_finish (&ctx, digest); num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } return num_failed; } /* Calculated SHA-256 as two iterations for whole data */ static int test2_str (void) { int num_failed = 0; unsigned int i; for (i = 0; i < units1_num; i++) { struct sha1_ctx ctx; uint8_t digest[SHA1_DIGEST_SIZE]; size_t part_s = data_units1[i].str_l.len / 4; MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, part_s); MHD_SHA1_update (&ctx, (const uint8_t *) data_units1[i].str_l.str + part_s, data_units1[i].str_l.len - part_s); MHD_SHA1_finish (&ctx, digest); num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } return num_failed; } static int test2_bin (void) { int num_failed = 0; unsigned int i; for (i = 0; i < units2_num; i++) { struct sha1_ctx ctx; uint8_t digest[SHA1_DIGEST_SIZE]; size_t part_s = data_units2[i].bin_l.len * 2 / 3; MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, data_units2[i].bin_l.bin, part_s); MHD_SHA1_update (&ctx, data_units2[i].bin_l.bin + part_s, data_units2[i].bin_l.len - part_s); MHD_SHA1_finish (&ctx, digest); num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } return num_failed; } /* Use data set number 7 as it has the longest sequence */ #define DATA_POS 6 #define MAX_OFFSET 31 static int test_unaligned (void) { int num_failed = 0; unsigned int offset; uint8_t *buf; uint8_t *digest_buf; const struct data_unit2 *const tdata = data_units2 + DATA_POS; buf = malloc (tdata->bin_l.len + MAX_OFFSET); digest_buf = malloc (SHA1_DIGEST_SIZE + MAX_OFFSET); if ((NULL == buf) || (NULL == digest_buf)) exit (99); for (offset = MAX_OFFSET; offset >= 1; --offset) { struct sha1_ctx ctx; uint8_t *unaligned_digest; uint8_t *unaligned_buf; unaligned_buf = buf + offset; memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len); unaligned_digest = digest_buf + MAX_OFFSET - offset; memset (unaligned_digest, 0, SHA1_DIGEST_SIZE); MHD_SHA1_init (&ctx); MHD_SHA1_update (&ctx, unaligned_buf, tdata->bin_l.len); MHD_SHA1_finish (&ctx, unaligned_digest); num_failed += check_result (MHD_FUNC_, MAX_OFFSET - offset, unaligned_digest, tdata->digest); } free (digest_buf); free (buf); return num_failed; } int main (int argc, char *argv[]) { int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose")) verbose = 1; num_failed += test1_str (); num_failed += test1_bin (); num_failed += test2_str (); num_failed += test2_bin (); num_failed += test_unaligned (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.10/src/microhttpd/mhd_panic.c0000644000175000017500000000577214760713574015201 /* This file is part of libmicrohttpd Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_panic.h * @brief MHD_panic() function and helpers * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "mhd_panic.h" #include "platform.h" #include "microhttpd.h" /** * Handler for fatal errors. */ MHD_PanicCallback mhd_panic = (MHD_PanicCallback) NULL; /** * Closure argument for #mhd_panic. */ void *mhd_panic_cls = NULL; /** * Default implementation of the panic function, * prints an error message and aborts. * * @param cls unused * @param file name of the file with the problem * @param line line number with the problem * @param reason error message with details */ _MHD_NORETURN static void mhd_panic_std (void *cls, const char *file, unsigned int line, const char *reason) { (void) cls; /* Mute compiler warning. */ #ifdef HAVE_MESSAGES fprintf (stderr, _ ("Fatal error in GNU libmicrohttpd %s:%u: %s\n"), file, line, reason); #else /* ! HAVE_MESSAGES */ (void) file; /* Mute compiler warning. */ (void) line; /* Mute compiler warning. */ (void) reason; /* Mute compiler warning. */ #endif abort (); } /** * Sets the global error handler to a different implementation. * * @a cb will only be called in the case of typically fatal, serious internal * consistency issues or serious system failures like failed lock of mutex. * * These issues should only arise in the case of serious memory corruption or * similar problems with the architecture, there is no safe way to continue * even for closing of the application. * * The default implementation that is used if no panic function is set simply * prints an error message and calls `abort()`. * Alternative implementations might call `exit()` or other similar functions. * * @param cb new error handler or NULL to use default handler * @param cls passed to @a cb * @ingroup logging */ _MHD_EXTERN void MHD_set_panic_func (MHD_PanicCallback cb, void *cls) { if ((MHD_PanicCallback) NULL != cb) mhd_panic = cb; else mhd_panic = &mhd_panic_std; mhd_panic_cls = cls; } libmicrohttpd-1.0.10/src/microhttpd/test_postprocessor_large.c0000664000175000017500000000722615232103064020371 /* This file is part of libmicrohttpd Copyright (C) 2008 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_postprocessor_large.c * @brief Testcase with very large input for postprocessor * @author Christian Grothoff */ #include "platform.h" #include "microhttpd.h" #include "internal.h" #include "mhd_compat.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif static enum MHD_Result value_checker (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { size_t *pos = (size_t *) cls; (void) kind; (void) key; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; (void) data; (void) off; /* Unused. Silent compiler warning. */ #if 0 fprintf (stderr, "VC: %" PRIu64 " %u `%s' `%s' `%s' `%s' `%.*s'\n", off, size, key, filename, content_type, transfer_encoding, size, data); #endif if (size == 0) return MHD_YES; *pos += size; return MHD_YES; } static unsigned int test_simple_large (void) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; size_t i; size_t delta; size_t size; char data[102400]; size_t pos; pos = 0; memset (data, 'A', sizeof (data)); memcpy (data, "key=", 4); data[sizeof (data) - 1] = '\0'; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.header_size = strlen (header.header); header.value_size = strlen (header.value); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 1024, &value_checker, &pos); i = 0; size = strlen (data); while (i < size) { delta = 1 + ((size_t) MHD_random_ ()) % (size - i); if (MHD_YES != MHD_post_process (pp, &data[i], delta)) { fprintf (stderr, "MHD_post_process() failed!\n"); MHD_destroy_post_processor (pp); return 1; } i += delta; } MHD_destroy_post_processor (pp); if (pos != sizeof (data) - 5) /* minus 0-termination and 'key=' */ return 1; return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errorCount += test_simple_large (); if (errorCount != 0) fprintf (stderr, "Error (code: %u)\n", errorCount); return errorCount != 0; /* 0 == pass */ } libmicrohttpd-1.0.10/src/microhttpd/md5.c0000644000175000017500000005076515035214301013722 /* This file is part of GNU libmicrohttpd Copyright (C) 2022-2023 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/md5.c * @brief Calculation of MD5 digest as defined in RFC 1321 * @author Karlson2k (Evgeny Grin) */ #include "md5.h" #include #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #include "mhd_bithelpers.h" #include "mhd_assert.h" /** * Initialise structure for MD5 calculation. * * @param ctx the calculation context */ void MHD_MD5_init (struct Md5Ctx *ctx) { /* Initial hash values, see RFC 1321, Clause 3.3 (step 3). */ /* Note: values specified in RFC by bytes and should be loaded in little-endian mode, therefore hash values here are initialised with original bytes used in little-endian order. */ ctx->H[0] = UINT32_C (0x67452301); ctx->H[1] = UINT32_C (0xefcdab89); ctx->H[2] = UINT32_C (0x98badcfe); ctx->H[3] = UINT32_C (0x10325476); /* Initialise the number of bytes. */ ctx->count = 0; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /** * Base of MD5 transformation. * Gets full 64 bytes block of data and updates hash values; * @param H hash values * @param M the data buffer with #MD5_BLOCK_SIZE bytes block */ static void md5_transform (uint32_t H[MD5_HASH_SIZE_WORDS], const void *M) { /* Working variables, See RFC 1321, Clause 3.4 (step 4). */ uint32_t A = H[0]; uint32_t B = H[1]; uint32_t C = H[2]; uint32_t D = H[3]; /* The data buffer. See RFC 1321, Clause 3.4 (step 4). */ uint32_t X[16]; #ifndef _MHD_GET_32BIT_LE_UNALIGNED if (0 != (((uintptr_t) M) % _MHD_UINT32_ALIGN)) { /* The input data is unaligned. */ /* Copy the unaligned input data to the aligned buffer. */ memcpy (X, M, sizeof(X)); /* The X[] buffer itself will be used as the source of the data, * but the data will be reloaded in correct bytes order on * the next steps. */ M = (const void *) X; } #endif /* _MHD_GET_32BIT_LE_UNALIGNED */ /* Four auxiliary functions, see RFC 1321, Clause 3.4 (step 4). */ /* Some optimisations used. */ /* #define F_FUNC(x,y,z) (((x)&(y)) | ((~(x))&(z))) */ /* Original version */ #define F_FUNC(x,y,z) ((((y) ^ (z)) & (x)) ^ (z)) /* #define G_FUNC_1(x,y,z) (((x)&(z)) | ((y)&(~(z)))) */ /* Original version */ /* #define G_FUNC_2(x,y,z) UINT32_C(0) */ /* Original version */ #ifndef MHD_FAVOR_SMALL_CODE # define G_FUNC_1(x,y,z) ((~(z)) & (y)) # define G_FUNC_2(x,y,z) ((z) & (x)) #else /* MHD_FAVOR_SMALL_CODE */ # define G_FUNC_1(x,y,z) ((((x) ^ (y)) & (z)) ^ (y)) # define G_FUNC_2(x,y,z) UINT32_C(0) #endif /* MHD_FAVOR_SMALL_CODE */ #define H_FUNC(x,y,z) ((x) ^ (y) ^ (z)) /* Original version */ /* #define I_FUNC(x,y,z) ((y) ^ ((x) | (~(z)))) */ /* Original version */ #define I_FUNC(x,y,z) (((~(z)) | (x)) ^ (y)) /* One step of round 1 of MD5 computation, see RFC 1321, Clause 3.4 (step 4). The original function was modified to use X[k] and T[i] as direct inputs. */ #define MD5STEP_R1(va,vb,vc,vd,vX,vs,vT) do { \ (va) += (vX) + (vT); \ (va) += F_FUNC((vb),(vc),(vd)); \ (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0) /* Get value of X(k) from input data buffer. See RFC 1321 Clause 3.4 (step 4). */ #define GET_X_FROM_DATA(buf,t) \ _MHD_GET_32BIT_LE (((const uint32_t*) (buf)) + (t)) /* One step of round 2 of MD5 computation, see RFC 1321, Clause 3.4 (step 4). The original function was modified to use X[k] and T[i] as direct inputs. */ #define MD5STEP_R2(va,vb,vc,vd,vX,vs,vT) do { \ (va) += (vX) + (vT); \ (va) += G_FUNC_1((vb),(vc),(vd)); \ (va) += G_FUNC_2((vb),(vc),(vd)); \ (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0) /* One step of round 3 of MD5 computation, see RFC 1321, Clause 3.4 (step 4). The original function was modified to use X[k] and T[i] as direct inputs. */ #define MD5STEP_R3(va,vb,vc,vd,vX,vs,vT) do { \ (va) += (vX) + (vT); \ (va) += H_FUNC((vb),(vc),(vd)); \ (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0) /* One step of round 4 of MD5 computation, see RFC 1321, Clause 3.4 (step 4). The original function was modified to use X[k] and T[i] as direct inputs. */ #define MD5STEP_R4(va,vb,vc,vd,vX,vs,vT) do { \ (va) += (vX) + (vT); \ (va) += I_FUNC((vb),(vc),(vd)); \ (va) = _MHD_ROTL32((va),(vs)) + (vb); } while (0) #if ! defined(MHD_FAVOR_SMALL_CODE) /* Round 1. */ #if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN if ((const void *) X == M) { /* The input data is already in the data buffer X[] in correct bytes order. */ MD5STEP_R1 (A, B, C, D, X[0], 7, UINT32_C (0xd76aa478)); MD5STEP_R1 (D, A, B, C, X[1], 12, UINT32_C (0xe8c7b756)); MD5STEP_R1 (C, D, A, B, X[2], 17, UINT32_C (0x242070db)); MD5STEP_R1 (B, C, D, A, X[3], 22, UINT32_C (0xc1bdceee)); MD5STEP_R1 (A, B, C, D, X[4], 7, UINT32_C (0xf57c0faf)); MD5STEP_R1 (D, A, B, C, X[5], 12, UINT32_C (0x4787c62a)); MD5STEP_R1 (C, D, A, B, X[6], 17, UINT32_C (0xa8304613)); MD5STEP_R1 (B, C, D, A, X[7], 22, UINT32_C (0xfd469501)); MD5STEP_R1 (A, B, C, D, X[8], 7, UINT32_C (0x698098d8)); MD5STEP_R1 (D, A, B, C, X[9], 12, UINT32_C (0x8b44f7af)); MD5STEP_R1 (C, D, A, B, X[10], 17, UINT32_C (0xffff5bb1)); MD5STEP_R1 (B, C, D, A, X[11], 22, UINT32_C (0x895cd7be)); MD5STEP_R1 (A, B, C, D, X[12], 7, UINT32_C (0x6b901122)); MD5STEP_R1 (D, A, B, C, X[13], 12, UINT32_C (0xfd987193)); MD5STEP_R1 (C, D, A, B, X[14], 17, UINT32_C (0xa679438e)); MD5STEP_R1 (B, C, D, A, X[15], 22, UINT32_C (0x49b40821)); } else /* Combined with the next 'if' */ #endif /* _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN */ if (1) { /* The input data is loaded in correct (little-endian) format before calculations on each step. */ MD5STEP_R1 (A, B, C, D, X[0] = GET_X_FROM_DATA (M, 0), 7, \ UINT32_C (0xd76aa478)); MD5STEP_R1 (D, A, B, C, X[1] = GET_X_FROM_DATA (M, 1), 12, \ UINT32_C (0xe8c7b756)); MD5STEP_R1 (C, D, A, B, X[2] = GET_X_FROM_DATA (M, 2), 17, \ UINT32_C (0x242070db)); MD5STEP_R1 (B, C, D, A, X[3] = GET_X_FROM_DATA (M, 3), 22, \ UINT32_C (0xc1bdceee)); MD5STEP_R1 (A, B, C, D, X[4] = GET_X_FROM_DATA (M, 4), 7, \ UINT32_C (0xf57c0faf)); MD5STEP_R1 (D, A, B, C, X[5] = GET_X_FROM_DATA (M, 5), 12, \ UINT32_C (0x4787c62a)); MD5STEP_R1 (C, D, A, B, X[6] = GET_X_FROM_DATA (M, 6), 17, \ UINT32_C (0xa8304613)); MD5STEP_R1 (B, C, D, A, X[7] = GET_X_FROM_DATA (M, 7), 22, \ UINT32_C (0xfd469501)); MD5STEP_R1 (A, B, C, D, X[8] = GET_X_FROM_DATA (M, 8), 7, \ UINT32_C (0x698098d8)); MD5STEP_R1 (D, A, B, C, X[9] = GET_X_FROM_DATA (M, 9), 12, \ UINT32_C (0x8b44f7af)); MD5STEP_R1 (C, D, A, B, X[10] = GET_X_FROM_DATA (M, 10), 17, \ UINT32_C (0xffff5bb1)); MD5STEP_R1 (B, C, D, A, X[11] = GET_X_FROM_DATA (M, 11), 22, \ UINT32_C (0x895cd7be)); MD5STEP_R1 (A, B, C, D, X[12] = GET_X_FROM_DATA (M, 12), 7, \ UINT32_C (0x6b901122)); MD5STEP_R1 (D, A, B, C, X[13] = GET_X_FROM_DATA (M, 13), 12, \ UINT32_C (0xfd987193)); MD5STEP_R1 (C, D, A, B, X[14] = GET_X_FROM_DATA (M, 14), 17, \ UINT32_C (0xa679438e)); MD5STEP_R1 (B, C, D, A, X[15] = GET_X_FROM_DATA (M, 15), 22, \ UINT32_C (0x49b40821)); } /* Round 2. */ MD5STEP_R2 (A, B, C, D, X[1], 5, UINT32_C (0xf61e2562)); MD5STEP_R2 (D, A, B, C, X[6], 9, UINT32_C (0xc040b340)); MD5STEP_R2 (C, D, A, B, X[11], 14, UINT32_C (0x265e5a51)); MD5STEP_R2 (B, C, D, A, X[0], 20, UINT32_C (0xe9b6c7aa)); MD5STEP_R2 (A, B, C, D, X[5], 5, UINT32_C (0xd62f105d)); MD5STEP_R2 (D, A, B, C, X[10], 9, UINT32_C (0x02441453)); MD5STEP_R2 (C, D, A, B, X[15], 14, UINT32_C (0xd8a1e681)); MD5STEP_R2 (B, C, D, A, X[4], 20, UINT32_C (0xe7d3fbc8)); MD5STEP_R2 (A, B, C, D, X[9], 5, UINT32_C (0x21e1cde6)); MD5STEP_R2 (D, A, B, C, X[14], 9, UINT32_C (0xc33707d6)); MD5STEP_R2 (C, D, A, B, X[3], 14, UINT32_C (0xf4d50d87)); MD5STEP_R2 (B, C, D, A, X[8], 20, UINT32_C (0x455a14ed)); MD5STEP_R2 (A, B, C, D, X[13], 5, UINT32_C (0xa9e3e905)); MD5STEP_R2 (D, A, B, C, X[2], 9, UINT32_C (0xfcefa3f8)); MD5STEP_R2 (C, D, A, B, X[7], 14, UINT32_C (0x676f02d9)); MD5STEP_R2 (B, C, D, A, X[12], 20, UINT32_C (0x8d2a4c8a)); /* Round 3. */ MD5STEP_R3 (A, B, C, D, X[5], 4, UINT32_C (0xfffa3942)); MD5STEP_R3 (D, A, B, C, X[8], 11, UINT32_C (0x8771f681)); MD5STEP_R3 (C, D, A, B, X[11], 16, UINT32_C (0x6d9d6122)); MD5STEP_R3 (B, C, D, A, X[14], 23, UINT32_C (0xfde5380c)); MD5STEP_R3 (A, B, C, D, X[1], 4, UINT32_C (0xa4beea44)); MD5STEP_R3 (D, A, B, C, X[4], 11, UINT32_C (0x4bdecfa9)); MD5STEP_R3 (C, D, A, B, X[7], 16, UINT32_C (0xf6bb4b60)); MD5STEP_R3 (B, C, D, A, X[10], 23, UINT32_C (0xbebfbc70)); MD5STEP_R3 (A, B, C, D, X[13], 4, UINT32_C (0x289b7ec6)); MD5STEP_R3 (D, A, B, C, X[0], 11, UINT32_C (0xeaa127fa)); MD5STEP_R3 (C, D, A, B, X[3], 16, UINT32_C (0xd4ef3085)); MD5STEP_R3 (B, C, D, A, X[6], 23, UINT32_C (0x04881d05)); MD5STEP_R3 (A, B, C, D, X[9], 4, UINT32_C (0xd9d4d039)); MD5STEP_R3 (D, A, B, C, X[12], 11, UINT32_C (0xe6db99e5)); MD5STEP_R3 (C, D, A, B, X[15], 16, UINT32_C (0x1fa27cf8)); MD5STEP_R3 (B, C, D, A, X[2], 23, UINT32_C (0xc4ac5665)); /* Round 4. */ MD5STEP_R4 (A, B, C, D, X[0], 6, UINT32_C (0xf4292244)); MD5STEP_R4 (D, A, B, C, X[7], 10, UINT32_C (0x432aff97)); MD5STEP_R4 (C, D, A, B, X[14], 15, UINT32_C (0xab9423a7)); MD5STEP_R4 (B, C, D, A, X[5], 21, UINT32_C (0xfc93a039)); MD5STEP_R4 (A, B, C, D, X[12], 6, UINT32_C (0x655b59c3)); MD5STEP_R4 (D, A, B, C, X[3], 10, UINT32_C (0x8f0ccc92)); MD5STEP_R4 (C, D, A, B, X[10], 15, UINT32_C (0xffeff47d)); MD5STEP_R4 (B, C, D, A, X[1], 21, UINT32_C (0x85845dd1)); MD5STEP_R4 (A, B, C, D, X[8], 6, UINT32_C (0x6fa87e4f)); MD5STEP_R4 (D, A, B, C, X[15], 10, UINT32_C (0xfe2ce6e0)); MD5STEP_R4 (C, D, A, B, X[6], 15, UINT32_C (0xa3014314)); MD5STEP_R4 (B, C, D, A, X[13], 21, UINT32_C (0x4e0811a1)); MD5STEP_R4 (A, B, C, D, X[4], 6, UINT32_C (0xf7537e82)); MD5STEP_R4 (D, A, B, C, X[11], 10, UINT32_C (0xbd3af235)); MD5STEP_R4 (C, D, A, B, X[2], 15, UINT32_C (0x2ad7d2bb)); MD5STEP_R4 (B, C, D, A, X[9], 21, UINT32_C (0xeb86d391)); #else /* MHD_FAVOR_SMALL_CODE */ if (1) { static const uint32_t T[64] = { UINT32_C (0xd76aa478), UINT32_C (0xe8c7b756), UINT32_C (0x242070db), UINT32_C (0xc1bdceee), UINT32_C (0xf57c0faf), UINT32_C (0x4787c62a), UINT32_C (0xa8304613), UINT32_C (0xfd469501), UINT32_C (0x698098d8), UINT32_C (0x8b44f7af), UINT32_C (0xffff5bb1), UINT32_C (0x895cd7be), UINT32_C (0x6b901122), UINT32_C (0xfd987193), UINT32_C (0xa679438e), UINT32_C (0x49b40821), UINT32_C (0xf61e2562), UINT32_C (0xc040b340), UINT32_C (0x265e5a51), UINT32_C (0xe9b6c7aa), UINT32_C (0xd62f105d), UINT32_C (0x02441453), UINT32_C (0xd8a1e681), UINT32_C (0xe7d3fbc8), UINT32_C (0x21e1cde6), UINT32_C (0xc33707d6), UINT32_C (0xf4d50d87), UINT32_C (0x455a14ed), UINT32_C (0xa9e3e905), UINT32_C (0xfcefa3f8), UINT32_C (0x676f02d9), UINT32_C (0x8d2a4c8a), UINT32_C (0xfffa3942), UINT32_C (0x8771f681), UINT32_C (0x6d9d6122), UINT32_C (0xfde5380c), UINT32_C (0xa4beea44), UINT32_C (0x4bdecfa9), UINT32_C (0xf6bb4b60), UINT32_C (0xbebfbc70), UINT32_C (0x289b7ec6), UINT32_C (0xeaa127fa), UINT32_C (0xd4ef3085), UINT32_C (0x04881d05), UINT32_C (0xd9d4d039), UINT32_C (0xe6db99e5), UINT32_C (0x1fa27cf8), UINT32_C (0xc4ac5665), UINT32_C (0xf4292244), UINT32_C (0x432aff97), UINT32_C (0xab9423a7), UINT32_C (0xfc93a039), UINT32_C (0x655b59c3), UINT32_C (0x8f0ccc92), UINT32_C (0xffeff47d), UINT32_C (0x85845dd1), UINT32_C (0x6fa87e4f), UINT32_C (0xfe2ce6e0), UINT32_C (0xa3014314), UINT32_C (0x4e0811a1), UINT32_C (0xf7537e82), UINT32_C (0xbd3af235), UINT32_C (0x2ad7d2bb), UINT32_C (0xeb86d391) }; unsigned int i; /**< Zero-based index */ /* Round 1. */ i = 0; do { /* The input data is loaded in correct (little-endian) format before calculations on each step. */ MD5STEP_R1 (A, B, C, D, X[i] = GET_X_FROM_DATA (M, i), 7, T[i]); ++i; MD5STEP_R1 (D, A, B, C, X[i] = GET_X_FROM_DATA (M, i), 12, T[i]); ++i; MD5STEP_R1 (C, D, A, B, X[i] = GET_X_FROM_DATA (M, i), 17, T[i]); ++i; MD5STEP_R1 (B, C, D, A, X[i] = GET_X_FROM_DATA (M, i), 22, T[i]); ++i; } while (i < 16); /* Round 2. */ do { const unsigned int idx_add = i; MD5STEP_R2 (A, B, C, D, X[(1U + idx_add) & 15U], 5, T[i]); ++i; MD5STEP_R2 (D, A, B, C, X[(6U + idx_add) & 15U], 9, T[i]); ++i; MD5STEP_R2 (C, D, A, B, X[(11U + idx_add) & 15U], 14, T[i]); ++i; MD5STEP_R2 (B, C, D, A, X[(0U + idx_add) & 15U], 20, T[i]); ++i; } while (i < 32); /* Round 3. */ do { const unsigned int idx_add = i; MD5STEP_R3 (A, B, C, D, X[(5U + 64U - idx_add) & 15U], 4, T[i]); ++i; MD5STEP_R3 (D, A, B, C, X[(8U + 64U - idx_add) & 15U], 11, T[i]); ++i; MD5STEP_R3 (C, D, A, B, X[(11U + 64U - idx_add) & 15U], 16, T[i]); ++i; MD5STEP_R3 (B, C, D, A, X[(14U + 64U - idx_add) & 15U], 23, T[i]); ++i; } while (i < 48); /* Round 4. */ do { const unsigned int idx_add = i; MD5STEP_R4 (A, B, C, D, X[(0U + 64U - idx_add) & 15U], 6, T[i]); ++i; MD5STEP_R4 (D, A, B, C, X[(7U + 64U - idx_add) & 15U], 10, T[i]); ++i; MD5STEP_R4 (C, D, A, B, X[(14U + 64U - idx_add) & 15U], 15, T[i]); ++i; MD5STEP_R4 (B, C, D, A, X[(5U + 64U - idx_add) & 15U], 21, T[i]); ++i; } while (i < 64); } #endif /* MHD_FAVOR_SMALL_CODE */ /* Finally increment and store working variables. See RFC 1321, end of Clause 3.4 (step 4). */ H[0] += A; H[1] += B; H[2] += C; H[3] += D; } /** * Process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_MD5_update (struct Md5Ctx *ctx, const uint8_t *data, size_t length) { unsigned int bytes_have; /**< Number of bytes in the context buffer */ mhd_assert ((data != NULL) || (length == 0)); #ifndef MHD_FAVOR_SMALL_CODE if (0 == length) return; /* Shortcut, do nothing */ #endif /* MHD_FAVOR_SMALL_CODE */ /* Note: (count & (MD5_BLOCK_SIZE-1)) equals (count % MD5_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned int) (ctx->count & (MD5_BLOCK_SIZE - 1)); ctx->count += length; if (0 != bytes_have) { unsigned int bytes_left = MD5_BLOCK_SIZE - bytes_have; if (length >= bytes_left) { /* Combine new data with data in the buffer and process the full block. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, bytes_left); data += bytes_left; length -= bytes_left; md5_transform (ctx->H, ctx->buffer); bytes_have = 0; } } while (MD5_BLOCK_SIZE <= length) { /* Process any full blocks of new data directly, without copying to the buffer. */ md5_transform (ctx->H, data); data += MD5_BLOCK_SIZE; length -= MD5_BLOCK_SIZE; } if (0 != length) { /* Copy incomplete block of new data (if any) to the buffer. */ memcpy (((uint8_t *) ctx->buffer) + bytes_have, data, length); } } /** * Size of "length" insertion in bits. * See RFC 1321, end of Clause 3.2 (step 2). */ #define MD5_SIZE_OF_LEN_ADD_BITS 64 /** * Size of "length" insertion in bytes. */ #define MD5_SIZE_OF_LEN_ADD (MD5_SIZE_OF_LEN_ADD_BITS / 8) /** * Finalise MD5 calculation, return digest. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes */ void MHD_MD5_finish (struct Md5Ctx *ctx, uint8_t digest[MD5_DIGEST_SIZE]) { uint64_t num_bits; /**< Number of processed bits */ unsigned int bytes_have; /**< Number of bytes in the context buffer */ /* Memorise the number of processed bits. The padding and other data added here during the postprocessing must not change the amount of hashed data. */ num_bits = ctx->count << 3; /* Note: (count & (MD5_BLOCK_SIZE-1)) equals (count % MD5_BLOCK_SIZE) for this block size. */ bytes_have = (unsigned int) (ctx->count & (MD5_BLOCK_SIZE - 1)); /* Input data must be padded with a single bit "1", then with zeros and the finally the length of data in bits must be added as the final bytes of the last block. See RFC 1321, Clauses 3.1 and 3.2 (steps 1 and 2). */ /* Data is always processed in form of bytes (not by individual bits), therefore position of the first padding bit in byte is always predefined (0x80). */ /* Buffer always have space for one byte at least (as full buffers are processed immediately). */ ((uint8_t *) ctx->buffer)[bytes_have++] = 0x80; if (MD5_BLOCK_SIZE - bytes_have < MD5_SIZE_OF_LEN_ADD) { /* No space in the current block to put the total length of message. Pad the current block with zeros and process it. */ if (bytes_have < MD5_BLOCK_SIZE) memset (((uint8_t *) ctx->buffer) + bytes_have, 0, MD5_BLOCK_SIZE - bytes_have); /* Process the full block. */ md5_transform (ctx->H, ctx->buffer); /* Start the new block. */ bytes_have = 0; } /* Pad the rest of the buffer with zeros. */ memset (((uint8_t *) ctx->buffer) + bytes_have, 0, MD5_BLOCK_SIZE - MD5_SIZE_OF_LEN_ADD - bytes_have); /* Put the number of bits in processed data as little-endian value. See RFC 1321, clauses 2 and 3.2 (step 2). */ _MHD_PUT_64BIT_LE_SAFE (ctx->buffer + MD5_BLOCK_SIZE_WORDS - 2, num_bits); /* Process the full final block. */ md5_transform (ctx->H, ctx->buffer); /* Put in LE mode the hash as the final digest. See RFC 1321, clauses 2 and 3.5 (step 5). */ #ifndef _MHD_PUT_32BIT_LE_UNALIGNED if (1 #ifndef MHD_FAVOR_SMALL_CODE && (0 != ((uintptr_t) digest) % _MHD_UINT32_ALIGN) #endif /* MHD_FAVOR_SMALL_CODE */ ) { /* If storing of the final result requires aligned address and the destination address is not aligned or compact code is used, store the final digest in aligned temporary buffer first, then copy it to the destination. */ uint32_t alig_dgst[MD5_DIGEST_SIZE_WORDS]; _MHD_PUT_32BIT_LE (alig_dgst + 0, ctx->H[0]); _MHD_PUT_32BIT_LE (alig_dgst + 1, ctx->H[1]); _MHD_PUT_32BIT_LE (alig_dgst + 2, ctx->H[2]); _MHD_PUT_32BIT_LE (alig_dgst + 3, ctx->H[3]); /* Copy result to the unaligned destination address. */ memcpy (digest, alig_dgst, MD5_DIGEST_SIZE); } #ifndef MHD_FAVOR_SMALL_CODE else /* Combined with the next 'if' */ #endif /* MHD_FAVOR_SMALL_CODE */ #endif /* ! _MHD_PUT_32BIT_LE_UNALIGNED */ #if ! defined(MHD_FAVOR_SMALL_CODE) || defined(_MHD_PUT_32BIT_LE_UNALIGNED) if (1) { /* Use cast to (void*) here to mute compiler alignment warnings. * Compilers are not smart enough to see that alignment has been checked. */ _MHD_PUT_32BIT_LE ((void *) (digest + 0 * MD5_BYTES_IN_WORD), ctx->H[0]); _MHD_PUT_32BIT_LE ((void *) (digest + 1 * MD5_BYTES_IN_WORD), ctx->H[1]); _MHD_PUT_32BIT_LE ((void *) (digest + 2 * MD5_BYTES_IN_WORD), ctx->H[2]); _MHD_PUT_32BIT_LE ((void *) (digest + 3 * MD5_BYTES_IN_WORD), ctx->H[3]); } #endif /* ! MHD_FAVOR_SMALL_CODE || _MHD_PUT_32BIT_LE_UNALIGNED */ /* Erase potentially sensitive data. */ memset (ctx, 0, sizeof(struct Md5Ctx)); } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ libmicrohttpd-1.0.10/src/microhttpd/mhd_bithelpers.h0000644000175000017500000004023615035214301016223 /* This file is part of libmicrohttpd Copyright (C) 2019-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/mhd_bithelpers.h * @brief macros for bits manipulations * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_BITHELPERS_H #define MHD_BITHELPERS_H 1 #include "mhd_options.h" #include #if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Declarations for VC & Clang/C2 built-ins */ #include #endif /* _MSC_FULL_VER */ #include "mhd_byteorder.h" #if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN || _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #include "mhd_align.h" #endif /* _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN || _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */ #ifndef __has_builtin /* Avoid precompiler errors with non-clang */ # define __has_builtin(x) 0 # define _MHD_has_builtin_dummy 1 #endif MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ #ifdef MHD_HAVE___BUILTIN_BSWAP32 #define _MHD_BYTES_SWAP32(value32) \ ((uint32_t) __builtin_bswap32 ((uint32_t) value32)) #elif defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Clang/C2 may not inline this function if optimizations are turned off. */ #ifndef __clang__ #pragma intrinsic(_byteswap_ulong) #endif /* ! __clang__ */ #define _MHD_BYTES_SWAP32(value32) \ ((uint32_t) _byteswap_ulong ((uint32_t) value32)) #elif \ __has_builtin (__builtin_bswap32) #define _MHD_BYTES_SWAP32(value32) \ ((uint32_t) __builtin_bswap32 ((uint32_t) value32)) #else /* ! __has_builtin(__builtin_bswap32) */ #define _MHD_BYTES_SWAP32(value32) \ ( (((uint32_t) (value32)) << 24) \ | ((((uint32_t) (value32)) & ((uint32_t) 0x0000FF00)) << 8) \ | ((((uint32_t) (value32)) & ((uint32_t) 0x00FF0000)) >> 8) \ | (((uint32_t) (value32)) >> 24) ) #endif /* ! __has_builtin(__builtin_bswap32) */ #ifdef MHD_HAVE___BUILTIN_BSWAP64 #define _MHD_BYTES_SWAP64(value64) \ ((uint64_t) __builtin_bswap64 ((uint64_t) value64)) #elif defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Clang/C2 may not inline this function if optimizations are turned off. */ #ifndef __clang__ #pragma intrinsic(_byteswap_uint64) #endif /* ! __clang__ */ #define _MHD_BYTES_SWAP64(value64) \ ((uint64_t) _byteswap_uint64 ((uint64_t) value64)) #elif \ __has_builtin (__builtin_bswap64) #define _MHD_BYTES_SWAP64(value64) \ ((uint64_t) __builtin_bswap64 ((uint64_t) value64)) #else /* ! __has_builtin(__builtin_bswap64) */ #define _MHD_BYTES_SWAP64(value64) \ ( (((uint64_t) (value64)) << 56) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x000000000000FF00)) << 40) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x0000000000FF0000)) << 24) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x00000000FF000000)) << 8) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x000000FF00000000)) >> 8) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x0000FF0000000000)) >> 24) \ | ((((uint64_t) (value64)) & ((uint64_t) 0x00FF000000000000)) >> 40) \ | (((uint64_t) (value64)) >> 56) ) #endif /* ! __has_builtin(__builtin_bswap64) */ /* _MHD_PUT_64BIT_LE (addr, value64) * put native-endian 64-bit value64 to addr * in little-endian mode. */ /* Slow version that works with unaligned addr and with any bytes order */ #define _MHD_PUT_64BIT_LE_SLOW(addr, value64) do { \ ((uint8_t*) (addr))[0] = (uint8_t) ((uint64_t) (value64)); \ ((uint8_t*) (addr))[1] = (uint8_t) (((uint64_t) (value64)) >> 8); \ ((uint8_t*) (addr))[2] = (uint8_t) (((uint64_t) (value64)) >> 16); \ ((uint8_t*) (addr))[3] = (uint8_t) (((uint64_t) (value64)) >> 24); \ ((uint8_t*) (addr))[4] = (uint8_t) (((uint64_t) (value64)) >> 32); \ ((uint8_t*) (addr))[5] = (uint8_t) (((uint64_t) (value64)) >> 40); \ ((uint8_t*) (addr))[6] = (uint8_t) (((uint64_t) (value64)) >> 48); \ ((uint8_t*) (addr))[7] = (uint8_t) (((uint64_t) (value64)) >> 56); \ } while (0) #if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_PUT_64BIT_LE(addr, value64) \ ((*(uint64_t*) (addr)) = (uint64_t) (value64)) #elif _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_PUT_64BIT_LE(addr, value64) \ ((*(uint64_t*) (addr)) = _MHD_BYTES_SWAP64 (value64)) #else /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_PUT_64BIT_LE(addr, value64) do { \ ((uint8_t*) (addr))[0] = (uint8_t) ((uint64_t) (value64)); \ ((uint8_t*) (addr))[1] = (uint8_t) (((uint64_t) (value64)) >> 8); \ ((uint8_t*) (addr))[2] = (uint8_t) (((uint64_t) (value64)) >> 16); \ ((uint8_t*) (addr))[3] = (uint8_t) (((uint64_t) (value64)) >> 24); \ ((uint8_t*) (addr))[4] = (uint8_t) (((uint64_t) (value64)) >> 32); \ ((uint8_t*) (addr))[5] = (uint8_t) (((uint64_t) (value64)) >> 40); \ ((uint8_t*) (addr))[6] = (uint8_t) (((uint64_t) (value64)) >> 48); \ ((uint8_t*) (addr))[7] = (uint8_t) (((uint64_t) (value64)) >> 56); \ } while (0) /* Indicate that _MHD_PUT_64BIT_LE does not need aligned pointer */ #define _MHD_PUT_64BIT_LE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* Put result safely to unaligned address */ _MHD_static_inline void _MHD_PUT_64BIT_LE_SAFE (void *dst, uint64_t value) { #ifndef _MHD_PUT_64BIT_LE_UNALIGNED if (0 != ((uintptr_t) dst) % (_MHD_UINT64_ALIGN)) _MHD_PUT_64BIT_LE_SLOW (dst, value); else #endif /* ! _MHD_PUT_64BIT_LE_UNALIGNED */ _MHD_PUT_64BIT_LE (dst, value); } /* _MHD_PUT_32BIT_LE (addr, value32) * put native-endian 32-bit value32 to addr * in little-endian mode. */ #if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_PUT_32BIT_LE(addr,value32) \ ((*(uint32_t*) (addr)) = (uint32_t) (value32)) #elif _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_PUT_32BIT_LE(addr, value32) \ ((*(uint32_t*) (addr)) = _MHD_BYTES_SWAP32 (value32)) #else /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_PUT_32BIT_LE(addr, value32) do { \ ((uint8_t*) (addr))[0] = (uint8_t) ((uint32_t) (value32)); \ ((uint8_t*) (addr))[1] = (uint8_t) (((uint32_t) (value32)) >> 8); \ ((uint8_t*) (addr))[2] = (uint8_t) (((uint32_t) (value32)) >> 16); \ ((uint8_t*) (addr))[3] = (uint8_t) (((uint32_t) (value32)) >> 24); \ } while (0) /* Indicate that _MHD_PUT_32BIT_LE does not need aligned pointer */ #define _MHD_PUT_32BIT_LE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* _MHD_GET_32BIT_LE (addr) * get little-endian 32-bit value storied at addr * and return it in native-endian mode. */ #if _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_GET_32BIT_LE(addr) \ (*(const uint32_t*) (addr)) #elif _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_GET_32BIT_LE(addr) \ _MHD_BYTES_SWAP32 (*(const uint32_t*) (addr)) #else /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_GET_32BIT_LE(addr) \ ( ( (uint32_t) (((const uint8_t*) addr)[0])) \ | (((uint32_t) (((const uint8_t*) addr)[1])) << 8) \ | (((uint32_t) (((const uint8_t*) addr)[2])) << 16) \ | (((uint32_t) (((const uint8_t*) addr)[3])) << 24) ) /* Indicate that _MHD_GET_32BIT_LE does not need aligned pointer */ #define _MHD_GET_32BIT_LE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN */ /* _MHD_PUT_64BIT_BE (addr, value64) * put native-endian 64-bit value64 to addr * in big-endian mode. */ /* Slow version that works with unaligned addr and with any bytes order */ #define _MHD_PUT_64BIT_BE_SLOW(addr, value64) do { \ ((uint8_t*) (addr))[7] = (uint8_t) ((uint64_t) (value64)); \ ((uint8_t*) (addr))[6] = (uint8_t) (((uint64_t) (value64)) >> 8); \ ((uint8_t*) (addr))[5] = (uint8_t) (((uint64_t) (value64)) >> 16); \ ((uint8_t*) (addr))[4] = (uint8_t) (((uint64_t) (value64)) >> 24); \ ((uint8_t*) (addr))[3] = (uint8_t) (((uint64_t) (value64)) >> 32); \ ((uint8_t*) (addr))[2] = (uint8_t) (((uint64_t) (value64)) >> 40); \ ((uint8_t*) (addr))[1] = (uint8_t) (((uint64_t) (value64)) >> 48); \ ((uint8_t*) (addr))[0] = (uint8_t) (((uint64_t) (value64)) >> 56); \ } while (0) #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_PUT_64BIT_BE(addr, value64) \ ((*(uint64_t*) (addr)) = (uint64_t) (value64)) #elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_PUT_64BIT_BE(addr, value64) \ ((*(uint64_t*) (addr)) = _MHD_BYTES_SWAP64 (value64)) #else /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_PUT_64BIT_BE(addr, value64) _MHD_PUT_64BIT_BE_SLOW(addr, value64) /* Indicate that _MHD_PUT_64BIT_BE does not need aligned pointer */ #define _MHD_PUT_64BIT_BE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* Put result safely to unaligned address */ _MHD_static_inline void _MHD_PUT_64BIT_BE_SAFE (void *dst, uint64_t value) { #ifndef _MHD_PUT_64BIT_BE_UNALIGNED if (0 != ((uintptr_t) dst) % (_MHD_UINT64_ALIGN)) _MHD_PUT_64BIT_BE_SLOW (dst, value); else #endif /* ! _MHD_PUT_64BIT_BE_UNALIGNED */ _MHD_PUT_64BIT_BE (dst, value); } /* _MHD_GET_64BIT_BE (addr) * load 64-bit value located at addr in big endian mode. */ #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_GET_64BIT_BE(addr) \ (*(const uint64_t*) (addr)) #elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_GET_64BIT_BE(addr) \ _MHD_BYTES_SWAP64 (*(const uint64_t*) (addr)) #else /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_GET_64BIT_BE(addr) \ ( (((uint64_t) (((const uint8_t*) addr)[0])) << 56) \ | (((uint64_t) (((const uint8_t*) addr)[1])) << 48) \ | (((uint64_t) (((const uint8_t*) addr)[2])) << 40) \ | (((uint64_t) (((const uint8_t*) addr)[3])) << 32) \ | (((uint64_t) (((const uint8_t*) addr)[4])) << 24) \ | (((uint64_t) (((const uint8_t*) addr)[5])) << 16) \ | (((uint64_t) (((const uint8_t*) addr)[6])) << 8) \ | ((uint64_t) (((const uint8_t*) addr)[7])) ) /* Indicate that _MHD_GET_64BIT_BE does not need aligned pointer */ #define _MHD_GET_64BIT_BE_ALLOW_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* _MHD_PUT_32BIT_BE (addr, value32) * put native-endian 32-bit value32 to addr * in big-endian mode. */ #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_PUT_32BIT_BE(addr, value32) \ ((*(uint32_t*) (addr)) = (uint32_t) (value32)) #elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_PUT_32BIT_BE(addr, value32) \ ((*(uint32_t*) (addr)) = _MHD_BYTES_SWAP32 (value32)) #else /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_PUT_32BIT_BE(addr, value32) do { \ ((uint8_t*) (addr))[3] = (uint8_t) ((uint32_t) (value32)); \ ((uint8_t*) (addr))[2] = (uint8_t) (((uint32_t) (value32)) >> 8); \ ((uint8_t*) (addr))[1] = (uint8_t) (((uint32_t) (value32)) >> 16); \ ((uint8_t*) (addr))[0] = (uint8_t) (((uint32_t) (value32)) >> 24); \ } while (0) /* Indicate that _MHD_PUT_32BIT_BE does not need aligned pointer */ #define _MHD_PUT_32BIT_BE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* _MHD_GET_32BIT_BE (addr) * get big-endian 32-bit value storied at addr * and return it in native-endian mode. */ #if _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #define _MHD_GET_32BIT_BE(addr) \ (*(const uint32_t*) (addr)) #elif _MHD_BYTE_ORDER == _MHD_LITTLE_ENDIAN #define _MHD_GET_32BIT_BE(addr) \ _MHD_BYTES_SWAP32 (*(const uint32_t*) (addr)) #else /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /* Endianness was not detected or non-standard like PDP-endian */ #define _MHD_GET_32BIT_BE(addr) \ ( (((uint32_t) (((const uint8_t*) addr)[0])) << 24) \ | (((uint32_t) (((const uint8_t*) addr)[1])) << 16) \ | (((uint32_t) (((const uint8_t*) addr)[2])) << 8) \ | ((uint32_t) (((const uint8_t*) addr)[3])) ) /* Indicate that _MHD_GET_32BIT_BE does not need aligned pointer */ #define _MHD_GET_32BIT_BE_UNALIGNED 1 #endif /* _MHD_BYTE_ORDER != _MHD_LITTLE_ENDIAN */ /** * Rotate right 32-bit value by number of bits. * bits parameter must be more than zero and must be less than 32. */ #if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Clang/C2 do not inline this function if optimizations are turned off. */ #ifndef __clang__ #pragma intrinsic(_rotr) #endif /* ! __clang__ */ #define _MHD_ROTR32(value32, bits) \ ((uint32_t) _rotr ((uint32_t) (value32),(bits))) #elif __has_builtin (__builtin_rotateright32) #define _MHD_ROTR32(value32, bits) \ ((uint32_t) __builtin_rotateright32 ((value32), (bits))) #else /* ! __builtin_rotateright32 */ _MHD_static_inline uint32_t _MHD_ROTR32 (uint32_t value32, int bits) { bits %= 32; if (0 == bits) return value32; /* Defined in form which modern compiler could optimize. */ return (value32 >> bits) | (value32 << (32 - bits)); } #endif /* ! __builtin_rotateright32 */ /** * Rotate left 32-bit value by number of bits. * bits parameter must be more than zero and must be less than 32. */ #if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Clang/C2 do not inline this function if optimizations are turned off. */ #ifndef __clang__ #pragma intrinsic(_rotl) #endif /* ! __clang__ */ #define _MHD_ROTL32(value32, bits) \ ((uint32_t) _rotl ((uint32_t) (value32),(bits))) #elif __has_builtin (__builtin_rotateleft32) #define _MHD_ROTL32(value32, bits) \ ((uint32_t) __builtin_rotateleft32 ((value32), (bits))) #else /* ! __builtin_rotateleft32 */ _MHD_static_inline uint32_t _MHD_ROTL32 (uint32_t value32, int bits) { bits %= 32; if (0 == bits) return value32; /* Defined in form which modern compiler could optimize. */ return (value32 << bits) | (value32 >> (32 - bits)); } #endif /* ! __builtin_rotateleft32 */ /** * Rotate right 64-bit value by number of bits. * bits parameter must be more than zero and must be less than 64. */ #if defined(_MSC_FULL_VER) && (! defined(__clang__) || (defined(__c2__) && \ defined(__OPTIMIZE__))) /* Clang/C2 do not inline this function if optimisations are turned off. */ #ifndef __clang__ #pragma intrinsic(_rotr64) #endif /* ! __clang__ */ #define _MHD_ROTR64(value64, bits) \ ((uint64_t) _rotr64 ((uint64_t) (value64),(bits))) #elif __has_builtin (__builtin_rotateright64) #define _MHD_ROTR64(value64, bits) \ ((uint64_t) __builtin_rotateright64 ((value64), (bits))) #else /* ! __builtin_rotateright64 */ _MHD_static_inline uint64_t _MHD_ROTR64 (uint64_t value64, int bits) { bits %= 64; if (0 == bits) return value64; /* Defined in form which modern compiler could optimise. */ return (value64 >> bits) | (value64 << (64 - bits)); } #endif /* ! __builtin_rotateright64 */ MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ #ifdef _MHD_has_builtin_dummy /* Remove macro function replacement to avoid misdetection in files which * include this header */ # undef __has_builtin #endif #endif /* ! MHD_BITHELPERS_H */ libmicrohttpd-1.0.10/src/microhttpd/test_shutdown_select.c0000664000175000017500000002433015232103064017477 /* This file is part of libmicrohttpd Copyright (C) 2016 Karlson2k (Evgeny Grin) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file microhttpd/test_shutdown_select.c * @brief Test whether shutdown socket triggers select()/poll() * @details On some platforms shutting down the socket in one thread * triggers select() or poll() waiting for this socket in * other thread. libmicrohttpd depends on this behavior on * these platforms. This program check whether select() * and poll() (if available) work as expected. * @author Karlson2k (Evgeny Grin) */ #include "MHD_config.h" #include "platform.h" #include "mhd_sockets.h" #include #include #include #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #ifdef HAVE_TIME_H #include #endif /* HAVE_TIME_H */ #if defined(MHD_USE_POSIX_THREADS) #include #endif /* MHD_USE_POSIX_THREADS */ #if defined(MHD_WINSOCK_SOCKETS) #include #include #define sock_errno (WSAGetLastError ()) #elif defined(MHD_POSIX_SOCKETS) #ifdef HAVE_SYS_TYPES_H #include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_SYS_SOCKET_H #include #endif /* HAVE_SYS_SOCKET_H */ #ifdef HAVE_NETINET_IN_H #include #endif /* HAVE_NETINET_IN_H */ #ifdef HAVE_ARPA_INET_H #include #endif /* HAVE_ARPA_INET_H */ #ifdef HAVE_SYS_SELECT_H #include #endif /* HAVE_SYS_SELECT_H */ #if defined(HAVE_POLL) && defined(HAVE_POLL_H) #include #endif /* HAVE_POLL && HAVE_POLL_H */ #define sock_errno (errno) #endif /* MHD_POSIX_SOCKETS */ #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ #include "mhd_threads.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef SOMAXCONN #define SOMAXCONN 511 #endif /* ! SOMAXCONN */ #if ! defined(SHUT_RDWR) && defined(SD_BOTH) #define SHUT_RDWR SD_BOTH #endif static bool check_err; static bool has_in_name (const char *prog_name, const char *marker) { size_t name_pos; size_t pos; if (! prog_name || ! marker) return 0; pos = 0; name_pos = 0; while (prog_name[pos]) { if ('/' == prog_name[pos]) name_pos = pos + 1; #if defined(_WIN32) || defined(__CYGWIN__) else if ('\\' == prog_name[pos]) name_pos = pos + 1; #endif /* _WIN32 || __CYGWIN__ */ pos++; } if (name_pos == pos) return true; return strstr (prog_name + name_pos, marker) != NULL; } static MHD_socket start_socket_listen (int domain) { /* Create sockets similarly to daemon.c */ MHD_socket fd; int cloexec_set; struct sockaddr_in sock_addr; socklen_t addrlen; #ifdef MHD_WINSOCK_SOCKETS unsigned long flags = 1; #else /* MHD_POSIX_SOCKETS */ int flags; #endif /* MHD_POSIX_SOCKETS */ #if defined(MHD_POSIX_SOCKETS) && defined(SOCK_CLOEXEC) fd = socket (domain, SOCK_STREAM | SOCK_CLOEXEC, 0); cloexec_set = 1; #elif defined(MHD_WINSOCK_SOCKETS) && defined(WSA_FLAG_NO_HANDLE_INHERIT) fd = WSASocketW (domain, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_NO_HANDLE_INHERIT); cloexec_set = 1; #else /* !SOCK_CLOEXEC */ fd = socket (domain, SOCK_STREAM, 0); cloexec_set = 0; #endif /* !SOCK_CLOEXEC */ if ( (MHD_INVALID_SOCKET == fd) && (cloexec_set) ) { fd = socket (domain, SOCK_STREAM, 0); cloexec_set = 0; } if (MHD_INVALID_SOCKET == fd) { fprintf (stderr, "Can't create socket: %u\n", (unsigned) sock_errno); return MHD_INVALID_SOCKET; } if (! cloexec_set) { #ifdef MHD_WINSOCK_SOCKETS if (! SetHandleInformation ((HANDLE) fd, HANDLE_FLAG_INHERIT, 0)) fprintf (stderr, "Failed to make socket non-inheritable: %u\n", (unsigned int) GetLastError ()); #else /* MHD_POSIX_SOCKETS */ flags = fcntl (fd, F_GETFD); if ( ( (-1 == flags) || ( (flags != (flags | FD_CLOEXEC)) && (0 != fcntl (fd, F_SETFD, flags | FD_CLOEXEC)) ) ) ) fprintf (stderr, "Failed to make socket non-inheritable: %s\n", MHD_socket_last_strerr_ ()); #endif /* MHD_POSIX_SOCKETS */ } memset (&sock_addr, 0, sizeof (struct sockaddr_in)); sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons (0); #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN sock_addr.sin_len = sizeof (struct sockaddr_in); #endif addrlen = sizeof (struct sockaddr_in); if (bind (fd, (const struct sockaddr *) &sock_addr, addrlen) < 0) { fprintf (stderr, "Failed to bind socket: %u\n", (unsigned) sock_errno); MHD_socket_close_chk_ (fd); return MHD_INVALID_SOCKET; } #ifdef MHD_WINSOCK_SOCKETS if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) { fprintf (stderr, "Failed to make socket non-blocking: %u\n", (unsigned) sock_errno); MHD_socket_close_chk_ (fd); return MHD_INVALID_SOCKET; } #else /* MHD_POSIX_SOCKETS */ flags = fcntl (fd, F_GETFL); if ( ( (-1 == flags) || ( (flags != (flags | O_NONBLOCK)) && (0 != fcntl (fd, F_SETFL, flags | O_NONBLOCK)) ) ) ) { fprintf (stderr, "Failed to make socket non-blocking: %s\n", MHD_socket_last_strerr_ ()); MHD_socket_close_chk_ (fd); return MHD_INVALID_SOCKET; } #endif /* MHD_POSIX_SOCKETS */ if (listen (fd, SOMAXCONN) < 0) { fprintf (stderr, "Failed to listen on socket: %u\n", (unsigned) sock_errno); MHD_socket_close_chk_ (fd); return MHD_INVALID_SOCKET; } return fd; } static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ select_thread (void *data) { /* use select() like in daemon.c */ MHD_socket listen_sock = *((MHD_socket *) data); fd_set rs, ws; struct timeval timeout; FD_ZERO (&rs); FD_ZERO (&ws); FD_SET (listen_sock, &rs); timeout.tv_usec = 0; timeout.tv_sec = 7; check_err = (0 > MHD_SYS_select_ (listen_sock + 1, &rs, &ws, NULL, &timeout)); return (MHD_THRD_RTRN_TYPE_) 0; } #ifdef HAVE_POLL static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ poll_thread (void *data) { /* use poll() like in daemon.c */ struct pollfd p[1]; MHD_socket listen_sock = *((MHD_socket *) data); p[0].fd = listen_sock; p[0].events = POLLIN; p[0].revents = 0; check_err = (0 > MHD_sys_poll_ (p, 1, 7000)); return (MHD_THRD_RTRN_TYPE_) 0; } #endif /* HAVE_POLL */ static void local_sleep (unsigned seconds) { #if defined(_WIN32) && ! defined(__CYGWIN__) Sleep (seconds * 1000); #else unsigned seconds_left = seconds; do { seconds_left = sleep (seconds_left); } while (seconds_left > 0); #endif } int main (int argc, char *const *argv) { int i; time_t start_t, end_t; int result = 0; MHD_THRD_RTRN_TYPE_ (MHD_THRD_CALL_SPEC_ * test_func)(void *data); #ifdef MHD_WINSOCK_SOCKETS WORD ver_req; WSADATA wsa_data; int err; #endif /* MHD_WINSOCK_SOCKETS */ bool test_poll; bool must_ignore; (void) argc; /* Unused. Silent compiler warning. */ test_poll = has_in_name (argv[0], "_poll"); must_ignore = has_in_name (argv[0], "_ignore"); if (! test_poll) test_func = &select_thread; else { #ifndef HAVE_POLL return 77; #else /* ! HAVE_POLL */ test_func = &poll_thread; #endif /* ! HAVE_POLL */ } #ifdef MHD_WINSOCK_SOCKETS ver_req = MAKEWORD (2, 2); err = WSAStartup (ver_req, &wsa_data); if ((err != 0) || (MAKEWORD (2, 2) != wsa_data.wVersion)) { printf ("WSAStartup() failed\n"); WSACleanup (); return 99; } #endif /* MHD_WINSOCK_SOCKETS */ /* try several times to ensure that accidental incoming connection * didn't interfere with test results */ for (i = 0; i < 5 && result == 0; i++) { MHD_thread_handle_native_ sel_thrd; /* fprintf(stdout, "Creating, binding and listening socket...\n"); */ MHD_socket listen_socket = start_socket_listen (AF_INET); if (MHD_INVALID_SOCKET == listen_socket) return 99; check_err = true; /* fprintf (stdout, "Starting select() thread...\n"); */ #if defined(MHD_USE_POSIX_THREADS) if (0 != pthread_create (&sel_thrd, NULL, test_func, &listen_socket)) { MHD_socket_close_chk_ (listen_socket); fprintf (stderr, "Can't start thread\n"); return 99; } #elif defined(MHD_USE_W32_THREADS) sel_thrd = (HANDLE) (uintptr_t) _beginthreadex (NULL, 0, test_func, &listen_socket, 0, NULL); if (0 == (sel_thrd)) { MHD_socket_close_chk_ (listen_socket); fprintf (stderr, "Can't start select() thread\n"); return 99; } #else #error No threading lib available #endif /* fprintf (stdout, "Waiting...\n"); */ local_sleep (1); /* make sure that select() is started */ /* fprintf (stdout, "Shutting down socket...\n"); */ start_t = time (NULL); shutdown (listen_socket, SHUT_RDWR); /* fprintf (stdout, "Waiting for thread to finish...\n"); */ if (! MHD_join_thread_ (sel_thrd)) { MHD_socket_close_chk_ (listen_socket); fprintf (stderr, "Can't join select() thread\n"); return 99; } if (check_err) { MHD_socket_close_chk_ (listen_socket); fprintf (stderr, "Error in waiting thread\n"); return 99; } end_t = time (NULL); /* fprintf (stdout, "Thread finished.\n"); */ MHD_socket_close_chk_ (listen_socket); if ((start_t == (time_t) -1) || (end_t == (time_t) -1) ) { MHD_socket_close_chk_ (listen_socket); fprintf (stderr, "Can't get current time\n"); return 99; } if (end_t - start_t > 3) result++; } #ifdef MHD_WINSOCK_SOCKETS WSACleanup (); #endif /* MHD_WINSOCK_SOCKETS */ return must_ignore ? (! result) : (result); } libmicrohttpd-1.0.10/src/microhttpd/tsearch.c0000644000175000017500000000671114760713574014702 /* * Tree search generalized from Knuth (6.2.2) Algorithm T just like * the AT&T man page says. * * The node_t structure is for internal use only, lint doesn't grok it. * * Written by reading the System V Interface Definition, not the code. * * Totally public domain. */ #include "mhd_options.h" #include "tsearch.h" #ifdef HAVE_STDDEF_H #include #endif /* HAVE_STDDEF_H */ #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ typedef struct node { const void *key; struct node *llink, *rlink; } node_t; /* $NetBSD: tsearch.c,v 1.7 2012/06/25 22:32:45 abs Exp $ */ /* find or insert datum into search tree */ void * tsearch (const void *vkey, void **vrootp, int (*compar)(const void *, const void *)) { node_t *q; node_t **rootp = (node_t **) vrootp; if (rootp == NULL) return NULL; while (*rootp != NULL) /* Knuth's T1: */ { int r; if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */ return *rootp; /* we found it! */ rootp = (r < 0) ? &(*rootp)->llink : /* T3: follow left branch */ &(*rootp)->rlink; /* T4: follow right branch */ } q = malloc (sizeof(node_t)); /* T5: key not found */ if (q != NULL) /* make new node */ { *rootp = q; /* link new node to old */ q->key = vkey; /* initialize new node */ q->llink = q->rlink = NULL; } return q; } /* $NetBSD: tfind.c,v 1.7 2012/06/25 22:32:45 abs Exp $ */ /* find a node by key "vkey" in tree "vrootp", or return 0 */ void * tfind (const void *vkey, void * const *vrootp, int (*compar)(const void *, const void *)) { node_t * const *rootp = (node_t * const *) vrootp; if (rootp == NULL) return NULL; while (*rootp != NULL) /* T1: */ { int r; if ((r = (*compar)(vkey, (*rootp)->key)) == 0) /* T2: */ return *rootp; /* key found */ rootp = (r < 0) ? &(*rootp)->llink : /* T3: follow left branch */ &(*rootp)->rlink; /* T4: follow right branch */ } return NULL; } /* $NetBSD: tdelete.c,v 1.8 2016/01/20 20:47:41 christos Exp $ */ /* find a node with key "vkey" in tree "vrootp" */ void * tdelete (const void *vkey, void **vrootp, int (*compar)(const void *, const void *)) { node_t **rootp = (node_t **) vrootp; node_t *p, *q, *r; int cmp; if ((rootp == NULL) || ((p = *rootp) == NULL) ) return NULL; while ((cmp = (*compar)(vkey, (*rootp)->key)) != 0) { p = *rootp; rootp = (cmp < 0) ? &(*rootp)->llink : /* follow llink branch */ &(*rootp)->rlink; /* follow rlink branch */ if (*rootp == NULL) return NULL; /* key not found */ } r = (*rootp)->rlink; /* D1: */ if ((q = (*rootp)->llink) == NULL) /* Left NULL? */ q = r; else if (r != NULL) /* Right link is NULL? */ { if (r->llink == NULL) /* D2: Find successor */ { r->llink = q; q = r; } else /* D3: Find NULL link */ { for (q = r->llink; q->llink != NULL; q = r->llink) r = q; r->llink = q->rlink; q->llink = (*rootp)->llink; q->rlink = (*rootp)->rlink; } } free (*rootp); /* D4: Free node */ *rootp = q; /* link parent to new node */ return p; } /* end of tsearch.c */ libmicrohttpd-1.0.10/src/microhttpd/mhd_assert.h0000644000175000017500000000370014760713577015405 /* This file is part of libmicrohttpd Copyright (C) 2017-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/mhd_assert.h * @brief macros for mhd_assert() * @author Karlson2k (Evgeny Grin) */ /* Unlike POSIX version of 'assert.h', MHD version of 'assert' header * does not allow multiple redefinition of 'mhd_assert' macro within single * source file. */ #ifndef MHD_ASSERT_H #define MHD_ASSERT_H 1 #include "mhd_options.h" #if ! defined(_DEBUG) && ! defined(NDEBUG) #ifndef DEBUG /* Used by some toolchains */ #define NDEBUG 1 /* Use NDEBUG by default */ #else /* DEBUG */ #define _DEBUG 1 #endif /* DEBUG */ #endif /* !_DEBUG && !NDEBUG */ #if defined(_DEBUG) && defined(NDEBUG) #error Both _DEBUG and NDEBUG are defined #endif /* _DEBUG && NDEBUG */ #ifdef NDEBUG # define mhd_assert(ignore) ((void) 0) #else /* _DEBUG */ # ifdef HAVE_ASSERT # include # define mhd_assert(CHK) assert (CHK) # else /* ! HAVE_ASSERT */ # include # include # define mhd_assert(CHK) \ do { \ if (! (CHK)) { \ fprintf (stderr, "%s:%u Assertion failed: %s\nProgram aborted.\n", \ __FILE__, (unsigned) __LINE__, #CHK); \ fflush (stderr); abort (); } \ } while (0) # endif /* ! HAVE_ASSERT */ #endif /* _DEBUG */ #endif /* ! MHD_ASSERT_H */ libmicrohttpd-1.0.10/src/microhttpd/test_auth_parse.c0000664000175000017500000024042715232103064016427 /* This file is part of libmicrohttpd Copyright (C) 2022-2023 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_auth_parse.c * @brief Unit tests for request's 'Authorization" headers parsing * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include #include "gen_auth.h" #ifdef BAUTH_SUPPORT #include "basicauth.h" #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT #include "digestauth.h" #endif /* DAUTH_SUPPORT */ #include "mhd_assert.h" #include "internal.h" #include "connection.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func(NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func(errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } /* Declarations for local replacements of MHD functions */ /* None, headers are included */ /* Local replacements implementations */ void * MHD_connection_alloc_memory_ (struct MHD_Connection *connection, size_t size) { void *ret; if (NULL == connection) mhdErrorExitDesc ("'connection' parameter is NULL"); /* Use 'read_buffer' just as a flag */ if (NULL != connection->read_buffer) { /* Use 'write_buffer' just as a flag */ if (NULL != connection->write_buffer) mhdErrorExitDesc ("Unexpected third memory allocation, " \ "while previous allocations was not freed"); } /* Just use simple "malloc()" here */ ret = malloc (size); if (NULL == ret) externalErrorExit (); /* Track up to two allocations */ if (NULL == connection->read_buffer) connection->read_buffer = (char *) ret; else connection->write_buffer = (char *) ret; return ret; } /** * Static variable to avoid additional malloc()/free() pairs */ static struct MHD_Connection conn; void MHD_DLOG (const struct MHD_Daemon *daemon, const char *format, ...) { (void) daemon; if (! conn.rq.client_aware) { fprintf (stderr, "Unexpected call of 'MHD_LOG(), format is '%s'.\n", format); fprintf (stderr, "'Authorization' header value: '%s'.\n", (NULL == conn.rq.headers_received) ? "NULL" : (conn.rq.headers_received->value)); mhdErrorExit (); } conn.rq.client_aware = false; /* Clear the flag */ return; } /** * Static variable to avoid additional malloc()/free() pairs */ static struct MHD_HTTP_Req_Header req_header; static void test_global_init (void) { memset (&conn, 0, sizeof(conn)); memset (&req_header, 0, sizeof(req_header)); } /** * Add "Authorization" client test header. * * @param hdr the pointer to the headr value, must be valid until end of * checking of this header * @param hdr_len the length of the @a hdr * @note The function is NOT thread-safe */ static void add_AuthHeader (const char *hdr, size_t hdr_len) { if ((NULL != conn.rq.headers_received) || (NULL != conn.rq.headers_received_tail)) externalErrorExitDesc ("Connection's test headers are not empty already"); if (NULL != hdr) { /* Skip initial whitespaces, emulate MHD's headers processing */ while (' ' == hdr[0] || '\t' == hdr[0]) { hdr++; hdr_len--; } req_header.header = MHD_HTTP_HEADER_AUTHORIZATION; /* Static string */ req_header.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION); req_header.value = hdr; req_header.value_size = hdr_len; req_header.kind = MHD_HEADER_KIND; req_header.prev = NULL; req_header.next = NULL; conn.rq.headers_received = &req_header; conn.rq.headers_received_tail = &req_header; } else { conn.rq.headers_received = NULL; conn.rq.headers_received_tail = NULL; } conn.state = MHD_CONNECTION_FULL_REQ_RECEIVED; /* Should be a typical value */ } #ifdef BAUTH_SUPPORT /** * Parse previously added Basic Authorization client header and return * result of the parsing. * * Function performs basic checking of the parsing result * @return result of header parsing * @note The function is NOT thread-safe */ static const struct MHD_RqBAuth * get_BAuthRqParams (void) { const struct MHD_RqBAuth *res1; const struct MHD_RqBAuth *res2; /* Store pointer in some member unused in this test */ res1 = MHD_get_rq_bauth_params_ (&conn); if (! conn.rq.bauth_tried) mhdErrorExitDesc ("'rq.bauth_tried' is not set"); res2 = MHD_get_rq_bauth_params_ (&conn); if (res1 != res2) mhdErrorExitDesc ("MHD_get_rq_bauth_params_() returned another pointer " \ "when called for the second time"); return res2; } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /** * Parse previously added Digest Authorization client header and return * result of the parsing. * * Function performs basic checking of the parsing result * @return result of header parsing * @note The function is NOT thread-safe */ static const struct MHD_RqDAuth * get_DAuthRqParams (void) { const struct MHD_RqDAuth *res1; const struct MHD_RqDAuth *res2; /* Store pointer in some member unused in this test */ res1 = MHD_get_rq_dauth_params_ (&conn); if (! conn.rq.dauth_tried) mhdErrorExitDesc ("'rq.dauth_tried' is not set"); res2 = MHD_get_rq_dauth_params_ (&conn); if (res1 != res2) mhdErrorExitDesc ("MHD_get_rq_bauth_params_() returned another pointer " \ "when called for the second time"); return res2; } #endif /* DAUTH_SUPPORT */ static void clean_AuthHeaders (void) { conn.state = MHD_CONNECTION_INIT; free (conn.read_buffer); free (conn.write_buffer); #ifdef BAUTH_SUPPORT conn.rq.bauth_tried = false; #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT conn.rq.dauth_tried = false; #endif /* BAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT if ((NULL != conn.rq.bauth) && (conn.read_buffer != (const char *) conn.rq.bauth) && (conn.write_buffer != (const char *) conn.rq.bauth)) externalErrorExitDesc ("Memory allocation is not tracked as it should be"); conn.rq.bauth = NULL; #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT if ((NULL != conn.rq.dauth) && (conn.read_buffer != (const char *) conn.rq.dauth) && (conn.write_buffer != (const char *) conn.rq.dauth)) externalErrorExitDesc ("Memory allocation is not tracked as it should be"); conn.rq.dauth = NULL; #endif /* BAUTH_SUPPORT */ conn.rq.headers_received = NULL; conn.rq.headers_received_tail = NULL; conn.read_buffer = NULL; conn.write_buffer = NULL; conn.rq.client_aware = false; } enum MHD_TestAuthType { MHD_TEST_AUTHTYPE_NONE, MHD_TEST_AUTHTYPE_BASIC, MHD_TEST_AUTHTYPE_DIGEST, }; /* return zero if succeed, non-zero otherwise */ static unsigned int expect_result_type_n (const char *hdr, size_t hdr_len, const enum MHD_TestAuthType expected_type, int expect_log, unsigned int line_num) { unsigned int ret; ret = 0; add_AuthHeader (hdr, hdr_len); if (expect_log) conn.rq.client_aware = true; /* Use like a flag */ else conn.rq.client_aware = false; #ifdef BAUTH_SUPPORT if (MHD_TEST_AUTHTYPE_BASIC == expected_type) { if (NULL == get_BAuthRqParams ()) { fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Basic Authorization was not found, while it should be.\n"); ret++; } } else #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT if (MHD_TEST_AUTHTYPE_DIGEST == expected_type) { if (NULL == get_DAuthRqParams ()) { fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Digest Authorization was not found, while it should be.\n"); ret++; } } else #endif /* BAUTH_SUPPORT */ { #ifdef BAUTH_SUPPORT if (NULL != get_BAuthRqParams ()) { fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Found Basic Authorization, while it should not be.\n"); ret++; } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT if (NULL != get_DAuthRqParams ()) { fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Found Digest Authorization, while it should not be.\n"); ret++; } #endif /* DAUTH_SUPPORT */ } #if defined(BAUTH_SUPPORT) && defined(DAUTH_SUPPORT) if (conn.rq.client_aware) { fprintf (stderr, "'Authorization' header parsing ERROR:\n" "Log function must be called, but it was not.\n"); ret++; } #endif /* BAUTH_SUPPORT && DAUTH_SUPPORT */ if (ret) { if (NULL == hdr) fprintf (stderr, "Input: Absence of 'Authorization' header.\n"); else if (0 == hdr_len) fprintf (stderr, "Input: empty 'Authorization' header.\n"); else fprintf (stderr, "Input Header: '%.*s'\n", (int) hdr_len, hdr); fprintf (stderr, "The check is at line: %u\n\n", line_num); ret = 1; } clean_AuthHeaders (); return ret; } #define expect_result_type(h,t,l) \ expect_result_type_n(h,MHD_STATICSTR_LEN_(h),t,l,__LINE__) static unsigned int check_type (void) { unsigned int r = 0; /**< The number of errors */ r += expect_result_type_n (NULL, 0, MHD_TEST_AUTHTYPE_NONE, 0, __LINE__); r += expect_result_type ("", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" \t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t \t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" \t ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" \t \t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t \t ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" Basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\tBasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t Basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" \tBasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" Basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t\tBasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \tBasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \t Basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic \t", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic \t ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic 123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic \t123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("Basic abc ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" \tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t\tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \tbAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \t bAsIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC \t", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC \t ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC 123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC \t123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("bAsIC abc ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\tbasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" \tbasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t\tbasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \tbasic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \t basic", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic \t", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic \t ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic 123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic \t123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("basic abc ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" BASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t BASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" \tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type (" BASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t\tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \tBASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("\t\t \t BASIC", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC \t", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC \t ", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC 123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC \t123", MHD_TEST_AUTHTYPE_BASIC, 0); r += expect_result_type ("BASIC abc ", MHD_TEST_AUTHTYPE_BASIC, 0); /* Only single token is allowed for 'Basic' Authorization */ r += expect_result_type ("Basic a b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic a\tb", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic a\tb", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic abc1 b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic c abc1", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic c abc1 ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic c abc1\t", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic c\tabc1\t", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic c abc1 b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic zyx, b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic zyx,b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic zyx ,b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic zyx;b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic zyx; b", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Basic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" Basic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" Basic2 ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\tBasic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t Basic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" \tBasic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" Basic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t\t\tBasic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t\t \tBasic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t\t \t Basic2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 \t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 \t ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 123", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 \t123", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic2 abc ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" BasicBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\tBasicBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\t BasicBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" \tBasicBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicBasic ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicBasic \t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicBasic \t\t", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicDigest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" BasicDigest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("BasicDigest ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Basic\0", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\0" "Basic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" Digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t Digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" \tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" Digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t\tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \tDigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \t Digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tDigest ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" Digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t \tDigest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t digEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" \tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t\tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \tdigEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \t digEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digEST ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tdigEST ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t \tdigEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" \tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t\tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \tdigest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \t digest", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digest ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("digest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tdigest ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" digest \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t \tdigest \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" \tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t\tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \tDIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t\t \t DIGEST", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("DIGEST ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("DIGEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("DIGEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\tDIGEST ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type (" DIGEST \t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("\t \tDIGEST \t ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,\t", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest , ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest , ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,\t, ,\t, ,\t, ,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,\t,\t,\t,\t,\t,\t,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a=b", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a=\"b\"", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc=1", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc=\"1\"", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a=b ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a=\"b\" ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc=1 ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc=\"1\" ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a = b", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a\t=\t\"b\"", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc =1", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc= \"1\"", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a=\tb ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest a = \"b\" ", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc\t\t\t= 1 ", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc =\t\t\t\"1\" ", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc =1,,,,", MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc =1 ,,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,,nc= \"1 \"", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \" 1\"", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \"1\",,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \"1\" ,,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \"1\" ,,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \"1\" ,,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest ,,,, nc= \"1\" ,,,,,", \ MHD_TEST_AUTHTYPE_DIGEST, 0); r += expect_result_type ("Digest nc", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc ,", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc , ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest \tnc\t ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest \tnc\t ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc,", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc,uri", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,uri", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,uri ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,uri,", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1, uri,", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,uri ,", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,uri , ", \ MHD_TEST_AUTHTYPE_NONE, 1); /* Binary zero */ r += expect_result_type ("Digest nc=1\0", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1\0" " ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1\t\0", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\0" "1", MHD_TEST_AUTHTYPE_NONE, 1); /* Semicolon */ r += expect_result_type ("Digest nc=1;", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1; ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=;1", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc;=1", MHD_TEST_AUTHTYPE_NONE, 1); /* The equal sign alone */ r += expect_result_type ("Digest =", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest =", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest = ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest ,=", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest , =", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest ,= ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest , = ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1,=", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=1, =", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=bar,=", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=bar, =", \ MHD_TEST_AUTHTYPE_NONE, 1); /* Unclosed quotation */ r += expect_result_type ("Digest nc=\"", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"abc", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\" ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"abc ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\" abc", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\" abc", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"\\", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"\\\"", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\" \\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"\\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\" \\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc=\"\\\"\\\"\\\"\\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"abc", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \" ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"abc ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \" abc", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \" abc", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"\\", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"\\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \" \\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"\\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \" \\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest nc= \"\\\"\\\"\\\"\\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"bar", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" ", MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"bar ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" bar", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" bar", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo= \" bar", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\", bar", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" bar,", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"\\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" \\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"\\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\" \\\" ", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest foo=\"\\\"\\\"\\\"\\\"", \ MHD_TEST_AUTHTYPE_NONE, 1); /* Full set of parameters with semicolon inside */ r += expect_result_type ("Digest username=\"test@example.com\", " \ "realm=\"users@example.com\", nonce=\"32141232413abcde\", " \ "uri=\"/example\", qop=auth, nc=00000001; cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest username=\"test@example.com\", " \ "realm=\"users@example.com\", nonce=\"32141232413abcde\", " \ "uri=\"/example\", qop=auth, nc=00000001;cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest username;=\"test@example.com\", " \ "realm=\"users@example.com\", nonce=\"32141232413abcde\", " \ "uri=\"/example\", qop=auth, nc=00000001, cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", \ MHD_TEST_AUTHTYPE_NONE, 1); r += expect_result_type ("Digest2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("2Digest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Digest" "a", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("a" "Digest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" Digest2", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" 2Digest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" Digest" "a", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" a" "Digest", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Digest2 ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("2Digest ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Digest" "a", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("a" "Digest ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("DigestBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("DigestBasic ", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type (" DigestBasic", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("DigestBasic" "a", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("Digest" "\0", MHD_TEST_AUTHTYPE_NONE, 0); r += expect_result_type ("\0" "Digest", MHD_TEST_AUTHTYPE_NONE, 0); return r; } #ifdef BAUTH_SUPPORT /* return zero if succeed, 1 otherwise */ static unsigned int expect_basic_n (const char *hdr, size_t hdr_len, const char *tkn, size_t tkn_len, unsigned int line_num) { const struct MHD_RqBAuth *h; unsigned int ret; mhd_assert (NULL != hdr); mhd_assert (0 != hdr_len); add_AuthHeader (hdr, hdr_len); h = get_BAuthRqParams (); if (NULL == h) mhdErrorExitDesc ("'MHD_get_rq_bauth_params_()' returned NULL"); ret = 1; if (tkn_len != h->token68.len) fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Wrong token length:\tRESULT[%u]: %.*s\tEXPECTED[%u]: %.*s\n", (unsigned) h->token68.len, (int) h->token68.len, h->token68.str ? h->token68.str : "(NULL)", (unsigned) tkn_len, (int) tkn_len, tkn ? tkn : "(NULL)"); else if ( ((NULL == tkn) != (NULL == h->token68.str)) || ((NULL != tkn) && (0 != memcmp (tkn, h->token68.str, tkn_len))) ) fprintf (stderr, "'Authorization' header parsing FAILED:\n" "Wrong token string:\tRESULT[%u]: %.*s\tEXPECTED[%u]: %.*s\n", (unsigned) h->token68.len, (int) h->token68.len, h->token68.str ? h->token68.str : "(NULL)", (unsigned) tkn_len, (int) tkn_len, tkn ? tkn : "(NULL)"); else ret = 0; if (0 != ret) { fprintf (stderr, "Input Header: '%.*s'\n", (int) hdr_len, hdr); fprintf (stderr, "The check is at line: %u\n\n", line_num); } clean_AuthHeaders (); return ret; } #define expect_basic(h,t) \ expect_basic_n(h,MHD_STATICSTR_LEN_(h),t,MHD_STATICSTR_LEN_(t),__LINE__) static unsigned int check_basic (void) { unsigned int r = 0; /**< The number of errors */ r += expect_basic ("Basic a", "a"); r += expect_basic ("Basic a", "a"); r += expect_basic ("Basic \ta", "a"); r += expect_basic ("Basic \ta\t", "a"); r += expect_basic ("Basic \ta ", "a"); r += expect_basic ("Basic a ", "a"); r += expect_basic ("Basic \t a\t ", "a"); r += expect_basic ("Basic \t abc\t ", "abc"); r += expect_basic ("Basic 2143sdfa4325sdfgfdab354354314SDSDFc", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic ("Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic ("Basic 2143sdfa4325sdfgfdab354354314SDSDFc", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic ("Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic (" Basic 2143sdfa4325sdfgfdab354354314SDSDFc", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic (" Basic 2143sdfa4325sdfgfdab354354314SDSDFc", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic (" Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic (" Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic (" Basic 2143sdfa4325sdfgfdab354354314SDSDFc ", \ "2143sdfa4325sdfgfdab354354314SDSDFc"); r += expect_basic ("Basic -A.1-z~9+/=====", "-A.1-z~9+/====="); r += expect_basic (" Basic -A.1-z~9+/===== ", "-A.1-z~9+/====="); r += expect_basic_n ("Basic", MHD_STATICSTR_LEN_ ("Basic"), NULL, 0,__LINE__); r += expect_basic_n (" Basic", MHD_STATICSTR_LEN_ (" Basic"), NULL, 0, __LINE__); r += expect_basic_n ("Basic ", MHD_STATICSTR_LEN_ ("Basic "), NULL, 0, __LINE__); r += expect_basic_n ("Basic \t\t", MHD_STATICSTR_LEN_ ("Basic \t\t"), NULL, 0, __LINE__); return r; } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /* return zero if succeed, 1 otherwise */ static unsigned int cmp_dauth_param (const char *pname, const struct MHD_RqDAuthParam *param, const char *expected_value) { unsigned int ret; size_t expected_len; bool expected_quoted; mhd_assert (NULL != param); mhd_assert (NULL != pname); ret = 0; if (NULL == expected_value) { expected_len = 0; expected_quoted = false; if (NULL != param->value.str) ret = 1; else if (param->value.len != expected_len) ret = 1; else if (param->quoted != expected_quoted) ret = 1; } else { expected_len = strlen (expected_value); expected_quoted = (NULL != memchr (expected_value, '\\', expected_len)); if (NULL == param->value.str) ret = 1; else if (param->value.len != expected_len) ret = 1; else if (param->quoted != expected_quoted) ret = 1; else if (0 != memcmp (param->value.str, expected_value, expected_len)) ret = 1; } if (0 != ret) { fprintf (stderr, "Parameter '%s' parsed incorrectly:\n", pname); fprintf (stderr, "\tRESULT :\tvalue.str: %.*s", (int) (param->value.str ? param->value.len : 6), param->value.str ? param->value.str : "(NULL)"); fprintf (stderr, "\tvalue.len: %u", (unsigned) param->value.len); fprintf (stderr, "\tquoted: %s\n", (unsigned) param->quoted ? "true" : "false"); fprintf (stderr, "\tEXPECTED:\tvalue.str: %.*s", (int) (expected_value ? expected_len : 6), expected_value ? expected_value : "(NULL)"); fprintf (stderr, "\tvalue.len: %u", (unsigned) expected_len); fprintf (stderr, "\tquoted: %s\n", (unsigned) expected_quoted ? "true" : "false"); } return ret; } /* return zero if succeed, 1 otherwise */ static unsigned int expect_digest_n (const char *hdr, size_t hdr_len, const char *nonce, enum MHD_DigestAuthAlgo3 algo3, const char *response, const char *username, const char *username_ext, const char *realm, const char *uri, const char *qop_raw, enum MHD_DigestAuthQOP qop, const char *cnonce, const char *nc, int userhash, unsigned int line_num) { const struct MHD_RqDAuth *h; unsigned int ret; mhd_assert (NULL != hdr); mhd_assert (0 != hdr_len); add_AuthHeader (hdr, hdr_len); h = get_DAuthRqParams (); if (NULL == h) mhdErrorExitDesc ("'MHD_get_rq_dauth_params_()' returned NULL"); ret = 0; ret += cmp_dauth_param ("nonce", &h->nonce, nonce); if (h->algo3 != algo3) { ret += 1; fprintf (stderr, "Parameter 'algorithm' detected incorrectly:\n"); fprintf (stderr, "\tRESULT :\t%u\n", (unsigned) h->algo3); fprintf (stderr, "\tEXPECTED:\t%u\n", (unsigned) algo3); } ret += cmp_dauth_param ("response", &h->response, response); ret += cmp_dauth_param ("username", &h->username, username); ret += cmp_dauth_param ("username_ext", &h->username_ext, username_ext); ret += cmp_dauth_param ("realm", &h->realm, realm); ret += cmp_dauth_param ("uri", &h->uri, uri); ret += cmp_dauth_param ("qop", &h->qop_raw, qop_raw); if (h->qop != qop) { ret += 1; fprintf (stderr, "Parameter 'qop' detected incorrectly:\n"); fprintf (stderr, "\tRESULT :\t%u\n", (unsigned) h->qop); fprintf (stderr, "\tEXPECTED:\t%u\n", (unsigned) qop); } ret += cmp_dauth_param ("cnonce", &h->cnonce, cnonce); ret += cmp_dauth_param ("nc", &h->nc, nc); if (h->userhash != ! (! userhash)) { ret += 1; fprintf (stderr, "Parameter 'userhash' parsed incorrectly:\n"); fprintf (stderr, "\tRESULT :\t%s\n", h->userhash ? "true" : "false"); fprintf (stderr, "\tEXPECTED:\t%s\n", userhash ? "true" : "false"); } if (0 != ret) { fprintf (stderr, "Input Header: '%.*s'\n", (int) hdr_len, hdr); fprintf (stderr, "The check is at line: %u\n\n", line_num); } clean_AuthHeaders (); return ret; } #define expect_digest(h,no,a,rs,un,ux,rm,ur,qr,qe,c,nc,uh) \ expect_digest_n(h,MHD_STATICSTR_LEN_(h),\ no,a,rs,un,ux,rm,ur,qr,qe,c,nc,uh,__LINE__) /** * Check the properties of the algorithm and QOP enumerations that the * consumers of the parsed header rely on. * * The "invalid" members have the numeric value zero, which means that the * usual "is the client value allowed by the application" test * * if (client_value != (client_value & allowed_mask)) * reject (); * * lets the "invalid" value pass for every possible @a allowed_mask. Every * consumer must therefore reject the "invalid" value explicitly before * using it. Failing to do so made an unknown 'algorithm=' token in the * request abort the whole daemon. * * @return zero if succeed, number of failures otherwise */ static unsigned int check_digest_enum_sentinels (void) { unsigned int r = 0; /**< The number of errors */ if (0 != (unsigned int) MHD_DIGEST_AUTH_ALGO3_INVALID) { r++; fprintf (stderr, "MHD_DIGEST_AUTH_ALGO3_INVALID is not zero. Line: %u\n", (unsigned int) __LINE__); } if (0 != (unsigned int) MHD_DIGEST_BASE_ALGO_INVALID) { r++; fprintf (stderr, "MHD_DIGEST_BASE_ALGO_INVALID is not zero. Line: %u\n", (unsigned int) __LINE__); } if (0 != (unsigned int) MHD_DIGEST_AUTH_QOP_INVALID) { r++; fprintf (stderr, "MHD_DIGEST_AUTH_QOP_INVALID is not zero. Line: %u\n", (unsigned int) __LINE__); } /* The bitmask test alone does not reject the "invalid" values. */ if (0 != (((unsigned int) MHD_DIGEST_AUTH_ALGO3_INVALID) & ~((unsigned int) MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION))) { r++; fprintf (stderr, "The bitmask check unexpectedly rejects " "MHD_DIGEST_AUTH_ALGO3_INVALID. Line: %u\n", (unsigned int) __LINE__); } return r; } static unsigned int check_digest (void) { unsigned int r = 0; /**< The number of errors */ r += check_digest_enum_sentinels (); r += expect_digest ("Digest", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest nc=1", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, NULL, \ MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=\"1\"", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=\"1\" ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest ,nc=\"1\" ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=\"1\", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=\"1\" , ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=1, ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest nc=1 , ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest ,,,nc=1, ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest ,,,nc=1 , ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1", 0); r += expect_digest ("Digest ,,,nc=\"1 \", ", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0); r += expect_digest ("Digest nc=\"1 \"", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0); r += expect_digest ("Digest nc=\"1 \" ,", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0); r += expect_digest ("Digest nc=\"1 \", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1 ", 0); r += expect_digest ("Digest nc=\"1;\", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1;", 0); r += expect_digest ("Digest nc=\"1\\;\", ", NULL, MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, "1\\;", 0); r += expect_digest ("Digest userhash=false", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest userhash=\"false\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest userhash=foo", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest userhash=true", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash=\"true\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash=\"\\t\\r\\u\\e\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash=TRUE", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash=True", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash = true", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 1); r += expect_digest ("Digest userhash=True2", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest userhash=\" true\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=md5", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=Md5", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=mD5", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"MD5\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"\\M\\D\\5\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"\\m\\d\\5\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-256", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=sha-256", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=Sha-256", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"SHA-256\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"SHA\\-25\\6\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"shA-256\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5-sess", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5-SESS", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=md5-Sess", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5_SESSION, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-256-seSS", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-512-256", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA512_256, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-512-256-sess", NULL, \ MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5-2", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5-sess2", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-256-512", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); /* More spellings that the client may send and that must all be reported as #MHD_DIGEST_AUTH_ALGO3_INVALID. Note that the numeric value of that enumeration member is zero, so a consumer that only validates the value with a bitmask ("(algo & allowed) == algo") accepts every one of these; the consumer must check for the INVALID value explicitly. */ r += expect_digest ("Digest algorithm=BOGUS", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"BOGUS\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-512", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=SHA-1", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=MD5 ", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"MD5 \"", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\" MD5\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=\"MD\\5\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); /* A duplicated parameter is accepted and the last occurrence wins. Both orders are checked so that any change of that behaviour is noticed: a client that can make different HTTP implementations pick different occurrences of the same parameter is a source of trouble. */ r += expect_digest ("Digest algorithm=MD5,algorithm=BOGUS", NULL, \ MHD_DIGEST_AUTH_ALGO3_INVALID, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest algorithm=BOGUS,algorithm=MD5", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ NULL, MHD_DIGEST_AUTH_QOP_NONE, NULL, NULL, 0); r += expect_digest ("Digest qop=auth", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0); r += expect_digest ("Digest qop=\"auth\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0); r += expect_digest ("Digest qop=Auth", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "Auth", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0); r += expect_digest ("Digest qop=AUTH", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "AUTH", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0); r += expect_digest ("Digest qop=\"\\A\\ut\\H\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "\\A\\ut\\H", MHD_DIGEST_AUTH_QOP_AUTH, NULL, NULL, 0); r += expect_digest ("Digest qop=\"auth \"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auth ", MHD_DIGEST_AUTH_QOP_INVALID, NULL, NULL, 0); r += expect_digest ("Digest qop=auth-int", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auth-int", MHD_DIGEST_AUTH_QOP_AUTH_INT, NULL, NULL, 0); r += expect_digest ("Digest qop=\"auth-int\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auth-int", MHD_DIGEST_AUTH_QOP_AUTH_INT, NULL, NULL, 0); r += expect_digest ("Digest qop=\"auTh-iNt\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auTh-iNt", MHD_DIGEST_AUTH_QOP_AUTH_INT, NULL, NULL, 0); r += expect_digest ("Digest qop=\"auTh-iNt2\"", NULL, \ MHD_DIGEST_AUTH_ALGO3_MD5, \ NULL, NULL, NULL, NULL, NULL, \ "auTh-iNt2", MHD_DIGEST_AUTH_QOP_INVALID, NULL, NULL, 0); r += expect_digest ("Digest username=\"test@example.com\", " \ "realm=\"users@example.com\", " \ "nonce=\"32141232413abcde\", " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_MD5, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ NULL, "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, \ "0a4f113b", "00000001", 0); r += expect_digest ("Digest username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest username=test@example.com, " \ "realm=users@example.com, algorithm=\"SHA-256-sess\", " \ "nonce=32141232413abcde, " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=/example, qop=\"auth\", nc=\"00000001\", " \ "cnonce=0a4f113b, " \ "response=6629fae49393a05397450978507c4ef1, " \ "opaque=sadfljk32sdaf", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest username = \"test@example.com\", " \ "realm\t=\t\"users@example.com\", algorithm\t= SHA-256, " \ "nonce\t= \"32141232413abcde\", " \ "username*\t=\tUTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri = \"/example\", qop = auth, nc\t=\t00000001, " \ "cnonce\t\t\t= \"0a4f113b\", " \ "response =\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\t\t\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest username=\"test@example.com\"," \ "realm=\"users@example.com\",algorithm=SHA-512-256," \ "nonce=\"32141232413abcde\"," \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates," \ "uri=\"/example\",qop=auth,nc=00000001," \ "cnonce=\"0a4f113b\"," \ "response=\"6629fae49393a05397450978507c4ef1\"," \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA512_256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest username=\"test@example.com\"," \ "realm=\"users@example.com\",algorithm=SHA-256," \ "nonce=\"32141232413abcde\",asdf=asdffdsaf," \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates," \ "uri=\"/example\",qop=auth,nc=00000001,cnonce=\"0a4f113b\"," \ "response=\"6629fae49393a05397450978507c4ef1\"," \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=zyx, username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=zyx,,,,,,,username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\"", "32141232413abcde", MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=zyx,,,,,,,username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\",,,,,", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=zyx,,,,,,,username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx\", username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx, abc\", " \ "username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx, abc=cde\", " \ "username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\",foo=bar", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx, abc=cde\", " \ "username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " \ "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\", foo=\"bar1, bar2\"", \ "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx, \\\\\"abc=cde\\\\\"\", " \ "username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\", foo=\"bar1, bar2\"", \ "32141232413abcde", MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); r += expect_digest ("Digest abc=\"zyx, \\\\\"abc=cde\\\\\"\", " \ "username=\"test@example.com\", " \ "realm=\"users@example.com\", algorithm=SHA-256, " \ "nonce=\"32141232413abcde\", " \ "username*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates, " \ "uri=\"/example\", qop=auth, nc=00000001, " "cnonce=\"0a4f113b\", " \ "response=\"6629fae49393a05397450978507c4ef1\", " \ "opaque=\"sadfljk32sdaf\", foo=\",nc=02\"", "32141232413abcde", \ MHD_DIGEST_AUTH_ALGO3_SHA256, \ "6629fae49393a05397450978507c4ef1", "test@example.com", \ "UTF-8''%c2%a3%20and%20%e2%82%ac%20rates", \ "users@example.com", "/example", \ "auth", MHD_DIGEST_AUTH_QOP_AUTH, "0a4f113b", \ "00000001", 0); return r; } #endif /* DAUTH_SUPPORT */ #define TEST_AUTH_STR "dXNlcjpwYXNz" static unsigned int check_two_auths (void) { unsigned int ret; static struct MHD_HTTP_Req_Header h1; static struct MHD_HTTP_Req_Header h2; static struct MHD_HTTP_Req_Header h3; #ifdef BAUTH_SUPPORT const struct MHD_RqBAuth *bauth; #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT const struct MHD_RqDAuth *dauth; #endif /* DAUTH_SUPPORT */ if ((NULL != conn.rq.headers_received) || (NULL != conn.rq.headers_received_tail)) externalErrorExitDesc ("Connection's test headers are not empty already"); /* Init and use both Basic and Digest Auth headers */ memset (&h1, 0, sizeof(h1)); memset (&h2, 0, sizeof(h2)); memset (&h3, 0, sizeof(h3)); h1.kind = MHD_HEADER_KIND; h1.header = MHD_HTTP_HEADER_HOST; /* Just some random header */ h1.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_HOST); h1.value = "localhost"; h1.value_size = strlen (h1.value); h2.kind = MHD_HEADER_KIND; h2.header = MHD_HTTP_HEADER_AUTHORIZATION; h2.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION); h2.value = "Basic " TEST_AUTH_STR; h2.value_size = strlen (h2.value); h3.kind = MHD_HEADER_KIND; h3.header = MHD_HTTP_HEADER_AUTHORIZATION; h3.header_size = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION); h3.value = "Digest cnonce=" TEST_AUTH_STR; h3.value_size = strlen (h3.value); conn.rq.headers_received = &h1; h1.next = &h2; h2.prev = &h1; h2.next = &h3; h3.prev = &h2; conn.rq.headers_received_tail = &h3; conn.state = MHD_CONNECTION_FULL_REQ_RECEIVED; /* Should be a typical value */ ret = 0; #ifdef BAUTH_SUPPORT bauth = get_BAuthRqParams (); #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT dauth = get_DAuthRqParams (); #endif /* DAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT if (NULL == bauth) { fprintf (stderr, "No Basic Authorization header detected. Line: %u\n", (unsigned int) __LINE__); ret++; } else if ((MHD_STATICSTR_LEN_ (TEST_AUTH_STR) != bauth->token68.len) || (0 != memcmp (bauth->token68.str, TEST_AUTH_STR, bauth->token68.len))) { fprintf (stderr, "Basic Authorization token does not match. Line: %u\n", (unsigned int) __LINE__); ret++; } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT if (NULL == dauth) { fprintf (stderr, "No Digest Authorization header detected. Line: %u\n", (unsigned int) __LINE__); ret++; } else if ((MHD_STATICSTR_LEN_ (TEST_AUTH_STR) != dauth->cnonce.value.len) || (0 != memcmp (dauth->cnonce.value.str, TEST_AUTH_STR, dauth->cnonce.value.len))) { fprintf (stderr, "Digest Authorization 'cnonce' does not match. Line: %u\n", (unsigned int) __LINE__); ret++; } #endif /* DAUTH_SUPPORT */ /* Cleanup */ conn.rq.headers_received = NULL; conn.rq.headers_received_tail = NULL; conn.state = MHD_CONNECTION_INIT; return ret; } int main (int argc, char *argv[]) { unsigned int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ test_global_init (); errcount += check_type (); #ifdef BAUTH_SUPPORT errcount += check_basic (); #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT errcount += check_digest (); #endif /* DAUTH_SUPPORT */ errcount += check_two_auths (); if (0 == errcount) printf ("All tests were passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.10/src/microhttpd/digestauth.c0000664000175000017500000043370615232141556015412 /* This file is part of libmicrohttpd Copyright (C) 2010, 2011, 2012, 2015, 2018 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file digestauth.c * @brief Implements HTTP digest authentication * @author Amr Ali * @author Matthieu Speder * @author Christian Grothoff (RFC 7616 support) * @author Karlson2k (Evgeny Grin) (fixes, new API, improvements, large rewrite, * many RFC 7616 features implementation, * old RFC 2069 support) */ #include "digestauth.h" #include "gen_auth.h" #include "platform.h" #include "mhd_limits.h" #include "internal.h" #include "response.h" #ifdef MHD_MD5_SUPPORT # include "mhd_md5_wrap.h" #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT # include "mhd_sha256_wrap.h" #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT # include "sha512_256.h" #endif /* MHD_SHA512_256_SUPPORT */ #include "mhd_locks.h" #include "mhd_mono_clock.h" #include "mhd_str.h" #include "mhd_compat.h" #include "mhd_bithelpers.h" #include "mhd_assert.h" #include "mhd_check.h" /** * Allow re-use of the nonce-nc map array slot after #REUSE_TIMEOUT seconds, * if this slot is needed for the new nonce, while the old nonce was not used * even one time by the client. * Typically clients immediately use generated nonce for new request. */ #define REUSE_TIMEOUT 30 /** * The maximum value of artificial timestamp difference to avoid clashes. * The value must be suitable for bitwise AND operation. */ #define DAUTH_JUMPBACK_MAX (0x7F) /** * 48 bit value in bytes */ #define TIMESTAMP_BIN_SIZE (48 / 8) /** * Trim value to the TIMESTAMP_BIN_SIZE size */ #define TRIM_TO_TIMESTAMP(value) \ ((value) & ((UINT64_C (1) << (TIMESTAMP_BIN_SIZE * 8)) - 1)) /** * The printed timestamp size in chars */ #define TIMESTAMP_CHARS_LEN (TIMESTAMP_BIN_SIZE * 2) /** * Standard server nonce length, not including terminating null, * * @param digest_size digest size */ #define NONCE_STD_LEN(digest_size) \ ((digest_size) * 2 + TIMESTAMP_CHARS_LEN) #ifdef MHD_SHA512_256_SUPPORT /** * Maximum size of any digest hash supported by MHD. * (SHA-512/256 > MD5). */ #define MAX_DIGEST SHA512_256_DIGEST_SIZE /** * The common size of SHA-256 digest and SHA-512/256 digest */ #define SHA256_SHA512_256_DIGEST_SIZE SHA512_256_DIGEST_SIZE #elif defined(MHD_SHA256_SUPPORT) /** * Maximum size of any digest hash supported by MHD. * (SHA-256 > MD5). */ #define MAX_DIGEST SHA256_DIGEST_SIZE /** * The common size of SHA-256 digest and SHA-512/256 digest */ #define SHA256_SHA512_256_DIGEST_SIZE SHA256_DIGEST_SIZE #elif defined(MHD_MD5_SUPPORT) /** * Maximum size of any digest hash supported by MHD. */ #define MAX_DIGEST MD5_DIGEST_SIZE #else /* ! MHD_MD5_SUPPORT */ #error At least one hashing algorithm must be enabled #endif /* ! MHD_MD5_SUPPORT */ /** * Macro to avoid using VLAs if the compiler does not support them. */ #ifndef HAVE_C_VARARRAYS /** * Return #MAX_DIGEST. * * @param n length of the digest to be used for a VLA */ #define VLA_ARRAY_LEN_DIGEST(n) (MAX_DIGEST) #else /** * Return @a n. * * @param n length of the digest to be used for a VLA */ #define VLA_ARRAY_LEN_DIGEST(n) (n) #endif /** * Check that @a n is below #MAX_DIGEST */ #define VLA_CHECK_LEN_DIGEST(n) \ do { if ((n) > MAX_DIGEST) MHD_PANIC (_ ("VLA too big.\n")); } while (0) /** * Maximum length of a username for digest authentication. */ #define MAX_USERNAME_LENGTH 128 /** * Maximum length of a realm for digest authentication. */ #define MAX_REALM_LENGTH 256 /** * Maximum length of the response in digest authentication. */ #define MAX_AUTH_RESPONSE_LENGTH (MAX_DIGEST * 2) /** * The required prefix of parameter with the extended notation */ #define MHD_DAUTH_EXT_PARAM_PREFIX "UTF-8'" /** * The minimal size of the prefix for parameter with the extended notation */ #define MHD_DAUTH_EXT_PARAM_MIN_LEN \ MHD_STATICSTR_LEN_ (MHD_DAUTH_EXT_PARAM_PREFIX "'") /** * The result of nonce-nc map array check. */ enum MHD_CheckNonceNC_ { /** * The nonce and NC are OK (valid and NC was not used before). */ MHD_CHECK_NONCENC_OK = MHD_DAUTH_OK, /** * The 'nonce' was overwritten with newer 'nonce' in the same slot or * NC was already used. * The validity of the 'nonce' was not be checked. */ MHD_CHECK_NONCENC_STALE = MHD_DAUTH_NONCE_STALE, /** * The 'nonce' is wrong, it was not generated before. */ MHD_CHECK_NONCENC_WRONG = MHD_DAUTH_NONCE_WRONG }; /** * Get base hash calculation algorithm from #MHD_DigestAuthAlgo3 value. * @param algo3 the MHD_DigestAuthAlgo3 value * @return the base hash calculation algorithm */ _MHD_static_inline enum MHD_DigestBaseAlgo get_base_digest_algo (enum MHD_DigestAuthAlgo3 algo3) { unsigned int base_algo; base_algo = ((unsigned int) algo3) & ~((unsigned int) (MHD_DIGEST_AUTH_ALGO3_NON_SESSION | MHD_DIGEST_AUTH_ALGO3_SESSION)); return (enum MHD_DigestBaseAlgo) base_algo; } /** * Get digest size for specified algorithm. * * Internal inline version. * @param algo3 the algorithm to check * @return the size of the digest or zero if the input value is not * supported/valid */ _MHD_static_inline size_t digest_get_hash_size (enum MHD_DigestAuthAlgo3 algo3) { #ifdef MHD_MD5_SUPPORT mhd_assert (MHD_MD5_DIGEST_SIZE == MD5_DIGEST_SIZE); #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT mhd_assert (MHD_SHA256_DIGEST_SIZE == SHA256_DIGEST_SIZE); #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT mhd_assert (MHD_SHA512_256_DIGEST_SIZE == SHA512_256_DIGEST_SIZE); #ifdef MHD_SHA256_SUPPORT mhd_assert (SHA256_DIGEST_SIZE == SHA512_256_DIGEST_SIZE); #endif /* MHD_SHA256_SUPPORT */ #endif /* MHD_SHA512_256_SUPPORT */ /* Only one algorithm must be specified */ mhd_assert (1 == \ (((0 != (algo3 & MHD_DIGEST_BASE_ALGO_MD5)) ? 1 : 0) \ + ((0 != (algo3 & MHD_DIGEST_BASE_ALGO_SHA256)) ? 1 : 0) \ + ((0 != (algo3 & MHD_DIGEST_BASE_ALGO_SHA512_256)) ? 1 : 0))); #ifdef MHD_MD5_SUPPORT if (0 != (((unsigned int) algo3) & ((unsigned int) MHD_DIGEST_BASE_ALGO_MD5))) return MHD_MD5_DIGEST_SIZE; else #endif /* MHD_MD5_SUPPORT */ #if defined(MHD_SHA256_SUPPORT) && defined(MHD_SHA512_256_SUPPORT) if (0 != (((unsigned int) algo3) & ( ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA256) | ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA512_256)))) return MHD_SHA256_DIGEST_SIZE; /* The same as SHA512_256_DIGEST_SIZE */ else #elif defined(MHD_SHA256_SUPPORT) if (0 != (((unsigned int) algo3) & ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA256))) return MHD_SHA256_DIGEST_SIZE; else #elif defined(MHD_SHA512_256_SUPPORT) if (0 != (((unsigned int) algo3) & ((unsigned int) MHD_DIGEST_BASE_ALGO_SHA512_256))) return MHD_SHA512_256_DIGEST_SIZE; else #endif /* MHD_SHA512_256_SUPPORT */ (void) 0; /* Unsupported algorithm */ return 0; /* Wrong input or unsupported algorithm */ } /** * Get digest size for specified algorithm. * * The size of the digest specifies the size of the userhash, userdigest * and other parameters which size depends on used hash algorithm. * @param algo3 the algorithm to check * @return the size of the digest (either #MHD_MD5_DIGEST_SIZE or * #MHD_SHA256_DIGEST_SIZE/MHD_SHA512_256_DIGEST_SIZE) * or zero if the input value is not supported or not valid * @sa #MHD_digest_auth_calc_userdigest() * @sa #MHD_digest_auth_calc_userhash(), #MHD_digest_auth_calc_userhash_hex() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN size_t MHD_digest_get_hash_size (enum MHD_DigestAuthAlgo3 algo3) { return digest_get_hash_size (algo3); } /** * Digest context data */ union DigestCtx { #ifdef MHD_MD5_SUPPORT struct Md5CtxWr md5_ctx; #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT struct Sha256CtxWr sha256_ctx; #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT struct Sha512_256Ctx sha512_256_ctx; #endif /* MHD_SHA512_256_SUPPORT */ }; /** * The digest calculation structure. */ struct DigestAlgorithm { /** * A context for the digest algorithm, already initialized to be * useful for @e init, @e update and @e digest. */ union DigestCtx ctx; /** * The hash calculation algorithm. */ enum MHD_DigestBaseAlgo algo; /** * Buffer for hex-print of the final digest. */ #ifdef _DEBUG bool uninitialised; /**< The structure has been not set-up */ bool algo_selected; /**< The algorithm has been selected */ bool ready_for_hashing; /**< The structure is ready to hash data */ bool hashing; /**< Some data has been hashed, but the digest has not finalised yet */ #endif /* _DEBUG */ }; /** * Return the size of the digest. * @param da the digest calculation structure to identify * @return the size of the digest. */ _MHD_static_inline unsigned int digest_get_size (struct DigestAlgorithm *da) { mhd_assert (! da->uninitialised); mhd_assert (da->algo_selected); #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) return MD5_DIGEST_SIZE; #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) return SHA256_DIGEST_SIZE; #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo) return SHA512_256_DIGEST_SIZE; #endif /* MHD_SHA512_256_SUPPORT */ mhd_assert (0); /* May not happen */ return 0; } #if defined(MHD_MD5_HAS_DEINIT) || defined(MHD_SHA256_HAS_DEINIT) /** * Indicates presence of digest_deinit() function */ #define MHD_DIGEST_HAS_DEINIT 1 #endif /* MHD_MD5_HAS_DEINIT || MHD_SHA256_HAS_DEINIT */ #ifdef MHD_DIGEST_HAS_DEINIT /** * Zero-initialise digest calculation structure. * * This initialisation is enough to safely call #digest_deinit() only. * To make any real digest calculation, #digest_setup_and_init() must be called. * @param da the digest calculation */ _MHD_static_inline void digest_setup_zero (struct DigestAlgorithm *da) { #ifdef _DEBUG da->uninitialised = false; da->algo_selected = false; da->ready_for_hashing = false; da->hashing = false; #endif /* _DEBUG */ da->algo = MHD_DIGEST_BASE_ALGO_INVALID; } /** * De-initialise digest calculation structure. * * This function must be called if #digest_setup_and_init() was called for * @a da. * This function must not be called if @a da was not initialised by * #digest_setup_and_init() or by #digest_setup_zero(). * @param da the digest calculation */ _MHD_static_inline void digest_deinit (struct DigestAlgorithm *da) { mhd_assert (! da->uninitialised); #ifdef MHD_MD5_HAS_DEINIT if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) MHD_MD5_deinit (&da->ctx.md5_ctx); else #endif /* MHD_MD5_HAS_DEINIT */ #ifdef MHD_SHA256_HAS_DEINIT if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) MHD_SHA256_deinit (&da->ctx.sha256_ctx); else #endif /* MHD_SHA256_HAS_DEINIT */ (void) 0; digest_setup_zero (da); } #else /* ! MHD_DIGEST_HAS_DEINIT */ #define digest_setup_zero(da) (void) 0 #define digest_deinit(da) (void) 0 #endif /* ! MHD_DIGEST_HAS_DEINIT */ /** * Set-up the digest calculation structure and initialise with initial values. * * If @a da was successfully initialised, #digest_deinit() must be called * after finishing using of the @a da. * * This function must not be called more than once for any @a da. * * @param da the structure to set-up * @param algo the algorithm to use for digest calculation * @return boolean 'true' if successfully set-up, * false otherwise. */ _MHD_static_inline bool digest_init_one_time (struct DigestAlgorithm *da, enum MHD_DigestBaseAlgo algo) { #ifdef _DEBUG da->uninitialised = false; da->algo_selected = false; da->ready_for_hashing = false; da->hashing = false; #endif /* _DEBUG */ #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_BASE_ALGO_MD5 == algo) { da->algo = MHD_DIGEST_BASE_ALGO_MD5; #ifdef _DEBUG da->algo_selected = true; #endif MHD_MD5_init_one_time (&da->ctx.md5_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif return true; } #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA256 == algo) { da->algo = MHD_DIGEST_BASE_ALGO_SHA256; #ifdef _DEBUG da->algo_selected = true; #endif MHD_SHA256_init_one_time (&da->ctx.sha256_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif return true; } #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA512_256 == algo) { da->algo = MHD_DIGEST_BASE_ALGO_SHA512_256; #ifdef _DEBUG da->algo_selected = true; #endif MHD_SHA512_256_init (&da->ctx.sha512_256_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif return true; } #endif /* MHD_SHA512_256_SUPPORT */ da->algo = MHD_DIGEST_BASE_ALGO_INVALID; return false; /* Unsupported or bad algorithm */ } /** * Feed digest calculation with more data. * @param da the digest calculation * @param data the data to process * @param length the size of the @a data in bytes */ _MHD_static_inline void digest_update (struct DigestAlgorithm *da, const void *data, size_t length) { mhd_assert (! da->uninitialised); mhd_assert (da->algo_selected); mhd_assert (da->ready_for_hashing); #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) MHD_MD5_update (&da->ctx.md5_ctx, (const uint8_t *) data, length); else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) MHD_SHA256_update (&da->ctx.sha256_ctx, (const uint8_t *) data, length); else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo) MHD_SHA512_256_update (&da->ctx.sha512_256_ctx, (const uint8_t *) data, length); else #endif /* MHD_SHA512_256_SUPPORT */ mhd_assert (0); /* May not happen */ #ifdef _DEBUG da->hashing = true; #endif } /** * Feed digest calculation with more data from string. * @param da the digest calculation * @param str the zero-terminated string to process */ _MHD_static_inline void digest_update_str (struct DigestAlgorithm *da, const char *str) { const size_t str_len = strlen (str); digest_update (da, (const uint8_t *) str, str_len); } /** * Feed digest calculation with single colon ':' character. * @param da the digest calculation * @param str the zero-terminated string to process */ _MHD_static_inline void digest_update_with_colon (struct DigestAlgorithm *da) { static const uint8_t colon = (uint8_t) ':'; digest_update (da, &colon, 1); } /** * Finally calculate hash (the digest). * @param da the digest calculation * @param[out] digest the pointer to the buffer to put calculated digest, * must be at least digest_get_size(da) bytes large */ _MHD_static_inline void digest_calc_hash (struct DigestAlgorithm *da, uint8_t *digest) { mhd_assert (! da->uninitialised); mhd_assert (da->algo_selected); mhd_assert (da->ready_for_hashing); #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) { #ifdef MHD_MD5_HAS_FINISH MHD_MD5_finish (&da->ctx.md5_ctx, digest); #ifdef _DEBUG da->ready_for_hashing = false; #endif /* _DEBUG */ #else /* ! MHD_MD5_HAS_FINISH */ MHD_MD5_finish_reset (&da->ctx.md5_ctx, digest); #ifdef _DEBUG da->ready_for_hashing = true; #endif /* _DEBUG */ #endif /* ! MHD_MD5_HAS_FINISH */ } else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) { #ifdef MHD_SHA256_HAS_FINISH MHD_SHA256_finish (&da->ctx.sha256_ctx, digest); #ifdef _DEBUG da->ready_for_hashing = false; #endif /* _DEBUG */ #else /* ! MHD_SHA256_HAS_FINISH */ MHD_SHA256_finish_reset (&da->ctx.sha256_ctx, digest); #ifdef _DEBUG da->ready_for_hashing = true; #endif /* _DEBUG */ #endif /* ! MHD_SHA256_HAS_FINISH */ } else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo) { MHD_SHA512_256_finish (&da->ctx.sha512_256_ctx, digest); #ifdef _DEBUG da->ready_for_hashing = false; #endif /* _DEBUG */ } else #endif /* MHD_SHA512_256_SUPPORT */ mhd_assert (0); /* Should not happen */ #ifdef _DEBUG da->hashing = false; #endif /* _DEBUG */ } /** * Reset the digest calculation structure. * * @param da the structure to reset */ _MHD_static_inline void digest_reset (struct DigestAlgorithm *da) { mhd_assert (! da->uninitialised); mhd_assert (da->algo_selected); mhd_assert (! da->hashing); #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) { #ifdef MHD_MD5_HAS_FINISH mhd_assert (! da->ready_for_hashing); #else /* ! MHD_MD5_HAS_FINISH */ mhd_assert (da->ready_for_hashing); #endif /* ! MHD_MD5_HAS_FINISH */ MHD_MD5_reset (&da->ctx.md5_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif /* _DEBUG */ } else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) { #ifdef MHD_SHA256_HAS_FINISH mhd_assert (! da->ready_for_hashing); #else /* ! MHD_SHA256_HAS_FINISH */ mhd_assert (da->ready_for_hashing); #endif /* ! MHD_SHA256_HAS_FINISH */ MHD_SHA256_reset (&da->ctx.sha256_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif /* _DEBUG */ } else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_BASE_ALGO_SHA512_256 == da->algo) { mhd_assert (! da->ready_for_hashing); MHD_SHA512_256_init (&da->ctx.sha512_256_ctx); #ifdef _DEBUG da->ready_for_hashing = true; #endif } else #endif /* MHD_SHA512_256_SUPPORT */ { #ifdef _DEBUG da->ready_for_hashing = false; #endif mhd_assert (0); /* May not happen, bad algorithm */ } } #if defined(MHD_MD5_HAS_EXT_ERROR) || defined(MHD_SHA256_HAS_EXT_ERROR) /** * Indicates that digest algorithm has external error status */ #define MHD_DIGEST_HAS_EXT_ERROR 1 #endif /* MHD_MD5_HAS_EXT_ERROR || MHD_SHA256_HAS_EXT_ERROR */ #ifdef MHD_DIGEST_HAS_EXT_ERROR /** * Get external error code. * * When external digest calculation used, an error may occur during * initialisation or hashing data. This function checks whether external * error has been reported for digest calculation. * @param da the digest calculation * @return true if external error occurs */ _MHD_static_inline bool digest_ext_error (struct DigestAlgorithm *da) { mhd_assert (! da->uninitialised); mhd_assert (da->algo_selected); #ifdef MHD_MD5_HAS_EXT_ERROR if (MHD_DIGEST_BASE_ALGO_MD5 == da->algo) return 0 != da->ctx.md5_ctx.ext_error; #endif /* MHD_MD5_HAS_EXT_ERROR */ #ifdef MHD_SHA256_HAS_EXT_ERROR if (MHD_DIGEST_BASE_ALGO_SHA256 == da->algo) return 0 != da->ctx.sha256_ctx.ext_error; #endif /* MHD_MD5_HAS_EXT_ERROR */ return false; } #else /* ! MHD_DIGEST_HAS_EXT_ERROR */ #define digest_ext_error(da) (false) #endif /* ! MHD_DIGEST_HAS_EXT_ERROR */ /** * Extract timestamp from the given nonce. * @param nonce the nonce to check * @param noncelen the length of the nonce, zero for autodetect * @param[out] ptimestamp the pointer to store extracted timestamp * @return true if timestamp was extracted, * false if nonce does not have valid timestamp. */ static bool get_nonce_timestamp (const char *const nonce, size_t noncelen, uint64_t *const ptimestamp) { if (0 == noncelen) noncelen = strlen (nonce); if (true #ifdef MHD_MD5_SUPPORT && (NONCE_STD_LEN (MD5_DIGEST_SIZE) != noncelen) #endif /* MHD_MD5_SUPPORT */ #if defined(MHD_SHA256_SUPPORT) || defined(MHD_SHA512_256_SUPPORT) && (NONCE_STD_LEN (SHA256_SHA512_256_DIGEST_SIZE) != noncelen) #endif /* MHD_SHA256_SUPPORT */ ) return false; if (TIMESTAMP_CHARS_LEN != MHD_strx_to_uint64_n_ (nonce + noncelen - TIMESTAMP_CHARS_LEN, TIMESTAMP_CHARS_LEN, ptimestamp)) return false; return true; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /** * Super-fast xor-based "hash" function * * @param data the data to calculate hash for * @param data_size the size of the data in bytes * @return the "hash" */ static uint32_t fast_simple_hash (const uint8_t *data, size_t data_size) { uint32_t hash; if (0 != data_size) { size_t i; hash = data[0]; for (i = 1; i < data_size; i++) hash = _MHD_ROTL32 (hash, 7) ^ data[i]; } else hash = 0; return hash; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ /** * Get index of the nonce in the nonce-nc map array. * * @param arr_size the size of nonce_nc array * @param nonce the pointer that referenced a zero-terminated array of nonce * @param noncelen the length of @a nonce, in characters * @return #MHD_YES if successful, #MHD_NO if invalid (or we have no NC array) */ static size_t get_nonce_nc_idx (size_t arr_size, const char *nonce, size_t noncelen) { mhd_assert (0 != arr_size); mhd_assert (0 != noncelen); return fast_simple_hash ((const uint8_t *) nonce, noncelen) % arr_size; } /** * Check nonce-nc map array with the new nonce counter. * * @param connection The MHD connection structure * @param nonce the pointer that referenced hex nonce, does not need to be * zero-terminated * @param noncelen the length of @a nonce, in characters * @param nc The nonce counter * @return #MHD_DAUTH_NONCENC_OK if successful, * #MHD_DAUTH_NONCENC_STALE if nonce is stale (or no nonce-nc array * is available), * #MHD_DAUTH_NONCENC_WRONG if nonce was not recodered in nonce-nc map * array, while it should. */ static enum MHD_CheckNonceNC_ check_nonce_nc (struct MHD_Connection *connection, const char *nonce, size_t noncelen, uint64_t nonce_time, uint64_t nc) { struct MHD_Daemon *daemon = MHD_get_master (connection->daemon); struct MHD_NonceNc *nn; uint32_t mod; enum MHD_CheckNonceNC_ ret; mhd_assert (0 != noncelen); mhd_assert (0 != nc); if (MAX_DIGEST_NONCE_LENGTH < noncelen) return MHD_CHECK_NONCENC_WRONG; /* This should be impossible, but static analysis tools have a hard time with it *and* this also protects against unsafe modifications that may happen in the future... */ mod = daemon->nonce_nc_size; if (0 == mod) return MHD_CHECK_NONCENC_STALE; /* no array! */ if (nc >= UINT32_MAX - 64) return MHD_CHECK_NONCENC_STALE; /* Overflow, unrealistically high value */ nn = &daemon->nnc[get_nonce_nc_idx (mod, nonce, noncelen)]; MHD_mutex_lock_chk_ (&daemon->nnc_lock); /* The nonces recorded in the array do not all have the same length: the * daemon may serve several digest algorithms at the same time and the * length of the nonce depends on the size of the digest (44 characters * for MD5, 76 for SHA-256 and SHA-512/256). The slot selected by the * hash of the client's nonce may therefore hold a nonce of a completely * different length, which must not be inspected with the client's * length. */ if (strlen (nn->nonce) != noncelen) { if (0 == nn->nonce[0]) { /* The slot was never used, while the client's nonce value should be * recorded when it was generated by MHD */ ret = MHD_CHECK_NONCENC_WRONG; } else { /* The slot holds a nonce generated for another digest algorithm. * The client's nonce is not (or no longer) recorded. */ ret = MHD_CHECK_NONCENC_STALE; } } else if (0 != memcmp (nn->nonce, nonce, noncelen)) { /* The nonce in the slot does not match nonce from the client */ if (0 == nn->nonce[0]) { /* The slot was never used, while the client's nonce value should be * recorded when it was generated by MHD */ ret = MHD_CHECK_NONCENC_WRONG; } else { uint64_t slot_ts; /**< The timestamp in the slot */ if (! get_nonce_timestamp (nn->nonce, noncelen, &slot_ts)) { mhd_assert (0); /* The value is the slot is wrong */ ret = MHD_CHECK_NONCENC_STALE; } else { /* Unsigned value, will be large if nonce_time is less than slot_ts */ const uint64_t ts_diff = TRIM_TO_TIMESTAMP (nonce_time - slot_ts); if ((REUSE_TIMEOUT * 1000) >= ts_diff) { /* The nonce from the client may not have been placed in the slot * because another nonce in that slot has not yet expired. */ ret = MHD_CHECK_NONCENC_STALE; } else if (TRIM_TO_TIMESTAMP (UINT64_MAX) / 2 >= ts_diff) { /* Too large value means that nonce_time is less than slot_ts. * The nonce from the client may have been overwritten by the newer * nonce. */ ret = MHD_CHECK_NONCENC_STALE; } else { /* The nonce from the client should be generated after the nonce * in the slot has been expired, the nonce must be recorded, but * it's not. */ ret = MHD_CHECK_NONCENC_WRONG; } } } } else if (nc > nn->nc) { /* 'nc' is larger, shift bitmask and bump limit */ const uint32_t jump_size = (uint32_t) nc - nn->nc; if (64 > jump_size) { /* small jump, less than mask width */ nn->nmask <<= jump_size; /* Set bit for the old 'nc' value */ nn->nmask |= (UINT64_C (1) << (jump_size - 1)); } else if (64 == jump_size) nn->nmask = (UINT64_C (1) << 63); else nn->nmask = 0; /* big jump, unset all bits in the mask */ nn->nc = (uint32_t) nc; ret = MHD_CHECK_NONCENC_OK; } else if (nc < nn->nc) { /* Note that we use 64 here, as we do not store the bit for 'nn->nc' itself in 'nn->nmask' */ if ( (nc + 64 >= nn->nc) && (0 == ((UINT64_C (1) << (nn->nc - nc - 1)) & nn->nmask)) ) { /* Out-of-order nonce, but within 64-bit bitmask, set bit */ nn->nmask |= (UINT64_C (1) << (nn->nc - nc - 1)); ret = MHD_CHECK_NONCENC_OK; } else /* 'nc' was already used or too old (more then 64 values ago) */ ret = MHD_CHECK_NONCENC_STALE; } else /* if (nc == nn->nc) */ /* 'nc' was already used */ ret = MHD_CHECK_NONCENC_STALE; MHD_mutex_unlock_chk_ (&daemon->nnc_lock); return ret; } /** * Get username type used by the client. * This function does not check whether userhash can be decoded or * extended notation (if used) is valid. * @param params the Digest Authorization parameters * @return the type of username */ _MHD_static_inline enum MHD_DigestAuthUsernameType get_rq_uname_type (const struct MHD_RqDAuth *params) { if (NULL != params->username.value.str) { if (NULL == params->username_ext.value.str) return params->userhash ? MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH : MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD; else /* Both 'username' and 'username*' are used */ return MHD_DIGEST_AUTH_UNAME_TYPE_INVALID; } else if (NULL != params->username_ext.value.str) { if (! params->username_ext.quoted && ! params->userhash && (MHD_DAUTH_EXT_PARAM_MIN_LEN <= params->username_ext.value.len) ) return MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED; else return MHD_DIGEST_AUTH_UNAME_TYPE_INVALID; } return MHD_DIGEST_AUTH_UNAME_TYPE_MISSING; } /** * Get total size required for 'username' and 'userhash_bin' * @param params the Digest Authorization parameters * @param uname_type the type of username * @return the total size required for 'username' and * 'userhash_bin' is userhash is used */ _MHD_static_inline size_t get_rq_unames_size (const struct MHD_RqDAuth *params, enum MHD_DigestAuthUsernameType uname_type) { size_t s; mhd_assert (get_rq_uname_type (params) == uname_type); s = 0; if ((MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD == uname_type) || (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == uname_type) ) { s += params->username.value.len + 1; /* Add one byte for zero-termination */ if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == uname_type) s += (params->username.value.len + 1) / 2; } else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED == uname_type) s += params->username_ext.value.len - MHD_DAUTH_EXT_PARAM_MIN_LEN + 1; /* Add one byte for zero-termination */ return s; } /** * Get unquoted version of Digest Authorization parameter. * This function automatically zero-teminate the result. * @param param the parameter to extract * @param[out] buf the output buffer, must be enough size to hold the result, * the recommended size is 'param->value.len + 1' * @return the size of the result, not including the terminating zero */ static size_t get_rq_param_unquoted_copy_z (const struct MHD_RqDAuthParam *param, char *buf) { size_t len; mhd_assert (NULL != param->value.str); if (! param->quoted) { memcpy (buf, param->value.str, param->value.len); buf [param->value.len] = 0; return param->value.len; } len = MHD_str_unquote (param->value.str, param->value.len, buf); mhd_assert (0 != len); mhd_assert (len < param->value.len); buf[len] = 0; return len; } /** * Get decoded version of username from extended notation. * This function automatically zero-teminate the result. * @param uname_ext the string of client's 'username*' parameter value * @param uname_ext_len the length of @a uname_ext in chars * @param[out] buf the output buffer to put decoded username value * @param buf_size the size of @a buf * @return the number of characters copied to the output buffer or * -1 if wrong extended notation is used. */ static ssize_t get_rq_extended_uname_copy_z (const char *uname_ext, size_t uname_ext_len, char *buf, size_t buf_size) { size_t r; size_t w; if ((size_t) SSIZE_MAX < uname_ext_len) return -1; /* Too long input string */ if (MHD_DAUTH_EXT_PARAM_MIN_LEN > uname_ext_len) return -1; /* Required prefix is missing */ if (! MHD_str_equal_caseless_bin_n_ (uname_ext, MHD_DAUTH_EXT_PARAM_PREFIX, MHD_STATICSTR_LEN_ ( \ MHD_DAUTH_EXT_PARAM_PREFIX))) return -1; /* Only UTF-8 is supported, as it is implied by RFC 7616 */ r = MHD_STATICSTR_LEN_ (MHD_DAUTH_EXT_PARAM_PREFIX); /* Skip language tag */ while (r < uname_ext_len && '\'' != uname_ext[r]) { const char chr = uname_ext[r]; if ((' ' == chr) || ('\t' == chr) || ('\"' == chr) || (',' == chr) || (';' == chr) ) return -1; /* Wrong char in language tag */ r++; } if (r >= uname_ext_len) return -1; /* The end of the language tag was not found */ r++; /* Advance to the next char */ w = MHD_str_pct_decode_strict_n_ (uname_ext + r, uname_ext_len - r, buf, buf_size); if ((0 == w) && (0 != uname_ext_len - r)) return -1; /* Broken percent encoding */ buf[w] = 0; /* Zero terminate the result */ mhd_assert (SSIZE_MAX > w); return (ssize_t) w; } /** * Get copy of username used by the client. * @param params the Digest Authorization parameters * @param uname_type the type of username * @param[out] uname_info the pointer to the structure to be filled * @param buf the buffer to be used for usernames * @param buf_size the size of the @a buf * @return the size of the @a buf used by pointers in @a unames structure */ static size_t get_rq_uname (const struct MHD_RqDAuth *params, enum MHD_DigestAuthUsernameType uname_type, struct MHD_DigestAuthUsernameInfo *uname_info, uint8_t *buf, size_t buf_size) { size_t buf_used; buf_used = 0; mhd_assert (get_rq_uname_type (params) == uname_type); mhd_assert (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID != uname_type); mhd_assert (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING != uname_type); uname_info->username = NULL; uname_info->username_len = 0; uname_info->userhash_hex = NULL; uname_info->userhash_hex_len = 0; uname_info->userhash_bin = NULL; if (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD == uname_type) { uname_info->username = (char *) (buf + buf_used); uname_info->username_len = get_rq_param_unquoted_copy_z (¶ms->username, uname_info->username); buf_used += uname_info->username_len + 1; uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD; } else if (MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH == uname_type) { size_t res; uname_info->userhash_hex = (char *) (buf + buf_used); uname_info->userhash_hex_len = get_rq_param_unquoted_copy_z (¶ms->username, uname_info->userhash_hex); buf_used += uname_info->userhash_hex_len + 1; uname_info->userhash_bin = (uint8_t *) (buf + buf_used); res = MHD_hex_to_bin (uname_info->userhash_hex, uname_info->userhash_hex_len, uname_info->userhash_bin); if (res != uname_info->userhash_hex_len / 2) { uname_info->userhash_bin = NULL; uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_INVALID; } else { /* Avoid pointers outside allocated region when the size is zero */ if (0 == res) uname_info->userhash_bin = (uint8_t *) uname_info->username; uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_USERHASH; buf_used += res; } } else if (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED == uname_type) { ssize_t res; res = get_rq_extended_uname_copy_z (params->username_ext.value.str, params->username_ext.value.len, (char *) (buf + buf_used), buf_size - buf_used); if (0 > res) uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_INVALID; else { uname_info->username = (char *) (buf + buf_used); uname_info->username_len = (size_t) res; uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED; buf_used += uname_info->username_len + 1; } } else { mhd_assert (0); uname_info->uname_type = MHD_DIGEST_AUTH_UNAME_TYPE_INVALID; } mhd_assert (buf_size >= buf_used); return buf_used; } /** * Result of request's Digest Authorization 'nc' value extraction */ enum MHD_GetRqNCResult { MHD_GET_RQ_NC_NONE = -1, /**< No 'nc' value */ MHD_GET_RQ_NC_VALID = 0, /**< Readable 'nc' value */ MHD_GET_RQ_NC_TOO_LONG = 1, /**< The 'nc' value is too long */ MHD_GET_RQ_NC_TOO_LARGE = 2,/**< The 'nc' value is too big to fit uint32_t */ MHD_GET_RQ_NC_BROKEN = 3 /**< The 'nc' value is not a number */ }; /** * Get 'nc' value from request's Authorization header * @param params the request digest authentication * @param[out] nc the pointer to put nc value to * @return enum value indicating the result */ static enum MHD_GetRqNCResult get_rq_nc (const struct MHD_RqDAuth *params, uint32_t *nc) { const struct MHD_RqDAuthParam *const nc_param = ¶ms->nc; char unq[16]; const char *val; size_t val_len; size_t res; uint64_t nc_val; if (NULL == nc_param->value.str) return MHD_GET_RQ_NC_NONE; if (0 == nc_param->value.len) return MHD_GET_RQ_NC_BROKEN; if (! nc_param->quoted) { val = nc_param->value.str; val_len = nc_param->value.len; } else { /* Actually no backslashes must be used in 'nc' */ if (sizeof(unq) < params->nc.value.len) return MHD_GET_RQ_NC_TOO_LONG; val_len = MHD_str_unquote (nc_param->value.str, nc_param->value.len, unq); if (0 == val_len) return MHD_GET_RQ_NC_BROKEN; val = unq; } res = MHD_strx_to_uint64_n_ (val, val_len, &nc_val); if (0 == res) { const char f = val[0]; if ( (('9' >= f) && ('0' <= f)) || (('F' >= f) && ('A' <= f)) || (('a' <= f) && ('f' >= f)) ) return MHD_GET_RQ_NC_TOO_LARGE; else return MHD_GET_RQ_NC_BROKEN; } if (val_len != res) return MHD_GET_RQ_NC_BROKEN; if (UINT32_MAX < nc_val) return MHD_GET_RQ_NC_TOO_LARGE; *nc = (uint32_t) nc_val; return MHD_GET_RQ_NC_VALID; } /** * Get information about Digest Authorization client's header. * * @param connection The MHD connection structure * @return NULL no valid Digest Authorization header is used in the request; * a pointer structure with information if the valid request header * found, free using #MHD_free(). * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_DigestAuthInfo * MHD_digest_auth_get_request_info3 (struct MHD_Connection *connection) { const struct MHD_RqDAuth *params; struct MHD_DigestAuthInfo *info; enum MHD_DigestAuthUsernameType uname_type; size_t unif_buf_size; uint8_t *unif_buf_ptr; size_t unif_buf_used; enum MHD_GetRqNCResult nc_res; params = MHD_get_rq_dauth_params_ (connection); if (NULL == params) return NULL; unif_buf_size = 0; uname_type = get_rq_uname_type (params); unif_buf_size += get_rq_unames_size (params, uname_type); if (NULL != params->opaque.value.str) unif_buf_size += params->opaque.value.len + 1; /* Add one for zero-termination */ if (NULL != params->realm.value.str) unif_buf_size += params->realm.value.len + 1; /* Add one for zero-termination */ info = (struct MHD_DigestAuthInfo *) MHD_calloc_ (1, (sizeof(struct MHD_DigestAuthInfo)) + unif_buf_size); if (NULL == info) return NULL; unif_buf_ptr = (uint8_t *) (info + 1); unif_buf_used = 0; info->algo3 = params->algo3; if ( (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING != uname_type) && (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID != uname_type) ) unif_buf_used += get_rq_uname (params, uname_type, (struct MHD_DigestAuthUsernameInfo *) info, unif_buf_ptr + unif_buf_used, unif_buf_size - unif_buf_used); else info->uname_type = uname_type; if (NULL != params->opaque.value.str) { info->opaque = (char *) (unif_buf_ptr + unif_buf_used); info->opaque_len = get_rq_param_unquoted_copy_z (¶ms->opaque, info->opaque); unif_buf_used += info->opaque_len + 1; } if (NULL != params->realm.value.str) { info->realm = (char *) (unif_buf_ptr + unif_buf_used); info->realm_len = get_rq_param_unquoted_copy_z (¶ms->realm, info->realm); unif_buf_used += info->realm_len + 1; } mhd_assert (unif_buf_size >= unif_buf_used); info->qop = params->qop; if (NULL != params->cnonce.value.str) info->cnonce_len = params->cnonce.value.len; else info->cnonce_len = 0; nc_res = get_rq_nc (params, &info->nc); if (MHD_GET_RQ_NC_VALID != nc_res) info->nc = MHD_DIGEST_AUTH_INVALID_NC_VALUE; return info; } /** * Get the username from Digest Authorization client's header. * * @param connection The MHD connection structure * @return NULL if no valid Digest Authorization header is used in the request, * or no username parameter is present in the header, or username is * provided incorrectly by client (see description for * #MHD_DIGEST_AUTH_UNAME_TYPE_INVALID); * a pointer structure with information if the valid request header * found, free using #MHD_free(). * @sa MHD_digest_auth_get_request_info3() provides more complete information * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN struct MHD_DigestAuthUsernameInfo * MHD_digest_auth_get_username3 (struct MHD_Connection *connection) { const struct MHD_RqDAuth *params; struct MHD_DigestAuthUsernameInfo *uname_info; enum MHD_DigestAuthUsernameType uname_type; size_t unif_buf_size; uint8_t *unif_buf_ptr; size_t unif_buf_used; params = MHD_get_rq_dauth_params_ (connection); if (NULL == params) return NULL; uname_type = get_rq_uname_type (params); if ( (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING == uname_type) || (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID == uname_type) ) return NULL; unif_buf_size = get_rq_unames_size (params, uname_type); uname_info = (struct MHD_DigestAuthUsernameInfo *) MHD_calloc_ (1, (sizeof(struct MHD_DigestAuthUsernameInfo)) + unif_buf_size); if (NULL == uname_info) return NULL; unif_buf_ptr = (uint8_t *) (uname_info + 1); unif_buf_used = get_rq_uname (params, uname_type, uname_info, unif_buf_ptr, unif_buf_size); mhd_assert (unif_buf_size >= unif_buf_used); (void) unif_buf_used; /* Mute compiler warning on non-debug builds */ mhd_assert (MHD_DIGEST_AUTH_UNAME_TYPE_MISSING != uname_info->uname_type); if (MHD_DIGEST_AUTH_UNAME_TYPE_INVALID == uname_info->uname_type) { free (uname_info); return NULL; } mhd_assert (uname_type == uname_info->uname_type); uname_info->algo3 = params->algo3; return uname_info; } /** * Get the username from the authorization header sent by the client * * This function supports username in standard and extended notations. * "userhash" is not supported by this function. * * @param connection The MHD connection structure * @return NULL if no username could be found, username provided as * "userhash", extended notation broken or memory allocation error * occurs; * a pointer to the username if found, free using #MHD_free(). * @warning Returned value must be freed by #MHD_free(). * @sa #MHD_digest_auth_get_username3() * @ingroup authentication */ _MHD_EXTERN char * MHD_digest_auth_get_username (struct MHD_Connection *connection) { const struct MHD_RqDAuth *params; char *username; size_t buf_size; enum MHD_DigestAuthUsernameType uname_type; params = MHD_get_rq_dauth_params_ (connection); if (NULL == params) return NULL; uname_type = get_rq_uname_type (params); if ( (MHD_DIGEST_AUTH_UNAME_TYPE_STANDARD != uname_type) && (MHD_DIGEST_AUTH_UNAME_TYPE_EXTENDED != uname_type) ) return NULL; buf_size = get_rq_unames_size (params, uname_type); mhd_assert (0 != buf_size); username = (char *) MHD_calloc_ (1, buf_size); if (NULL == username) return NULL; if (1) { struct MHD_DigestAuthUsernameInfo uname_strct; size_t used; memset (&uname_strct, 0, sizeof(uname_strct)); used = get_rq_uname (params, uname_type, &uname_strct, (uint8_t *) username, buf_size); if (uname_type != uname_strct.uname_type) { /* Broken encoding for extended notation */ free (username); return NULL; } (void) used; /* Mute compiler warning for non-debug builds */ mhd_assert (buf_size >= used); } return username; } /** * Calculate the server nonce so that it mitigates replay attacks * The current format of the nonce is ... * H(timestamp:random data:various parameters) + Hex(timestamp) * * @param nonce_time The amount of time in seconds for a nonce to be invalid * @param mthd_e HTTP method as enum value * @param method HTTP method as a string * @param rnd the pointer to a character array for the random seed * @param rnd_size The size of the random seed array @a rnd * @param saddr the pointer to the socket address structure * @param saddr_size the size of the socket address structure @a saddr * @param uri the HTTP URI (in MHD, without the arguments ("?k=v") * @param uri_len the length of the @a uri * @param first_header the pointer to the first request's header * @param realm A string of characters that describes the realm of auth. * @param realm_len the length of the @a realm. * @param bind_options the nonce bind options (#MHD_DAuthBindNonce values). * @param da digest algorithm to use * @param[out] nonce the pointer to a character array for the nonce to put in, * must provide NONCE_STD_LEN(digest_get_size(da)) bytes, * result is NOT zero-terminated */ static void calculate_nonce (uint64_t nonce_time, enum MHD_HTTP_Method mthd_e, const char *method, const char *rnd, size_t rnd_size, const struct sockaddr_storage *saddr, size_t saddr_size, const char *uri, size_t uri_len, const struct MHD_HTTP_Req_Header *first_header, const char *realm, size_t realm_len, unsigned int bind_options, struct DigestAlgorithm *da, char *nonce) { mhd_assert (! da->hashing); if (1) { /* Add the timestamp to the hash calculation */ uint8_t timestamp[TIMESTAMP_BIN_SIZE]; /* If the nonce_time is milliseconds, then the same 48 bit value will repeat * every 8 919 years, which is more than enough to mitigate a replay attack */ #if TIMESTAMP_BIN_SIZE != 6 #error The code needs to be updated here #endif timestamp[0] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 0))); timestamp[1] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 1))); timestamp[2] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 2))); timestamp[3] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 3))); timestamp[4] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 4))); timestamp[5] = (uint8_t) (nonce_time >> (8 * (TIMESTAMP_BIN_SIZE - 1 - 5))); MHD_bin_to_hex (timestamp, sizeof (timestamp), nonce + digest_get_size (da) * 2); digest_update (da, timestamp, sizeof (timestamp)); } if (rnd_size > 0) { /* Add the unique random value to the hash calculation */ digest_update_with_colon (da); digest_update (da, rnd, rnd_size); } if ( (MHD_DAUTH_BIND_NONCE_NONE == bind_options) && (0 != saddr_size) ) { /* Add full client address including source port to make unique nonces * for requests received exactly at the same time */ digest_update_with_colon (da); digest_update (da, saddr, saddr_size); } if ( (0 != (bind_options & MHD_DAUTH_BIND_NONCE_CLIENT_IP)) && (0 != saddr_size) ) { /* Add the client's IP address to the hash calculation */ digest_update_with_colon (da); if (AF_INET == saddr->ss_family) digest_update (da, &((const struct sockaddr_in *) saddr)->sin_addr, sizeof(((const struct sockaddr_in *) saddr)->sin_addr)); #ifdef HAVE_INET6 else if (AF_INET6 == saddr->ss_family) digest_update (da, &((const struct sockaddr_in6 *) saddr)->sin6_addr, sizeof(((const struct sockaddr_in6 *) saddr)->sin6_addr)); #endif /* HAVE_INET6 */ } if ( (MHD_DAUTH_BIND_NONCE_NONE == bind_options) || (0 != (bind_options & MHD_DAUTH_BIND_NONCE_URI))) { /* Add the request method to the hash calculation */ digest_update_with_colon (da); if (MHD_HTTP_MTHD_OTHER != mthd_e) { uint8_t mthd_for_hash; if (MHD_HTTP_MTHD_HEAD != mthd_e) mthd_for_hash = (uint8_t) mthd_e; else /* Treat HEAD method in the same way as GET method */ mthd_for_hash = (uint8_t) MHD_HTTP_MTHD_GET; digest_update (da, &mthd_for_hash, sizeof(mthd_for_hash)); } else digest_update_str (da, method); } if (0 != (bind_options & MHD_DAUTH_BIND_NONCE_URI)) { /* Add the request URI to the hash calculation */ digest_update_with_colon (da); digest_update (da, uri, uri_len); } if (0 != (bind_options & MHD_DAUTH_BIND_NONCE_URI_PARAMS)) { /* Add the request URI parameters to the hash calculation */ const struct MHD_HTTP_Req_Header *h; digest_update_with_colon (da); for (h = first_header; NULL != h; h = h->next) { if (MHD_GET_ARGUMENT_KIND != h->kind) continue; digest_update (da, "\0", 2); if (0 != h->header_size) digest_update (da, h->header, h->header_size); digest_update (da, "", 1); if (0 != h->value_size) digest_update (da, h->value, h->value_size); } } if ( (MHD_DAUTH_BIND_NONCE_NONE == bind_options) || (0 != (bind_options & MHD_DAUTH_BIND_NONCE_REALM))) { /* Add the realm to the hash calculation */ digest_update_with_colon (da); digest_update (da, realm, realm_len); } if (1) { uint8_t hash[MAX_DIGEST]; digest_calc_hash (da, hash); MHD_bin_to_hex (hash, digest_get_size (da), nonce); } } /** * Check whether it is possible to use slot in nonce-nc map array. * * Should be called with mutex held to avoid external modification of * the slot data. * * @param nn the pointer to the nonce-nc slot * @param now the current time * @param new_nonce the new nonce supposed to be stored in this slot, * zero-terminated * @param new_nonce_len the length of the @a new_nonce in chars, not including * the terminating zero. * @return true if the slot can be used to store the new nonce, * false otherwise. */ static bool is_slot_available (const struct MHD_NonceNc *const nn, const uint64_t now, const char *const new_nonce, size_t new_nonce_len) { uint64_t timestamp; bool timestamp_valid; mhd_assert (new_nonce_len <= NONCE_STD_LEN (MAX_DIGEST)); mhd_assert (NONCE_STD_LEN (MAX_DIGEST) <= MAX_DIGEST_NONCE_LENGTH); if (0 == nn->nonce[0]) return true; /* The slot is empty */ if (0 == memcmp (nn->nonce, new_nonce, new_nonce_len)) { /* The slot has the same nonce already. This nonce cannot be registered * again as it would just clear 'nc' usage history. */ return false; } if (0 != nn->nc) return true; /* Client already used the nonce in this slot at least one time, re-use the slot */ /* The nonce must be zero-terminated */ mhd_assert (0 == nn->nonce[sizeof(nn->nonce) - 1]); if (0 != nn->nonce[sizeof(nn->nonce) - 1]) return true; /* Wrong nonce format in the slot */ timestamp_valid = get_nonce_timestamp (nn->nonce, 0, ×tamp); mhd_assert (timestamp_valid); if (! timestamp_valid) return true; /* Invalid timestamp in nonce-nc, should not be possible */ if ((REUSE_TIMEOUT * 1000) < TRIM_TO_TIMESTAMP (now - timestamp)) return true; return false; } /** * Calculate the server nonce so that it mitigates replay attacks and add * the new nonce to the nonce-nc map array. * * @param connection the MHD connection structure * @param timestamp the current timestamp * @param realm the string of characters that describes the realm of auth * @param realm_len the length of the @a realm * @param da the digest algorithm to use * @param[out] nonce the pointer to a character array for the nonce to put in, * must provide NONCE_STD_LEN(digest_get_size(da)) bytes, * result is NOT zero-terminated * @return true if the new nonce has been added to the nonce-nc map array, * false otherwise. */ static bool calculate_add_nonce (struct MHD_Connection *const connection, uint64_t timestamp, const char *realm, size_t realm_len, struct DigestAlgorithm *da, char *nonce) { struct MHD_Daemon *const daemon = MHD_get_master (connection->daemon); struct MHD_NonceNc *nn; const size_t nonce_size = NONCE_STD_LEN (digest_get_size (da)); bool ret; mhd_assert (! da->hashing); mhd_assert (MAX_DIGEST_NONCE_LENGTH >= nonce_size); mhd_assert (0 != nonce_size); calculate_nonce (timestamp, connection->rq.http_mthd, connection->rq.method, daemon->digest_auth_random, daemon->digest_auth_rand_size, connection->addr, (size_t) connection->addr_len, connection->rq.url, connection->rq.url_len, connection->rq.headers_received, realm, realm_len, daemon->dauth_bind_type, da, nonce); #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return false; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ if (0 == daemon->nonce_nc_size) return false; /* Sanity check for values */ mhd_assert (MAX_DIGEST_NONCE_LENGTH == NONCE_STD_LEN (MAX_DIGEST)); nn = daemon->nnc + get_nonce_nc_idx (daemon->nonce_nc_size, nonce, nonce_size); MHD_mutex_lock_chk_ (&daemon->nnc_lock); if (is_slot_available (nn, timestamp, nonce, nonce_size)) { memcpy (nn->nonce, nonce, nonce_size); nn->nonce[nonce_size] = 0; /* With terminating zero */ nn->nc = 0; nn->nmask = 0; ret = true; } else ret = false; MHD_mutex_unlock_chk_ (&daemon->nnc_lock); return ret; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_DISABLE_ /** * Calculate the server nonce so that it mitigates replay attacks and add * the new nonce to the nonce-nc map array. * * @param connection the MHD connection structure * @param realm A string of characters that describes the realm of auth. * @param da digest algorithm to use * @param[out] nonce the pointer to a character array for the nonce to put in, * must provide NONCE_STD_LEN(digest_get_size(da)) bytes, * result is NOT zero-terminated */ static bool calculate_add_nonce_with_retry (struct MHD_Connection *const connection, const char *realm, struct DigestAlgorithm *da, char *nonce) { const uint64_t timestamp1 = MHD_monotonic_msec_counter (); const size_t realm_len = strlen (realm); mhd_assert (! da->hashing); #ifdef HAVE_MESSAGES if (0 == MHD_get_master (connection->daemon)->digest_auth_rand_size) MHD_DLOG (connection->daemon, _ ("Random value was not initialised by " \ "MHD_OPTION_DIGEST_AUTH_RANDOM or " \ "MHD_OPTION_DIGEST_AUTH_RANDOM_COPY, generated nonces " \ "are predictable.\n")); #endif if (! calculate_add_nonce (connection, timestamp1, realm, realm_len, da, nonce)) { /* Either: * 1. The same nonce was already generated. If it will be used then one * of the clients will fail (as no initial 'nc' value could be given to * the client, the second client which will use 'nc=00000001' will fail). * 2. Another nonce uses the same slot, and this nonce never has been * used by the client and this nonce is still fresh enough. */ const size_t digest_size = digest_get_size (da); char nonce2[NONCE_STD_LEN (MAX_DIGEST) + 1]; uint64_t timestamp2; #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return false; /* No need to re-try */ #endif /* MHD_DIGEST_HAS_EXT_ERROR */ if (0 == MHD_get_master (connection->daemon)->nonce_nc_size) return false; /* No need to re-try */ timestamp2 = MHD_monotonic_msec_counter (); if (timestamp1 == timestamp2) { /* The timestamps are equal, need to generate some arbitrary * difference for nonce. */ /* As the number is needed only to differentiate clients, weak * pseudo-random generators could be used. Seeding is not needed. */ uint64_t base1; uint32_t base2; uint16_t base3; uint8_t base4; #ifdef HAVE_RANDOM base1 = ((uint64_t) random ()) ^ UINT64_C (0x54a5acff5be47e63); base4 = 0xb8; #elif defined(HAVE_RAND) base1 = ((uint64_t) rand ()) ^ UINT64_C (0xc4bcf553b12f3965); base4 = 0x92; #else /* Monotonic msec counter alone does not really help here as it is already known that this value is not unique. */ base1 = ((uint64_t) (uintptr_t) nonce2) ^ UINT64_C (0xf2e1b21bc6c92655); base2 = ((uint32_t) (base1 >> 32)) ^ ((uint32_t) base1); base2 = _MHD_ROTR32 (base2, 4); base3 = ((uint16_t) (base2 >> 16)) ^ ((uint16_t) base2); base4 = ((uint8_t) (base3 >> 8)) ^ ((uint8_t) base3); base1 = ((uint64_t) MHD_monotonic_msec_counter ()) ^ UINT64_C (0xccab93f72cf5b15); #endif base2 = ((uint32_t) (base1 >> 32)) ^ ((uint32_t) base1); base2 = _MHD_ROTL32 (base2, (((base4 >> 4) ^ base4) % 32)); base3 = ((uint16_t) (base2 >> 16)) ^ ((uint16_t) base2); base4 = ((uint8_t) (base3 >> 8)) ^ ((uint8_t) base3); /* Use up to 127 ms difference */ timestamp2 -= (base4 & DAUTH_JUMPBACK_MAX); if (timestamp1 == timestamp2) timestamp2 -= 2; /* Fallback value */ } digest_reset (da); if (! calculate_add_nonce (connection, timestamp2, realm, realm_len, da, nonce2)) { /* No free slot has been found. Re-tries are expensive, just use * the generated nonce. As it is not stored in nonce-nc map array, * the next request of the client will be recognized as valid, but 'stale' * so client should re-try automatically. */ return false; } memcpy (nonce, nonce2, NONCE_STD_LEN (digest_size)); } return true; } MHD_DATA_TRUNCATION_RUNTIME_CHECK_RESTORE_ /** * Calculate userdigest, return it as binary data. * * It is equal to H(A1) for non-session algorithms. * * MHD internal version. * * @param da the digest algorithm * @param username the username to use * @param username_len the length of the @a username * @param realm the realm to use * @param realm_len the length of the @a realm * @param password the password, must be zero-terminated * @param[out] ha1_bin the output buffer, must have at least * #digest_get_size(da) bytes available */ _MHD_static_inline void calc_userdigest (struct DigestAlgorithm *da, const char *username, const size_t username_len, const char *realm, const size_t realm_len, const char *password, uint8_t *ha1_bin) { mhd_assert (! da->hashing); digest_update (da, username, username_len); digest_update_with_colon (da); digest_update (da, realm, realm_len); digest_update_with_colon (da); digest_update_str (da, password); digest_calc_hash (da, ha1_bin); } /** * Calculate userdigest, return it as a binary data. * * The "userdigest" is the hash of the "username:realm:password" string. * * The "userdigest" can be used to avoid storing the password in clear text * in database/files * * This function is designed to improve security of stored credentials, * the "userdigest" does not improve security of the authentication process. * * The results can be used to store username & userdigest pairs instead of * username & password pairs. To further improve security, application may * store username & userhash & userdigest triplets. * * @param algo3 the digest algorithm * @param username the username * @param realm the realm * @param password the password * @param[out] userdigest_bin the output buffer for userdigest; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3) bytes of * userdigest upon return * @param bin_buf_size the size of the @a userdigest_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3) bytes long * @return MHD_YES on success, * MHD_NO if @a userdigest_bin is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH). * @sa #MHD_digest_auth_check_digest3() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userdigest (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, const char *password, void *userdigest_bin, size_t bin_buf_size) { struct DigestAlgorithm da; enum MHD_Result ret; if (! digest_init_one_time (&da, get_base_digest_algo (algo3))) return MHD_NO; if (digest_get_size (&da) > bin_buf_size) ret = MHD_NO; else { calc_userdigest (&da, username, strlen (username), realm, strlen (realm), password, userdigest_bin); ret = MHD_YES; #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (&da)) ret = MHD_NO; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ } digest_deinit (&da); return ret; } /** * Calculate userhash, return it as binary data. * * MHD internal version. * * @param da the digest algorithm * @param username the username to use * @param username_len the length of the @a username * @param realm the realm to use * @param realm_len the length of the @a realm * @param[out] digest_bin the output buffer, must have at least * #MHD_digest_get_hash_size(algo3) bytes available */ _MHD_static_inline void calc_userhash (struct DigestAlgorithm *da, const char *username, const size_t username_len, const char *realm, const size_t realm_len, uint8_t *digest_bin) { mhd_assert (NULL != username); mhd_assert (! da->hashing); digest_update (da, username, username_len); digest_update_with_colon (da); digest_update (da, realm, realm_len); digest_calc_hash (da, digest_bin); } /** * Calculate "userhash", return it as binary data. * * The "userhash" is the hash of the string "username:realm". * * The "userhash" could be used to avoid sending username in cleartext in Digest * Authorization client's header. * * Userhash is not designed to hide the username in local database or files, * as username in cleartext is required for #MHD_digest_auth_check3() function * to check the response, but it can be used to hide username in HTTP headers. * * This function could be used when the new username is added to the username * database to save the "userhash" alongside with the username (preferably) or * when loading list of the usernames to generate the userhash for every loaded * username (this will cause delays at the start with the long lists). * * Once "userhash" is generated it could be used to identify users by clients * with "userhash" support. * Avoid repetitive usage of this function for the same username/realm * combination as it will cause excessive CPU load; save and re-use the result * instead. * * @param algo3 the algorithm for userhash calculations * @param username the username * @param realm the realm * @param[out] userhash_bin the output buffer for userhash as binary data; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3) bytes of userhash * upon return * @param bin_buf_size the size of the @a userhash_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3) bytes long * @return MHD_YES on success, * MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH) * @sa #MHD_digest_auth_calc_userhash_hex() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userhash (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, void *userhash_bin, size_t bin_buf_size) { struct DigestAlgorithm da; enum MHD_Result ret; if (! digest_init_one_time (&da, get_base_digest_algo (algo3))) return MHD_NO; if (digest_get_size (&da) > bin_buf_size) ret = MHD_NO; else { calc_userhash (&da, username, strlen (username), realm, strlen (realm), userhash_bin); ret = MHD_YES; #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (&da)) ret = MHD_NO; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ } digest_deinit (&da); return ret; } /** * Calculate "userhash", return it as hexadecimal string. * * The "userhash" is the hash of the string "username:realm". * * The "userhash" could be used to avoid sending username in cleartext in Digest * Authorization client's header. * * Userhash is not designed to hide the username in local database or files, * as username in cleartext is required for #MHD_digest_auth_check3() function * to check the response, but it can be used to hide username in HTTP headers. * * This function could be used when the new username is added to the username * database to save the "userhash" alongside with the username (preferably) or * when loading list of the usernames to generate the userhash for every loaded * username (this will cause delays at the start with the long lists). * * Once "userhash" is generated it could be used to identify users by clients * with "userhash" support. * Avoid repetitive usage of this function for the same username/realm * combination as it will cause excessive CPU load; save and re-use the result * instead. * * @param algo3 the algorithm for userhash calculations * @param username the username * @param realm the realm * @param[out] userhash_hex the output buffer for userhash as hex string; * if this function succeeds, then this buffer has * #MHD_digest_get_hash_size(algo3)*2 chars long * userhash zero-terminated string * @param bin_buf_size the size of the @a userhash_bin buffer, must be * at least #MHD_digest_get_hash_size(algo3)*2+1 chars long * @return MHD_YES on success, * MHD_NO if @a bin_buf_size is too small or if @a algo3 algorithm is * not supported (or external error has occurred, * see #MHD_FEATURE_EXTERN_HASH). * @sa #MHD_digest_auth_calc_userhash() * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_digest_auth_calc_userhash_hex (enum MHD_DigestAuthAlgo3 algo3, const char *username, const char *realm, char *userhash_hex, size_t hex_buf_size) { uint8_t userhash_bin[MAX_DIGEST]; size_t digest_size; digest_size = digest_get_hash_size (algo3); if (digest_size * 2 + 1 > hex_buf_size) return MHD_NO; if (MHD_NO == MHD_digest_auth_calc_userhash (algo3, username, realm, userhash_bin, MAX_DIGEST)) return MHD_NO; MHD_bin_to_hex_z (userhash_bin, digest_size, userhash_hex); return MHD_YES; } struct test_header_param { struct MHD_Connection *connection; size_t num_headers; }; /** * Test if the given key-value pair is in the headers for the * given connection. * * @param cls the test context * @param key the key * @param key_size number of bytes in @a key * @param value the value, can be NULL * @param value_size number of bytes in @a value * @param kind type of the header * @return #MHD_YES if the key-value pair is in the headers, * #MHD_NO if not */ static enum MHD_Result test_header (void *cls, const char *key, size_t key_size, const char *value, size_t value_size, enum MHD_ValueKind kind) { struct test_header_param *const param = (struct test_header_param *) cls; struct MHD_Connection *connection = param->connection; struct MHD_HTTP_Req_Header *pos; size_t i; param->num_headers++; i = 0; for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if (kind != pos->kind) continue; if (++i == param->num_headers) { if (key_size != pos->header_size) return MHD_NO; if (value_size != pos->value_size) return MHD_NO; if (0 != key_size) { mhd_assert (NULL != key); mhd_assert (NULL != pos->header); if (0 != memcmp (key, pos->header, key_size)) return MHD_NO; } if (0 != value_size) { mhd_assert (NULL != value); mhd_assert (NULL != pos->value); if (0 != memcmp (value, pos->value, value_size)) return MHD_NO; } return MHD_YES; } } return MHD_NO; } /** * Check that the arguments given by the client as part * of the authentication header match the arguments we * got as part of the HTTP request URI. * * @param connection connections with headers to compare against * @param args the copy of argument URI string (after "?" in URI), will be * modified by this function * @return boolean true if the arguments match, * boolean false if not */ static bool check_argument_match (struct MHD_Connection *connection, char *args) { struct MHD_HTTP_Req_Header *pos; enum MHD_Result ret; struct test_header_param param; param.connection = connection; param.num_headers = 0; ret = MHD_parse_arguments_ (connection, MHD_GET_ARGUMENT_KIND, args, &test_header, ¶m); if (MHD_NO == ret) { return false; } /* also check that the number of headers matches */ for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if (MHD_GET_ARGUMENT_KIND != pos->kind) continue; param.num_headers--; } if (0 != param.num_headers) { /* argument count mismatch */ return false; } return true; } /** * Check that the URI provided by the client as part * of the authentication header match the real HTTP request URI. * * @param connection connections with headers to compare against * @param uri the copy of URI in the authentication header, should point to * modifiable buffer at least @a uri_len + 1 characters long, * will be modified by this function, not valid upon return * @param uri_len the length of the @a uri string in characters * @return boolean true if the URIs match, * boolean false if not */ static bool check_uri_match (struct MHD_Connection *connection, char *uri, size_t uri_len) { char *qmark; char *args; struct MHD_Daemon *const daemon = connection->daemon; uri[uri_len] = 0; qmark = memchr (uri, '?', uri_len); if (NULL != qmark) *qmark = '\0'; /* Need to unescape URI before comparing with connection->url */ uri_len = daemon->unescape_callback (daemon->unescape_callback_cls, connection, uri); if ((uri_len != connection->rq.url_len) || (0 != memcmp (uri, connection->rq.url, uri_len))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Authentication failed, URI does not match.\n")); #endif return false; } args = (NULL != qmark) ? (qmark + 1) : uri + uri_len; if (! check_argument_match (connection, args) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Authentication failed, arguments do not match.\n")); #endif return false; } return true; } /** * The size of the unquoting buffer in stack */ #define _MHD_STATIC_UNQ_BUFFER_SIZE 128 /** * Get the pointer to buffer with required size * @param tmp1 the first buffer with fixed size * @param ptmp2 the pointer to pointer to malloc'ed buffer * @param ptmp2_size the pointer to the size of the buffer pointed by @a ptmp2 * @param required_size the required size in buffer * @return the pointer to the buffer or NULL if failed to allocate buffer with * requested size */ static char * get_buffer_for_size (char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE], char **ptmp2, size_t *ptmp2_size, size_t required_size) { mhd_assert ((0 == *ptmp2_size) || (NULL != *ptmp2)); mhd_assert ((NULL != *ptmp2) || (0 == *ptmp2_size)); mhd_assert ((0 == *ptmp2_size) || \ (_MHD_STATIC_UNQ_BUFFER_SIZE < *ptmp2_size)); if (required_size <= _MHD_STATIC_UNQ_BUFFER_SIZE) return tmp1; if (required_size <= *ptmp2_size) return *ptmp2; if (required_size > _MHD_AUTH_DIGEST_MAX_PARAM_SIZE) return NULL; if (NULL != *ptmp2) free (*ptmp2); *ptmp2 = (char *) malloc (required_size); if (NULL == *ptmp2) *ptmp2_size = 0; else *ptmp2_size = required_size; return *ptmp2; } /** * The result of parameter unquoting */ enum _MHD_GetUnqResult { _MHD_UNQ_OK = 0, /**< Got unquoted string */ _MHD_UNQ_TOO_LARGE = -7, /**< The string is too large to unquote */ _MHD_UNQ_OUT_OF_MEM = 3 /**< Out of memory error */ }; /** * Get Digest authorisation parameter as unquoted string. * @param param the parameter to process * @param tmp1 the small buffer in stack * @param ptmp2 the pointer to pointer to malloc'ed buffer * @param ptmp2_size the pointer to the size of the buffer pointed by @a ptmp2 * @param[out] unquoted the pointer to store the result, NOT zero terminated * @return enum code indicating result of the process */ static enum _MHD_GetUnqResult get_unquoted_param (const struct MHD_RqDAuthParam *param, char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE], char **ptmp2, size_t *ptmp2_size, struct _MHD_str_w_len *unquoted) { char *str; size_t len; mhd_assert (NULL != param->value.str); mhd_assert (0 != param->value.len); if (! param->quoted) { unquoted->str = param->value.str; unquoted->len = param->value.len; return _MHD_UNQ_OK; } /* The value is present and is quoted, needs to be copied and unquoted */ str = get_buffer_for_size (tmp1, ptmp2, ptmp2_size, param->value.len); if (NULL == str) return (param->value.len > _MHD_AUTH_DIGEST_MAX_PARAM_SIZE) ? _MHD_UNQ_TOO_LARGE : _MHD_UNQ_OUT_OF_MEM; len = MHD_str_unquote (param->value.str, param->value.len, str); unquoted->str = str; unquoted->len = len; mhd_assert (0 != unquoted->len); mhd_assert (unquoted->len < param->value.len); return _MHD_UNQ_OK; } /** * Get copy of Digest authorisation parameter as unquoted string. * @param param the parameter to process * @param tmp1 the small buffer in stack * @param ptmp2 the pointer to pointer to malloc'ed buffer * @param ptmp2_size the pointer to the size of the buffer pointed by @a ptmp2 * @param[out] unquoted the pointer to store the result, NOT zero terminated, * but with enough space to zero-terminate * @return enum code indicating result of the process */ static enum _MHD_GetUnqResult get_unquoted_param_copy (const struct MHD_RqDAuthParam *param, char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE], char **ptmp2, size_t *ptmp2_size, struct _MHD_mstr_w_len *unquoted) { mhd_assert (NULL != param->value.str); mhd_assert (0 != param->value.len); /* The value is present and is quoted, needs to be copied and unquoted */ /* Allocate buffer with one more additional byte for zero-termination */ unquoted->str = get_buffer_for_size (tmp1, ptmp2, ptmp2_size, param->value.len + 1); if (NULL == unquoted->str) return (param->value.len + 1 > _MHD_AUTH_DIGEST_MAX_PARAM_SIZE) ? _MHD_UNQ_TOO_LARGE : _MHD_UNQ_OUT_OF_MEM; if (! param->quoted) { memcpy (unquoted->str, param->value.str, param->value.len); unquoted->len = param->value.len; return _MHD_UNQ_OK; } unquoted->len = MHD_str_unquote (param->value.str, param->value.len, unquoted->str); mhd_assert (0 != unquoted->len); mhd_assert (unquoted->len < param->value.len); return _MHD_UNQ_OK; } /** * Check whether Digest Auth request parameter is equal to given string * @param param the parameter to check * @param str the string to compare with, does not need to be zero-terminated * @param str_len the length of the @a str * @return true is parameter is equal to the given string, * false otherwise */ _MHD_static_inline bool is_param_equal (const struct MHD_RqDAuthParam *param, const char *const str, const size_t str_len) { mhd_assert (NULL != param->value.str); mhd_assert (0 != param->value.len); if (param->quoted) return MHD_str_equal_quoted_bin_n (param->value.str, param->value.len, str, str_len); return (str_len == param->value.len) && (0 == memcmp (str, param->value.str, str_len)); } /** * Check whether Digest Auth request parameter is caseless equal to given string * @param param the parameter to check * @param str the string to compare with, does not need to be zero-terminated * @param str_len the length of the @a str * @return true is parameter is caseless equal to the given string, * false otherwise */ _MHD_static_inline bool is_param_equal_caseless (const struct MHD_RqDAuthParam *param, const char *const str, const size_t str_len) { mhd_assert (NULL != param->value.str); mhd_assert (0 != param->value.len); if (param->quoted) return MHD_str_equal_caseless_quoted_bin_n (param->value.str, param->value.len, str, str_len); return (str_len == param->value.len) && (MHD_str_equal_caseless_bin_n_ (str, param->value.str, str_len)); } /** * Authenticates the authorization header sent by the client * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request new nonce must be * generated and client repeat all requests twice (the first time to get a new * nonce and the second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param password the password used in the authentication, * must be NULL if @a userdigest is not NULL * @param userdigest the precalculated binary hash of the string * "username:realm:password", * must be NULL if @a password is not NULL * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * unlike #digest_auth_check_all() zero is used literally * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * unlike #digest_auth_check_all() zero is treated as "no limit" * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm specified * by the client is not allowed by this parameter * @param[out] pbuf the pointer to pointer to internally malloc'ed buffer, * to be freed if not NULL upon return * @return #MHD_DAUTH_OK if authenticated, * error code otherwise. * @ingroup authentication */ static enum MHD_DigestAuthResult digest_auth_check_all_inner (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, const uint8_t *userdigest, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3, char **pbuf, struct DigestAlgorithm *da) { struct MHD_Daemon *daemon = MHD_get_master (connection->daemon); enum MHD_DigestAuthAlgo3 c_algo; /**< Client's algorithm */ enum MHD_DigestAuthQOP c_qop; /**< Client's QOP */ unsigned int digest_size; uint8_t hash1_bin[MAX_DIGEST]; uint8_t hash2_bin[MAX_DIGEST]; #if 0 const char *hentity = NULL; /* "auth-int" is not supported */ #endif uint64_t nonce_time; uint64_t nci; const struct MHD_RqDAuth *params; /** * Temporal buffer in stack for unquoting and other needs */ char tmp1[_MHD_STATIC_UNQ_BUFFER_SIZE]; char **const ptmp2 = pbuf; /**< Temporal malloc'ed buffer for unquoting */ size_t tmp2_size; /**< The size of @a tmp2 buffer */ struct _MHD_str_w_len unquoted; struct _MHD_mstr_w_len unq_copy; enum _MHD_GetUnqResult unq_res; size_t username_len; size_t realm_len; mhd_assert ((NULL != password) || (NULL != userdigest)); mhd_assert (! ((NULL != userdigest) && (NULL != password))); tmp2_size = 0; params = MHD_get_rq_dauth_params_ (connection); if (NULL == params) return MHD_DAUTH_WRONG_HEADER; /* ** Initial parameters checks and setup ** */ /* Get client's algorithm */ c_algo = params->algo3; /* Check whether client's algorithm is allowed by function parameter */ if (((unsigned int) c_algo) != (((unsigned int) c_algo) & ((unsigned int) malgo3))) return MHD_DAUTH_WRONG_ALGO; if (MHD_DIGEST_AUTH_ALGO3_INVALID == c_algo) return MHD_DAUTH_WRONG_ALGO; /* Check whether client's algorithm is supported */ if (0 != (((unsigned int) c_algo) & MHD_DIGEST_AUTH_ALGO3_SESSION)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The 'session' algorithms are not supported.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #ifndef MHD_MD5_SUPPORT if (0 != (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_MD5)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The MD5 algorithm is not supported by this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_MD5_SUPPORT */ #ifndef MHD_SHA256_SUPPORT if (0 != (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_SHA256)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The SHA-256 algorithm is not supported by " "this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_SHA256_SUPPORT */ #ifndef MHD_SHA512_256_SUPPORT if (0 != (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_SHA512_256)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The SHA-512/256 algorithm is not supported by " "this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_SHA512_256_SUPPORT */ if (! digest_init_one_time (da, get_base_digest_algo (c_algo))) MHD_PANIC (_ ("Wrong 'malgo3' value, API violation")); /* Check 'mqop' value */ c_qop = params->qop; /* Check whether client's QOP is allowed by function parameter */ if (((unsigned int) c_qop) != (((unsigned int) c_qop) & ((unsigned int) mqop))) return MHD_DAUTH_WRONG_QOP; /* The numeric value of #MHD_DIGEST_AUTH_QOP_INVALID is zero, therefore the bitmask check above passes it for any 'mqop' value. */ if (MHD_DIGEST_AUTH_QOP_INVALID == c_qop) return MHD_DAUTH_WRONG_QOP; if (0 != (((unsigned int) c_qop) & MHD_DIGEST_AUTH_QOP_AUTH_INT)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The 'auth-int' QOP is not supported.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_QOP; } #ifdef HAVE_MESSAGES if ((MHD_DIGEST_AUTH_QOP_NONE == c_qop) && (0 == (((unsigned int) c_algo) & MHD_DIGEST_BASE_ALGO_MD5))) MHD_DLOG (connection->daemon, _ ("RFC2069 with SHA-256 or SHA-512/256 algorithm is " \ "non-standard extension.\n")); #endif /* HAVE_MESSAGES */ digest_size = digest_get_size (da); /* ** A quick check for presence of all required parameters ** */ if ((NULL == params->username.value.str) && (NULL == params->username_ext.value.str)) return MHD_DAUTH_WRONG_USERNAME; else if ((NULL != params->username.value.str) && (NULL != params->username_ext.value.str)) return MHD_DAUTH_WRONG_USERNAME; /* Parameters cannot be used together */ else if ((NULL != params->username.value.str) && (0 == params->username.value.len)) return MHD_DAUTH_WRONG_USERNAME; /* Empty username */ else if ((NULL != params->username_ext.value.str) && (MHD_DAUTH_EXT_PARAM_MIN_LEN > params->username_ext.value.len)) return MHD_DAUTH_WRONG_USERNAME; /* Broken extended notation */ else if (params->userhash && (NULL == params->username.value.str)) return MHD_DAUTH_WRONG_USERNAME; /* Userhash cannot be used with extended notation */ else if (params->userhash && (digest_size * 2 > params->username.value.len)) return MHD_DAUTH_WRONG_USERNAME; /* Too few chars for correct userhash */ else if (params->userhash && (digest_size * 4 < params->username.value.len)) return MHD_DAUTH_WRONG_USERNAME; /* Too many chars for correct userhash */ if (NULL == params->realm.value.str) return MHD_DAUTH_WRONG_REALM; else if (0 == params->realm.value.len) return MHD_DAUTH_WRONG_REALM; /* Empty realm */ else if (((NULL == userdigest) || params->userhash) && (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < params->realm.value.len)) return MHD_DAUTH_TOO_LARGE; /* Realm is too large and should be used in hash calculations */ if (MHD_DIGEST_AUTH_QOP_NONE != c_qop) { if (NULL == params->nc.value.str) return MHD_DAUTH_WRONG_HEADER; else if (0 == params->nc.value.len) return MHD_DAUTH_WRONG_HEADER; else if (4 * 8 < params->nc.value.len) /* Four times more than needed */ return MHD_DAUTH_WRONG_HEADER; if (NULL == params->cnonce.value.str) return MHD_DAUTH_WRONG_HEADER; else if (0 == params->cnonce.value.len) return MHD_DAUTH_WRONG_HEADER; else if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < params->cnonce.value.len) return MHD_DAUTH_TOO_LARGE; } /* The QOP parameter was checked already */ if (NULL == params->uri.value.str) return MHD_DAUTH_WRONG_URI; else if (0 == params->uri.value.len) return MHD_DAUTH_WRONG_URI; else if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < params->uri.value.len) return MHD_DAUTH_TOO_LARGE; if (NULL == params->nonce.value.str) return MHD_DAUTH_NONCE_WRONG; else if (0 == params->nonce.value.len) return MHD_DAUTH_NONCE_WRONG; else if (NONCE_STD_LEN (digest_size) * 2 < params->nonce.value.len) return MHD_DAUTH_NONCE_WRONG; if (NULL == params->response.value.str) return MHD_DAUTH_RESPONSE_WRONG; else if (0 == params->response.value.len) return MHD_DAUTH_RESPONSE_WRONG; else if (digest_size * 4 < params->response.value.len) return MHD_DAUTH_RESPONSE_WRONG; /* ** Check simple parameters match ** */ /* Check 'algorithm' */ /* The 'algorithm' was checked at the start of the function */ /* 'algorithm' valid */ /* Check 'qop' */ /* The 'qop' was checked at the start of the function */ /* 'qop' valid */ /* Check 'realm' */ realm_len = strlen (realm); if (! is_param_equal (¶ms->realm, realm, realm_len)) return MHD_DAUTH_WRONG_REALM; /* 'realm' valid */ /* Check 'username' */ username_len = strlen (username); if (! params->userhash) { if (NULL != params->username.value.str) { /* Username in standard notation */ if (! is_param_equal (¶ms->username, username, username_len)) return MHD_DAUTH_WRONG_USERNAME; } else { /* Username in extended notation */ char *r_uname; size_t buf_size = params->username_ext.value.len; ssize_t res; mhd_assert (NULL != params->username_ext.value.str); mhd_assert (MHD_DAUTH_EXT_PARAM_MIN_LEN <= buf_size); /* It was checked already */ buf_size += 1; /* For zero-termination */ buf_size -= MHD_DAUTH_EXT_PARAM_MIN_LEN; r_uname = get_buffer_for_size (tmp1, ptmp2, &tmp2_size, buf_size); if (NULL == r_uname) return (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < buf_size) ? MHD_DAUTH_TOO_LARGE : MHD_DAUTH_ERROR; res = get_rq_extended_uname_copy_z (params->username_ext.value.str, params->username_ext.value.len, r_uname, buf_size); if (0 > res) return MHD_DAUTH_WRONG_HEADER; /* Broken extended notation */ if ((username_len != (size_t) res) || (0 != memcmp (username, r_uname, username_len))) return MHD_DAUTH_WRONG_USERNAME; } } else { /* Userhash */ mhd_assert (NULL != params->username.value.str); calc_userhash (da, username, username_len, realm, realm_len, hash1_bin); #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return MHD_DAUTH_ERROR; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ /* MHD_bin_to_hex() takes no output size and writes exactly 2 * digest_size bytes into this fixed-size stack buffer */ MHD_CHECK_ (connection->daemon, (2 * digest_size) <= sizeof (tmp1), return MHD_DAUTH_ERROR); MHD_bin_to_hex (hash1_bin, digest_size, tmp1); if (! is_param_equal_caseless (¶ms->username, tmp1, 2 * digest_size)) return MHD_DAUTH_WRONG_USERNAME; /* To simplify the logic, the digest is reset here instead of resetting before the next hash calculation. */ digest_reset (da); } /* 'username' valid */ /* ** Do basic nonce and nonce-counter checks (size, timestamp) ** */ /* Get 'nc' digital value */ if (MHD_DIGEST_AUTH_QOP_NONE != c_qop) { unq_res = get_unquoted_param (¶ms->nc, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; if (unquoted.len != MHD_strx_to_uint64_n_ (unquoted.str, unquoted.len, &nci)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Authentication failed, invalid nc format.\n")); #endif return MHD_DAUTH_WRONG_HEADER; /* invalid nonce format */ } if (0 == nci) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Authentication failed, invalid 'nc' value.\n")); #endif return MHD_DAUTH_WRONG_HEADER; /* invalid nc value */ } if ((0 != max_nc) && (max_nc < nci)) return MHD_DAUTH_NONCE_STALE; /* Too large 'nc' value */ } else nci = 1; /* Force 'nc' value */ /* Got 'nc' digital value */ /* Get 'nonce' with basic checks */ unq_res = get_unquoted_param (¶ms->nonce, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; if ((NONCE_STD_LEN (digest_size) != unquoted.len) || (! get_nonce_timestamp (unquoted.str, unquoted.len, &nonce_time))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Authentication failed, invalid nonce format.\n")); #endif return MHD_DAUTH_NONCE_WRONG; } if (1) { uint64_t t; t = MHD_monotonic_msec_counter (); /* * First level vetting for the nonce validity: if the timestamp * attached to the nonce exceeds `nonce_timeout', then the nonce is * stale. */ if (TRIM_TO_TIMESTAMP (t - nonce_time) > (nonce_timeout * 1000)) return MHD_DAUTH_NONCE_STALE; /* too old */ } if (1) { enum MHD_CheckNonceNC_ nonce_nc_check; /* * Checking if that combination of nonce and nc is sound * and not a replay attack attempt. Refuse if nonce was not * generated previously. */ nonce_nc_check = check_nonce_nc (connection, unquoted.str, NONCE_STD_LEN (digest_size), nonce_time, nci); if (MHD_CHECK_NONCENC_STALE == nonce_nc_check) { #ifdef HAVE_MESSAGES if (MHD_DIGEST_AUTH_QOP_NONE != c_qop) MHD_DLOG (daemon, _ ("Stale nonce received. If this happens a lot, you should " "probably increase the size of the nonce array.\n")); else MHD_DLOG (daemon, _ ("Stale nonce received. This is expected when client " \ "uses RFC2069-compatible mode and makes more than one " \ "request.\n")); #endif return MHD_DAUTH_NONCE_STALE; } else if (MHD_CHECK_NONCENC_WRONG == nonce_nc_check) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Received nonce that was not " "generated by MHD. This may indicate an attack attempt.\n")); #endif return MHD_DAUTH_NONCE_WRONG; } mhd_assert (MHD_CHECK_NONCENC_OK == nonce_nc_check); } /* The nonce was generated by MHD, is not stale and nonce-nc combination was not used before */ /* ** Build H(A2) and check URI match in the header and in the request ** */ /* Get 'uri' */ mhd_assert (! da->hashing); digest_update_str (da, connection->rq.method); digest_update_with_colon (da); #if 0 /* TODO: add support for "auth-int" */ digest_update_str (da, hentity); digest_update_with_colon (da); #endif unq_res = get_unquoted_param_copy (¶ms->uri, tmp1, ptmp2, &tmp2_size, &unq_copy); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; digest_update (da, unq_copy.str, unq_copy.len); /* The next check will modify copied URI string */ if (! check_uri_match (connection, unq_copy.str, unq_copy.len)) return MHD_DAUTH_WRONG_URI; digest_calc_hash (da, hash2_bin); #ifdef MHD_DIGEST_HAS_EXT_ERROR /* Skip digest calculation external error check, the next one checks both */ #endif /* MHD_DIGEST_HAS_EXT_ERROR */ /* Got H(A2) */ /* ** Build H(A1) ** */ if (NULL == userdigest) { mhd_assert (! da->hashing); digest_reset (da); calc_userdigest (da, username, username_len, realm, realm_len, password, hash1_bin); } /* TODO: support '-sess' versions */ #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return MHD_DAUTH_ERROR; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ /* Got H(A1) */ /* ** Check 'response' ** */ mhd_assert (! da->hashing); digest_reset (da); /* Update digest with H(A1) */ MHD_CHECK_ (connection->daemon, (digest_size * 2) <= sizeof (tmp1), return MHD_DAUTH_ERROR); if (NULL == userdigest) MHD_bin_to_hex (hash1_bin, digest_size, tmp1); else MHD_bin_to_hex (userdigest, digest_size, tmp1); digest_update (da, (const uint8_t *) tmp1, digest_size * 2); /* H(A1) is not needed anymore, reuse the buffer. * Use hash1_bin for the client's 'response' decoded to binary form. */ unq_res = get_unquoted_param (¶ms->response, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; if (unquoted.len > MAX_AUTH_RESPONSE_LENGTH) return MHD_DAUTH_ERROR; if (digest_size != MHD_hex_to_bin (unquoted.str, unquoted.len, hash1_bin)) return MHD_DAUTH_RESPONSE_WRONG; /* Update digest with ':' */ digest_update_with_colon (da); /* Update digest with 'nonce' text value */ unq_res = get_unquoted_param (¶ms->nonce, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; digest_update (da, (const uint8_t *) unquoted.str, unquoted.len); /* Update digest with ':' */ digest_update_with_colon (da); if (MHD_DIGEST_AUTH_QOP_NONE != c_qop) { /* Update digest with 'nc' text value */ unq_res = get_unquoted_param (¶ms->nc, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; digest_update (da, (const uint8_t *) unquoted.str, unquoted.len); /* Update digest with ':' */ digest_update_with_colon (da); /* Update digest with 'cnonce' value */ unq_res = get_unquoted_param (¶ms->cnonce, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; digest_update (da, (const uint8_t *) unquoted.str, unquoted.len); /* Update digest with ':' */ digest_update_with_colon (da); /* Update digest with 'qop' value */ unq_res = get_unquoted_param (¶ms->qop_raw, tmp1, ptmp2, &tmp2_size, &unquoted); if (_MHD_UNQ_OK != unq_res) return MHD_DAUTH_ERROR; digest_update (da, (const uint8_t *) unquoted.str, unquoted.len); /* Update digest with ':' */ digest_update_with_colon (da); } /* Update digest with H(A2) */ MHD_bin_to_hex (hash2_bin, digest_size, tmp1); digest_update (da, (const uint8_t *) tmp1, digest_size * 2); /* H(A2) is not needed anymore, reuse the buffer. * Use hash2_bin for the calculated response in binary form */ digest_calc_hash (da, hash2_bin); #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return MHD_DAUTH_ERROR; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ if (0 != memcmp (hash1_bin, hash2_bin, digest_size)) return MHD_DAUTH_RESPONSE_WRONG; if (MHD_DAUTH_BIND_NONCE_NONE != daemon->dauth_bind_type) { mhd_assert (sizeof(tmp1) >= (NONCE_STD_LEN (digest_size) + 1)); /* It was already checked that 'nonce' (including timestamp) was generated by MHD. */ mhd_assert (! da->hashing); digest_reset (da); calculate_nonce (nonce_time, connection->rq.http_mthd, connection->rq.method, daemon->digest_auth_random, daemon->digest_auth_rand_size, connection->addr, (size_t) connection->addr_len, connection->rq.url, connection->rq.url_len, connection->rq.headers_received, realm, realm_len, daemon->dauth_bind_type, da, tmp1); #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) return MHD_DAUTH_ERROR; #endif /* MHD_DIGEST_HAS_EXT_ERROR */ if (! is_param_equal (¶ms->nonce, tmp1, NONCE_STD_LEN (digest_size))) return MHD_DAUTH_NONCE_OTHER_COND; /* The 'nonce' was generated in the same conditions */ } return MHD_DAUTH_OK; } /** * Authenticates the authorization header sent by the client * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request new nonce must be * generated and client repeat all requests twice (the first time to get a new * nonce and the second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param password the password used in the authentication, * must be NULL if @a userdigest is not NULL * @param userdigest the precalculated binary hash of the string * "username:realm:password", * must be NULL if @a password is not NULL * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * if set to zero then daemon's default value is used * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * if set to zero then daemon's default value is used * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm specified * by the client is not allowed by this parameter * @return #MHD_DAUTH_OK if authenticated, * error code otherwise. * @ingroup authentication */ static enum MHD_DigestAuthResult digest_auth_check_all (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, const uint8_t *userdigest, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3) { enum MHD_DigestAuthResult res; char *buf; struct DigestAlgorithm da; buf = NULL; digest_setup_zero (&da); if (0 == nonce_timeout) nonce_timeout = connection->daemon->dauth_def_nonce_timeout; if (0 == max_nc) max_nc = connection->daemon->dauth_def_max_nc; res = digest_auth_check_all_inner (connection, realm, username, password, userdigest, nonce_timeout, max_nc, mqop, malgo3, &buf, &da); digest_deinit (&da); if (NULL != buf) free (buf); return res; } /** * Authenticates the authorization header sent by the client. * Uses #MHD_DIGEST_ALG_MD5 (for now, for backwards-compatibility). * Note that this MAY change to #MHD_DIGEST_ALG_AUTO in the future. * If you want to be sure you get MD5, use #MHD_digest_auth_check2() * and specify MD5 explicitly. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param password The password used in the authentication * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @deprecated use MHD_digest_auth_check3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout) { return MHD_digest_auth_check2 (connection, realm, username, password, nonce_timeout, MHD_DIGEST_ALG_MD5); } /** * Authenticates the authorization header sent by the client. * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request a new nonce must * be generated and client repeats all requests twice (first time to get a new * nonce and second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param password the password matching the @a username (and the @a realm) * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * if zero is specified then daemon default value is used. * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * if zero is specified then daemon default value is used. * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm used * by the client is not allowed by this parameter * @return #MHD_DAUTH_OK if authenticated, * the error code otherwise * @note Available since #MHD_VERSION 0x00097708 * @ingroup authentication */ _MHD_EXTERN enum MHD_DigestAuthResult MHD_digest_auth_check3 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3) { mhd_assert (NULL != password); return digest_auth_check_all (connection, realm, username, password, NULL, nonce_timeout, max_nc, mqop, malgo3); } /** * Authenticates the authorization header sent by the client by using * hash of "username:realm:password". * * If RFC2069 mode is allowed by setting bit #MHD_DIGEST_AUTH_QOP_NONE in * @a mqop and the client uses this mode, then server generated nonces are * used as one-time nonces because nonce-count is not supported in this old RFC. * Communication in this mode is very inefficient, especially if the client * requests several resources one-by-one as for every request a new nonce must * be generated and client repeats all requests twice (first time to get a new * nonce and second time to perform an authorised request). * * @param connection the MHD connection structure * @param realm the realm for authorization of the client * @param username the username to be authenticated, must be in clear text * even if userhash is used by the client * @param userdigest the precalculated binary hash of the string * "username:realm:password", * see #MHD_digest_auth_calc_userdigest() * @param userdigest_size the size of the @a userdigest in bytes, must match the * hashing algorithm (see #MHD_MD5_DIGEST_SIZE, * #MHD_SHA256_DIGEST_SIZE, #MHD_SHA512_256_DIGEST_SIZE, * #MHD_digest_get_hash_size()) * @param nonce_timeout the period of seconds since nonce generation, when * the nonce is recognised as valid and not stale; * if zero is specified then daemon default value is used. * @param max_nc the maximum allowed nc (Nonce Count) value, if client's nc * exceeds the specified value then MHD_DAUTH_NONCE_STALE is * returned; * if zero is specified then daemon default value is used. * @param mqop the QOP to use * @param malgo3 digest algorithms allowed to use, fail if algorithm used * by the client is not allowed by this parameter; * more than one base algorithms (MD5, SHA-256, SHA-512/256) * cannot be used at the same time for this function * as @a userdigest must match specified algorithm * @return #MHD_DAUTH_OK if authenticated, * the error code otherwise * @sa #MHD_digest_auth_calc_userdigest() * @note Available since #MHD_VERSION 0x00097708 * @ingroup authentication */ _MHD_EXTERN enum MHD_DigestAuthResult MHD_digest_auth_check_digest3 (struct MHD_Connection *connection, const char *realm, const char *username, const void *userdigest, size_t userdigest_size, unsigned int nonce_timeout, uint32_t max_nc, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3) { if (1 != (((0 != (malgo3 & MHD_DIGEST_BASE_ALGO_MD5)) ? 1 : 0) + ((0 != (malgo3 & MHD_DIGEST_BASE_ALGO_SHA256)) ? 1 : 0) + ((0 != (malgo3 & MHD_DIGEST_BASE_ALGO_SHA512_256)) ? 1 : 0))) MHD_PANIC (_ ("Wrong 'malgo3' value, only one base hashing algorithm " \ "(MD5, SHA-256 or SHA-512/256) must be specified, " \ "API violation")); #ifndef MHD_MD5_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_MD5)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The MD5 algorithm is not supported by this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_MD5_SUPPORT */ #ifndef MHD_SHA256_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA256)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The SHA-256 algorithm is not supported by " "this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_SHA256_SUPPORT */ #ifndef MHD_SHA512_256_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA512_256)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The SHA-512/256 algorithm is not supported by " "this MHD build.\n")); #endif /* HAVE_MESSAGES */ return MHD_DAUTH_WRONG_ALGO; } #endif /* ! MHD_SHA512_256_SUPPORT */ if (digest_get_hash_size ((enum MHD_DigestAuthAlgo3) malgo3) != userdigest_size) MHD_PANIC (_ ("Wrong 'userdigest_size' value, does not match 'malgo3', " "API violation")); return digest_auth_check_all (connection, realm, username, NULL, (const uint8_t *) userdigest, nonce_timeout, max_nc, mqop, malgo3); } /** * Authenticates the authorization header sent by the client. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param password The password used in the authentication * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @param algo digest algorithms allowed for verification * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096200 * @deprecated use MHD_digest_auth_check3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check2 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) { enum MHD_DigestAuthResult res; enum MHD_DigestAuthMultiAlgo3 malgo3; if (MHD_DIGEST_ALG_AUTO == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION; else if (MHD_DIGEST_ALG_MD5 == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_MD5; else if (MHD_DIGEST_ALG_SHA256 == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256; else MHD_PANIC (_ ("Wrong 'algo' value, API violation")); res = MHD_digest_auth_check3 (connection, realm, username, password, nonce_timeout, 0, MHD_DIGEST_AUTH_MULT_QOP_AUTH, malgo3); if (MHD_DAUTH_OK == res) return MHD_YES; else if ((MHD_DAUTH_NONCE_STALE == res) || (MHD_DAUTH_NONCE_WRONG == res) || (MHD_DAUTH_NONCE_OTHER_COND == res) ) return MHD_INVALID_NONCE; return MHD_NO; } /** * Authenticates the authorization header sent by the client. * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param digest An `unsigned char *' pointer to the binary MD5 sum * for the precalculated hash value "username:realm:password" * of @a digest_size bytes * @param digest_size number of bytes in @a digest (size must match @a algo!) * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @param algo digest algorithm allowed for verification; exactly one * algorithm must be named, as @a digest is a hash produced by one * specific algorithm. #MHD_DIGEST_ALG_AUTO cannot be used here * and makes this function return #MHD_NO * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096200 * @deprecated use MHD_digest_auth_check_digest3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check_digest2 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, size_t digest_size, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) { enum MHD_DigestAuthResult res; enum MHD_DigestAuthMultiAlgo3 malgo3; if (MHD_DIGEST_ALG_AUTO == algo) { /* MHD_DIGEST_ALG_AUTO maps to more than one base hashing algorithm, * but @a digest is a hash of one specific algorithm and its length * does not identify which one (SHA-256 and SHA-512/256 hashes are * both 32 bytes). Forwarding AUTO to * MHD_digest_auth_check_digest3() would therefore reach the * MHD_PANIC() in that function and kill the process. Report it as * a failed authentication instead; the caller cannot recover from * an abort, but it can handle MHD_NO. */ #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("MHD_DIGEST_ALG_AUTO cannot be used with a " \ "pre-calculated digest: exactly one algorithm must be " \ "named, as the digest was produced by one.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } else if (MHD_DIGEST_ALG_MD5 == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_MD5; else if (MHD_DIGEST_ALG_SHA256 == algo) malgo3 = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256; else MHD_PANIC (_ ("Wrong 'algo' value, API violation")); res = MHD_digest_auth_check_digest3 (connection, realm, username, digest, digest_size, nonce_timeout, 0, MHD_DIGEST_AUTH_MULT_QOP_AUTH, malgo3); if (MHD_DAUTH_OK == res) return MHD_YES; else if ((MHD_DAUTH_NONCE_STALE == res) || (MHD_DAUTH_NONCE_WRONG == res) || (MHD_DAUTH_NONCE_OTHER_COND == res) ) return MHD_INVALID_NONCE; return MHD_NO; } /** * Authenticates the authorization header sent by the client * Uses #MHD_DIGEST_ALG_MD5 (required, as @a digest is of fixed * size). * * @param connection The MHD connection structure * @param realm The realm presented to the client * @param username The username needs to be authenticated * @param digest An `unsigned char *' pointer to the binary hash * for the precalculated hash value "username:realm:password"; * length must be #MHD_MD5_DIGEST_SIZE bytes * @param nonce_timeout The amount of time for a nonce to be * invalid in seconds * @return #MHD_YES if authenticated, #MHD_NO if not, * #MHD_INVALID_NONCE if nonce is invalid or stale * @note Available since #MHD_VERSION 0x00096000 * @deprecated use #MHD_digest_auth_check_digest3() * @ingroup authentication */ _MHD_EXTERN int MHD_digest_auth_check_digest (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t digest[MHD_MD5_DIGEST_SIZE], unsigned int nonce_timeout) { return MHD_digest_auth_check_digest2 (connection, realm, username, digest, MHD_MD5_DIGEST_SIZE, nonce_timeout, MHD_DIGEST_ALG_MD5); } /** * Internal version of #MHD_queue_auth_required_response3() to simplify * cleanups. * * @param connection the MHD connection structure * @param realm the realm presented to the client * @param opaque the string for opaque value, can be NULL, but NULL is * not recommended for better compatibility with clients; * the recommended format is hex or Base64 encoded string * @param domain the optional space-separated list of URIs for which the * same authorisation could be used, URIs can be in form * "path-absolute" (the path for the same host with initial slash) * or in form "absolute-URI" (the full path with protocol), in * any case client may assume that URI is in the same "protection * space" if it starts with any of values specified here; * could be NULL (clients typically assume that the same * credentials could be used for any URI on the same host) * @param response the reply to send; should contain the "access denied" * body; note that this function sets the "WWW Authenticate" * header and that the caller should not do this; * the NULL is tolerated * @param signal_stale set to #MHD_YES if the nonce is stale to add 'stale=true' * to the authentication header, this instructs the client * to retry immediately with the new nonce and the same * credentials, without asking user for the new password * @param mqop the QOP to use * @param malgo3 digest algorithm to use, MHD selects; if several algorithms * are allowed then MD5 is preferred (currently, may be changed * in next versions) * @param userhash_support if set to non-zero value (#MHD_YES) then support of * userhash is indicated, the client may provide * hash("username:realm") instead of username in * clear text; * note that clients are allowed to provide the username * in cleartext even if this parameter set to non-zero; * when userhash is used, application must be ready to * identify users by provided userhash value instead of * username; see #MHD_digest_auth_calc_userhash() and * #MHD_digest_auth_calc_userhash_hex() * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is * added, indicating for the client that UTF-8 encoding * is preferred * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is * added, indicating for the client that UTF-8 encoding * is preferred * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ static enum MHD_Result queue_auth_required_response3_inner (struct MHD_Connection *connection, const char *realm, const char *opaque, const char *domain, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3, int userhash_support, int prefer_utf8, char **buf_ptr, struct DigestAlgorithm *da) { static const char prefix_realm[] = "realm=\""; static const char prefix_qop[] = "qop=\""; static const char prefix_algo[] = "algorithm="; static const char prefix_nonce[] = "nonce=\""; static const char prefix_opaque[] = "opaque=\""; static const char prefix_domain[] = "domain=\""; static const char str_charset[] = "charset=UTF-8"; static const char str_userhash[] = "userhash=true"; static const char str_stale[] = "stale=true"; enum MHD_DigestAuthAlgo3 s_algo; /**< Selected algorithm */ size_t realm_len; size_t opaque_len; size_t domain_len; size_t buf_size; char *buf; size_t p; /* The position in the buffer */ char *hdr_name; if ((0 == (((unsigned int) malgo3) & MHD_DIGEST_AUTH_ALGO3_NON_SESSION)) || (0 != (((unsigned int) malgo3) & MHD_DIGEST_AUTH_ALGO3_SESSION))) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Only non-'session' algorithms are supported.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } malgo3 = (enum MHD_DigestAuthMultiAlgo3) (malgo3 & (~((enum MHD_DigestAuthMultiAlgo3) MHD_DIGEST_AUTH_ALGO3_NON_SESSION))); #ifdef MHD_MD5_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_MD5)) s_algo = MHD_DIGEST_AUTH_ALGO3_MD5; else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA256)) s_algo = MHD_DIGEST_AUTH_ALGO3_SHA256; else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (0 != (((unsigned int) malgo3) & MHD_DIGEST_BASE_ALGO_SHA512_256)) s_algo = MHD_DIGEST_AUTH_ALGO3_SHA512_256; else #endif /* MHD_SHA512_256_SUPPORT */ { if (0 == (((unsigned int) malgo3) & (MHD_DIGEST_BASE_ALGO_MD5 | MHD_DIGEST_BASE_ALGO_SHA256 | MHD_DIGEST_BASE_ALGO_SHA512_256))) MHD_PANIC (_ ("Wrong 'malgo3' value, API violation")); else { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("No requested algorithm is supported by this MHD build.\n")); #endif /* HAVE_MESSAGES */ } return MHD_NO; } if (MHD_DIGEST_AUTH_MULT_QOP_AUTH_INT == mqop) MHD_PANIC (_ ("Wrong 'mqop' value, API violation")); mqop = (enum MHD_DigestAuthMultiQOP) (mqop & (~((enum MHD_DigestAuthMultiQOP) MHD_DIGEST_AUTH_QOP_AUTH_INT))); if (! digest_init_one_time (da, get_base_digest_algo (s_algo))) MHD_PANIC (_ ("Wrong 'algo' value, API violation")); if (MHD_DIGEST_AUTH_MULT_QOP_NONE == mqop) { #ifdef HAVE_MESSAGES if ((0 != userhash_support) || (0 != prefer_utf8)) MHD_DLOG (connection->daemon, _ ("The 'userhash' and 'charset' ('prefer_utf8') parameters " \ "are not compatible with RFC2069 and ignored.\n")); if (0 == (((unsigned int) s_algo) & MHD_DIGEST_BASE_ALGO_MD5)) MHD_DLOG (connection->daemon, _ ("RFC2069 with SHA-256 or SHA-512/256 algorithm is " \ "non-standard extension.\n")); #endif userhash_support = 0; prefer_utf8 = 0; } if (0 == MHD_get_master (connection->daemon)->nonce_nc_size) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The nonce array size is zero.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } /* Calculate required size */ buf_size = 0; /* 'Digest ' */ buf_size += MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE) + 1; /* 1 for ' ' */ buf_size += MHD_STATICSTR_LEN_ (prefix_realm) + 3; /* 3 for '", ' */ /* 'realm="xxxx", ' */ realm_len = strlen (realm); if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < realm_len) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The 'realm' is too large.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } if ((NULL != memchr (realm, '\r', realm_len)) || (NULL != memchr (realm, '\n', realm_len))) return MHD_NO; buf_size += realm_len * 2; /* Quoting may double the size */ /* 'qop="xxxx", ' */ if (MHD_DIGEST_AUTH_MULT_QOP_NONE != mqop) { buf_size += MHD_STATICSTR_LEN_ (prefix_qop) + 3; /* 3 for '", ' */ buf_size += MHD_STATICSTR_LEN_ (MHD_TOKEN_AUTH_); } /* 'algorithm="xxxx", ' */ if (((MHD_DIGEST_AUTH_MULT_QOP_NONE) != mqop) || (0 == (((unsigned int) s_algo) & MHD_DIGEST_BASE_ALGO_MD5))) { buf_size += MHD_STATICSTR_LEN_ (prefix_algo) + 2; /* 2 for ', ' */ #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_MD5 == s_algo) buf_size += MHD_STATICSTR_LEN_ (_MHD_MD5_TOKEN); else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_SHA256 == s_algo) buf_size += MHD_STATICSTR_LEN_ (_MHD_SHA256_TOKEN); else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_SHA512_256 == s_algo) buf_size += MHD_STATICSTR_LEN_ (_MHD_SHA512_256_TOKEN); else #endif /* MHD_SHA512_256_SUPPORT */ mhd_assert (0); } /* 'nonce="xxxx", ' */ buf_size += MHD_STATICSTR_LEN_ (prefix_nonce) + 3; /* 3 for '", ' */ buf_size += NONCE_STD_LEN (digest_get_size (da)); /* Escaping not needed */ /* 'opaque="xxxx", ' */ if (NULL != opaque) { buf_size += MHD_STATICSTR_LEN_ (prefix_opaque) + 3; /* 3 for '", ' */ opaque_len = strlen (opaque); if ((NULL != memchr (opaque, '\r', opaque_len)) || (NULL != memchr (opaque, '\n', opaque_len))) return MHD_NO; buf_size += opaque_len * 2; /* Quoting may double the size */ } else opaque_len = 0; /* 'domain="xxxx", ' */ if (NULL != domain) { buf_size += MHD_STATICSTR_LEN_ (prefix_domain) + 3; /* 3 for '", ' */ domain_len = strlen (domain); if ((NULL != memchr (domain, '\r', domain_len)) || (NULL != memchr (domain, '\n', domain_len))) return MHD_NO; buf_size += domain_len * 2; /* Quoting may double the size */ } else domain_len = 0; /* 'charset=UTF-8' */ if (MHD_NO != prefer_utf8) buf_size += MHD_STATICSTR_LEN_ (str_charset) + 2; /* 2 for ', ' */ /* 'userhash=true' */ if (MHD_NO != userhash_support) buf_size += MHD_STATICSTR_LEN_ (str_userhash) + 2; /* 2 for ', ' */ /* 'stale=true' */ if (MHD_NO != signal_stale) buf_size += MHD_STATICSTR_LEN_ (str_stale) + 2; /* 2 for ', ' */ /* The calculated length is for string ended with ", ". One character will * be used for zero-termination, the last one will not be used. */ /* Allocate the buffer */ buf = malloc (buf_size); if (NULL == buf) return MHD_NO; *buf_ptr = buf; /* Build the challenge string */ p = 0; /* 'Digest: ' */ memcpy (buf + p, _MHD_AUTH_DIGEST_BASE, MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE)); p += MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE); buf[p++] = ' '; /* 'realm="xxxx", ' */ memcpy (buf + p, prefix_realm, MHD_STATICSTR_LEN_ (prefix_realm)); p += MHD_STATICSTR_LEN_ (prefix_realm); mhd_assert ((buf_size - p) >= (realm_len * 2)); if (1) { size_t quoted_size; quoted_size = MHD_str_quote (realm, realm_len, buf + p, buf_size - p); if (_MHD_AUTH_DIGEST_MAX_PARAM_SIZE < quoted_size) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The 'realm' is too large after 'quoting'.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } p += quoted_size; } buf[p++] = '\"'; buf[p++] = ','; buf[p++] = ' '; /* 'qop="xxxx", ' */ if (MHD_DIGEST_AUTH_MULT_QOP_NONE != mqop) { memcpy (buf + p, prefix_qop, MHD_STATICSTR_LEN_ (prefix_qop)); p += MHD_STATICSTR_LEN_ (prefix_qop); memcpy (buf + p, MHD_TOKEN_AUTH_, MHD_STATICSTR_LEN_ (MHD_TOKEN_AUTH_)); p += MHD_STATICSTR_LEN_ (MHD_TOKEN_AUTH_); buf[p++] = '\"'; buf[p++] = ','; buf[p++] = ' '; } /* 'algorithm="xxxx", ' */ if (((MHD_DIGEST_AUTH_MULT_QOP_NONE) != mqop) || (0 == (((unsigned int) s_algo) & MHD_DIGEST_BASE_ALGO_MD5))) { memcpy (buf + p, prefix_algo, MHD_STATICSTR_LEN_ (prefix_algo)); p += MHD_STATICSTR_LEN_ (prefix_algo); #ifdef MHD_MD5_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_MD5 == s_algo) { memcpy (buf + p, _MHD_MD5_TOKEN, MHD_STATICSTR_LEN_ (_MHD_MD5_TOKEN)); p += MHD_STATICSTR_LEN_ (_MHD_MD5_TOKEN); } else #endif /* MHD_MD5_SUPPORT */ #ifdef MHD_SHA256_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_SHA256 == s_algo) { memcpy (buf + p, _MHD_SHA256_TOKEN, MHD_STATICSTR_LEN_ (_MHD_SHA256_TOKEN)); p += MHD_STATICSTR_LEN_ (_MHD_SHA256_TOKEN); } else #endif /* MHD_SHA256_SUPPORT */ #ifdef MHD_SHA512_256_SUPPORT if (MHD_DIGEST_AUTH_ALGO3_SHA512_256 == s_algo) { memcpy (buf + p, _MHD_SHA512_256_TOKEN, MHD_STATICSTR_LEN_ (_MHD_SHA512_256_TOKEN)); p += MHD_STATICSTR_LEN_ (_MHD_SHA512_256_TOKEN); } else #endif /* MHD_SHA512_256_SUPPORT */ mhd_assert (0); buf[p++] = ','; buf[p++] = ' '; } /* 'nonce="xxxx", ' */ memcpy (buf + p, prefix_nonce, MHD_STATICSTR_LEN_ (prefix_nonce)); p += MHD_STATICSTR_LEN_ (prefix_nonce); mhd_assert ((buf_size - p) >= (NONCE_STD_LEN (digest_get_size (da)))); if (! calculate_add_nonce_with_retry (connection, realm, da, buf + p)) { #ifdef MHD_DIGEST_HAS_EXT_ERROR if (digest_ext_error (da)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("TLS library reported hash calculation error, nonce could " "not be generated.\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #endif /* MHD_DIGEST_HAS_EXT_ERROR */ #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Could not register nonce. Client's requests with this " "nonce will be always 'stale'. Probably clients' requests " "are too intensive.\n")); #endif /* HAVE_MESSAGES */ (void) 0; /* Mute compiler warning for builds without messages */ } p += NONCE_STD_LEN (digest_get_size (da)); buf[p++] = '\"'; buf[p++] = ','; buf[p++] = ' '; /* 'opaque="xxxx", ' */ if (NULL != opaque) { memcpy (buf + p, prefix_opaque, MHD_STATICSTR_LEN_ (prefix_opaque)); p += MHD_STATICSTR_LEN_ (prefix_opaque); mhd_assert ((buf_size - p) >= (opaque_len * 2)); p += MHD_str_quote (opaque, opaque_len, buf + p, buf_size - p); buf[p++] = '\"'; buf[p++] = ','; buf[p++] = ' '; } /* 'domain="xxxx", ' */ if (NULL != domain) { memcpy (buf + p, prefix_domain, MHD_STATICSTR_LEN_ (prefix_domain)); p += MHD_STATICSTR_LEN_ (prefix_domain); mhd_assert ((buf_size - p) >= (domain_len * 2)); p += MHD_str_quote (domain, domain_len, buf + p, buf_size - p); buf[p++] = '\"'; buf[p++] = ','; buf[p++] = ' '; } /* 'charset=UTF-8' */ if (MHD_NO != prefer_utf8) { memcpy (buf + p, str_charset, MHD_STATICSTR_LEN_ (str_charset)); p += MHD_STATICSTR_LEN_ (str_charset); buf[p++] = ','; buf[p++] = ' '; } /* 'userhash=true' */ if (MHD_NO != userhash_support) { memcpy (buf + p, str_userhash, MHD_STATICSTR_LEN_ (str_userhash)); p += MHD_STATICSTR_LEN_ (str_userhash); buf[p++] = ','; buf[p++] = ' '; } /* 'stale=true' */ if (MHD_NO != signal_stale) { memcpy (buf + p, str_stale, MHD_STATICSTR_LEN_ (str_stale)); p += MHD_STATICSTR_LEN_ (str_stale); buf[p++] = ','; buf[p++] = ' '; } mhd_assert (buf_size >= p); /* The built string ends with ", ". Replace comma with zero-termination. */ --p; buf[--p] = 0; hdr_name = malloc (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_WWW_AUTHENTICATE) + 1); if (NULL != hdr_name) { memcpy (hdr_name, MHD_HTTP_HEADER_WWW_AUTHENTICATE, MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_WWW_AUTHENTICATE) + 1); if (MHD_add_response_entry_no_alloc_ (response, MHD_HEADER_KIND, hdr_name, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_WWW_AUTHENTICATE), buf, p)) { *buf_ptr = NULL; /* The buffer will be free()ed when the response is destroyed */ return MHD_queue_response (connection, MHD_HTTP_UNAUTHORIZED, response); } #ifdef HAVE_MESSAGES else { MHD_DLOG (connection->daemon, _ ("Failed to add Digest auth header.\n")); } #endif /* HAVE_MESSAGES */ free (hdr_name); } return MHD_NO; } /** * Queues a response to request authentication from the client * * This function modifies provided @a response. The @a response must not be * reused and should be destroyed (by #MHD_destroy_response()) after call of * this function. * * If @a mqop allows both RFC 2069 (MHD_DIGEST_AUTH_QOP_NONE) and QOP with * value, then response is formed like if MHD_DIGEST_AUTH_QOP_NONE bit was * not set, because such response should be backward-compatible with RFC 2069. * * If @a mqop allows only MHD_DIGEST_AUTH_MULT_QOP_NONE, then the response is * formed in strict accordance with RFC 2069 (no 'qop', no 'userhash', no * 'charset'). For better compatibility with clients, it is recommended (but * not required) to set @a domain to NULL in this mode. * * @param connection the MHD connection structure * @param realm the realm presented to the client * @param opaque the string for opaque value, can be NULL, but NULL is * not recommended for better compatibility with clients; * the recommended format is hex or Base64 encoded string * @param domain the optional space-separated list of URIs for which the * same authorisation could be used, URIs can be in form * "path-absolute" (the path for the same host with initial slash) * or in form "absolute-URI" (the full path with protocol), in * any case client may assume that URI is in the same "protection * space" if it starts with any of values specified here; * could be NULL (clients typically assume that the same * credentials could be used for any URI on the same host); * this list provides information for the client only and does * not actually restrict anything on the server side * @param response the reply to send; should contain the "access denied" * body; * note: this function sets the "WWW Authenticate" header and * the caller should not set this header; * the NULL is tolerated * @param signal_stale if set to #MHD_YES then indication of stale nonce used in * the client's request is signalled by adding 'stale=true' * to the authentication header, this instructs the client * to retry immediately with the new nonce and the same * credentials, without asking user for the new password * @param mqop the QOP to use * @param malgo3 digest algorithm to use; if several algorithms are allowed * then MD5 is preferred (currently, may be changed in next * versions) * @param userhash_support if set to non-zero value (#MHD_YES) then support of * userhash is indicated, allowing client to provide * hash("username:realm") instead of the username in * clear text; * note that clients are allowed to provide the username * in cleartext even if this parameter set to non-zero; * when userhash is used, application must be ready to * identify users by provided userhash value instead of * username; see #MHD_digest_auth_calc_userhash() and * #MHD_digest_auth_calc_userhash_hex() * @param prefer_utf8 if not set to #MHD_NO, parameter 'charset=UTF-8' is * added, indicating for the client that UTF-8 encoding for * the username is preferred * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00097701 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_required_response3 (struct MHD_Connection *connection, const char *realm, const char *opaque, const char *domain, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthMultiQOP mqop, enum MHD_DigestAuthMultiAlgo3 malgo3, int userhash_support, int prefer_utf8) { struct DigestAlgorithm da; char *buf_ptr; enum MHD_Result ret; buf_ptr = NULL; digest_setup_zero (&da); ret = queue_auth_required_response3_inner (connection, realm, opaque, domain, response, signal_stale, mqop, malgo3, userhash_support, prefer_utf8, &buf_ptr, &da); digest_deinit (&da); if (NULL != buf_ptr) free (buf_ptr); return ret; } /** * Queues a response to request authentication from the client * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param opaque string to user for opaque value * @param response reply to send; should contain the "access denied" * body; note that this function will set the "WWW Authenticate" * header and that the caller should not do this; the NULL is tolerated * @param signal_stale #MHD_YES if the nonce is stale to add * 'stale=true' to the authentication header * @param algo digest algorithm to use * @return #MHD_YES on success, #MHD_NO otherwise * @note Available since #MHD_VERSION 0x00096200 * @ingroup authentication */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_fail_response2 (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthAlgorithm algo) { enum MHD_DigestAuthMultiAlgo3 algo3; if (MHD_DIGEST_ALG_MD5 == algo) algo3 = MHD_DIGEST_AUTH_MULT_ALGO3_MD5; else if (MHD_DIGEST_ALG_SHA256 == algo) algo3 = MHD_DIGEST_AUTH_MULT_ALGO3_SHA256; else if (MHD_DIGEST_ALG_AUTO == algo) algo3 = MHD_DIGEST_AUTH_MULT_ALGO3_ANY_NON_SESSION; else MHD_PANIC (_ ("Wrong algo value.\n")); /* API violation! */ return MHD_queue_auth_required_response3 (connection, realm, opaque, NULL, response, signal_stale, MHD_DIGEST_AUTH_MULT_QOP_AUTH, algo3, 0, 0); } /** * Queues a response to request authentication from the client. * For now uses MD5 (for backwards-compatibility). Still, if you * need to be sure, use #MHD_queue_auth_fail_response2(). * * @param connection The MHD connection structure * @param realm the realm presented to the client * @param opaque string to user for opaque value * @param response reply to send; should contain the "access denied" * body; note that this function will set the "WWW Authenticate" * header and that the caller should not do this; the NULL is tolerated * @param signal_stale #MHD_YES if the nonce is stale to add * 'stale=true' to the authentication header * @return #MHD_YES on success, #MHD_NO otherwise * @ingroup authentication * @deprecated use MHD_queue_auth_fail_response2() */ _MHD_EXTERN enum MHD_Result MHD_queue_auth_fail_response (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale) { return MHD_queue_auth_fail_response2 (connection, realm, opaque, response, signal_stale, MHD_DIGEST_ALG_MD5); } /* end of digestauth.c */ libmicrohttpd-1.0.10/src/microhttpd/mhd_limits.h0000644000175000017500000001033715035214301015362 /* This file is part of libmicrohttpd Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_limits.h * @brief limits values definitions * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_LIMITS_H #define MHD_LIMITS_H #include "platform.h" #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #define MHD_UNSIGNED_TYPE_MAX_(type) ((type) - 1) /* Assume 8 bits per byte, no padding bits. */ #define MHD_SIGNED_TYPE_MAX_(type) \ ( (type) ((( ((type) 1) << (sizeof(type) * 8 - 2)) - 1) * 2 + 1) ) #define MHD_TYPE_IS_SIGNED_(type) (((type) 0)>((type) - 1)) #ifndef INT_MAX #ifdef __INT_MAX__ #define INT_MAX __INT_MAX__ #else /* ! __UINT_MAX__ */ #define INT_MAX MHD_SIGNED_TYPE_MAX_ (int) #endif /* ! __UINT_MAX__ */ #endif /* !UINT_MAX */ #ifndef UINT_MAX #ifdef __UINT_MAX__ #define UINT_MAX __UINT_MAX__ #else /* ! __UINT_MAX__ */ #define UINT_MAX MHD_UNSIGNED_TYPE_MAX_ (unsigned int) #endif /* ! __UINT_MAX__ */ #endif /* !UINT_MAX */ #ifndef LONG_MAX #ifdef __LONG_MAX__ #define LONG_MAX __LONG_MAX__ #else /* ! __LONG_MAX__ */ #define LONG_MAX MHD_SIGNED_TYPE_MAX (long) #endif /* ! __LONG_MAX__ */ #endif /* !LONG_MAX */ #ifndef ULLONG_MAX #ifdef ULONGLONG_MAX #define ULLONG_MAX ULONGLONG_MAX #else /* ! ULONGLONG_MAX */ #define ULLONG_MAX MHD_UNSIGNED_TYPE_MAX_ (MHD_UNSIGNED_LONG_LONG) #endif /* ! ULONGLONG_MAX */ #endif /* !ULLONG_MAX */ #ifndef INT32_MAX #ifdef __INT32_MAX__ #define INT32_MAX __INT32_MAX__ #else /* ! __INT32_MAX__ */ #define INT32_MAX ((int32_t) 0x7FFFFFFF) #endif /* ! __INT32_MAX__ */ #endif /* !INT32_MAX */ #ifndef UINT32_MAX #ifdef __UINT32_MAX__ #define UINT32_MAX __UINT32_MAX__ #else /* ! __UINT32_MAX__ */ #define UINT32_MAX ((int32_t) 0xFFFFFFFF) #endif /* ! __UINT32_MAX__ */ #endif /* !UINT32_MAX */ #ifndef UINT64_MAX #ifdef __UINT64_MAX__ #define UINT64_MAX __UINT64_MAX__ #else /* ! __UINT64_MAX__ */ #define UINT64_MAX ((uint64_t) 0xFFFFFFFFFFFFFFFF) #endif /* ! __UINT64_MAX__ */ #endif /* !UINT64_MAX */ #ifndef INT64_MAX #ifdef __INT64_MAX__ #define INT64_MAX __INT64_MAX__ #else /* ! __INT64_MAX__ */ #define INT64_MAX ((int64_t) 0x7FFFFFFFFFFFFFFF) #endif /* ! __UINT64_MAX__ */ #endif /* !INT64_MAX */ #ifndef SIZE_MAX #ifdef __SIZE_MAX__ #define SIZE_MAX __SIZE_MAX__ #elif defined(UINTPTR_MAX) #define SIZE_MAX UINTPTR_MAX #else /* ! __SIZE_MAX__ */ #define SIZE_MAX MHD_UNSIGNED_TYPE_MAX_ (size_t) #endif /* ! __SIZE_MAX__ */ #endif /* !SIZE_MAX */ #ifndef SSIZE_MAX #ifdef __SSIZE_MAX__ #define SSIZE_MAX __SSIZE_MAX__ #elif defined(INTPTR_MAX) #define SSIZE_MAX INTPTR_MAX #else #define SSIZE_MAX MHD_SIGNED_TYPE_MAX_ (ssize_t) #endif #endif /* ! SSIZE_MAX */ #ifndef OFF_T_MAX #ifdef OFF_MAX #define OFF_T_MAX OFF_MAX #elif defined(OFFT_MAX) #define OFF_T_MAX OFFT_MAX #elif defined(__APPLE__) && defined(__MACH__) #define OFF_T_MAX INT64_MAX #else #define OFF_T_MAX MHD_SIGNED_TYPE_MAX_ (off_t) #endif #endif /* !OFF_T_MAX */ #if defined(_LARGEFILE64_SOURCE) && ! defined(OFF64_T_MAX) #define OFF64_T_MAX MHD_SIGNED_TYPE_MAX_ (uint64_t) #endif /* _LARGEFILE64_SOURCE && !OFF64_T_MAX */ #ifndef TIME_T_MAX #define TIME_T_MAX ((time_t) \ (MHD_TYPE_IS_SIGNED_ (time_t) ? \ MHD_SIGNED_TYPE_MAX_ (time_t) : \ MHD_UNSIGNED_TYPE_MAX_ (time_t))) #endif /* !TIME_T_MAX */ #ifndef TIMEVAL_TV_SEC_MAX #ifndef _WIN32 #define TIMEVAL_TV_SEC_MAX TIME_T_MAX #else /* _WIN32 */ #define TIMEVAL_TV_SEC_MAX LONG_MAX #endif /* _WIN32 */ #endif /* !TIMEVAL_TV_SEC_MAX */ #endif /* MHD_LIMITS_H */ libmicrohttpd-1.0.10/src/microhttpd/test_str_pct.c0000664000175000017500000011274415232103064015752 /* This file is part of libmicrohttpd Copyright (C) 2022 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_pct.c * @brief Unit tests for percent (URL) encoded strings processing * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ static char tmp_bufs[4][4 * 1024]; /* should be enough for testing */ static size_t buf_idx = 0; /* print non-printable chars as char codes */ static char * n_prnt (const char *str, size_t len) { static char *buf; /* should be enough for testing */ static const size_t buf_size = sizeof(tmp_bufs[0]); size_t r_pos = 0; size_t w_pos = 0; if (++buf_idx >= (sizeof(tmp_bufs) / sizeof(tmp_bufs[0]))) buf_idx = 0; buf = tmp_bufs[buf_idx]; while (len > r_pos && w_pos + 1 < buf_size) { const unsigned char c = (unsigned char) str[r_pos]; if ((c == '\\') || (c == '"') ) { if (w_pos + 2 >= buf_size) break; buf[w_pos++] = '\\'; buf[w_pos++] = (char) c; } else if ((c >= 0x20) && (c <= 0x7E) ) buf[w_pos++] = (char) c; else { if (w_pos + 4 >= buf_size) break; if (snprintf (buf + w_pos, buf_size - w_pos, "\\x%02hX", (short unsigned int) c) != 4) break; w_pos += 4; } r_pos++; } if (len != r_pos) { /* not full string is printed */ /* enough space for "..." ? */ if (w_pos + 3 > buf_size) w_pos = buf_size - 4; buf[w_pos++] = '.'; buf[w_pos++] = '.'; buf[w_pos++] = '.'; } buf[w_pos] = 0; return buf; } #define TEST_BIN_MAX_SIZE 1024 /* return zero if succeed, number of failures otherwise */ static unsigned int expect_decoded_n (const char *const encoded, const size_t encoded_len, const char *const decoded, const size_t decoded_size, const unsigned int line_num) { static const char fill_chr = '#'; static char buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != encoded); mhd_assert (NULL != decoded); mhd_assert (TEST_BIN_MAX_SIZE > decoded_size + 1); mhd_assert (TEST_BIN_MAX_SIZE > encoded_len + 1); mhd_assert (encoded_len >= decoded_size); ret = 0; /* check MHD_str_pct_decode_strict_n_() with small out buffer */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf, decoded_size + 1); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "A char written outside the buffer:\n"); } else { memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf, decoded_size); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong returned value:\n"); } } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) decoded_size, (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) decoded_size, (unsigned) decoded_size); } } /* check MHD_str_pct_decode_strict_n_() with large out buffer */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf, encoded_len + 1); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "A char written outside the buffer:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) (encoded_len + 1), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) (encoded_len + 1), (unsigned) decoded_size); } } /* check MHD_str_pct_decode_lenient_n_() with small out buffer */ if (1) { unsigned int check_res = 0; bool is_broken = true; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, decoded_size + 1, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "A char written outside the buffer:\n"); } else { is_broken = true; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, decoded_size, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } } if (is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->%s) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) decoded_size, is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->false) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) decoded_size, (unsigned) decoded_size); } } /* check MHD_str_pct_decode_lenient_n_() with large out buffer */ if (1) { unsigned int check_res = 0; bool is_broken = true; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, encoded_len + 1, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "A char written outside the buffer:\n"); } if (is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->%s) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) (encoded_len + 1), is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->false) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) (encoded_len + 1), (unsigned) decoded_size); } } if (strlen (encoded) == encoded_len) { /* check MHD_str_pct_decode_in_place_strict_() */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ memcpy (buf, encoded, encoded_len); buf[encoded_len] = 0; res_size = MHD_str_pct_decode_in_place_strict_ (buf); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: " "Wrong returned value:\n"); } else { if (0 != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: " "The result is not zero-terminated:\n"); } if (((res_size + 1) < encoded_len) ? (encoded[res_size + 1] != buf[res_size + 1]) : (fill_chr != buf[res_size + 1])) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: " "A char written outside the buffer:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_in_place_strict_ (\"%s\" " "-> \"%s\") -> %u\n", n_prnt (encoded, encoded_len), n_prnt (buf, res_size), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_in_place_strict_ (\"%s\" " "-> \"%s\") -> %u\n", n_prnt (encoded, encoded_len), n_prnt (decoded, decoded_size), (unsigned) decoded_size); } } /* check MHD_str_pct_decode_in_place_lenient_() */ if (1) { unsigned int check_res = 0; bool is_broken = true; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ memcpy (buf, encoded, encoded_len); buf[encoded_len] = 0; res_size = MHD_str_pct_decode_in_place_lenient_ (buf, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong returned value:\n"); } else { if (0 != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "The result is not zero-terminated:\n"); } if (((res_size + 1) < encoded_len) ? (encoded[res_size + 1] != buf[res_size + 1]) : (fill_chr != buf[res_size + 1])) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "A char written outside the buffer:\n"); } if (is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_in_place_lenient_ (\"%s\" " "-> \"%s\", ->%s) -> %u\n", n_prnt (encoded, encoded_len), n_prnt (buf, res_size), is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_in_place_lenient_ (\"%s\" " "-> \"%s\", ->false) -> %u\n", n_prnt (encoded, encoded_len), n_prnt (decoded, decoded_size), (unsigned) decoded_size); } } } if (0 != ret) { fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_decoded(e,d) \ expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\ d,MHD_STATICSTR_LEN_(d), \ __LINE__) static unsigned int check_decode_str (void) { unsigned int r = 0; /**< The number of errors */ r += expect_decoded ("", ""); /* Base sequences without percent symbol */ r += expect_decoded ("aaa", "aaa"); r += expect_decoded ("bbb", "bbb"); r += expect_decoded ("ccc", "ccc"); r += expect_decoded ("ddd", "ddd"); r += expect_decoded ("lll", "lll"); r += expect_decoded ("mmm", "mmm"); r += expect_decoded ("nnn", "nnn"); r += expect_decoded ("ooo", "ooo"); r += expect_decoded ("www", "www"); r += expect_decoded ("xxx", "xxx"); r += expect_decoded ("yyy", "yyy"); r += expect_decoded ("zzz", "zzz"); r += expect_decoded ("AAA", "AAA"); r += expect_decoded ("GGG", "GGG"); r += expect_decoded ("MMM", "MMM"); r += expect_decoded ("TTT", "TTT"); r += expect_decoded ("ZZZ", "ZZZ"); r += expect_decoded ("012", "012"); r += expect_decoded ("345", "345"); r += expect_decoded ("678", "678"); r += expect_decoded ("901", "901"); r += expect_decoded ("aaaaaa", "aaaaaa"); r += expect_decoded ("bbbbbb", "bbbbbb"); r += expect_decoded ("cccccc", "cccccc"); r += expect_decoded ("dddddd", "dddddd"); r += expect_decoded ("llllll", "llllll"); r += expect_decoded ("mmmmmm", "mmmmmm"); r += expect_decoded ("nnnnnn", "nnnnnn"); r += expect_decoded ("oooooo", "oooooo"); r += expect_decoded ("wwwwww", "wwwwww"); r += expect_decoded ("xxxxxx", "xxxxxx"); r += expect_decoded ("yyyyyy", "yyyyyy"); r += expect_decoded ("zzzzzz", "zzzzzz"); r += expect_decoded ("AAAAAA", "AAAAAA"); r += expect_decoded ("GGGGGG", "GGGGGG"); r += expect_decoded ("MMMMMM", "MMMMMM"); r += expect_decoded ("TTTTTT", "TTTTTT"); r += expect_decoded ("ZZZZZZ", "ZZZZZZ"); r += expect_decoded ("012012", "012012"); r += expect_decoded ("345345", "345345"); r += expect_decoded ("678678", "678678"); r += expect_decoded ("901901", "901901"); r += expect_decoded ("a", "a"); r += expect_decoded ("bc", "bc"); r += expect_decoded ("DEFG", "DEFG"); r += expect_decoded ("123t", "123t"); r += expect_decoded ("12345", "12345"); r += expect_decoded ("TestStr", "TestStr"); r += expect_decoded ("Teststring", "Teststring"); r += expect_decoded ("Teststring.", "Teststring."); r += expect_decoded ("Longerstring", "Longerstring"); r += expect_decoded ("Longerstring.", "Longerstring."); r += expect_decoded ("Longerstring2.", "Longerstring2."); /* Simple percent-encoded strings */ r += expect_decoded ("Test%20string", "Test string"); r += expect_decoded ("Test%3Fstring.", "Test?string."); r += expect_decoded ("100%25", "100%"); r += expect_decoded ("a%2C%20b%3Dc%26e%3Dg", "a, b=c&e=g"); r += expect_decoded ("%20%21%23%24%25%26%27%28%29%2A%2B%2C" "%2F%3A%3B%3D%3F%40%5B%5D%09", " !#$%&'()*+,/:;=?@[]\t"); return r; } #define expect_decoded_arr(e,a) \ expect_decoded_n(e,MHD_STATICSTR_LEN_(e),\ (const char *)a,(sizeof(a)/sizeof(a[0])), \ __LINE__) static unsigned int check_decode_bin (void) { unsigned int r = 0; /**< The number of errors */ if (1) { static const uint8_t bin[256] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; /* The lower case */ r += expect_decoded_arr ("%00%01%02%03%04%05%06%07%08%09%0a%0b%0c%0d%0e" \ "%0f%10%11%12%13%14%15%16%17%18%19%1a%1b%1c%1d" \ "%1e%1f%20%21%22%23%24%25%26%27%28%29%2a%2b%2c" \ "%2d%2e%2f%30%31%32%33%34%35%36%37%38%39%3a%3b" \ "%3c%3d%3e%3f%40%41%42%43%44%45%46%47%48%49%4a" \ "%4b%4c%4d%4e%4f%50%51%52%53%54%55%56%57%58%59" \ "%5a%5b%5c%5d%5e%5f%60%61%62%63%64%65%66%67%68" \ "%69%6a%6b%6c%6d%6e%6f%70%71%72%73%74%75%76%77" \ "%78%79%7a%7b%7c%7d%7e%7f%80%81%82%83%84%85%86" \ "%87%88%89%8a%8b%8c%8d%8e%8f%90%91%92%93%94%95" \ "%96%97%98%99%9a%9b%9c%9d%9e%9f%a0%a1%a2%a3%a4" \ "%a5%a6%a7%a8%a9%aa%ab%ac%ad%ae%af%b0%b1%b2%b3" \ "%b4%b5%b6%b7%b8%b9%ba%bb%bc%bd%be%bf%c0%c1%c2" \ "%c3%c4%c5%c6%c7%c8%c9%ca%cb%cc%cd%ce%cf%d0%d1" \ "%d2%d3%d4%d5%d6%d7%d8%d9%da%db%dc%dd%de%df%e0" \ "%e1%e2%e3%e4%e5%e6%e7%e8%e9%ea%eb%ec%ed%ee%ef" \ "%f0%f1%f2%f3%f4%f5%f6%f7%f8%f9%fa%fb%fc%fd%fe" \ "%ff", bin); } if (1) { static const uint8_t bin[256] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff }; /* The upper case */ r += expect_decoded_arr ("%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E" \ "%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D" \ "%1E%1F%20%21%22%23%24%25%26%27%28%29%2A%2B%2C" \ "%2D%2E%2F%30%31%32%33%34%35%36%37%38%39%3A%3B" \ "%3C%3D%3E%3F%40%41%42%43%44%45%46%47%48%49%4A" \ "%4B%4C%4D%4E%4F%50%51%52%53%54%55%56%57%58%59" \ "%5A%5B%5C%5D%5E%5F%60%61%62%63%64%65%66%67%68" \ "%69%6A%6B%6C%6D%6E%6F%70%71%72%73%74%75%76%77" \ "%78%79%7A%7B%7C%7D%7E%7F%80%81%82%83%84%85%86" \ "%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95" \ "%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4" \ "%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3" \ "%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2" \ "%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1" \ "%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0" \ "%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF" \ "%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE" \ "%FF", bin); } return r; } /* return zero if succeed, number of failures otherwise */ static unsigned int expect_decoded_bad_n (const char *const encoded, const size_t encoded_len, const char *const decoded, const size_t decoded_size, const unsigned int line_num) { static const char fill_chr = '#'; static char buf[TEST_BIN_MAX_SIZE]; size_t res_size; unsigned int ret; mhd_assert (NULL != encoded); mhd_assert (NULL != decoded); mhd_assert (TEST_BIN_MAX_SIZE > decoded_size + 1); mhd_assert (TEST_BIN_MAX_SIZE > encoded_len + 1); mhd_assert (encoded_len >= decoded_size); ret = 0; /* check MHD_str_pct_decode_strict_n_() with small out buffer */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf, decoded_size); if (res_size != 0) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong returned value:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) decoded_size, (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->(not defined), %u) -> 0\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, (unsigned) decoded_size); } } /* check MHD_str_pct_decode_strict_n_() with large out buffer */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_strict_n_ (encoded, encoded_len, buf, encoded_len + 1); if (res_size != 0) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_strict_n_ ()' FAILED: " "Wrong returned value:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->\"%s\", %u) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) (encoded_len + 1), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_strict_n_ (\"%s\", %u, " "->(not defined), %u) -> 0\n", n_prnt (encoded, encoded_len), (unsigned) (encoded_len + 1), (unsigned) decoded_size); } } /* check MHD_str_pct_decode_lenient_n_() with small out buffer */ if (1) { unsigned int check_res = 0; bool is_broken = false; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, decoded_size + 1, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "A char written outside the buffer:\n"); } else { is_broken = false; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, decoded_size, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } } if (! is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->%s) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) decoded_size, is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->true) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) decoded_size, (unsigned) decoded_size); } } /* check MHD_str_pct_decode_lenient_n_() with large out buffer */ if (1) { unsigned int check_res = 0; bool is_broken = false; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ res_size = MHD_str_pct_decode_lenient_n_ (encoded, encoded_len, buf, encoded_len + 1, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong returned value:\n"); } else { if (fill_chr != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "A char written outside the buffer:\n"); } if (! is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_lenient_n_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->%s) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (buf, res_size), (unsigned) (encoded_len + 1), is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_lenient_n_ (\"%s\", %u, " "->\"%s\", %u, ->true) -> %u\n", n_prnt (encoded, encoded_len), (unsigned) encoded_len, n_prnt (decoded, decoded_size), (unsigned) (encoded_len + 1), (unsigned) decoded_size); } } if (strlen (encoded) == encoded_len) { /* check MHD_str_pct_decode_in_place_strict_() */ if (1) { unsigned int check_res = 0; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ memcpy (buf, encoded, encoded_len); buf[encoded_len] = 0; res_size = MHD_str_pct_decode_in_place_strict_ (buf); if (res_size != 0) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_strict_ ()' FAILED: " "Wrong returned value:\n"); } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_in_place_strict_ (\"%s\" " "-> \"%s\") -> %u\n", n_prnt (encoded, encoded_len), n_prnt (buf, res_size), (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_in_place_strict_ (\"%s\" " "-> (not defined)) -> 0\n", n_prnt (encoded, encoded_len)); } } /* check MHD_str_pct_decode_in_place_lenient_() */ if (1) { unsigned int check_res = 0; bool is_broken = false; memset (buf, fill_chr, sizeof(buf)); /* Fill buffer with some character */ memcpy (buf, encoded, encoded_len); buf[encoded_len] = 0; res_size = MHD_str_pct_decode_in_place_lenient_ (buf, &is_broken); if (res_size != decoded_size) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong returned value:\n"); } else { if (0 != buf[res_size]) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "The result is not zero-terminated:\n"); } if (((res_size + 1) < encoded_len) ? (encoded[res_size + 1] != buf[res_size + 1]) : (fill_chr != buf[res_size + 1])) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "A char written outside the buffer:\n"); } if (! is_broken) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong 'broken_encoding' result:\n"); } if ((res_size == decoded_size) && (0 != decoded_size) && (0 != memcmp (buf, decoded, decoded_size))) { check_res = 1; fprintf (stderr, "'MHD_str_pct_decode_in_place_lenient_ ()' FAILED: " "Wrong output string:\n"); } } if (0 != check_res) { ret++; fprintf (stderr, "\tRESULT : MHD_str_pct_decode_in_place_lenient_ (\"%s\" " "-> \"%s\", ->%s) -> %u\n", n_prnt (encoded, encoded_len), n_prnt (buf, res_size), is_broken ? "true" : "false", (unsigned) res_size); fprintf (stderr, "\tEXPECTED: MHD_str_pct_decode_in_place_lenient_ (\"%s\" " "-> \"%s\", ->true) -> %u\n", n_prnt (encoded, encoded_len), n_prnt (decoded, decoded_size), (unsigned) decoded_size); } } } if (0 != ret) { fprintf (stderr, "The check is at line: %u\n\n", line_num); } return ret; } #define expect_decoded_bad(e,d) \ expect_decoded_bad_n(e,MHD_STATICSTR_LEN_(e),\ d,MHD_STATICSTR_LEN_(d), \ __LINE__) static unsigned int check_decode_bad_str (void) { unsigned int r = 0; /**< The number of errors */ r += expect_decoded_bad ("50%/50%", "50%/50%"); r += expect_decoded_bad ("This is 100% incorrect.", "This is 100% incorrect."); r += expect_decoded_bad ("Some %%", "Some %%"); r += expect_decoded_bad ("1 %", "1 %"); r += expect_decoded_bad ("%", "%"); r += expect_decoded_bad ("%a", "%a"); r += expect_decoded_bad ("%0", "%0"); r += expect_decoded_bad ("%0x", "%0x"); r += expect_decoded_bad ("%FX", "%FX"); r += expect_decoded_bad ("Valid%20and%2invalid", "Valid and%2invalid"); return r; } int main (int argc, char *argv[]) { unsigned int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_decode_str (); errcount += check_decode_bin (); errcount += check_decode_bad_str (); if (0 == errcount) printf ("All tests have been passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.10/src/microhttpd/mhd_sockets.h0000644000175000017500000007701214760713577015566 /* This file is part of libmicrohttpd Copyright (C) 2014-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_sockets.c * @brief Header for platform-independent sockets abstraction * @author Karlson2k (Evgeny Grin) * * Provides basic abstraction for sockets. * Any functions can be implemented as macro on some platforms * unless explicitly marked otherwise. * Any function argument can be skipped in macro, so avoid * variable modification in function parameters. */ #ifndef MHD_SOCKETS_H #define MHD_SOCKETS_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #include #ifdef HAVE_STDDEF_H #include #endif /* HAVE_STDDEF_H */ #if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED) # include # define _SSIZE_T_DEFINED typedef intptr_t ssize_t; #endif /* !_SSIZE_T_DEFINED */ #if ! defined(MHD_POSIX_SOCKETS) && ! defined(MHD_WINSOCK_SOCKETS) # if ! defined(_WIN32) || defined(__CYGWIN__) # define MHD_POSIX_SOCKETS 1 # else /* defined(_WIN32) && !defined(__CYGWIN__) */ # define MHD_WINSOCK_SOCKETS 1 # endif /* defined(_WIN32) && !defined(__CYGWIN__) */ #endif /* !MHD_POSIX_SOCKETS && !MHD_WINSOCK_SOCKETS */ /* * MHD require headers that define socket type, socket basic functions * (socket(), accept(), listen(), bind(), send(), recv(), select()), socket * parameters like SOCK_CLOEXEC, SOCK_NONBLOCK, additional socket functions * (poll(), epoll(), accept4()), struct timeval and other types, required * for socket function. */ #if defined(MHD_POSIX_SOCKETS) # ifdef HAVE_SYS_TYPES_H # include /* required on old platforms */ # endif # ifdef HAVE_SYS_TIME_H # include # endif # ifdef HAVE_TIME_H # include # endif # ifdef HAVE_STRING_H # include /* for strerror() */ # endif # ifdef HAVE_SYS_SOCKET_H # include # endif # if defined(__VXWORKS__) || defined(__vxworks) || defined(OS_VXWORKS) # include /* required for FD_SET (bzero() function) */ # ifdef HAVE_SOCKLIB_H # include # endif /* HAVE_SOCKLIB_H */ # ifdef HAVE_INETLIB_H # include # endif /* HAVE_INETLIB_H */ # endif /* __VXWORKS__ || __vxworks || OS_VXWORKS */ # ifdef HAVE_NETINET_IN_H # include # endif /* HAVE_NETINET_IN_H */ # ifdef HAVE_ARPA_INET_H # include # endif # ifdef HAVE_NET_IF_H # include # endif # ifdef HAVE_NETDB_H # include # endif # ifdef HAVE_SYS_SELECT_H # include # endif # ifdef EPOLL_SUPPORT # include # endif # ifdef HAVE_NETINET_TCP_H /* for TCP_FASTOPEN and TCP_CORK */ # include # endif #elif defined(MHD_WINSOCK_SOCKETS) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif /* !WIN32_LEAN_AND_MEAN */ # include # include #endif /* MHD_WINSOCK_SOCKETS */ #if defined(HAVE_POLL_H) && defined(HAVE_POLL) # include #endif #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) #include /* For __FreeBSD_version */ #endif /* __FreeBSD__ */ #include "mhd_limits.h" #ifdef _MHD_FD_SETSIZE_IS_DEFAULT # define _MHD_SYS_DEFAULT_FD_SETSIZE FD_SETSIZE #else /* ! _MHD_FD_SETSIZE_IS_DEFAULT */ # ifndef MHD_SYS_FD_SETSIZE_ # include "sysfdsetsize.h" # define _MHD_SYS_DEFAULT_FD_SETSIZE get_system_fdsetsize_value () # else /* MHD_SYS_FD_SETSIZE_ */ # define _MHD_SYS_DEFAULT_FD_SETSIZE MHD_SYS_FD_SETSIZE_ # endif /* MHD_SYS_FD_SETSIZE_ */ #endif /* ! _MHD_FD_SETSIZE_IS_DEFAULT */ #ifndef MHD_PANIC # include # include /* Simple implementation of MHD_PANIC, to be used outside lib */ # define MHD_PANIC(msg) \ do { fprintf (stderr, \ "Abnormal termination at %d line in file %s: %s\n", \ (int) __LINE__, __FILE__, msg); abort (); \ } while (0) #endif /* ! MHD_PANIC */ #ifndef MHD_SOCKET_DEFINED /** * MHD_socket is type for socket FDs */ # if defined(MHD_POSIX_SOCKETS) typedef int MHD_socket; # define MHD_INVALID_SOCKET (-1) # elif defined(MHD_WINSOCK_SOCKETS) typedef SOCKET MHD_socket; # define MHD_INVALID_SOCKET (INVALID_SOCKET) # endif /* MHD_WINSOCK_SOCKETS */ # define MHD_SOCKET_DEFINED 1 #endif /* ! MHD_SOCKET_DEFINED */ #ifdef SOCK_CLOEXEC # define SOCK_CLOEXEC_OR_ZERO SOCK_CLOEXEC #else /* ! SOCK_CLOEXEC */ # define SOCK_CLOEXEC_OR_ZERO 0 #endif /* ! SOCK_CLOEXEC */ #ifdef HAVE_SOCK_NONBLOCK # define SOCK_NONBLOCK_OR_ZERO SOCK_NONBLOCK #else /* ! HAVE_SOCK_NONBLOCK */ # define SOCK_NONBLOCK_OR_ZERO 0 #endif /* ! HAVE_SOCK_NONBLOCK */ #ifdef SOCK_NOSIGPIPE # define SOCK_NOSIGPIPE_OR_ZERO SOCK_NOSIGPIPE #else /* ! HAVE_SOCK_NONBLOCK */ # define SOCK_NOSIGPIPE_OR_ZERO 0 #endif /* ! HAVE_SOCK_NONBLOCK */ #ifdef MSG_NOSIGNAL # define MSG_NOSIGNAL_OR_ZERO MSG_NOSIGNAL #else /* ! MSG_NOSIGNAL */ # define MSG_NOSIGNAL_OR_ZERO 0 #endif /* ! MSG_NOSIGNAL */ #if ! defined(SHUT_WR) && defined(SD_SEND) # define SHUT_WR SD_SEND #endif #if ! defined(SHUT_RD) && defined(SD_RECEIVE) # define SHUT_RD SD_RECEIVE #endif #if ! defined(SHUT_RDWR) && defined(SD_BOTH) # define SHUT_RDWR SD_BOTH #endif #if defined(HAVE_ACCEPT4) && (defined(HAVE_SOCK_NONBLOCK) || \ defined(SOCK_CLOEXEC) || defined(SOCK_NOSIGPIPE)) # define USE_ACCEPT4 1 #endif #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || \ defined(__OpenBSD__) || defined(__NetBSD__) || \ defined(MHD_WINSOCK_SOCKETS) || defined(__MACH__) || defined(__sun) || \ defined(SOMEBSD) /* Most of OSes inherit nonblocking setting from the listen socket */ #define MHD_ACCEPT_INHERIT_NONBLOCK 1 #endif #if defined(HAVE_EPOLL_CREATE1) && defined(EPOLL_CLOEXEC) # define USE_EPOLL_CREATE1 1 #endif /* HAVE_EPOLL_CREATE1 && EPOLL_CLOEXEC */ #ifdef TCP_FASTOPEN /** * Default TCP fastopen queue size. */ #define MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT 10 #endif #if defined(TCP_CORK) /** * Value of TCP_CORK or TCP_NOPUSH */ #define MHD_TCP_CORK_NOPUSH TCP_CORK #elif defined(TCP_NOPUSH) /** * Value of TCP_CORK or TCP_NOPUSH */ #define MHD_TCP_CORK_NOPUSH TCP_NOPUSH #endif /* TCP_NOPUSH */ #ifdef MHD_TCP_CORK_NOPUSH #ifdef __linux__ /** * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network */ #define _MHD_CORK_RESET_PUSH_DATA 1 /** * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network * even if TCP_CORK/TCP_NOPUSH was in switched off state. */ #define _MHD_CORK_RESET_PUSH_DATA_ALWAYS 1 #endif /* __linux__ */ #if (defined(__FreeBSD__) && \ ((__FreeBSD__ + 0) >= 5 || (__FreeBSD_version + 0) >= 450000)) || \ (defined(__FreeBSD_kernel_version) && \ (__FreeBSD_kernel_version + 0) >= 450000) /* FreeBSD pushes data to the network with reset of TCP_NOPUSH * starting from version 4.5. */ /** * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network */ #define _MHD_CORK_RESET_PUSH_DATA 1 #endif /* __FreeBSD_version >= 450000 */ #ifdef __OpenBSD__ /* OpenBSD took implementation from FreeBSD */ /** * Indicate that reset of TCP_CORK / TCP_NOPUSH push data to the network */ #define _MHD_CORK_RESET_PUSH_DATA 1 #endif /* __OpenBSD__ */ #endif /* MHD_TCP_CORK_NOPUSH */ #ifdef __linux__ /** * Indicate that set of TCP_NODELAY push data to the network */ #define _MHD_NODELAY_SET_PUSH_DATA 1 /** * Indicate that set of TCP_NODELAY push data to the network even * if TCP_DELAY was already set and regardless of TCP_CORK / TCP_NOPUSH state */ #define _MHD_NODELAY_SET_PUSH_DATA_ALWAYS 1 #endif /* __linux__ */ #ifdef MSG_MORE #ifdef __linux__ /* MSG_MORE signal kernel to buffer outbond data and works like * TCP_CORK per call without actually setting TCP_CORK value. * It's known to work on Linux. Add more OSes if they are compatible. */ /** * Indicate MSG_MORE is usable for buffered send(). */ #define MHD_USE_MSG_MORE 1 #endif /* __linux__ */ #endif /* MSG_MORE */ /** * MHD_SCKT_OPT_BOOL_ is type for bool parameters for setsockopt()/getsockopt() */ #ifdef MHD_POSIX_SOCKETS typedef int MHD_SCKT_OPT_BOOL_; #else /* MHD_WINSOCK_SOCKETS */ typedef BOOL MHD_SCKT_OPT_BOOL_; #endif /* MHD_WINSOCK_SOCKETS */ /** * MHD_SCKT_SEND_SIZE_ is type used to specify size for send and recv * functions */ #if ! defined(MHD_WINSOCK_SOCKETS) typedef size_t MHD_SCKT_SEND_SIZE_; #else typedef int MHD_SCKT_SEND_SIZE_; #endif /** * MHD_SCKT_SEND_MAX_SIZE_ is maximum send()/recv() size value. */ #if ! defined(MHD_WINSOCK_SOCKETS) # define MHD_SCKT_SEND_MAX_SIZE_ SSIZE_MAX #else # define MHD_SCKT_SEND_MAX_SIZE_ INT_MAX #endif /** * MHD_socket_close_(fd) close any FDs (non-W32) / close only socket * FDs (W32). Note that on HP-UNIX, this function may leak the FD if * errno is set to EINTR. Do not use HP-UNIX. * * @param fd descriptor to close * @return boolean true on success (error codes like EINTR and EIO are * counted as success, only EBADF counts as an error!), * boolean false otherwise. */ #if ! defined(MHD_WINSOCK_SOCKETS) # define MHD_socket_close_(fd) ((0 == close ((fd))) || (EBADF != errno)) #else # define MHD_socket_close_(fd) (0 == closesocket ((fd))) #endif /** * MHD_socket_close_chk_(fd) close socket and abort execution * if error is detected. * @param fd socket to close */ #define MHD_socket_close_chk_(fd) do { \ if (! MHD_socket_close_ (fd)) \ MHD_PANIC (_ ("Close socket failed.\n")); \ } while (0) /** * MHD_send4_ is a wrapper for system's send() * @param s the socket to use * @param b the buffer with data to send * @param l the length of data in @a b * @param f the additional flags * @return ssize_t type value */ #define MHD_send4_(s,b,l,f) \ ((ssize_t) send ((s),(const void*) (b),(MHD_SCKT_SEND_SIZE_) (l), \ ((MSG_NOSIGNAL_OR_ZERO) | (f)))) /** * MHD_send_ is a simple wrapper for system's send() * @param s the socket to use * @param b the buffer with data to send * @param l the length of data in @a b * @return ssize_t type value */ #define MHD_send_(s,b,l) MHD_send4_((s),(b),(l), 0) /** * MHD_recv_ is wrapper for system's recv() * @param s the socket to use * @param b the buffer for data to receive * @param l the length of @a b * @return ssize_t type value */ #define MHD_recv_(s,b,l) \ ((ssize_t) recv ((s),(void*) (b),(MHD_SCKT_SEND_SIZE_) (l), 0)) /** * Check whether FD can be added to fd_set with specified FD_SETSIZE. * @param fd the fd to check * @param pset the pointer to fd_set to check or NULL to check * whether FD can be used with fd_sets. * @param setsize the value of FD_SETSIZE. * @return boolean true if FD can be added to fd_set, * boolean false otherwise. */ #if defined(MHD_POSIX_SOCKETS) # define MHD_SCKT_FD_FITS_FDSET_SETSIZE_(fd,pset,setsize) \ ((fd) < ((MHD_socket) (setsize))) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_SCKT_FD_FITS_FDSET_SETSIZE_(fd,pset,setsize) \ ( ((void*) (pset)== (void*) 0) || \ (((fd_set*) (pset))->fd_count < ((unsigned) setsize)) || \ (FD_ISSET ((fd), (pset))) ) #endif /** * Check whether FD can be added to fd_set with current FD_SETSIZE. * @param fd the fd to check * @param pset the pointer to fd_set to check or NULL to check * whether FD can be used with fd_sets. * @return boolean true if FD can be added to fd_set, * boolean false otherwise. */ #define MHD_SCKT_FD_FITS_FDSET_(fd,pset) \ MHD_SCKT_FD_FITS_FDSET_SETSIZE_ ((fd), (pset), FD_SETSIZE) /** * Add FD to fd_set with specified FD_SETSIZE. * @param fd the fd to add * @param pset the valid pointer to fd_set. * @param setsize the value of FD_SETSIZE. * @note To work on W32 with value of FD_SETSIZE different from currently defined value, * system definition of FD_SET() is not used. */ #if defined(MHD_POSIX_SOCKETS) # define MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_(fd,pset,setsize) \ FD_SET ((fd), (pset)) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_SCKT_ADD_FD_TO_FDSET_SETSIZE_(fd,pset,setsize) \ do { \ u_int _i_ = 0; \ fd_set*const _s_ = (fd_set*) (pset); \ while ((_i_ < _s_->fd_count) && ((fd) != _s_->fd_array [_i_])) {++_i_;} \ if ((_i_ == _s_->fd_count)) {_s_->fd_array [_s_->fd_count ++] = (fd);} \ } while (0) #endif /* MHD_SYS_select_ is wrapper macro for system select() function */ #if ! defined(MHD_WINSOCK_SOCKETS) # define MHD_SYS_select_(n,r,w,e,t) select ((n),(r),(w),(e),(t)) #else # define MHD_SYS_select_(n,r,w,e,t) \ ( ( (((void*) (r) == (void*) 0) || ((fd_set*) (r))->fd_count == 0) && \ (((void*) (w) == (void*) 0) || ((fd_set*) (w))->fd_count == 0) && \ (((void*) (e) == (void*) 0) || ((fd_set*) (e))->fd_count == 0) ) ? \ ( ((void*) (t) == (void*) 0) ? 0 : \ (Sleep ((DWORD)((struct timeval*) (t))->tv_sec * 1000 \ + (DWORD)((struct timeval*) (t))->tv_usec / 1000), 0) ) : \ (select ((int) 0,(r),(w),(e),(t))) ) #endif #if defined(HAVE_POLL) /* MHD_sys_poll_ is wrapper macro for system poll() function */ # if ! defined(MHD_WINSOCK_SOCKETS) # define MHD_sys_poll_ poll # else /* MHD_WINSOCK_SOCKETS */ # define MHD_sys_poll_ WSAPoll # endif /* MHD_WINSOCK_SOCKETS */ # ifdef POLLPRI # define MHD_POLLPRI_OR_ZERO POLLPRI # else /* ! POLLPRI */ # define MHD_POLLPRI_OR_ZERO 0 # endif /* ! POLLPRI */ # ifdef POLLRDBAND # define MHD_POLLRDBAND_OR_ZERO POLLRDBAND # else /* ! POLLRDBAND */ # define MHD_POLLRDBAND_OR_ZERO 0 # endif /* ! POLLRDBAND */ # ifdef POLLNVAL # define MHD_POLLNVAL_OR_ZERO POLLNVAL # else /* ! POLLNVAL */ # define MHD_POLLNVAL_OR_ZERO 0 # endif /* ! POLLNVAL */ /* MHD_POLL_EVENTS_ERR_DISC is 'events' mask for errors and disconnect. * Note: Out-of-band data is treated as error. */ # if defined(_WIN32) && ! defined(__CYGWIN__) # define MHD_POLL_EVENTS_ERR_DISC POLLRDBAND # elif defined(__linux__) # define MHD_POLL_EVENTS_ERR_DISC POLLPRI # else /* ! __linux__ */ # define MHD_POLL_EVENTS_ERR_DISC \ (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO) # endif /* ! __linux__ */ /* MHD_POLL_REVENTS_ERR_DISC is 'revents' mask for errors and disconnect. * Note: Out-of-band data is treated as error. */ # define MHD_POLL_REVENTS_ERR_DISC \ (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO | MHD_POLLNVAL_OR_ZERO \ | POLLERR | POLLHUP) /* MHD_POLL_REVENTS_ERRROR is 'revents' mask for errors. * Note: Out-of-band data is treated as error. */ # define MHD_POLL_REVENTS_ERRROR \ (MHD_POLLPRI_OR_ZERO | MHD_POLLRDBAND_OR_ZERO | MHD_POLLNVAL_OR_ZERO \ | POLLERR) #endif /* HAVE_POLL */ #define MHD_SCKT_MISSING_ERR_CODE_ 31450 #if defined(MHD_POSIX_SOCKETS) # if defined(EAGAIN) # define MHD_SCKT_EAGAIN_ EAGAIN # elif defined(EWOULDBLOCK) # define MHD_SCKT_EAGAIN_ EWOULDBLOCK # else /* !EAGAIN && !EWOULDBLOCK */ # define MHD_SCKT_EAGAIN_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* !EAGAIN && !EWOULDBLOCK */ # if defined(EWOULDBLOCK) # define MHD_SCKT_EWOULDBLOCK_ EWOULDBLOCK # elif defined(EAGAIN) # define MHD_SCKT_EWOULDBLOCK_ EAGAIN # else /* !EWOULDBLOCK && !EAGAIN */ # define MHD_SCKT_EWOULDBLOCK_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* !EWOULDBLOCK && !EAGAIN */ # ifdef EINTR # define MHD_SCKT_EINTR_ EINTR # else /* ! EINTR */ # define MHD_SCKT_EINTR_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EINTR */ # ifdef ECONNRESET # define MHD_SCKT_ECONNRESET_ ECONNRESET # else /* ! ECONNRESET */ # define MHD_SCKT_ECONNRESET_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ECONNRESET */ # ifdef ECONNABORTED # define MHD_SCKT_ECONNABORTED_ ECONNABORTED # else /* ! ECONNABORTED */ # define MHD_SCKT_ECONNABORTED_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ECONNABORTED */ # ifdef ENOTCONN # define MHD_SCKT_ENOTCONN_ ENOTCONN # else /* ! ENOTCONN */ # define MHD_SCKT_ENOTCONN_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOTCONN */ # ifdef EMFILE # define MHD_SCKT_EMFILE_ EMFILE # else /* ! EMFILE */ # define MHD_SCKT_EMFILE_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EMFILE */ # ifdef ENFILE # define MHD_SCKT_ENFILE_ ENFILE # else /* ! ENFILE */ # define MHD_SCKT_ENFILE_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENFILE */ # ifdef ENOMEM # define MHD_SCKT_ENOMEM_ ENOMEM # else /* ! ENOMEM */ # define MHD_SCKT_ENOMEM_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOMEM */ # ifdef ENOBUFS # define MHD_SCKT_ENOBUFS_ ENOBUFS # else /* ! ENOBUFS */ # define MHD_SCKT_ENOBUFS_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOBUFS */ # ifdef EBADF # define MHD_SCKT_EBADF_ EBADF # else /* ! EBADF */ # define MHD_SCKT_EBADF_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EBADF */ # ifdef ENOTSOCK # define MHD_SCKT_ENOTSOCK_ ENOTSOCK # else /* ! ENOTSOCK */ # define MHD_SCKT_ENOTSOCK_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOTSOCK */ # ifdef EINVAL # define MHD_SCKT_EINVAL_ EINVAL # else /* ! EINVAL */ # define MHD_SCKT_EINVAL_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EINVAL */ # ifdef EPIPE # define MHD_SCKT_EPIPE_ EPIPE # else /* ! EPIPE */ # define MHD_SCKT_EPIPE_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EPIPE */ # ifdef EFAULT # define MHD_SCKT_EFAUL_ EFAULT # else /* ! EFAULT */ # define MHD_SCKT_EFAUL_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EFAULT */ # ifdef ENOSYS # define MHD_SCKT_ENOSYS_ ENOSYS # else /* ! ENOSYS */ # define MHD_SCKT_ENOSYS_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOSYS */ # ifdef ENOPROTOOPT # define MHD_SCKT_ENOPROTOOPT_ ENOPROTOOPT # else /* ! ENOPROTOOPT */ # define MHD_SCKT_ENOPROTOOPT_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOPROTOOPT */ # ifdef ENOTSUP # define MHD_SCKT_ENOTSUP_ ENOTSUP # else /* ! ENOTSUP */ # define MHD_SCKT_ENOTSUP_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENOTSUP */ # ifdef EOPNOTSUPP # define MHD_SCKT_EOPNOTSUPP_ EOPNOTSUPP # else /* ! EOPNOTSUPP */ # define MHD_SCKT_EOPNOTSUPP_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EOPNOTSUPP */ # ifdef EACCES # define MHD_SCKT_EACCESS_ EACCES # else /* ! EACCES */ # define MHD_SCKT_EACCESS_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EACCES */ # ifdef ENETDOWN # define MHD_SCKT_ENETDOWN_ ENETDOWN # else /* ! ENETDOWN */ # define MHD_SCKT_ENETDOWN_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! ENETDOWN */ # ifdef EALREADY # define MHD_SCKT_EALREADY_ EALREADY # else /* ! EALREADY */ # define MHD_SCKT_EALREADY_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EALREADY */ # ifdef EINPROGRESS # define MHD_SCKT_EINPROGRESS_ EINPROGRESS # else /* ! EINPROGRESS */ # define MHD_SCKT_EINPROGRESS_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EINPROGRESS */ # ifdef EISCONN # define MHD_SCKT_EISCONN_ EISCONN # else /* ! EISCONN */ # define MHD_SCKT_EISCONN_ MHD_SCKT_MISSING_ERR_CODE_ # endif /* ! EISCONN */ #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_SCKT_EAGAIN_ WSAEWOULDBLOCK # define MHD_SCKT_EWOULDBLOCK_ WSAEWOULDBLOCK # define MHD_SCKT_EINTR_ WSAEINTR # define MHD_SCKT_ECONNRESET_ WSAECONNRESET # define MHD_SCKT_ECONNABORTED_ WSAECONNABORTED # define MHD_SCKT_ENOTCONN_ WSAENOTCONN # define MHD_SCKT_EMFILE_ WSAEMFILE # define MHD_SCKT_ENFILE_ MHD_SCKT_MISSING_ERR_CODE_ # define MHD_SCKT_ENOMEM_ MHD_SCKT_MISSING_ERR_CODE_ # define MHD_SCKT_ENOBUFS_ WSAENOBUFS # define MHD_SCKT_EBADF_ WSAEBADF # define MHD_SCKT_ENOTSOCK_ WSAENOTSOCK # define MHD_SCKT_EINVAL_ WSAEINVAL # define MHD_SCKT_EPIPE_ WSAESHUTDOWN # define MHD_SCKT_EFAUL_ WSAEFAULT # define MHD_SCKT_ENOSYS_ MHD_SCKT_MISSING_ERR_CODE_ # define MHD_SCKT_ENOPROTOOPT_ WSAENOPROTOOPT # define MHD_SCKT_ENOTSUP_ MHD_SCKT_MISSING_ERR_CODE_ # define MHD_SCKT_EOPNOTSUPP_ WSAEOPNOTSUPP # define MHD_SCKT_EACCESS_ WSAEACCES # define MHD_SCKT_ENETDOWN_ WSAENETDOWN # define MHD_SCKT_EALREADY_ WSAEALREADY # define MHD_SCKT_EINPROGRESS_ WSAEINPROGRESS # define MHD_SCKT_EISCONN_ WSAEISCONN #endif /** * MHD_socket_error_ return system native error code for last socket error. * @return system error code for last socket error. */ #if defined(MHD_POSIX_SOCKETS) # define MHD_socket_get_error_() (errno) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_socket_get_error_() WSAGetLastError () #endif #ifdef MHD_WINSOCK_SOCKETS /* POSIX-W32 sockets compatibility functions */ /** * Return pointer to string description of specified WinSock error * @param err the WinSock error code. * @return pointer to string description of specified WinSock error. */ const char *MHD_W32_strerror_winsock_ (int err); #endif /* MHD_WINSOCK_SOCKETS */ /* MHD_socket_last_strerr_ is description string of specified socket error code */ #if defined(MHD_POSIX_SOCKETS) # define MHD_socket_strerr_(err) strerror ((err)) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_socket_strerr_(err) MHD_W32_strerror_winsock_ ((err)) #endif /* MHD_socket_last_strerr_ is description string of last errno (non-W32) / * description string of last socket error (W32) */ #define MHD_socket_last_strerr_() MHD_socket_strerr_ (MHD_socket_get_error_ ()) /** * MHD_socket_fset_error_() set socket system native error code. */ #if defined(MHD_POSIX_SOCKETS) # define MHD_socket_fset_error_(err) (errno = (err)) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_socket_fset_error_(err) (WSASetLastError ((err))) #endif /** * MHD_socket_try_set_error_() set socket system native error code if * specified code is defined on system. * @return non-zero if specified @a err code is defined on system * and error was set; * zero if specified @a err code is not defined on system * and error was not set. */ #define MHD_socket_try_set_error_(err) \ ( (MHD_SCKT_MISSING_ERR_CODE_ != (err)) ? \ (MHD_socket_fset_error_ ((err)), ! 0) : 0) /** * MHD_socket_set_error_() set socket system native error code to * specified code or replacement code if specified code is not * defined on system. */ #if defined(MHD_POSIX_SOCKETS) # if defined(ENOSYS) # define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \ (errno = ENOSYS) : (errno = (err)) ) # elif defined(EOPNOTSUPP) # define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \ (errno = EOPNOTSUPP) : (errno = \ (err)) ) # elif defined(EFAULT) # define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \ (errno = EFAULT) : (errno = (err)) ) # elif defined(EINVAL) # define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \ (errno = EINVAL) : (errno = (err)) ) # else /* !EOPNOTSUPP && !EFAULT && !EINVAL */ # warning \ No suitable replacement for missing socket error code is found. Edit this file and add replacement code which is defined on system. # define MHD_socket_set_error_(err) (errno = (err)) # endif /* !EOPNOTSUPP && !EFAULT && !EINVAL*/ #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_socket_set_error_(err) ( (MHD_SCKT_MISSING_ERR_CODE_ == (err)) ? \ (WSASetLastError ((WSAEOPNOTSUPP))) : \ (WSASetLastError ((err))) ) #endif /** * Check whether given socket error is equal to specified system * native MHD_SCKT_E*_ code. * If platform don't have specific error code, result is * always boolean false. * @return boolean true if @a code is real error code and * @a err equals to MHD_SCKT_E*_ @a code; * boolean false otherwise */ #define MHD_SCKT_ERR_IS_(err,code) \ ( (MHD_SCKT_MISSING_ERR_CODE_ != (code)) && ((code) == (err)) ) /** * Check whether last socket error is equal to specified system * native MHD_SCKT_E*_ code. * If platform don't have specific error code, result is * always boolean false. * @return boolean true if @a code is real error code and * last socket error equals to MHD_SCKT_E*_ @a code; * boolean false otherwise */ #define MHD_SCKT_LAST_ERR_IS_(code) \ MHD_SCKT_ERR_IS_ (MHD_socket_get_error_ (), (code)) /* Specific error code checks */ /** * Check whether given socket error is equal to system's * socket error codes for EINTR. * @return boolean true if @a err is equal to sockets' EINTR code; * boolean false otherwise. */ #define MHD_SCKT_ERR_IS_EINTR_(err) MHD_SCKT_ERR_IS_ ((err),MHD_SCKT_EINTR_) /** * Check whether given socket error is equal to system's * socket error codes for EAGAIN or EWOULDBLOCK. * @return boolean true if @a err is equal to sockets' EAGAIN or EWOULDBLOCK codes; * boolean false otherwise. */ #if MHD_SCKT_EAGAIN_ == MHD_SCKT_EWOULDBLOCK_ # define MHD_SCKT_ERR_IS_EAGAIN_(err) MHD_SCKT_ERR_IS_ ((err),MHD_SCKT_EAGAIN_) #else /* MHD_SCKT_EAGAIN_ != MHD_SCKT_EWOULDBLOCK_ */ # define MHD_SCKT_ERR_IS_EAGAIN_(err) \ ( MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_EAGAIN_) || \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_EWOULDBLOCK_) ) #endif /* MHD_SCKT_EAGAIN_ != MHD_SCKT_EWOULDBLOCK_ */ /** * Check whether given socket error is any kind of "low resource" error. * @return boolean true if @a err is any kind of "low resource" error, * boolean false otherwise. */ #define MHD_SCKT_ERR_IS_LOW_RESOURCES_(err) \ ( MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_EMFILE_) || \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ENFILE_) || \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ENOMEM_) || \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ENOBUFS_) ) /** * Check whether is given socket error is type of "incoming connection * was disconnected before 'accept()' is called". * @return boolean true is @a err match described socket error code, * boolean false otherwise. */ #if defined(MHD_POSIX_SOCKETS) # define MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_(err) \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNABORTED_) #elif defined(MHD_WINSOCK_SOCKETS) # define MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_(err) \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNRESET_) #endif /** * Check whether is given socket error is type of "connection was terminated * by remote side". * @return boolean true is @a err match described socket error code, * boolean false otherwise. */ #define MHD_SCKT_ERR_IS_REMOTE_DISCNN_(err) \ ( MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNRESET_) || \ MHD_SCKT_ERR_IS_ ((err), MHD_SCKT_ECONNABORTED_) ) /* Specific error code set */ /** * Set socket's error code to ENOMEM or equivalent if ENOMEM is not * available on platform. */ #if MHD_SCKT_MISSING_ERR_CODE_ != MHD_SCKT_ENOMEM_ # define MHD_socket_set_error_to_ENOMEM() \ MHD_socket_set_error_ (MHD_SCKT_ENOMEM_) #elif MHD_SCKT_MISSING_ERR_CODE_ != MHD_SCKT_ENOBUFS_ # define MHD_socket_set_error_to_ENOMEM() \ MHD_socket_set_error_ (MHD_SCKT_ENOBUFS_) #else # warning \ No suitable replacement for ENOMEM error codes is found. Edit this file and add replacement code which is defined on system. # define MHD_socket_set_error_to_ENOMEM() MHD_socket_set_error_ ( \ MHD_SCKT_ENOMEM_) #endif /* Socket functions */ #if defined(AF_LOCAL) # define MHD_SCKT_LOCAL AF_LOCAL #elif defined(AF_UNIX) # define MHD_SCKT_LOCAL AF_UNIX #endif /* AF_UNIX */ #if defined(MHD_POSIX_SOCKETS) && defined(MHD_SCKT_LOCAL) # define MHD_socket_pair_(fdarr) \ (! socketpair (MHD_SCKT_LOCAL, SOCK_STREAM, 0, (fdarr))) # if defined(HAVE_SOCK_NONBLOCK) # define MHD_socket_pair_nblk_(fdarr) \ (! socketpair (MHD_SCKT_LOCAL, SOCK_STREAM | SOCK_NONBLOCK, 0, (fdarr))) # endif /* HAVE_SOCK_NONBLOCK*/ #elif defined(MHD_WINSOCK_SOCKETS) /** * Create pair of mutually connected TCP/IP sockets on loopback address * @param sockets_pair array to receive resulted sockets * @param non_blk if set to non-zero value, sockets created in non-blocking mode * otherwise sockets will be in blocking mode * @return non-zero if succeeded, zero otherwise */ int MHD_W32_socket_pair_ (SOCKET sockets_pair[2], int non_blk); # define MHD_socket_pair_(fdarr) MHD_W32_socket_pair_ ((fdarr), 0) # define MHD_socket_pair_nblk_(fdarr) MHD_W32_socket_pair_ ((fdarr), 1) #endif /** * Add @a fd to the @a set. If @a fd is * greater than @a max_fd, set @a max_fd to @a fd. * * @param fd file descriptor to add to the @a set * @param set set to modify * @param max_fd maximum value to potentially update * @param fd_setsize value of FD_SETSIZE * @return non-zero if succeeded, zero otherwise */ int MHD_add_to_fd_set_ (MHD_socket fd, fd_set *set, MHD_socket *max_fd, int fd_setsize); /** * Change socket options to be non-blocking. * * @param sock socket to manipulate * @return non-zero if succeeded, zero otherwise */ int MHD_socket_nonblocking_ (MHD_socket sock); /** * Disable Nagle's algorithm on @a sock. This is what we do by default for * all TCP sockets in MHD, unless the platform does not support the MSG_MORE * or MSG_CORK or MSG_NOPUSH options. * * @param sock socket to manipulate * @param on value to use * @return 0 on success */ int MHD_socket_set_nodelay_ (MHD_socket sock, bool on); /** * Change socket options to be non-inheritable. * * @param sock socket to manipulate * @return non-zero if succeeded, zero otherwise * @warning Does not set socket error on W32. */ int MHD_socket_noninheritable_ (MHD_socket sock); #if defined(SOL_SOCKET) && defined(SO_NOSIGPIPE) static const int _MHD_socket_int_one = 1; /** * Change socket options to no signal on remote disconnect. * * @param sock socket to manipulate * @return non-zero if succeeded, zero otherwise */ #define MHD_socket_nosignal_(sock) \ (! setsockopt ((sock),SOL_SOCKET,SO_NOSIGPIPE,&_MHD_socket_int_one, \ sizeof(_MHD_socket_int_one))) #endif /* SOL_SOCKET && SO_NOSIGPIPE */ #if defined(MHD_socket_nosignal_) || defined(MSG_NOSIGNAL) /** * Indicate that SIGPIPE can be suppressed by MHD for normal send() by flags * or socket options. * If this macro is undefined, MHD cannot suppress SIGPIPE for socket functions * so sendfile() or writev() calls are avoided in application threads. */ #define MHD_SEND_SPIPE_SUPPRESS_POSSIBLE 1 #endif /* MHD_WINSOCK_SOCKETS || MHD_socket_nosignal_ || MSG_NOSIGNAL */ #if ! defined(MHD_WINSOCK_SOCKETS) /** * Indicate that suppression of SIGPIPE is required. */ #define MHD_SEND_SPIPE_SUPPRESS_NEEDED 1 #endif /** * Create a listen socket, with noninheritable flag if possible. * * @param pf protocol family to use * @return created socket or MHD_INVALID_SOCKET in case of errors */ MHD_socket MHD_socket_create_listen_ (int pf); #endif /* ! MHD_SOCKETS_H */ libmicrohttpd-1.0.10/src/microhttpd/connection.h0000644000175000017500000001350314760713577015415 /* This file is part of libmicrohttpd Copyright (C) 2007 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file connection.h * @brief Methods for managing connections * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef CONNECTION_H #define CONNECTION_H #include "internal.h" /** * Error code similar to EGAIN or EINTR */ #define MHD_ERR_AGAIN_ (-3073) /** * Connection was hard-closed by remote peer. */ #define MHD_ERR_CONNRESET_ (-3074) /** * Connection is not connected anymore due to * network error or any other reason. */ #define MHD_ERR_NOTCONN_ (-3075) /** * "Not enough memory" error code */ #define MHD_ERR_NOMEM_ (-3076) /** * "Bad FD" error code */ #define MHD_ERR_BADF_ (-3077) /** * Error code similar to EINVAL */ #define MHD_ERR_INVAL_ (-3078) /** * Argument values are not supported */ #define MHD_ERR_OPNOTSUPP_ (-3079) /** * Socket is shut down for writing or no longer connected */ #define MHD_ERR_PIPE_ (-3080) /** * General TLS encryption or decryption error */ #define MHD_ERR_TLS_ (-4097) /** * Set callbacks for this connection to those for HTTP. * * @param connection connection to initialize */ void MHD_set_http_callbacks_ (struct MHD_Connection *connection); /** * Set initial internal states for the connection to start reading and * processing incoming data. * @param c the connection to process */ void MHD_connection_set_initial_state_ (struct MHD_Connection *c); /** * This function handles a particular connection when it has been * determined that there is data to be read off a socket. All * implementations (multithreaded, external polling, internal polling) * call this function to handle reads. * * @param connection connection to handle * @param socket_error set to true if socket error was detected */ void MHD_connection_handle_read (struct MHD_Connection *connection, bool socket_error); /** * This function was created to handle writes to sockets when it has * been determined that the socket can be written to. All * implementations (multithreaded, external select, internal select) * call this function * * @param connection connection to handle */ void MHD_connection_handle_write (struct MHD_Connection *connection); /** * This function was created to handle per-connection processing that * has to happen even if the socket cannot be read or written to. * All implementations (multithreaded, external select, internal select) * call this function. * @remark To be called only from thread that process connection's * recv(), send() and response. * * @param connection connection to handle * @return #MHD_YES if we should continue to process the * connection (not dead yet), #MHD_NO if it died */ enum MHD_Result MHD_connection_handle_idle (struct MHD_Connection *connection); /** * Mark connection as "closed". * @remark To be called from any thread. * * @param connection connection to close */ void MHD_connection_mark_closed_ (struct MHD_Connection *connection); /** * Close the given connection and give the * specified termination code to the user. * @remark To be called only from thread that * process connection's recv(), send() and response. * * @param connection connection to close * @param termination_code termination reason to give */ void MHD_connection_close_ (struct MHD_Connection *connection, enum MHD_RequestTerminationCode termination_code); #ifdef HTTPS_SUPPORT /** * Stop TLS forwarding on upgraded connection and * reflect remote disconnect state to socketpair. * @param connection the upgraded connection */ void MHD_connection_finish_forward_ (struct MHD_Connection *connection); #else /* ! HTTPS_SUPPORT */ #define MHD_connection_finish_forward_(conn) (void) conn #endif /* ! HTTPS_SUPPORT */ #ifdef EPOLL_SUPPORT /** * Perform epoll processing, possibly moving the connection back into * the epoll set if needed. * * @param connection connection to process * @return #MHD_YES if we should continue to process the * connection (not dead yet), #MHD_NO if it died */ enum MHD_Result MHD_connection_epoll_update_ (struct MHD_Connection *connection); #endif /** * Update the 'last_activity' field of the connection to the current time * and move the connection to the head of the 'normal_timeout' list if * the timeout for the connection uses the default value. * * @param connection the connection that saw some activity */ void MHD_update_last_activity_ (struct MHD_Connection *connection); /** * Allocate memory from connection's memory pool. * If memory pool doesn't have enough free memory but read or write buffer * have some unused memory, the size of the buffer will be reduced as needed. * @param connection the connection to use * @param size the size of allocated memory area * @return pointer to allocated memory region in the pool or * NULL if no memory is available */ void * MHD_connection_alloc_memory_ (struct MHD_Connection *connection, size_t size); #endif libmicrohttpd-1.0.10/src/microhttpd/test_daemon.c0000664000175000017500000001413315232103064015530 /* This file is part of libmicrohttpd Copyright (C) 2007, 2017 Christian Grothoff Copyright (C) 2014--2023 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_daemon.c * @brief Testcase for libmicrohttpd starts and stops * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef WINDOWS #include #endif static unsigned int testStartError (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_ERROR_LOG, 0, NULL, NULL, NULL, NULL); if (NULL != d) { MHD_stop_daemon (d); fprintf (stderr, "Succeeded to start without MHD_AccessHandlerCallback?\n"); return 1; } return 0; } static enum MHD_Result apc_nothing (void *cls, const struct sockaddr *addr, socklen_t addrlen) { (void) cls; (void) addr; (void) addrlen; /* Unused. Silent compiler warning. */ return MHD_NO; } static enum MHD_Result apc_all (void *cls, const struct sockaddr *addr, socklen_t addrlen) { (void) cls; (void) addr; (void) addrlen; /* Unused. Silent compiler warning. */ return MHD_YES; } static enum MHD_Result ahc_nothing (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; (void) connection; (void) url; /* Unused. Silent compiler warning. */ (void) method; (void) version; (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; (void) req_cls; /* Unused. Silent compiler warning. */ return MHD_NO; } static unsigned int testStartStop (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, 0, &apc_nothing, NULL, &ahc_nothing, NULL, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start daemon on port %u\n", (unsigned int) 0); exit (3); } MHD_stop_daemon (d); return 0; } static unsigned int testExternalRun (int use_no_thread_safe) { struct MHD_Daemon *d; fd_set rs; MHD_socket maxfd; int i; d = MHD_start_daemon (MHD_USE_ERROR_LOG | (use_no_thread_safe ? MHD_USE_NO_THREAD_SAFETY : 0), 0, &apc_all, NULL, &ahc_nothing, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start daemon on port %u\n", (unsigned int) 0); exit (3); } for (i = 0; i < 15; ++i) { maxfd = 0; FD_ZERO (&rs); if (MHD_YES != MHD_get_fdset (d, &rs, &rs, &rs, &maxfd)) { MHD_stop_daemon (d); fprintf (stderr, "Failed in MHD_get_fdset().\n"); return 256; } if (MHD_NO == MHD_run (d)) { MHD_stop_daemon (d); fprintf (stderr, "Failed in MHD_run().\n"); return 8; } } MHD_stop_daemon (d); return 0; } static unsigned int testThread (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_INTERNAL_POLLING_THREAD, 0, &apc_all, NULL, &ahc_nothing, NULL, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start daemon on port %u.\n", (unsigned int) 0); exit (3); } if (MHD_run (d) != MHD_NO) { fprintf (stderr, "Failed in MHD_run().\n"); return 32; } MHD_stop_daemon (d); return 0; } static unsigned int testMultithread (void) { struct MHD_Daemon *d; d = MHD_start_daemon (MHD_USE_ERROR_LOG | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_THREAD_PER_CONNECTION, 0, &apc_all, NULL, &ahc_nothing, NULL, MHD_OPTION_END); if (NULL == d) { fprintf (stderr, "Failed to start daemon on port %u\n", (unsigned int) 0); exit (3); } if (MHD_run (d) != MHD_NO) { fprintf (stderr, "Failed in MHD_run().\n"); return 128; } MHD_stop_daemon (d); return 0; } int main (int argc, char *const *argv) { unsigned int errorCount = 0; int has_threads_support; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ has_threads_support = (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_THREADS)); errorCount += testStartError (); if (has_threads_support) errorCount += testStartStop (); if (has_threads_support) errorCount += testExternalRun (0); errorCount += testExternalRun (! 0); if (has_threads_support) { errorCount += testThread (); errorCount += testMultithread (); } if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); return 0 != errorCount; /* 0 == pass */ } libmicrohttpd-1.0.10/src/microhttpd/mhd_str_types.h0000644000175000017500000000321214760713577016136 /* This file is part of libmicrohttpd Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_str_types.h * @brief Header for string manipulating helpers types * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_STR_TYPES_H #define MHD_STR_TYPES_H 1 #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /** * Constant string with length */ struct _MHD_cstr_w_len { const char *const str; const size_t len; }; /** * String with length */ struct _MHD_str_w_len { const char *str; size_t len; }; /** * Modifiable string with length */ struct _MHD_mstr_w_len { char *str; size_t len; }; /** * Static string initialiser for struct _MHD_str_w_len */ #define _MHD_S_STR_W_LEN(str) { str, MHD_STATICSTR_LEN_(str) } #endif /* MHD_STR_TYPES_H */ libmicrohttpd-1.0.10/src/microhttpd/Makefile.in0000664000175000017500000071141615235436270015152 # Makefile.in generated by automake 1.17 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2024 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # This Makefile.am is in the public domain VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) am__rm_f = rm -f $(am__rm_f_notfound) am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @W32_SHARED_LIB_EXP_TRUE@am__append_1 = $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def @W32_SHARED_LIB_EXP_TRUE@am__append_2 = $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def $(lt_cv_objdir)/libmicrohttpd.exp @USE_EXPORT_FILE_TRUE@@W32_SHARED_LIB_EXP_TRUE@am__append_3 = $(lt_cv_objdir)/libmicrohttpd.exp @W32_STATIC_LIB_TRUE@am__append_4 = $(lt_cv_objdir)/libmicrohttpd-static.lib @W32_STATIC_LIB_TRUE@am__append_5 = $(lt_cv_objdir)/libmicrohttpd-static.lib @USE_POSIX_THREADS_TRUE@am__append_6 = \ @USE_POSIX_THREADS_TRUE@ mhd_threads.c mhd_threads.h \ @USE_POSIX_THREADS_TRUE@ mhd_locks.h @USE_W32_THREADS_TRUE@am__append_7 = \ @USE_W32_THREADS_TRUE@ mhd_threads.c mhd_threads.h \ @USE_W32_THREADS_TRUE@ mhd_locks.h @NEED_SYS_FD_SET_SIZE_VALUE_TRUE@am__append_8 = \ @NEED_SYS_FD_SET_SIZE_VALUE_TRUE@ sysfdsetsize.c @USE_COVERAGE_TRUE@am__append_9 = --coverage @MHD_USE_SYS_TSEARCH_FALSE@am__append_10 = \ @MHD_USE_SYS_TSEARCH_FALSE@ tsearch.c tsearch.h @HAVE_POSTPROCESSOR_TRUE@am__append_11 = \ @HAVE_POSTPROCESSOR_TRUE@ postprocessor.c postprocessor.h @HAVE_ANYAUTH_TRUE@am__append_12 = \ @HAVE_ANYAUTH_TRUE@ gen_auth.c gen_auth.h @ENABLE_DAUTH_TRUE@am__append_13 = \ @ENABLE_DAUTH_TRUE@ digestauth.c digestauth.h \ @ENABLE_DAUTH_TRUE@ mhd_bithelpers.h mhd_byteorder.h mhd_align.h @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@am__append_14 = \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_TRUE@ mhd_md5_wrap.h @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_FALSE@@ENABLE_MD5_TRUE@am__append_15 = \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_FALSE@@ENABLE_MD5_TRUE@ md5.c md5.h @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_TRUE@@ENABLE_MD5_TRUE@am__append_16 = \ @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_TRUE@@ENABLE_MD5_TRUE@ md5_ext.c md5_ext.h @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@am__append_17 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_TRUE@ mhd_sha256_wrap.h @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_FALSE@@ENABLE_SHA256_TRUE@am__append_18 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_FALSE@@ENABLE_SHA256_TRUE@ sha256.c sha256.h @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_TRUE@@ENABLE_SHA256_TRUE@am__append_19 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_TRUE@@ENABLE_SHA256_TRUE@ sha256_ext.c sha256_ext.h @ENABLE_DAUTH_TRUE@@ENABLE_SHA512_256_TRUE@am__append_20 = \ @ENABLE_DAUTH_TRUE@@ENABLE_SHA512_256_TRUE@ sha512_256.c sha512_256.h @ENABLE_BAUTH_TRUE@am__append_21 = \ @ENABLE_BAUTH_TRUE@ basicauth.c basicauth.h @ENABLE_HTTPS_TRUE@am__append_22 = \ @ENABLE_HTTPS_TRUE@ connection_https.c connection_https.h check_PROGRAMS = test_str_compare$(EXEEXT) test_str_to_value$(EXEEXT) \ test_str_from_value$(EXEEXT) test_str_token$(EXEEXT) \ test_str_token_remove$(EXEEXT) test_str_tokens_remove$(EXEEXT) \ test_str_pct$(EXEEXT) test_str_bin_hex$(EXEEXT) \ test_http_reasons$(EXEEXT) test_sha1$(EXEEXT) \ test_start_stop$(EXEEXT) test_daemon$(EXEEXT) \ test_response_entries$(EXEEXT) test_postprocessor_md$(EXEEXT) \ test_client_put_shutdown$(EXEEXT) \ test_client_put_close$(EXEEXT) \ test_client_put_hard_close$(EXEEXT) \ test_client_put_steps_shutdown$(EXEEXT) \ test_client_put_steps_close$(EXEEXT) \ test_client_put_steps_hard_close$(EXEEXT) \ test_client_put_chunked_shutdown$(EXEEXT) \ test_client_put_chunked_close$(EXEEXT) \ test_client_put_chunked_hard_close$(EXEEXT) \ test_client_put_chunked_steps_shutdown$(EXEEXT) \ test_client_put_chunked_steps_close$(EXEEXT) \ test_client_put_chunked_steps_hard_close$(EXEEXT) \ test_options$(EXEEXT) test_mhd_version$(EXEEXT) \ test_set_panic$(EXEEXT) test_rq_shift_back$(EXEEXT) \ test_chunked_ext$(EXEEXT) test_raw_requests$(EXEEXT) \ test_option_matrix$(EXEEXT) $(am__EXEEXT_1) $(am__EXEEXT_2) \ $(am__EXEEXT_3) $(am__EXEEXT_4) $(am__EXEEXT_5) \ $(am__EXEEXT_6) $(am__EXEEXT_7) $(am__EXEEXT_8) \ $(am__EXEEXT_9) $(am__EXEEXT_10) $(am__EXEEXT_11) \ $(am__EXEEXT_12) @ENABLE_MD5_TRUE@am__append_23 = \ @ENABLE_MD5_TRUE@ test_md5 @ENABLE_SHA256_TRUE@am__append_24 = \ @ENABLE_SHA256_TRUE@ test_sha256 @ENABLE_SHA512_256_TRUE@am__append_25 = \ @ENABLE_SHA512_256_TRUE@ test_sha512_256 @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@am__append_26 = test_upgrade test_upgrade_large test_upgrade_vlarge @ENABLE_HTTPS_TRUE@@ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@@USE_UPGRADE_TLS_TESTS_TRUE@am__append_27 = test_upgrade_tls test_upgrade_large_tls test_upgrade_vlarge_tls @HAVE_POSTPROCESSOR_TRUE@am__append_28 = \ @HAVE_POSTPROCESSOR_TRUE@ test_postprocessor \ @HAVE_POSTPROCESSOR_TRUE@ test_postprocessor_large \ @HAVE_POSTPROCESSOR_TRUE@ test_postprocessor_amp # Do not test trigger of select by shutdown of listen socket # on Cygwin as this ability is deliberately ignored on Cygwin # to improve compatibility with core OS. @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_TRUE@@HAVE_POSIX_THREADS_TRUE@am__append_29 = \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_TRUE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_select \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_TRUE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_poll @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_FALSE@@HAVE_POSIX_THREADS_TRUE@am__append_30 = \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_FALSE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_select_ignore \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_FALSE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_poll_ignore @HAVE_ANYAUTH_TRUE@@HAVE_MESSAGES_TRUE@am__append_31 = \ @HAVE_ANYAUTH_TRUE@@HAVE_MESSAGES_TRUE@ test_auth_parse @ENABLE_DAUTH_TRUE@am__append_32 = \ @ENABLE_DAUTH_TRUE@ test_str_quote \ @ENABLE_DAUTH_TRUE@ test_dauth_userdigest \ @ENABLE_DAUTH_TRUE@ test_dauth_userhash \ @ENABLE_DAUTH_TRUE@ test_dauth_malformed @ENABLE_BAUTH_TRUE@am__append_33 = \ @ENABLE_BAUTH_TRUE@ test_str_base64 @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@am__append_34 = \ @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@ test_client_put_hard_close_stress_os \ @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@ test_client_put_steps_hard_close_stress_os \ @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@ test_client_put_chunked_steps_hard_close_stress_os @USE_POSIX_THREADS_TRUE@am__append_35 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_CFLAGS) @USE_POSIX_THREADS_TRUE@am__append_36 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_LIBS) @USE_POSIX_THREADS_TRUE@am__append_37 = \ @USE_POSIX_THREADS_TRUE@ $(AM_CFLAGS) $(PTHREAD_CFLAGS) @USE_POSIX_THREADS_TRUE@am__append_38 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_LIBS) @USE_POSIX_THREADS_TRUE@am__append_39 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_CFLAGS) @USE_POSIX_THREADS_TRUE@am__append_40 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_LIBS) @USE_POSIX_THREADS_TRUE@am__append_41 = \ @USE_POSIX_THREADS_TRUE@ $(AM_CFLAGS) $(PTHREAD_CFLAGS) @USE_POSIX_THREADS_TRUE@am__append_42 = \ @USE_POSIX_THREADS_TRUE@ $(PTHREAD_LIBS) @ENABLE_MD5_EXT_FALSE@am__append_43 = \ @ENABLE_MD5_EXT_FALSE@ md5.c md5.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h @ENABLE_MD5_EXT_TRUE@am__append_44 = \ @ENABLE_MD5_EXT_TRUE@ md5_ext.c md5_ext.h @ENABLE_SHA256_EXT_FALSE@am__append_45 = \ @ENABLE_SHA256_EXT_FALSE@ sha256.c sha256.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h @ENABLE_SHA256_EXT_TRUE@am__append_46 = \ @ENABLE_SHA256_EXT_TRUE@ sha256_ext.c sha256_ext.h subdir = src/microhttpd ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/ac_define_dir.m4 \ $(top_srcdir)/m4/ax_append_compile_flags.m4 \ $(top_srcdir)/m4/ax_append_flag.m4 \ $(top_srcdir)/m4/ax_append_link_flags.m4 \ $(top_srcdir)/m4/ax_check_compile_flag.m4 \ $(top_srcdir)/m4/ax_check_link_flag.m4 \ $(top_srcdir)/m4/ax_count_cpus.m4 \ $(top_srcdir)/m4/ax_pthread.m4 \ $(top_srcdir)/m4/ax_require_defined.m4 \ $(top_srcdir)/m4/libcurl.m4 $(top_srcdir)/m4/libgcrypt.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/mhd_append_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_bool.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_cflags.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflag.m4 \ $(top_srcdir)/m4/mhd_check_add_cc_ldflags.m4 \ $(top_srcdir)/m4/mhd_check_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_check_func.m4 \ $(top_srcdir)/m4/mhd_check_func_gettimeofday.m4 \ $(top_srcdir)/m4/mhd_check_func_run.m4 \ $(top_srcdir)/m4/mhd_check_link_run.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag.m4 \ $(top_srcdir)/m4/mhd_find_add_cc_cflag_ifelse.m4 \ $(top_srcdir)/m4/mhd_find_lib.m4 \ $(top_srcdir)/m4/mhd_norm_expd.m4 \ $(top_srcdir)/m4/mhd_prepend_flag_to_var.m4 \ $(top_srcdir)/m4/mhd_shutdown_socket_trigger.m4 \ $(top_srcdir)/m4/mhd_sys_extentions.m4 $(top_srcdir)/m4/pkg.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/MHD_config.h CONFIG_CLEAN_FILES = microhttpd_dll_res.rc CONFIG_CLEAN_VPATH_FILES = @ENABLE_MD5_TRUE@am__EXEEXT_1 = test_md5$(EXEEXT) @ENABLE_SHA256_TRUE@am__EXEEXT_2 = test_sha256$(EXEEXT) @ENABLE_SHA512_256_TRUE@am__EXEEXT_3 = test_sha512_256$(EXEEXT) @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@am__EXEEXT_4 = test_upgrade$(EXEEXT) \ @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@ test_upgrade_large$(EXEEXT) \ @ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@ test_upgrade_vlarge$(EXEEXT) @ENABLE_HTTPS_TRUE@@ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@@USE_UPGRADE_TLS_TESTS_TRUE@am__EXEEXT_5 = test_upgrade_tls$(EXEEXT) \ @ENABLE_HTTPS_TRUE@@ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@@USE_UPGRADE_TLS_TESTS_TRUE@ test_upgrade_large_tls$(EXEEXT) \ @ENABLE_HTTPS_TRUE@@ENABLE_UPGRADE_TRUE@@HAVE_POSIX_THREADS_TRUE@@USE_THREADS_TRUE@@USE_UPGRADE_TLS_TESTS_TRUE@ test_upgrade_vlarge_tls$(EXEEXT) @HAVE_POSTPROCESSOR_TRUE@am__EXEEXT_6 = test_postprocessor$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@ test_postprocessor_large$(EXEEXT) \ @HAVE_POSTPROCESSOR_TRUE@ test_postprocessor_amp$(EXEEXT) @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_TRUE@@HAVE_POSIX_THREADS_TRUE@am__EXEEXT_7 = test_shutdown_select$(EXEEXT) \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_TRUE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_poll$(EXEEXT) @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_FALSE@@HAVE_POSIX_THREADS_TRUE@am__EXEEXT_8 = test_shutdown_select_ignore$(EXEEXT) \ @CYGWIN_TARGET_FALSE@@HAVE_LISTEN_SHUTDOWN_FALSE@@HAVE_POSIX_THREADS_TRUE@ test_shutdown_poll_ignore$(EXEEXT) @HAVE_ANYAUTH_TRUE@@HAVE_MESSAGES_TRUE@am__EXEEXT_9 = test_auth_parse$(EXEEXT) @ENABLE_DAUTH_TRUE@am__EXEEXT_10 = test_str_quote$(EXEEXT) \ @ENABLE_DAUTH_TRUE@ test_dauth_userdigest$(EXEEXT) \ @ENABLE_DAUTH_TRUE@ test_dauth_userhash$(EXEEXT) \ @ENABLE_DAUTH_TRUE@ test_dauth_malformed$(EXEEXT) @ENABLE_BAUTH_TRUE@am__EXEEXT_11 = test_str_base64$(EXEEXT) @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@am__EXEEXT_12 = test_client_put_hard_close_stress_os$(EXEEXT) \ @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@ test_client_put_steps_hard_close_stress_os$(EXEEXT) \ @HEAVY_TESTS_TRUE@@TESTS_STRESS_OS_TRUE@ test_client_put_chunked_steps_hard_close_stress_os$(EXEEXT) am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__installdirs = "$(DESTDIR)$(libdir)" LTLIBRARIES = $(lib_LTLIBRARIES) am__DEPENDENCIES_1 = @HAVE_W32_TRUE@am__DEPENDENCIES_2 = \ @HAVE_W32_TRUE@ libmicrohttpd_la-microhttpd_dll_res.lo libmicrohttpd_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_2) am__libmicrohttpd_la_SOURCES_DIST = connection.c connection.h \ reason_phrase.c daemon.c internal.c internal.h memorypool.c \ memorypool.h mhd_mono_clock.c mhd_mono_clock.h mhd_limits.h \ sysfdsetsize.h mhd_str.c mhd_str.h mhd_str_types.h mhd_send.h \ mhd_send.c mhd_assert.h mhd_check.h mhd_sockets.c \ mhd_sockets.h mhd_itc.c mhd_itc.h mhd_itc_types.h mhd_compat.c \ mhd_compat.h mhd_panic.c mhd_panic.h response.c response.h \ mhd_threads.c mhd_threads.h mhd_locks.h sysfdsetsize.c \ tsearch.c tsearch.h postprocessor.c postprocessor.h gen_auth.c \ gen_auth.h digestauth.c digestauth.h mhd_bithelpers.h \ mhd_byteorder.h mhd_align.h mhd_md5_wrap.h md5.c md5.h \ md5_ext.c md5_ext.h mhd_sha256_wrap.h sha256.c sha256.h \ sha256_ext.c sha256_ext.h sha512_256.c sha512_256.h \ basicauth.c basicauth.h connection_https.c connection_https.h @USE_POSIX_THREADS_TRUE@am__objects_1 = \ @USE_POSIX_THREADS_TRUE@ libmicrohttpd_la-mhd_threads.lo @USE_W32_THREADS_TRUE@am__objects_2 = libmicrohttpd_la-mhd_threads.lo @NEED_SYS_FD_SET_SIZE_VALUE_TRUE@am__objects_3 = libmicrohttpd_la-sysfdsetsize.lo @MHD_USE_SYS_TSEARCH_FALSE@am__objects_4 = \ @MHD_USE_SYS_TSEARCH_FALSE@ libmicrohttpd_la-tsearch.lo @HAVE_POSTPROCESSOR_TRUE@am__objects_5 = \ @HAVE_POSTPROCESSOR_TRUE@ libmicrohttpd_la-postprocessor.lo @HAVE_ANYAUTH_TRUE@am__objects_6 = libmicrohttpd_la-gen_auth.lo @ENABLE_DAUTH_TRUE@am__objects_7 = libmicrohttpd_la-digestauth.lo am__objects_8 = @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_FALSE@@ENABLE_MD5_TRUE@am__objects_9 = libmicrohttpd_la-md5.lo @ENABLE_DAUTH_TRUE@@ENABLE_MD5_EXT_TRUE@@ENABLE_MD5_TRUE@am__objects_10 = libmicrohttpd_la-md5_ext.lo @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_FALSE@@ENABLE_SHA256_TRUE@am__objects_11 = libmicrohttpd_la-sha256.lo @ENABLE_DAUTH_TRUE@@ENABLE_SHA256_EXT_TRUE@@ENABLE_SHA256_TRUE@am__objects_12 = libmicrohttpd_la-sha256_ext.lo @ENABLE_DAUTH_TRUE@@ENABLE_SHA512_256_TRUE@am__objects_13 = libmicrohttpd_la-sha512_256.lo @ENABLE_BAUTH_TRUE@am__objects_14 = libmicrohttpd_la-basicauth.lo @ENABLE_HTTPS_TRUE@am__objects_15 = \ @ENABLE_HTTPS_TRUE@ libmicrohttpd_la-connection_https.lo am_libmicrohttpd_la_OBJECTS = libmicrohttpd_la-connection.lo \ libmicrohttpd_la-reason_phrase.lo libmicrohttpd_la-daemon.lo \ libmicrohttpd_la-internal.lo libmicrohttpd_la-memorypool.lo \ libmicrohttpd_la-mhd_mono_clock.lo libmicrohttpd_la-mhd_str.lo \ libmicrohttpd_la-mhd_send.lo libmicrohttpd_la-mhd_sockets.lo \ libmicrohttpd_la-mhd_itc.lo libmicrohttpd_la-mhd_compat.lo \ libmicrohttpd_la-mhd_panic.lo libmicrohttpd_la-response.lo \ $(am__objects_1) $(am__objects_2) $(am__objects_3) \ $(am__objects_4) $(am__objects_5) $(am__objects_6) \ $(am__objects_7) $(am__objects_8) $(am__objects_9) \ $(am__objects_10) $(am__objects_8) $(am__objects_11) \ $(am__objects_12) $(am__objects_13) $(am__objects_14) \ $(am__objects_15) libmicrohttpd_la_OBJECTS = $(am_libmicrohttpd_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libmicrohttpd_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(libmicrohttpd_la_CFLAGS) $(CFLAGS) \ $(libmicrohttpd_la_LDFLAGS) $(LDFLAGS) -o $@ am_test_auth_parse_OBJECTS = \ test_auth_parse-test_auth_parse.$(OBJEXT) \ test_auth_parse-gen_auth.$(OBJEXT) \ test_auth_parse-mhd_str.$(OBJEXT) test_auth_parse_OBJECTS = $(am_test_auth_parse_OBJECTS) test_auth_parse_LDADD = $(LDADD) am__objects_16 = mhd_opt_matrix.$(OBJEXT) am_test_chunked_ext_OBJECTS = test_chunked_ext.$(OBJEXT) \ $(am__objects_16) test_chunked_ext_OBJECTS = $(am_test_chunked_ext_OBJECTS) test_chunked_ext_DEPENDENCIES = $(builddir)/libmicrohttpd.la am_test_client_put_chunked_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_close_OBJECTS = \ $(am_test_client_put_chunked_close_OBJECTS) test_client_put_chunked_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_chunked_hard_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_hard_close_OBJECTS = \ $(am_test_client_put_chunked_hard_close_OBJECTS) test_client_put_chunked_hard_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_chunked_shutdown_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_shutdown_OBJECTS = \ $(am_test_client_put_chunked_shutdown_OBJECTS) test_client_put_chunked_shutdown_DEPENDENCIES = libmicrohttpd.la am_test_client_put_chunked_steps_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_steps_close_OBJECTS = \ $(am_test_client_put_chunked_steps_close_OBJECTS) test_client_put_chunked_steps_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_chunked_steps_hard_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_steps_hard_close_OBJECTS = \ $(am_test_client_put_chunked_steps_hard_close_OBJECTS) test_client_put_chunked_steps_hard_close_DEPENDENCIES = \ libmicrohttpd.la am__objects_17 = test_client_put_stop.$(OBJEXT) am_test_client_put_chunked_steps_hard_close_stress_os_OBJECTS = \ $(am__objects_17) test_client_put_chunked_steps_hard_close_stress_os_OBJECTS = $(am_test_client_put_chunked_steps_hard_close_stress_os_OBJECTS) test_client_put_chunked_steps_hard_close_stress_os_DEPENDENCIES = \ $(test_client_put_chunked_steps_hard_close_LDADD) am_test_client_put_chunked_steps_shutdown_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_chunked_steps_shutdown_OBJECTS = \ $(am_test_client_put_chunked_steps_shutdown_OBJECTS) test_client_put_chunked_steps_shutdown_DEPENDENCIES = \ libmicrohttpd.la am_test_client_put_close_OBJECTS = test_client_put_stop.$(OBJEXT) test_client_put_close_OBJECTS = $(am_test_client_put_close_OBJECTS) test_client_put_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_hard_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_hard_close_OBJECTS = \ $(am_test_client_put_hard_close_OBJECTS) test_client_put_hard_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_hard_close_stress_os_OBJECTS = $(am__objects_17) test_client_put_hard_close_stress_os_OBJECTS = \ $(am_test_client_put_hard_close_stress_os_OBJECTS) test_client_put_hard_close_stress_os_DEPENDENCIES = \ $(test_client_put_hard_close_LDADD) am_test_client_put_shutdown_OBJECTS = test_client_put_stop.$(OBJEXT) test_client_put_shutdown_OBJECTS = \ $(am_test_client_put_shutdown_OBJECTS) test_client_put_shutdown_DEPENDENCIES = libmicrohttpd.la am_test_client_put_steps_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_steps_close_OBJECTS = \ $(am_test_client_put_steps_close_OBJECTS) test_client_put_steps_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_steps_hard_close_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_steps_hard_close_OBJECTS = \ $(am_test_client_put_steps_hard_close_OBJECTS) test_client_put_steps_hard_close_DEPENDENCIES = libmicrohttpd.la am_test_client_put_steps_hard_close_stress_os_OBJECTS = \ $(am__objects_17) test_client_put_steps_hard_close_stress_os_OBJECTS = \ $(am_test_client_put_steps_hard_close_stress_os_OBJECTS) test_client_put_steps_hard_close_stress_os_DEPENDENCIES = \ $(test_client_put_steps_hard_close_LDADD) am_test_client_put_steps_shutdown_OBJECTS = \ test_client_put_stop.$(OBJEXT) test_client_put_steps_shutdown_OBJECTS = \ $(am_test_client_put_steps_shutdown_OBJECTS) test_client_put_steps_shutdown_DEPENDENCIES = libmicrohttpd.la am_test_daemon_OBJECTS = test_daemon.$(OBJEXT) test_daemon_OBJECTS = $(am_test_daemon_OBJECTS) test_daemon_DEPENDENCIES = $(builddir)/libmicrohttpd.la am_test_dauth_malformed_OBJECTS = test_dauth_malformed.$(OBJEXT) \ $(am__objects_16) test_dauth_malformed_OBJECTS = $(am_test_dauth_malformed_OBJECTS) test_dauth_malformed_DEPENDENCIES = $(builddir)/libmicrohttpd.la am_test_dauth_userdigest_OBJECTS = test_dauth_userdigest.$(OBJEXT) test_dauth_userdigest_OBJECTS = $(am_test_dauth_userdigest_OBJECTS) test_dauth_userdigest_DEPENDENCIES = libmicrohttpd.la am_test_dauth_userhash_OBJECTS = test_dauth_userhash.$(OBJEXT) test_dauth_userhash_OBJECTS = $(am_test_dauth_userhash_OBJECTS) test_dauth_userhash_DEPENDENCIES = libmicrohttpd.la am_test_http_reasons_OBJECTS = test_http_reasons.$(OBJEXT) \ reason_phrase.$(OBJEXT) mhd_str.$(OBJEXT) test_http_reasons_OBJECTS = $(am_test_http_reasons_OBJECTS) test_http_reasons_LDADD = $(LDADD) am__test_md5_SOURCES_DIST = test_md5.c test_helpers.h mhd_md5_wrap.h \ ../include/mhd_options.h md5.c md5.h mhd_bithelpers.h \ mhd_byteorder.h mhd_align.h md5_ext.c md5_ext.h @ENABLE_MD5_EXT_FALSE@am__objects_18 = test_md5-md5.$(OBJEXT) @ENABLE_MD5_EXT_TRUE@am__objects_19 = test_md5-md5_ext.$(OBJEXT) am_test_md5_OBJECTS = test_md5-test_md5.$(OBJEXT) $(am__objects_18) \ $(am__objects_19) test_md5_OBJECTS = $(am_test_md5_OBJECTS) @ENABLE_MD5_EXT_TRUE@test_md5_DEPENDENCIES = $(am__DEPENDENCIES_1) test_md5_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_md5_CFLAGS) \ $(CFLAGS) $(test_md5_LDFLAGS) $(LDFLAGS) -o $@ am_test_mhd_version_OBJECTS = test_mhd_version.$(OBJEXT) test_mhd_version_OBJECTS = $(am_test_mhd_version_OBJECTS) test_mhd_version_DEPENDENCIES = libmicrohttpd.la am_test_option_matrix_OBJECTS = test_option_matrix.$(OBJEXT) \ $(am__objects_16) test_option_matrix_OBJECTS = $(am_test_option_matrix_OBJECTS) test_option_matrix_DEPENDENCIES = $(builddir)/libmicrohttpd.la am_test_options_OBJECTS = test_options.$(OBJEXT) test_options_OBJECTS = $(am_test_options_OBJECTS) test_options_DEPENDENCIES = $(builddir)/libmicrohttpd.la am_test_postprocessor_OBJECTS = \ test_postprocessor-test_postprocessor.$(OBJEXT) test_postprocessor_OBJECTS = $(am_test_postprocessor_OBJECTS) test_postprocessor_DEPENDENCIES = $(builddir)/libmicrohttpd.la test_postprocessor_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_postprocessor_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_postprocessor_amp_OBJECTS = \ test_postprocessor_amp-test_postprocessor_amp.$(OBJEXT) test_postprocessor_amp_OBJECTS = $(am_test_postprocessor_amp_OBJECTS) test_postprocessor_amp_DEPENDENCIES = $(builddir)/libmicrohttpd.la test_postprocessor_amp_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_postprocessor_amp_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_postprocessor_large_OBJECTS = \ test_postprocessor_large-test_postprocessor_large.$(OBJEXT) test_postprocessor_large_OBJECTS = \ $(am_test_postprocessor_large_OBJECTS) test_postprocessor_large_DEPENDENCIES = $(builddir)/libmicrohttpd.la test_postprocessor_large_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_postprocessor_large_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_postprocessor_md_OBJECTS = \ test_postprocessor_md-test_postprocessor_md.$(OBJEXT) \ test_postprocessor_md-postprocessor.$(OBJEXT) \ test_postprocessor_md-internal.$(OBJEXT) \ test_postprocessor_md-mhd_str.$(OBJEXT) \ test_postprocessor_md-mhd_panic.$(OBJEXT) test_postprocessor_md_OBJECTS = $(am_test_postprocessor_md_OBJECTS) test_postprocessor_md_LDADD = $(LDADD) am_test_raw_requests_OBJECTS = test_raw_requests.$(OBJEXT) \ $(am__objects_16) test_raw_requests_OBJECTS = $(am_test_raw_requests_OBJECTS) test_raw_requests_DEPENDENCIES = $(builddir)/libmicrohttpd.la am_test_response_entries_OBJECTS = test_response_entries.$(OBJEXT) test_response_entries_OBJECTS = $(am_test_response_entries_OBJECTS) test_response_entries_DEPENDENCIES = libmicrohttpd.la am_test_rq_shift_back_OBJECTS = test_rq_shift_back.$(OBJEXT) \ $(am__objects_16) test_rq_shift_back_OBJECTS = $(am_test_rq_shift_back_OBJECTS) test_rq_shift_back_DEPENDENCIES = $(builddir)/libmicrohttpd.la am_test_set_panic_OBJECTS = test_set_panic.$(OBJEXT) test_set_panic_OBJECTS = $(am_test_set_panic_OBJECTS) test_set_panic_DEPENDENCIES = libmicrohttpd.la am_test_sha1_OBJECTS = test_sha1.$(OBJEXT) sha1.$(OBJEXT) test_sha1_OBJECTS = $(am_test_sha1_OBJECTS) test_sha1_LDADD = $(LDADD) am__test_sha256_SOURCES_DIST = test_sha256.c test_helpers.h \ mhd_sha256_wrap.h ../include/mhd_options.h sha256.c sha256.h \ mhd_bithelpers.h mhd_byteorder.h mhd_align.h sha256_ext.c \ sha256_ext.h @ENABLE_SHA256_EXT_FALSE@am__objects_20 = \ @ENABLE_SHA256_EXT_FALSE@ test_sha256-sha256.$(OBJEXT) @ENABLE_SHA256_EXT_TRUE@am__objects_21 = \ @ENABLE_SHA256_EXT_TRUE@ test_sha256-sha256_ext.$(OBJEXT) am_test_sha256_OBJECTS = test_sha256-test_sha256.$(OBJEXT) \ $(am__objects_20) $(am__objects_21) test_sha256_OBJECTS = $(am_test_sha256_OBJECTS) @ENABLE_SHA256_EXT_TRUE@test_sha256_DEPENDENCIES = \ @ENABLE_SHA256_EXT_TRUE@ $(am__DEPENDENCIES_1) test_sha256_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_sha256_CFLAGS) \ $(CFLAGS) $(test_sha256_LDFLAGS) $(LDFLAGS) -o $@ am_test_sha512_256_OBJECTS = test_sha512_256.$(OBJEXT) \ sha512_256.$(OBJEXT) test_sha512_256_OBJECTS = $(am_test_sha512_256_OBJECTS) test_sha512_256_LDADD = $(LDADD) am_test_shutdown_poll_OBJECTS = \ test_shutdown_poll-test_shutdown_select.$(OBJEXT) test_shutdown_poll_OBJECTS = $(am_test_shutdown_poll_OBJECTS) @USE_POSIX_THREADS_TRUE@am__DEPENDENCIES_3 = $(am__DEPENDENCIES_1) test_shutdown_poll_DEPENDENCIES = $(am__DEPENDENCIES_3) test_shutdown_poll_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_shutdown_poll_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_shutdown_poll_ignore_OBJECTS = \ test_shutdown_poll_ignore-test_shutdown_select.$(OBJEXT) test_shutdown_poll_ignore_OBJECTS = \ $(am_test_shutdown_poll_ignore_OBJECTS) test_shutdown_poll_ignore_DEPENDENCIES = $(am__DEPENDENCIES_3) test_shutdown_poll_ignore_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_shutdown_poll_ignore_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_shutdown_select_OBJECTS = \ test_shutdown_select-test_shutdown_select.$(OBJEXT) test_shutdown_select_OBJECTS = $(am_test_shutdown_select_OBJECTS) test_shutdown_select_DEPENDENCIES = $(am__DEPENDENCIES_3) test_shutdown_select_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_shutdown_select_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_shutdown_select_ignore_OBJECTS = \ test_shutdown_select_ignore-test_shutdown_select.$(OBJEXT) test_shutdown_select_ignore_OBJECTS = \ $(am_test_shutdown_select_ignore_OBJECTS) test_shutdown_select_ignore_DEPENDENCIES = $(am__DEPENDENCIES_3) test_shutdown_select_ignore_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_shutdown_select_ignore_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ am_test_start_stop_OBJECTS = test_start_stop.$(OBJEXT) test_start_stop_OBJECTS = $(am_test_start_stop_OBJECTS) test_start_stop_DEPENDENCIES = libmicrohttpd.la am_test_str_base64_OBJECTS = test_str_base64.$(OBJEXT) \ mhd_str.$(OBJEXT) test_str_base64_OBJECTS = $(am_test_str_base64_OBJECTS) test_str_base64_LDADD = $(LDADD) am_test_str_bin_hex_OBJECTS = test_str_bin_hex.$(OBJEXT) \ mhd_str.$(OBJEXT) test_str_bin_hex_OBJECTS = $(am_test_str_bin_hex_OBJECTS) test_str_bin_hex_LDADD = $(LDADD) am_test_str_compare_OBJECTS = test_str.$(OBJEXT) mhd_str.$(OBJEXT) test_str_compare_OBJECTS = $(am_test_str_compare_OBJECTS) test_str_compare_LDADD = $(LDADD) am_test_str_from_value_OBJECTS = test_str.$(OBJEXT) mhd_str.$(OBJEXT) test_str_from_value_OBJECTS = $(am_test_str_from_value_OBJECTS) test_str_from_value_LDADD = $(LDADD) am_test_str_pct_OBJECTS = test_str_pct.$(OBJEXT) mhd_str.$(OBJEXT) test_str_pct_OBJECTS = $(am_test_str_pct_OBJECTS) test_str_pct_LDADD = $(LDADD) am_test_str_quote_OBJECTS = test_str_quote.$(OBJEXT) mhd_str.$(OBJEXT) test_str_quote_OBJECTS = $(am_test_str_quote_OBJECTS) test_str_quote_LDADD = $(LDADD) am_test_str_to_value_OBJECTS = test_str.$(OBJEXT) mhd_str.$(OBJEXT) test_str_to_value_OBJECTS = $(am_test_str_to_value_OBJECTS) test_str_to_value_LDADD = $(LDADD) am_test_str_token_OBJECTS = test_str_token.$(OBJEXT) mhd_str.$(OBJEXT) test_str_token_OBJECTS = $(am_test_str_token_OBJECTS) test_str_token_LDADD = $(LDADD) am_test_str_token_remove_OBJECTS = test_str_token_remove.$(OBJEXT) \ mhd_str.$(OBJEXT) test_str_token_remove_OBJECTS = $(am_test_str_token_remove_OBJECTS) test_str_token_remove_LDADD = $(LDADD) am_test_str_tokens_remove_OBJECTS = test_str_tokens_remove.$(OBJEXT) \ mhd_str.$(OBJEXT) test_str_tokens_remove_OBJECTS = $(am_test_str_tokens_remove_OBJECTS) test_str_tokens_remove_LDADD = $(LDADD) am_test_upgrade_OBJECTS = test_upgrade-test_upgrade.$(OBJEXT) test_upgrade_OBJECTS = $(am_test_upgrade_OBJECTS) test_upgrade_DEPENDENCIES = $(builddir)/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) test_upgrade_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(test_upgrade_CFLAGS) \ $(CFLAGS) $(test_upgrade_LDFLAGS) $(LDFLAGS) -o $@ am__objects_22 = test_upgrade_large-test_upgrade.$(OBJEXT) am_test_upgrade_large_OBJECTS = $(am__objects_22) test_upgrade_large_OBJECTS = $(am_test_upgrade_large_OBJECTS) am__DEPENDENCIES_4 = $(builddir)/libmicrohttpd.la \ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) test_upgrade_large_DEPENDENCIES = $(am__DEPENDENCIES_4) test_upgrade_large_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_upgrade_large_CFLAGS) $(CFLAGS) \ $(test_upgrade_large_LDFLAGS) $(LDFLAGS) -o $@ am__objects_23 = test_upgrade_large_tls-test_upgrade.$(OBJEXT) am_test_upgrade_large_tls_OBJECTS = $(am__objects_23) test_upgrade_large_tls_OBJECTS = $(am_test_upgrade_large_tls_OBJECTS) test_upgrade_large_tls_DEPENDENCIES = $(am__DEPENDENCIES_4) test_upgrade_large_tls_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_upgrade_large_tls_CFLAGS) $(CFLAGS) \ $(test_upgrade_large_tls_LDFLAGS) $(LDFLAGS) -o $@ am__objects_24 = test_upgrade_tls-test_upgrade.$(OBJEXT) am_test_upgrade_tls_OBJECTS = $(am__objects_24) test_upgrade_tls_OBJECTS = $(am_test_upgrade_tls_OBJECTS) test_upgrade_tls_DEPENDENCIES = $(am__DEPENDENCIES_4) test_upgrade_tls_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_upgrade_tls_CFLAGS) $(CFLAGS) \ $(test_upgrade_tls_LDFLAGS) $(LDFLAGS) -o $@ am__objects_25 = test_upgrade_vlarge-test_upgrade.$(OBJEXT) am_test_upgrade_vlarge_OBJECTS = $(am__objects_25) test_upgrade_vlarge_OBJECTS = $(am_test_upgrade_vlarge_OBJECTS) test_upgrade_vlarge_DEPENDENCIES = $(am__DEPENDENCIES_4) test_upgrade_vlarge_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_upgrade_vlarge_CFLAGS) $(CFLAGS) \ $(test_upgrade_vlarge_LDFLAGS) $(LDFLAGS) -o $@ am__objects_26 = test_upgrade_vlarge_tls-test_upgrade.$(OBJEXT) am_test_upgrade_vlarge_tls_OBJECTS = $(am__objects_26) test_upgrade_vlarge_tls_OBJECTS = \ $(am_test_upgrade_vlarge_tls_OBJECTS) test_upgrade_vlarge_tls_DEPENDENCIES = $(am__DEPENDENCIES_4) test_upgrade_vlarge_tls_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(test_upgrade_vlarge_tls_CFLAGS) $(CFLAGS) \ $(test_upgrade_vlarge_tls_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__maybe_remake_depfiles = depfiles am__depfiles_remade = ./$(DEPDIR)/libmicrohttpd_la-basicauth.Plo \ ./$(DEPDIR)/libmicrohttpd_la-connection.Plo \ ./$(DEPDIR)/libmicrohttpd_la-connection_https.Plo \ ./$(DEPDIR)/libmicrohttpd_la-daemon.Plo \ ./$(DEPDIR)/libmicrohttpd_la-digestauth.Plo \ ./$(DEPDIR)/libmicrohttpd_la-gen_auth.Plo \ ./$(DEPDIR)/libmicrohttpd_la-internal.Plo \ ./$(DEPDIR)/libmicrohttpd_la-md5.Plo \ ./$(DEPDIR)/libmicrohttpd_la-md5_ext.Plo \ ./$(DEPDIR)/libmicrohttpd_la-memorypool.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_compat.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_itc.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_panic.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_send.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_sockets.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_str.Plo \ ./$(DEPDIR)/libmicrohttpd_la-mhd_threads.Plo \ ./$(DEPDIR)/libmicrohttpd_la-postprocessor.Plo \ ./$(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo \ ./$(DEPDIR)/libmicrohttpd_la-response.Plo \ ./$(DEPDIR)/libmicrohttpd_la-sha256.Plo \ ./$(DEPDIR)/libmicrohttpd_la-sha256_ext.Plo \ ./$(DEPDIR)/libmicrohttpd_la-sha512_256.Plo \ ./$(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Plo \ ./$(DEPDIR)/libmicrohttpd_la-tsearch.Plo \ ./$(DEPDIR)/mhd_opt_matrix.Po ./$(DEPDIR)/mhd_str.Po \ ./$(DEPDIR)/reason_phrase.Po ./$(DEPDIR)/sha1.Po \ ./$(DEPDIR)/sha512_256.Po \ ./$(DEPDIR)/test_auth_parse-gen_auth.Po \ ./$(DEPDIR)/test_auth_parse-mhd_str.Po \ ./$(DEPDIR)/test_auth_parse-test_auth_parse.Po \ ./$(DEPDIR)/test_chunked_ext.Po \ ./$(DEPDIR)/test_client_put_stop.Po ./$(DEPDIR)/test_daemon.Po \ ./$(DEPDIR)/test_dauth_malformed.Po \ ./$(DEPDIR)/test_dauth_userdigest.Po \ ./$(DEPDIR)/test_dauth_userhash.Po \ ./$(DEPDIR)/test_http_reasons.Po ./$(DEPDIR)/test_md5-md5.Po \ ./$(DEPDIR)/test_md5-md5_ext.Po \ ./$(DEPDIR)/test_md5-test_md5.Po \ ./$(DEPDIR)/test_mhd_version.Po \ ./$(DEPDIR)/test_option_matrix.Po ./$(DEPDIR)/test_options.Po \ ./$(DEPDIR)/test_postprocessor-test_postprocessor.Po \ ./$(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po \ ./$(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po \ ./$(DEPDIR)/test_postprocessor_md-internal.Po \ ./$(DEPDIR)/test_postprocessor_md-mhd_panic.Po \ ./$(DEPDIR)/test_postprocessor_md-mhd_str.Po \ ./$(DEPDIR)/test_postprocessor_md-postprocessor.Po \ ./$(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po \ ./$(DEPDIR)/test_raw_requests.Po \ ./$(DEPDIR)/test_response_entries.Po \ ./$(DEPDIR)/test_rq_shift_back.Po \ ./$(DEPDIR)/test_set_panic.Po ./$(DEPDIR)/test_sha1.Po \ ./$(DEPDIR)/test_sha256-sha256.Po \ ./$(DEPDIR)/test_sha256-sha256_ext.Po \ ./$(DEPDIR)/test_sha256-test_sha256.Po \ ./$(DEPDIR)/test_sha512_256.Po \ ./$(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po \ ./$(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po \ ./$(DEPDIR)/test_shutdown_select-test_shutdown_select.Po \ ./$(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po \ ./$(DEPDIR)/test_start_stop.Po ./$(DEPDIR)/test_str.Po \ ./$(DEPDIR)/test_str_base64.Po ./$(DEPDIR)/test_str_bin_hex.Po \ ./$(DEPDIR)/test_str_pct.Po ./$(DEPDIR)/test_str_quote.Po \ ./$(DEPDIR)/test_str_token.Po \ ./$(DEPDIR)/test_str_token_remove.Po \ ./$(DEPDIR)/test_str_tokens_remove.Po \ ./$(DEPDIR)/test_upgrade-test_upgrade.Po \ ./$(DEPDIR)/test_upgrade_large-test_upgrade.Po \ ./$(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po \ ./$(DEPDIR)/test_upgrade_tls-test_upgrade.Po \ ./$(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po \ ./$(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libmicrohttpd_la_SOURCES) $(test_auth_parse_SOURCES) \ $(test_chunked_ext_SOURCES) \ $(test_client_put_chunked_close_SOURCES) \ $(test_client_put_chunked_hard_close_SOURCES) \ $(test_client_put_chunked_shutdown_SOURCES) \ $(test_client_put_chunked_steps_close_SOURCES) \ $(test_client_put_chunked_steps_hard_close_SOURCES) \ $(test_client_put_chunked_steps_hard_close_stress_os_SOURCES) \ $(test_client_put_chunked_steps_shutdown_SOURCES) \ $(test_client_put_close_SOURCES) \ $(test_client_put_hard_close_SOURCES) \ $(test_client_put_hard_close_stress_os_SOURCES) \ $(test_client_put_shutdown_SOURCES) \ $(test_client_put_steps_close_SOURCES) \ $(test_client_put_steps_hard_close_SOURCES) \ $(test_client_put_steps_hard_close_stress_os_SOURCES) \ $(test_client_put_steps_shutdown_SOURCES) \ $(test_daemon_SOURCES) $(test_dauth_malformed_SOURCES) \ $(test_dauth_userdigest_SOURCES) \ $(test_dauth_userhash_SOURCES) $(test_http_reasons_SOURCES) \ $(test_md5_SOURCES) $(test_mhd_version_SOURCES) \ $(test_option_matrix_SOURCES) $(test_options_SOURCES) \ $(test_postprocessor_SOURCES) \ $(test_postprocessor_amp_SOURCES) \ $(test_postprocessor_large_SOURCES) \ $(test_postprocessor_md_SOURCES) $(test_raw_requests_SOURCES) \ $(test_response_entries_SOURCES) $(test_rq_shift_back_SOURCES) \ $(test_set_panic_SOURCES) $(test_sha1_SOURCES) \ $(test_sha256_SOURCES) $(test_sha512_256_SOURCES) \ $(test_shutdown_poll_SOURCES) \ $(test_shutdown_poll_ignore_SOURCES) \ $(test_shutdown_select_SOURCES) \ $(test_shutdown_select_ignore_SOURCES) \ $(test_start_stop_SOURCES) $(test_str_base64_SOURCES) \ $(test_str_bin_hex_SOURCES) $(test_str_compare_SOURCES) \ $(test_str_from_value_SOURCES) $(test_str_pct_SOURCES) \ $(test_str_quote_SOURCES) $(test_str_to_value_SOURCES) \ $(test_str_token_SOURCES) $(test_str_token_remove_SOURCES) \ $(test_str_tokens_remove_SOURCES) $(test_upgrade_SOURCES) \ $(test_upgrade_large_SOURCES) \ $(test_upgrade_large_tls_SOURCES) $(test_upgrade_tls_SOURCES) \ $(test_upgrade_vlarge_SOURCES) \ $(test_upgrade_vlarge_tls_SOURCES) DIST_SOURCES = $(am__libmicrohttpd_la_SOURCES_DIST) \ $(test_auth_parse_SOURCES) $(test_chunked_ext_SOURCES) \ $(test_client_put_chunked_close_SOURCES) \ $(test_client_put_chunked_hard_close_SOURCES) \ $(test_client_put_chunked_shutdown_SOURCES) \ $(test_client_put_chunked_steps_close_SOURCES) \ $(test_client_put_chunked_steps_hard_close_SOURCES) \ $(test_client_put_chunked_steps_hard_close_stress_os_SOURCES) \ $(test_client_put_chunked_steps_shutdown_SOURCES) \ $(test_client_put_close_SOURCES) \ $(test_client_put_hard_close_SOURCES) \ $(test_client_put_hard_close_stress_os_SOURCES) \ $(test_client_put_shutdown_SOURCES) \ $(test_client_put_steps_close_SOURCES) \ $(test_client_put_steps_hard_close_SOURCES) \ $(test_client_put_steps_hard_close_stress_os_SOURCES) \ $(test_client_put_steps_shutdown_SOURCES) \ $(test_daemon_SOURCES) $(test_dauth_malformed_SOURCES) \ $(test_dauth_userdigest_SOURCES) \ $(test_dauth_userhash_SOURCES) $(test_http_reasons_SOURCES) \ $(am__test_md5_SOURCES_DIST) $(test_mhd_version_SOURCES) \ $(test_option_matrix_SOURCES) $(test_options_SOURCES) \ $(test_postprocessor_SOURCES) \ $(test_postprocessor_amp_SOURCES) \ $(test_postprocessor_large_SOURCES) \ $(test_postprocessor_md_SOURCES) $(test_raw_requests_SOURCES) \ $(test_response_entries_SOURCES) $(test_rq_shift_back_SOURCES) \ $(test_set_panic_SOURCES) $(test_sha1_SOURCES) \ $(am__test_sha256_SOURCES_DIST) $(test_sha512_256_SOURCES) \ $(test_shutdown_poll_SOURCES) \ $(test_shutdown_poll_ignore_SOURCES) \ $(test_shutdown_select_SOURCES) \ $(test_shutdown_select_ignore_SOURCES) \ $(test_start_stop_SOURCES) $(test_str_base64_SOURCES) \ $(test_str_bin_hex_SOURCES) $(test_str_compare_SOURCES) \ $(test_str_from_value_SOURCES) $(test_str_pct_SOURCES) \ $(test_str_quote_SOURCES) $(test_str_to_value_SOURCES) \ $(test_str_token_SOURCES) $(test_str_token_remove_SOURCES) \ $(test_str_tokens_remove_SOURCES) $(test_upgrade_SOURCES) \ $(test_upgrade_large_SOURCES) \ $(test_upgrade_large_tls_SOURCES) $(test_upgrade_tls_SOURCES) \ $(test_upgrade_vlarge_SOURCES) \ $(test_upgrade_vlarge_tls_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DATA = $(noinst_DATA) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ $$am__collect_skipped_logs \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(IGNORE_SKIPPED_LOGS)'; then \ am__collect_skipped_logs='--collect-skipped-logs no'; \ else \ am__collect_skipped_logs=''; \ fi; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` AM_TESTSUITE_SUMMARY_HEADER = ' for $(PACKAGE_STRING)' RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/build-aux/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) am__DIST_COMMON = $(srcdir)/Makefile.in \ $(srcdir)/microhttpd_dll_res.rc.in \ $(top_srcdir)/build-aux/depcomp \ $(top_srcdir)/build-aux/test-driver DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_ASAN_OPTIONS = @AM_ASAN_OPTIONS@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AM_LSAN_OPTIONS = @AM_LSAN_OPTIONS@ AM_UBSAN_OPTIONS = @AM_UBSAN_OPTIONS@ AR = @AR@ AS = @AS@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CFLAGS_ac = @CFLAGS_ac@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CPPFLAGS_ac = @CPPFLAGS_ac@ CPU_COUNT = @CPU_COUNT@ CSCOPE = @CSCOPE@ CTAGS = @CTAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EMPTY_VAR = @EMPTY_VAR@ ETAGS = @ETAGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ FILECMD = @FILECMD@ GNUTLS_CFLAGS = @GNUTLS_CFLAGS@ GNUTLS_CPPFLAGS = @GNUTLS_CPPFLAGS@ GNUTLS_LDFLAGS = @GNUTLS_LDFLAGS@ GNUTLS_LIBS = @GNUTLS_LIBS@ GREP = @GREP@ HAVE_CURL_BINARY = @HAVE_CURL_BINARY@ HAVE_MAKEINFO_BINARY = @HAVE_MAKEINFO_BINARY@ HIDDEN_VISIBILITY_CFLAGS = @HIDDEN_VISIBILITY_CFLAGS@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LDFLAGS_ac = @LDFLAGS_ac@ LIBCURL = @LIBCURL@ LIBCURL_CPPFLAGS = @LIBCURL_CPPFLAGS@ LIBGCRYPT_CFLAGS = @LIBGCRYPT_CFLAGS@ LIBGCRYPT_CONFIG = @LIBGCRYPT_CONFIG@ LIBGCRYPT_LIBS = @LIBGCRYPT_LIBS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIB_VERSION_AGE = @LIB_VERSION_AGE@ LIB_VERSION_CURRENT = @LIB_VERSION_CURRENT@ LIB_VERSION_REVISION = @LIB_VERSION_REVISION@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MHD_AUX_DIR = @MHD_AUX_DIR@ MHD_LIBDEPS = @MHD_LIBDEPS@ MHD_LIBDEPS_PKGCFG = @MHD_LIBDEPS_PKGCFG@ MHD_LIB_CFLAGS = @MHD_LIB_CFLAGS@ MHD_LIB_CPPFLAGS = @MHD_LIB_CPPFLAGS@ MHD_LIB_LDFLAGS = @MHD_LIB_LDFLAGS@ MHD_PLUGIN_INSTALL_PREFIX = @MHD_PLUGIN_INSTALL_PREFIX@ MHD_REQ_PRIVATE = @MHD_REQ_PRIVATE@ MHD_TLS_LIBDEPS = @MHD_TLS_LIBDEPS@ MHD_TLS_LIB_CFLAGS = @MHD_TLS_LIB_CFLAGS@ MHD_TLS_LIB_CPPFLAGS = @MHD_TLS_LIB_CPPFLAGS@ MHD_TLS_LIB_LDFLAGS = @MHD_TLS_LIB_LDFLAGS@ MHD_W32_DLL_SUFF = @MHD_W32_DLL_SUFF@ MKDIR_P = @MKDIR_P@ MS_LIB_TOOL = @MS_LIB_TOOL@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PACKAGE_VERSION_MAJOR = @PACKAGE_VERSION_MAJOR@ PACKAGE_VERSION_MINOR = @PACKAGE_VERSION_MINOR@ PACKAGE_VERSION_SUBMINOR = @PACKAGE_VERSION_SUBMINOR@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ PTHREAD_CC = @PTHREAD_CC@ PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ PTHREAD_CXX = @PTHREAD_CXX@ PTHREAD_LIBS = @PTHREAD_LIBS@ RANLIB = @RANLIB@ RC = @RC@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOCAT = @SOCAT@ STRIP = @STRIP@ TESTS_ENVIRONMENT_ac = @TESTS_ENVIRONMENT_ac@ VERSION = @VERSION@ W32CRT = @W32CRT@ ZZUF = @ZZUF@ _libcurl_config = @_libcurl_config@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_configure_args = @ac_configure_args@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ am__xargs_n = @am__xargs_n@ ax_pthread_config = @ax_pthread_config@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ lt_cv_objdir = @lt_cv_objdir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ $(CPPFLAGS_ac) AM_CFLAGS = $(CFLAGS_ac) $(HIDDEN_VISIBILITY_CFLAGS) $(am__append_9) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) lib_LTLIBRARIES = \ libmicrohttpd.la noinst_DATA = $(am__append_1) $(am__append_3) $(am__append_4) MOSTLYCLEANFILES = $(am__append_2) $(am__append_5) # Test-only header, #included by every test program but not compiled on its # own and not part of the library; see mhd_panic_tripwire.h. EXTRA_DIST = \ mhd_panic_tripwire.h AM_V_LIB = $(am__v_LIB_@AM_V@) am__v_LIB_ = $(am__v_LIB_@AM_DEFAULT_V@) am__v_LIB_0 = @echo " LIB " $@; am__v_LIB_1 = @W32_SHARED_LIB_EXP_TRUE@AM_V_DLLTOOL = $(am__v_DLLTOOL_@AM_V@) @W32_SHARED_LIB_EXP_TRUE@am__v_DLLTOOL_ = $(am__v_DLLTOOL_@AM_DEFAULT_V@) @W32_SHARED_LIB_EXP_TRUE@am__v_DLLTOOL_0 = @echo " DLLTOOL " $@; @W32_SHARED_LIB_EXP_TRUE@am__v_DLLTOOL_1 = @W32_SHARED_LIB_EXP_FALSE@W32_MHD_LIB_LDFLAGS = @W32_SHARED_LIB_EXP_TRUE@W32_MHD_LIB_LDFLAGS = -Wl,--output-def,$(lt_cv_objdir)/libmicrohttpd.def -XCClinker -static-libgcc libmicrohttpd_la_SOURCES = connection.c connection.h reason_phrase.c \ daemon.c internal.c internal.h memorypool.c memorypool.h \ mhd_mono_clock.c mhd_mono_clock.h mhd_limits.h sysfdsetsize.h \ mhd_str.c mhd_str.h mhd_str_types.h mhd_send.h mhd_send.c \ mhd_assert.h mhd_check.h mhd_sockets.c mhd_sockets.h mhd_itc.c \ mhd_itc.h mhd_itc_types.h mhd_compat.c mhd_compat.h \ mhd_panic.c mhd_panic.h response.c response.h $(am__append_6) \ $(am__append_7) $(am__append_8) $(am__append_10) \ $(am__append_11) $(am__append_12) $(am__append_13) \ $(am__append_14) $(am__append_15) $(am__append_16) \ $(am__append_17) $(am__append_18) $(am__append_19) \ $(am__append_20) $(am__append_21) $(am__append_22) libmicrohttpd_la_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) \ -DBUILDING_MHD_LIB=1 libmicrohttpd_la_CFLAGS = \ $(AM_CFLAGS) $(MHD_LIB_CFLAGS) $(MHD_TLS_LIB_CFLAGS) libmicrohttpd_la_LDFLAGS = \ $(AM_LDFLAGS) $(MHD_LIB_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) \ $(W32_MHD_LIB_LDFLAGS) \ -export-dynamic -no-undefined \ -version-info @LIB_VERSION_CURRENT@:@LIB_VERSION_REVISION@:@LIB_VERSION_AGE@ libmicrohttpd_la_LIBADD = $(MHD_LIBDEPS) $(MHD_TLS_LIBDEPS) \ $(MHD_DLL_RES_LO) AM_V_RC = $(am__v_RC_@AM_V@) am__v_RC_ = $(am__v_RC_@AM_DEFAULT_V@) am__v_RC_0 = @echo " RC " $@; am__v_RC_1 = @HAVE_W32_FALSE@MHD_DLL_RES_LO = @HAVE_W32_TRUE@MHD_DLL_RES_LO = libmicrohttpd_la-microhttpd_dll_res.lo EXTRA_libmicrohttpd_la_DEPENDENCIES = $(MHD_DLL_RES_LO) TESTS = $(check_PROGRAMS) test_start_stop_SOURCES = \ test_start_stop.c test_start_stop_LDADD = \ libmicrohttpd.la test_daemon_SOURCES = \ test_daemon.c test_daemon_LDADD = \ $(builddir)/libmicrohttpd.la test_response_entries_SOURCES = \ test_response_entries.c test_response_entries_LDADD = \ libmicrohttpd.la test_upgrade_SOURCES = \ test_upgrade.c test_helpers.h mhd_sockets.h test_upgrade_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_upgrade_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_upgrade_LDFLAGS = \ $(MHD_TLS_LIB_LDFLAGS) test_upgrade_LDADD = \ $(builddir)/libmicrohttpd.la \ $(MHD_TLS_LIBDEPS) \ $(PTHREAD_LIBS) test_upgrade_large_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_large_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_large_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_large_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_large_LDADD = \ $(test_upgrade_LDADD) test_upgrade_vlarge_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_vlarge_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_vlarge_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_vlarge_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_vlarge_LDADD = \ $(test_upgrade_LDADD) test_upgrade_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_tls_LDADD = \ $(test_upgrade_LDADD) test_upgrade_large_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_large_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_large_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_large_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_large_tls_LDADD = \ $(test_upgrade_LDADD) test_upgrade_vlarge_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_vlarge_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_vlarge_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_vlarge_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_vlarge_tls_LDADD = \ $(test_upgrade_LDADD) test_postprocessor_SOURCES = \ test_postprocessor.c test_postprocessor_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_amp_SOURCES = \ test_postprocessor_amp.c test_postprocessor_amp_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_amp_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_amp_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_large_SOURCES = \ test_postprocessor_large.c test_postprocessor_large_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_large_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_large_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_md_SOURCES = \ test_postprocessor_md.c postprocessor.h postprocessor.c \ internal.h internal.c mhd_str.h mhd_str.c \ mhd_panic.h mhd_panic.c test_postprocessor_md_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_shutdown_select_SOURCES = \ test_shutdown_select.c test_shutdown_select_CFLAGS = $(AM_CFLAGS) $(am__append_35) test_shutdown_select_LDADD = $(LDADD) $(am__append_36) test_shutdown_poll_SOURCES = \ test_shutdown_select.c mhd_threads.h test_shutdown_poll_CFLAGS = $(AM_CFLAGS) $(am__append_37) test_shutdown_poll_LDADD = $(LDADD) $(am__append_38) test_shutdown_select_ignore_SOURCES = \ test_shutdown_select.c test_shutdown_select_ignore_CFLAGS = $(AM_CFLAGS) $(am__append_39) test_shutdown_select_ignore_LDADD = $(LDADD) $(am__append_40) test_shutdown_poll_ignore_SOURCES = \ test_shutdown_select.c mhd_threads.h test_shutdown_poll_ignore_CFLAGS = $(AM_CFLAGS) $(am__append_41) test_shutdown_poll_ignore_LDADD = $(LDADD) $(am__append_42) test_str_compare_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_to_value_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_from_value_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_token_SOURCES = \ test_str_token.c mhd_str.c mhd_str.h test_str_token_remove_SOURCES = \ test_str_token_remove.c mhd_str.c mhd_str.h mhd_assert.h ../include/mhd_options.h test_str_tokens_remove_SOURCES = \ test_str_tokens_remove.c mhd_str.c mhd_str.h mhd_assert.h ../include/mhd_options.h test_http_reasons_SOURCES = \ test_http_reasons.c \ reason_phrase.c mhd_str.c mhd_str.h test_md5_SOURCES = test_md5.c test_helpers.h mhd_md5_wrap.h \ ../include/mhd_options.h $(am__append_43) $(am__append_44) @ENABLE_MD5_EXT_FALSE@test_md5_CPPFLAGS = $(AM_CPPFLAGS) @ENABLE_MD5_EXT_TRUE@test_md5_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) @ENABLE_MD5_EXT_FALSE@test_md5_CFLAGS = $(AM_CFLAGS) @ENABLE_MD5_EXT_TRUE@test_md5_CFLAGS = $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) @ENABLE_MD5_EXT_FALSE@test_md5_LDFLAGS = $(AM_LDFLAGS) @ENABLE_MD5_EXT_TRUE@test_md5_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) @ENABLE_MD5_EXT_FALSE@test_md5_LDADD = $(LDADD) @ENABLE_MD5_EXT_TRUE@test_md5_LDADD = $(MHD_TLS_LIBDEPS) $(LDADD) test_sha256_SOURCES = test_sha256.c test_helpers.h mhd_sha256_wrap.h \ ../include/mhd_options.h $(am__append_45) $(am__append_46) @ENABLE_SHA256_EXT_FALSE@test_sha256_CPPFLAGS = $(AM_CPPFLAGS) @ENABLE_SHA256_EXT_TRUE@test_sha256_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) @ENABLE_SHA256_EXT_FALSE@test_sha256_CFLAGS = $(AM_CFLAGS) @ENABLE_SHA256_EXT_TRUE@test_sha256_CFLAGS = $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) @ENABLE_SHA256_EXT_FALSE@test_sha256_LDFLAGS = $(AM_LDFLAGS) @ENABLE_SHA256_EXT_TRUE@test_sha256_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) @ENABLE_SHA256_EXT_FALSE@test_sha256_LDADD = $(LDADD) @ENABLE_SHA256_EXT_TRUE@test_sha256_LDADD = $(MHD_TLS_LIBDEPS) $(LDADD) test_sha512_256_SOURCES = \ test_sha512_256.c test_helpers.h \ sha512_256.c sha512_256.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_sha1_SOURCES = \ test_sha1.c test_helpers.h \ sha1.c sha1.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_auth_parse_SOURCES = \ test_auth_parse.c gen_auth.c gen_auth.h mhd_str.h mhd_str.c mhd_assert.h test_auth_parse_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_str_quote_SOURCES = \ test_str_quote.c mhd_str.h mhd_str.c mhd_assert.h test_str_base64_SOURCES = \ test_str_base64.c mhd_str.h mhd_str.c mhd_assert.h test_str_pct_SOURCES = \ test_str_pct.c mhd_str.h mhd_str.c mhd_assert.h test_str_bin_hex_SOURCES = \ test_str_bin_hex.c mhd_str.h mhd_str.c mhd_assert.h test_options_SOURCES = \ test_options.c test_options_LDADD = \ $(builddir)/libmicrohttpd.la # The environment-driven daemon option matrix (see mhd_opt_matrix.h and # contrib/run-option-matrix.sh). It uses the public API only, so it is # simply compiled into every test that honours the matrix. MHD_OPT_MATRIX_SOURCES = \ mhd_opt_matrix.c mhd_opt_matrix.h test_rq_shift_back_SOURCES = \ test_rq_shift_back.c mhd_sockets.h mhd_assert.h \ $(MHD_OPT_MATRIX_SOURCES) test_rq_shift_back_LDADD = \ $(builddir)/libmicrohttpd.la test_chunked_ext_SOURCES = \ test_chunked_ext.c mhd_sockets.h mhd_assert.h \ $(MHD_OPT_MATRIX_SOURCES) test_chunked_ext_LDADD = \ $(builddir)/libmicrohttpd.la test_raw_requests_SOURCES = \ test_raw_requests.c mhd_sockets.h mhd_assert.h \ $(MHD_OPT_MATRIX_SOURCES) test_raw_requests_LDADD = \ $(builddir)/libmicrohttpd.la test_option_matrix_SOURCES = \ test_option_matrix.c mhd_sockets.h mhd_assert.h \ $(MHD_OPT_MATRIX_SOURCES) test_option_matrix_LDADD = \ $(builddir)/libmicrohttpd.la test_dauth_malformed_SOURCES = \ test_dauth_malformed.c mhd_sockets.h mhd_assert.h \ $(MHD_OPT_MATRIX_SOURCES) test_dauth_malformed_LDADD = \ $(builddir)/libmicrohttpd.la test_client_put_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_shutdown_LDADD = \ libmicrohttpd.la test_client_put_close_SOURCES = \ test_client_put_stop.c test_client_put_close_LDADD = \ libmicrohttpd.la test_client_put_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_hard_close_LDADD = \ libmicrohttpd.la test_client_put_hard_close_stress_os_SOURCES = \ $(test_client_put_hard_close_SOURCES) test_client_put_hard_close_stress_os_LDADD = \ $(test_client_put_hard_close_LDADD) test_client_put_steps_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_steps_shutdown_LDADD = \ libmicrohttpd.la test_client_put_steps_close_SOURCES = \ test_client_put_stop.c test_client_put_steps_close_LDADD = \ libmicrohttpd.la test_client_put_steps_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_steps_hard_close_LDADD = \ libmicrohttpd.la test_client_put_steps_hard_close_stress_os_SOURCES = \ $(test_client_put_steps_hard_close_SOURCES) test_client_put_steps_hard_close_stress_os_LDADD = \ $(test_client_put_steps_hard_close_LDADD) test_client_put_chunked_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_chunked_shutdown_LDADD = \ libmicrohttpd.la test_client_put_chunked_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_hard_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_shutdown_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_hard_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_hard_close_stress_os_SOURCES = \ $(test_client_put_chunked_steps_hard_close_SOURCES) test_client_put_chunked_steps_hard_close_stress_os_LDADD = \ $(test_client_put_chunked_steps_hard_close_LDADD) test_set_panic_SOURCES = \ test_set_panic.c test_set_panic_LDADD = \ libmicrohttpd.la test_dauth_userdigest_SOURCES = \ test_dauth_userdigest.c test_dauth_userdigest_LDADD = \ libmicrohttpd.la test_dauth_userhash_SOURCES = \ test_dauth_userhash.c test_dauth_userhash_LDADD = \ libmicrohttpd.la test_mhd_version_SOURCES = \ test_mhd_version.c test_mhd_version_LDADD = \ libmicrohttpd.la all: all-am .SUFFIXES: .SUFFIXES: .c .lo .log .o .obj .rc .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/microhttpd/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/microhttpd/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): microhttpd_dll_res.rc: $(top_builddir)/config.status $(srcdir)/microhttpd_dll_res.rc.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ clean-checkPROGRAMS: $(am__rm_f) $(check_PROGRAMS) test -z "$(EXEEXT)" || $(am__rm_f) $(check_PROGRAMS:$(EXEEXT)=) install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -$(am__rm_f) $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ echo rm -f $${locs}; \ $(am__rm_f) $${locs} libmicrohttpd.la: $(libmicrohttpd_la_OBJECTS) $(libmicrohttpd_la_DEPENDENCIES) $(EXTRA_libmicrohttpd_la_DEPENDENCIES) $(AM_V_CCLD)$(libmicrohttpd_la_LINK) -rpath $(libdir) $(libmicrohttpd_la_OBJECTS) $(libmicrohttpd_la_LIBADD) $(LIBS) test_auth_parse$(EXEEXT): $(test_auth_parse_OBJECTS) $(test_auth_parse_DEPENDENCIES) $(EXTRA_test_auth_parse_DEPENDENCIES) @rm -f test_auth_parse$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_auth_parse_OBJECTS) $(test_auth_parse_LDADD) $(LIBS) test_chunked_ext$(EXEEXT): $(test_chunked_ext_OBJECTS) $(test_chunked_ext_DEPENDENCIES) $(EXTRA_test_chunked_ext_DEPENDENCIES) @rm -f test_chunked_ext$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_chunked_ext_OBJECTS) $(test_chunked_ext_LDADD) $(LIBS) test_client_put_chunked_close$(EXEEXT): $(test_client_put_chunked_close_OBJECTS) $(test_client_put_chunked_close_DEPENDENCIES) $(EXTRA_test_client_put_chunked_close_DEPENDENCIES) @rm -f test_client_put_chunked_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_close_OBJECTS) $(test_client_put_chunked_close_LDADD) $(LIBS) test_client_put_chunked_hard_close$(EXEEXT): $(test_client_put_chunked_hard_close_OBJECTS) $(test_client_put_chunked_hard_close_DEPENDENCIES) $(EXTRA_test_client_put_chunked_hard_close_DEPENDENCIES) @rm -f test_client_put_chunked_hard_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_hard_close_OBJECTS) $(test_client_put_chunked_hard_close_LDADD) $(LIBS) test_client_put_chunked_shutdown$(EXEEXT): $(test_client_put_chunked_shutdown_OBJECTS) $(test_client_put_chunked_shutdown_DEPENDENCIES) $(EXTRA_test_client_put_chunked_shutdown_DEPENDENCIES) @rm -f test_client_put_chunked_shutdown$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_shutdown_OBJECTS) $(test_client_put_chunked_shutdown_LDADD) $(LIBS) test_client_put_chunked_steps_close$(EXEEXT): $(test_client_put_chunked_steps_close_OBJECTS) $(test_client_put_chunked_steps_close_DEPENDENCIES) $(EXTRA_test_client_put_chunked_steps_close_DEPENDENCIES) @rm -f test_client_put_chunked_steps_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_steps_close_OBJECTS) $(test_client_put_chunked_steps_close_LDADD) $(LIBS) test_client_put_chunked_steps_hard_close$(EXEEXT): $(test_client_put_chunked_steps_hard_close_OBJECTS) $(test_client_put_chunked_steps_hard_close_DEPENDENCIES) $(EXTRA_test_client_put_chunked_steps_hard_close_DEPENDENCIES) @rm -f test_client_put_chunked_steps_hard_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_steps_hard_close_OBJECTS) $(test_client_put_chunked_steps_hard_close_LDADD) $(LIBS) test_client_put_chunked_steps_hard_close_stress_os$(EXEEXT): $(test_client_put_chunked_steps_hard_close_stress_os_OBJECTS) $(test_client_put_chunked_steps_hard_close_stress_os_DEPENDENCIES) $(EXTRA_test_client_put_chunked_steps_hard_close_stress_os_DEPENDENCIES) @rm -f test_client_put_chunked_steps_hard_close_stress_os$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_steps_hard_close_stress_os_OBJECTS) $(test_client_put_chunked_steps_hard_close_stress_os_LDADD) $(LIBS) test_client_put_chunked_steps_shutdown$(EXEEXT): $(test_client_put_chunked_steps_shutdown_OBJECTS) $(test_client_put_chunked_steps_shutdown_DEPENDENCIES) $(EXTRA_test_client_put_chunked_steps_shutdown_DEPENDENCIES) @rm -f test_client_put_chunked_steps_shutdown$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_chunked_steps_shutdown_OBJECTS) $(test_client_put_chunked_steps_shutdown_LDADD) $(LIBS) test_client_put_close$(EXEEXT): $(test_client_put_close_OBJECTS) $(test_client_put_close_DEPENDENCIES) $(EXTRA_test_client_put_close_DEPENDENCIES) @rm -f test_client_put_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_close_OBJECTS) $(test_client_put_close_LDADD) $(LIBS) test_client_put_hard_close$(EXEEXT): $(test_client_put_hard_close_OBJECTS) $(test_client_put_hard_close_DEPENDENCIES) $(EXTRA_test_client_put_hard_close_DEPENDENCIES) @rm -f test_client_put_hard_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_hard_close_OBJECTS) $(test_client_put_hard_close_LDADD) $(LIBS) test_client_put_hard_close_stress_os$(EXEEXT): $(test_client_put_hard_close_stress_os_OBJECTS) $(test_client_put_hard_close_stress_os_DEPENDENCIES) $(EXTRA_test_client_put_hard_close_stress_os_DEPENDENCIES) @rm -f test_client_put_hard_close_stress_os$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_hard_close_stress_os_OBJECTS) $(test_client_put_hard_close_stress_os_LDADD) $(LIBS) test_client_put_shutdown$(EXEEXT): $(test_client_put_shutdown_OBJECTS) $(test_client_put_shutdown_DEPENDENCIES) $(EXTRA_test_client_put_shutdown_DEPENDENCIES) @rm -f test_client_put_shutdown$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_shutdown_OBJECTS) $(test_client_put_shutdown_LDADD) $(LIBS) test_client_put_steps_close$(EXEEXT): $(test_client_put_steps_close_OBJECTS) $(test_client_put_steps_close_DEPENDENCIES) $(EXTRA_test_client_put_steps_close_DEPENDENCIES) @rm -f test_client_put_steps_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_steps_close_OBJECTS) $(test_client_put_steps_close_LDADD) $(LIBS) test_client_put_steps_hard_close$(EXEEXT): $(test_client_put_steps_hard_close_OBJECTS) $(test_client_put_steps_hard_close_DEPENDENCIES) $(EXTRA_test_client_put_steps_hard_close_DEPENDENCIES) @rm -f test_client_put_steps_hard_close$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_steps_hard_close_OBJECTS) $(test_client_put_steps_hard_close_LDADD) $(LIBS) test_client_put_steps_hard_close_stress_os$(EXEEXT): $(test_client_put_steps_hard_close_stress_os_OBJECTS) $(test_client_put_steps_hard_close_stress_os_DEPENDENCIES) $(EXTRA_test_client_put_steps_hard_close_stress_os_DEPENDENCIES) @rm -f test_client_put_steps_hard_close_stress_os$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_steps_hard_close_stress_os_OBJECTS) $(test_client_put_steps_hard_close_stress_os_LDADD) $(LIBS) test_client_put_steps_shutdown$(EXEEXT): $(test_client_put_steps_shutdown_OBJECTS) $(test_client_put_steps_shutdown_DEPENDENCIES) $(EXTRA_test_client_put_steps_shutdown_DEPENDENCIES) @rm -f test_client_put_steps_shutdown$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_client_put_steps_shutdown_OBJECTS) $(test_client_put_steps_shutdown_LDADD) $(LIBS) test_daemon$(EXEEXT): $(test_daemon_OBJECTS) $(test_daemon_DEPENDENCIES) $(EXTRA_test_daemon_DEPENDENCIES) @rm -f test_daemon$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_daemon_OBJECTS) $(test_daemon_LDADD) $(LIBS) test_dauth_malformed$(EXEEXT): $(test_dauth_malformed_OBJECTS) $(test_dauth_malformed_DEPENDENCIES) $(EXTRA_test_dauth_malformed_DEPENDENCIES) @rm -f test_dauth_malformed$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_dauth_malformed_OBJECTS) $(test_dauth_malformed_LDADD) $(LIBS) test_dauth_userdigest$(EXEEXT): $(test_dauth_userdigest_OBJECTS) $(test_dauth_userdigest_DEPENDENCIES) $(EXTRA_test_dauth_userdigest_DEPENDENCIES) @rm -f test_dauth_userdigest$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_dauth_userdigest_OBJECTS) $(test_dauth_userdigest_LDADD) $(LIBS) test_dauth_userhash$(EXEEXT): $(test_dauth_userhash_OBJECTS) $(test_dauth_userhash_DEPENDENCIES) $(EXTRA_test_dauth_userhash_DEPENDENCIES) @rm -f test_dauth_userhash$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_dauth_userhash_OBJECTS) $(test_dauth_userhash_LDADD) $(LIBS) test_http_reasons$(EXEEXT): $(test_http_reasons_OBJECTS) $(test_http_reasons_DEPENDENCIES) $(EXTRA_test_http_reasons_DEPENDENCIES) @rm -f test_http_reasons$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_http_reasons_OBJECTS) $(test_http_reasons_LDADD) $(LIBS) test_md5$(EXEEXT): $(test_md5_OBJECTS) $(test_md5_DEPENDENCIES) $(EXTRA_test_md5_DEPENDENCIES) @rm -f test_md5$(EXEEXT) $(AM_V_CCLD)$(test_md5_LINK) $(test_md5_OBJECTS) $(test_md5_LDADD) $(LIBS) test_mhd_version$(EXEEXT): $(test_mhd_version_OBJECTS) $(test_mhd_version_DEPENDENCIES) $(EXTRA_test_mhd_version_DEPENDENCIES) @rm -f test_mhd_version$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_mhd_version_OBJECTS) $(test_mhd_version_LDADD) $(LIBS) test_option_matrix$(EXEEXT): $(test_option_matrix_OBJECTS) $(test_option_matrix_DEPENDENCIES) $(EXTRA_test_option_matrix_DEPENDENCIES) @rm -f test_option_matrix$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_option_matrix_OBJECTS) $(test_option_matrix_LDADD) $(LIBS) test_options$(EXEEXT): $(test_options_OBJECTS) $(test_options_DEPENDENCIES) $(EXTRA_test_options_DEPENDENCIES) @rm -f test_options$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_options_OBJECTS) $(test_options_LDADD) $(LIBS) test_postprocessor$(EXEEXT): $(test_postprocessor_OBJECTS) $(test_postprocessor_DEPENDENCIES) $(EXTRA_test_postprocessor_DEPENDENCIES) @rm -f test_postprocessor$(EXEEXT) $(AM_V_CCLD)$(test_postprocessor_LINK) $(test_postprocessor_OBJECTS) $(test_postprocessor_LDADD) $(LIBS) test_postprocessor_amp$(EXEEXT): $(test_postprocessor_amp_OBJECTS) $(test_postprocessor_amp_DEPENDENCIES) $(EXTRA_test_postprocessor_amp_DEPENDENCIES) @rm -f test_postprocessor_amp$(EXEEXT) $(AM_V_CCLD)$(test_postprocessor_amp_LINK) $(test_postprocessor_amp_OBJECTS) $(test_postprocessor_amp_LDADD) $(LIBS) test_postprocessor_large$(EXEEXT): $(test_postprocessor_large_OBJECTS) $(test_postprocessor_large_DEPENDENCIES) $(EXTRA_test_postprocessor_large_DEPENDENCIES) @rm -f test_postprocessor_large$(EXEEXT) $(AM_V_CCLD)$(test_postprocessor_large_LINK) $(test_postprocessor_large_OBJECTS) $(test_postprocessor_large_LDADD) $(LIBS) test_postprocessor_md$(EXEEXT): $(test_postprocessor_md_OBJECTS) $(test_postprocessor_md_DEPENDENCIES) $(EXTRA_test_postprocessor_md_DEPENDENCIES) @rm -f test_postprocessor_md$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_postprocessor_md_OBJECTS) $(test_postprocessor_md_LDADD) $(LIBS) test_raw_requests$(EXEEXT): $(test_raw_requests_OBJECTS) $(test_raw_requests_DEPENDENCIES) $(EXTRA_test_raw_requests_DEPENDENCIES) @rm -f test_raw_requests$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_raw_requests_OBJECTS) $(test_raw_requests_LDADD) $(LIBS) test_response_entries$(EXEEXT): $(test_response_entries_OBJECTS) $(test_response_entries_DEPENDENCIES) $(EXTRA_test_response_entries_DEPENDENCIES) @rm -f test_response_entries$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_response_entries_OBJECTS) $(test_response_entries_LDADD) $(LIBS) test_rq_shift_back$(EXEEXT): $(test_rq_shift_back_OBJECTS) $(test_rq_shift_back_DEPENDENCIES) $(EXTRA_test_rq_shift_back_DEPENDENCIES) @rm -f test_rq_shift_back$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_rq_shift_back_OBJECTS) $(test_rq_shift_back_LDADD) $(LIBS) test_set_panic$(EXEEXT): $(test_set_panic_OBJECTS) $(test_set_panic_DEPENDENCIES) $(EXTRA_test_set_panic_DEPENDENCIES) @rm -f test_set_panic$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_set_panic_OBJECTS) $(test_set_panic_LDADD) $(LIBS) test_sha1$(EXEEXT): $(test_sha1_OBJECTS) $(test_sha1_DEPENDENCIES) $(EXTRA_test_sha1_DEPENDENCIES) @rm -f test_sha1$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_sha1_OBJECTS) $(test_sha1_LDADD) $(LIBS) test_sha256$(EXEEXT): $(test_sha256_OBJECTS) $(test_sha256_DEPENDENCIES) $(EXTRA_test_sha256_DEPENDENCIES) @rm -f test_sha256$(EXEEXT) $(AM_V_CCLD)$(test_sha256_LINK) $(test_sha256_OBJECTS) $(test_sha256_LDADD) $(LIBS) test_sha512_256$(EXEEXT): $(test_sha512_256_OBJECTS) $(test_sha512_256_DEPENDENCIES) $(EXTRA_test_sha512_256_DEPENDENCIES) @rm -f test_sha512_256$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_sha512_256_OBJECTS) $(test_sha512_256_LDADD) $(LIBS) test_shutdown_poll$(EXEEXT): $(test_shutdown_poll_OBJECTS) $(test_shutdown_poll_DEPENDENCIES) $(EXTRA_test_shutdown_poll_DEPENDENCIES) @rm -f test_shutdown_poll$(EXEEXT) $(AM_V_CCLD)$(test_shutdown_poll_LINK) $(test_shutdown_poll_OBJECTS) $(test_shutdown_poll_LDADD) $(LIBS) test_shutdown_poll_ignore$(EXEEXT): $(test_shutdown_poll_ignore_OBJECTS) $(test_shutdown_poll_ignore_DEPENDENCIES) $(EXTRA_test_shutdown_poll_ignore_DEPENDENCIES) @rm -f test_shutdown_poll_ignore$(EXEEXT) $(AM_V_CCLD)$(test_shutdown_poll_ignore_LINK) $(test_shutdown_poll_ignore_OBJECTS) $(test_shutdown_poll_ignore_LDADD) $(LIBS) test_shutdown_select$(EXEEXT): $(test_shutdown_select_OBJECTS) $(test_shutdown_select_DEPENDENCIES) $(EXTRA_test_shutdown_select_DEPENDENCIES) @rm -f test_shutdown_select$(EXEEXT) $(AM_V_CCLD)$(test_shutdown_select_LINK) $(test_shutdown_select_OBJECTS) $(test_shutdown_select_LDADD) $(LIBS) test_shutdown_select_ignore$(EXEEXT): $(test_shutdown_select_ignore_OBJECTS) $(test_shutdown_select_ignore_DEPENDENCIES) $(EXTRA_test_shutdown_select_ignore_DEPENDENCIES) @rm -f test_shutdown_select_ignore$(EXEEXT) $(AM_V_CCLD)$(test_shutdown_select_ignore_LINK) $(test_shutdown_select_ignore_OBJECTS) $(test_shutdown_select_ignore_LDADD) $(LIBS) test_start_stop$(EXEEXT): $(test_start_stop_OBJECTS) $(test_start_stop_DEPENDENCIES) $(EXTRA_test_start_stop_DEPENDENCIES) @rm -f test_start_stop$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_start_stop_OBJECTS) $(test_start_stop_LDADD) $(LIBS) test_str_base64$(EXEEXT): $(test_str_base64_OBJECTS) $(test_str_base64_DEPENDENCIES) $(EXTRA_test_str_base64_DEPENDENCIES) @rm -f test_str_base64$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_base64_OBJECTS) $(test_str_base64_LDADD) $(LIBS) test_str_bin_hex$(EXEEXT): $(test_str_bin_hex_OBJECTS) $(test_str_bin_hex_DEPENDENCIES) $(EXTRA_test_str_bin_hex_DEPENDENCIES) @rm -f test_str_bin_hex$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_bin_hex_OBJECTS) $(test_str_bin_hex_LDADD) $(LIBS) test_str_compare$(EXEEXT): $(test_str_compare_OBJECTS) $(test_str_compare_DEPENDENCIES) $(EXTRA_test_str_compare_DEPENDENCIES) @rm -f test_str_compare$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_compare_OBJECTS) $(test_str_compare_LDADD) $(LIBS) test_str_from_value$(EXEEXT): $(test_str_from_value_OBJECTS) $(test_str_from_value_DEPENDENCIES) $(EXTRA_test_str_from_value_DEPENDENCIES) @rm -f test_str_from_value$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_from_value_OBJECTS) $(test_str_from_value_LDADD) $(LIBS) test_str_pct$(EXEEXT): $(test_str_pct_OBJECTS) $(test_str_pct_DEPENDENCIES) $(EXTRA_test_str_pct_DEPENDENCIES) @rm -f test_str_pct$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_pct_OBJECTS) $(test_str_pct_LDADD) $(LIBS) test_str_quote$(EXEEXT): $(test_str_quote_OBJECTS) $(test_str_quote_DEPENDENCIES) $(EXTRA_test_str_quote_DEPENDENCIES) @rm -f test_str_quote$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_quote_OBJECTS) $(test_str_quote_LDADD) $(LIBS) test_str_to_value$(EXEEXT): $(test_str_to_value_OBJECTS) $(test_str_to_value_DEPENDENCIES) $(EXTRA_test_str_to_value_DEPENDENCIES) @rm -f test_str_to_value$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_to_value_OBJECTS) $(test_str_to_value_LDADD) $(LIBS) test_str_token$(EXEEXT): $(test_str_token_OBJECTS) $(test_str_token_DEPENDENCIES) $(EXTRA_test_str_token_DEPENDENCIES) @rm -f test_str_token$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_token_OBJECTS) $(test_str_token_LDADD) $(LIBS) test_str_token_remove$(EXEEXT): $(test_str_token_remove_OBJECTS) $(test_str_token_remove_DEPENDENCIES) $(EXTRA_test_str_token_remove_DEPENDENCIES) @rm -f test_str_token_remove$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_token_remove_OBJECTS) $(test_str_token_remove_LDADD) $(LIBS) test_str_tokens_remove$(EXEEXT): $(test_str_tokens_remove_OBJECTS) $(test_str_tokens_remove_DEPENDENCIES) $(EXTRA_test_str_tokens_remove_DEPENDENCIES) @rm -f test_str_tokens_remove$(EXEEXT) $(AM_V_CCLD)$(LINK) $(test_str_tokens_remove_OBJECTS) $(test_str_tokens_remove_LDADD) $(LIBS) test_upgrade$(EXEEXT): $(test_upgrade_OBJECTS) $(test_upgrade_DEPENDENCIES) $(EXTRA_test_upgrade_DEPENDENCIES) @rm -f test_upgrade$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_LINK) $(test_upgrade_OBJECTS) $(test_upgrade_LDADD) $(LIBS) test_upgrade_large$(EXEEXT): $(test_upgrade_large_OBJECTS) $(test_upgrade_large_DEPENDENCIES) $(EXTRA_test_upgrade_large_DEPENDENCIES) @rm -f test_upgrade_large$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_large_LINK) $(test_upgrade_large_OBJECTS) $(test_upgrade_large_LDADD) $(LIBS) test_upgrade_large_tls$(EXEEXT): $(test_upgrade_large_tls_OBJECTS) $(test_upgrade_large_tls_DEPENDENCIES) $(EXTRA_test_upgrade_large_tls_DEPENDENCIES) @rm -f test_upgrade_large_tls$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_large_tls_LINK) $(test_upgrade_large_tls_OBJECTS) $(test_upgrade_large_tls_LDADD) $(LIBS) test_upgrade_tls$(EXEEXT): $(test_upgrade_tls_OBJECTS) $(test_upgrade_tls_DEPENDENCIES) $(EXTRA_test_upgrade_tls_DEPENDENCIES) @rm -f test_upgrade_tls$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_tls_LINK) $(test_upgrade_tls_OBJECTS) $(test_upgrade_tls_LDADD) $(LIBS) test_upgrade_vlarge$(EXEEXT): $(test_upgrade_vlarge_OBJECTS) $(test_upgrade_vlarge_DEPENDENCIES) $(EXTRA_test_upgrade_vlarge_DEPENDENCIES) @rm -f test_upgrade_vlarge$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_vlarge_LINK) $(test_upgrade_vlarge_OBJECTS) $(test_upgrade_vlarge_LDADD) $(LIBS) test_upgrade_vlarge_tls$(EXEEXT): $(test_upgrade_vlarge_tls_OBJECTS) $(test_upgrade_vlarge_tls_DEPENDENCIES) $(EXTRA_test_upgrade_vlarge_tls_DEPENDENCIES) @rm -f test_upgrade_vlarge_tls$(EXEEXT) $(AM_V_CCLD)$(test_upgrade_vlarge_tls_LINK) $(test_upgrade_vlarge_tls_OBJECTS) $(test_upgrade_vlarge_tls_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-basicauth.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-connection.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-connection_https.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-daemon.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-digestauth.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-gen_auth.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-internal.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-md5.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-md5_ext.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-memorypool.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_compat.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_itc.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_panic.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_send.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_sockets.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_str.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-mhd_threads.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-postprocessor.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-response.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-sha256.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-sha256_ext.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-sha512_256.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmicrohttpd_la-tsearch.Plo@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd_opt_matrix.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mhd_str.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/reason_phrase.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sha1.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sha512_256.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_auth_parse-gen_auth.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_auth_parse-mhd_str.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_auth_parse-test_auth_parse.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_chunked_ext.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_client_put_stop.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_daemon.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_dauth_malformed.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_dauth_userdigest.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_dauth_userhash.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_http_reasons.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_md5-md5.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_md5-md5_ext.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_md5-test_md5.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_mhd_version.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_option_matrix.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_options.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor-test_postprocessor.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_md-internal.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_md-mhd_panic.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_md-mhd_str.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_md-postprocessor.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_raw_requests.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_response_entries.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_rq_shift_back.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_set_panic.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sha1.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sha256-sha256.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sha256-sha256_ext.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sha256-test_sha256.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_sha512_256.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_shutdown_select-test_shutdown_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_start_stop.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_base64.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_bin_hex.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_pct.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_quote.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_token.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_token_remove.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_str_tokens_remove.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade-test_upgrade.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade_large-test_upgrade.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade_tls-test_upgrade.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po@am__quote@ # am--include-marker @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po@am__quote@ # am--include-marker $(am__depfiles_remade): @$(MKDIR_P) $(@D) @: >>$@ am--depfiles: $(am__depfiles_remade) .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< libmicrohttpd_la-connection.lo: connection.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-connection.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-connection.Tpo -c -o libmicrohttpd_la-connection.lo `test -f 'connection.c' || echo '$(srcdir)/'`connection.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-connection.Tpo $(DEPDIR)/libmicrohttpd_la-connection.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='connection.c' object='libmicrohttpd_la-connection.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-connection.lo `test -f 'connection.c' || echo '$(srcdir)/'`connection.c libmicrohttpd_la-reason_phrase.lo: reason_phrase.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-reason_phrase.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-reason_phrase.Tpo -c -o libmicrohttpd_la-reason_phrase.lo `test -f 'reason_phrase.c' || echo '$(srcdir)/'`reason_phrase.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-reason_phrase.Tpo $(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='reason_phrase.c' object='libmicrohttpd_la-reason_phrase.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-reason_phrase.lo `test -f 'reason_phrase.c' || echo '$(srcdir)/'`reason_phrase.c libmicrohttpd_la-daemon.lo: daemon.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-daemon.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-daemon.Tpo -c -o libmicrohttpd_la-daemon.lo `test -f 'daemon.c' || echo '$(srcdir)/'`daemon.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-daemon.Tpo $(DEPDIR)/libmicrohttpd_la-daemon.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='daemon.c' object='libmicrohttpd_la-daemon.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-daemon.lo `test -f 'daemon.c' || echo '$(srcdir)/'`daemon.c libmicrohttpd_la-internal.lo: internal.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-internal.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-internal.Tpo -c -o libmicrohttpd_la-internal.lo `test -f 'internal.c' || echo '$(srcdir)/'`internal.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-internal.Tpo $(DEPDIR)/libmicrohttpd_la-internal.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='internal.c' object='libmicrohttpd_la-internal.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-internal.lo `test -f 'internal.c' || echo '$(srcdir)/'`internal.c libmicrohttpd_la-memorypool.lo: memorypool.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-memorypool.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-memorypool.Tpo -c -o libmicrohttpd_la-memorypool.lo `test -f 'memorypool.c' || echo '$(srcdir)/'`memorypool.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-memorypool.Tpo $(DEPDIR)/libmicrohttpd_la-memorypool.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='memorypool.c' object='libmicrohttpd_la-memorypool.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-memorypool.lo `test -f 'memorypool.c' || echo '$(srcdir)/'`memorypool.c libmicrohttpd_la-mhd_mono_clock.lo: mhd_mono_clock.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_mono_clock.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Tpo -c -o libmicrohttpd_la-mhd_mono_clock.lo `test -f 'mhd_mono_clock.c' || echo '$(srcdir)/'`mhd_mono_clock.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_mono_clock.c' object='libmicrohttpd_la-mhd_mono_clock.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_mono_clock.lo `test -f 'mhd_mono_clock.c' || echo '$(srcdir)/'`mhd_mono_clock.c libmicrohttpd_la-mhd_str.lo: mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_str.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_str.Tpo -c -o libmicrohttpd_la-mhd_str.lo `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_str.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_str.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_str.c' object='libmicrohttpd_la-mhd_str.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_str.lo `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c libmicrohttpd_la-mhd_send.lo: mhd_send.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_send.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_send.Tpo -c -o libmicrohttpd_la-mhd_send.lo `test -f 'mhd_send.c' || echo '$(srcdir)/'`mhd_send.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_send.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_send.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_send.c' object='libmicrohttpd_la-mhd_send.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_send.lo `test -f 'mhd_send.c' || echo '$(srcdir)/'`mhd_send.c libmicrohttpd_la-mhd_sockets.lo: mhd_sockets.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_sockets.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_sockets.Tpo -c -o libmicrohttpd_la-mhd_sockets.lo `test -f 'mhd_sockets.c' || echo '$(srcdir)/'`mhd_sockets.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_sockets.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_sockets.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_sockets.c' object='libmicrohttpd_la-mhd_sockets.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_sockets.lo `test -f 'mhd_sockets.c' || echo '$(srcdir)/'`mhd_sockets.c libmicrohttpd_la-mhd_itc.lo: mhd_itc.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_itc.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_itc.Tpo -c -o libmicrohttpd_la-mhd_itc.lo `test -f 'mhd_itc.c' || echo '$(srcdir)/'`mhd_itc.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_itc.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_itc.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_itc.c' object='libmicrohttpd_la-mhd_itc.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_itc.lo `test -f 'mhd_itc.c' || echo '$(srcdir)/'`mhd_itc.c libmicrohttpd_la-mhd_compat.lo: mhd_compat.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_compat.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_compat.Tpo -c -o libmicrohttpd_la-mhd_compat.lo `test -f 'mhd_compat.c' || echo '$(srcdir)/'`mhd_compat.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_compat.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_compat.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_compat.c' object='libmicrohttpd_la-mhd_compat.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_compat.lo `test -f 'mhd_compat.c' || echo '$(srcdir)/'`mhd_compat.c libmicrohttpd_la-mhd_panic.lo: mhd_panic.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_panic.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_panic.Tpo -c -o libmicrohttpd_la-mhd_panic.lo `test -f 'mhd_panic.c' || echo '$(srcdir)/'`mhd_panic.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_panic.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_panic.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_panic.c' object='libmicrohttpd_la-mhd_panic.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_panic.lo `test -f 'mhd_panic.c' || echo '$(srcdir)/'`mhd_panic.c libmicrohttpd_la-response.lo: response.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-response.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-response.Tpo -c -o libmicrohttpd_la-response.lo `test -f 'response.c' || echo '$(srcdir)/'`response.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-response.Tpo $(DEPDIR)/libmicrohttpd_la-response.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='response.c' object='libmicrohttpd_la-response.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-response.lo `test -f 'response.c' || echo '$(srcdir)/'`response.c libmicrohttpd_la-mhd_threads.lo: mhd_threads.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-mhd_threads.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-mhd_threads.Tpo -c -o libmicrohttpd_la-mhd_threads.lo `test -f 'mhd_threads.c' || echo '$(srcdir)/'`mhd_threads.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-mhd_threads.Tpo $(DEPDIR)/libmicrohttpd_la-mhd_threads.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_threads.c' object='libmicrohttpd_la-mhd_threads.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-mhd_threads.lo `test -f 'mhd_threads.c' || echo '$(srcdir)/'`mhd_threads.c libmicrohttpd_la-sysfdsetsize.lo: sysfdsetsize.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-sysfdsetsize.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Tpo -c -o libmicrohttpd_la-sysfdsetsize.lo `test -f 'sysfdsetsize.c' || echo '$(srcdir)/'`sysfdsetsize.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Tpo $(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sysfdsetsize.c' object='libmicrohttpd_la-sysfdsetsize.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-sysfdsetsize.lo `test -f 'sysfdsetsize.c' || echo '$(srcdir)/'`sysfdsetsize.c libmicrohttpd_la-tsearch.lo: tsearch.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-tsearch.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-tsearch.Tpo -c -o libmicrohttpd_la-tsearch.lo `test -f 'tsearch.c' || echo '$(srcdir)/'`tsearch.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-tsearch.Tpo $(DEPDIR)/libmicrohttpd_la-tsearch.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='tsearch.c' object='libmicrohttpd_la-tsearch.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-tsearch.lo `test -f 'tsearch.c' || echo '$(srcdir)/'`tsearch.c libmicrohttpd_la-postprocessor.lo: postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-postprocessor.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-postprocessor.Tpo -c -o libmicrohttpd_la-postprocessor.lo `test -f 'postprocessor.c' || echo '$(srcdir)/'`postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-postprocessor.Tpo $(DEPDIR)/libmicrohttpd_la-postprocessor.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='postprocessor.c' object='libmicrohttpd_la-postprocessor.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-postprocessor.lo `test -f 'postprocessor.c' || echo '$(srcdir)/'`postprocessor.c libmicrohttpd_la-gen_auth.lo: gen_auth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-gen_auth.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-gen_auth.Tpo -c -o libmicrohttpd_la-gen_auth.lo `test -f 'gen_auth.c' || echo '$(srcdir)/'`gen_auth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-gen_auth.Tpo $(DEPDIR)/libmicrohttpd_la-gen_auth.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='gen_auth.c' object='libmicrohttpd_la-gen_auth.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-gen_auth.lo `test -f 'gen_auth.c' || echo '$(srcdir)/'`gen_auth.c libmicrohttpd_la-digestauth.lo: digestauth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-digestauth.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-digestauth.Tpo -c -o libmicrohttpd_la-digestauth.lo `test -f 'digestauth.c' || echo '$(srcdir)/'`digestauth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-digestauth.Tpo $(DEPDIR)/libmicrohttpd_la-digestauth.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='digestauth.c' object='libmicrohttpd_la-digestauth.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-digestauth.lo `test -f 'digestauth.c' || echo '$(srcdir)/'`digestauth.c libmicrohttpd_la-md5.lo: md5.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-md5.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-md5.Tpo -c -o libmicrohttpd_la-md5.lo `test -f 'md5.c' || echo '$(srcdir)/'`md5.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-md5.Tpo $(DEPDIR)/libmicrohttpd_la-md5.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5.c' object='libmicrohttpd_la-md5.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-md5.lo `test -f 'md5.c' || echo '$(srcdir)/'`md5.c libmicrohttpd_la-md5_ext.lo: md5_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-md5_ext.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-md5_ext.Tpo -c -o libmicrohttpd_la-md5_ext.lo `test -f 'md5_ext.c' || echo '$(srcdir)/'`md5_ext.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-md5_ext.Tpo $(DEPDIR)/libmicrohttpd_la-md5_ext.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5_ext.c' object='libmicrohttpd_la-md5_ext.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-md5_ext.lo `test -f 'md5_ext.c' || echo '$(srcdir)/'`md5_ext.c libmicrohttpd_la-sha256.lo: sha256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-sha256.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-sha256.Tpo -c -o libmicrohttpd_la-sha256.lo `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-sha256.Tpo $(DEPDIR)/libmicrohttpd_la-sha256.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256.c' object='libmicrohttpd_la-sha256.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-sha256.lo `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c libmicrohttpd_la-sha256_ext.lo: sha256_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-sha256_ext.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-sha256_ext.Tpo -c -o libmicrohttpd_la-sha256_ext.lo `test -f 'sha256_ext.c' || echo '$(srcdir)/'`sha256_ext.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-sha256_ext.Tpo $(DEPDIR)/libmicrohttpd_la-sha256_ext.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256_ext.c' object='libmicrohttpd_la-sha256_ext.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-sha256_ext.lo `test -f 'sha256_ext.c' || echo '$(srcdir)/'`sha256_ext.c libmicrohttpd_la-sha512_256.lo: sha512_256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-sha512_256.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-sha512_256.Tpo -c -o libmicrohttpd_la-sha512_256.lo `test -f 'sha512_256.c' || echo '$(srcdir)/'`sha512_256.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-sha512_256.Tpo $(DEPDIR)/libmicrohttpd_la-sha512_256.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha512_256.c' object='libmicrohttpd_la-sha512_256.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-sha512_256.lo `test -f 'sha512_256.c' || echo '$(srcdir)/'`sha512_256.c libmicrohttpd_la-basicauth.lo: basicauth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-basicauth.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-basicauth.Tpo -c -o libmicrohttpd_la-basicauth.lo `test -f 'basicauth.c' || echo '$(srcdir)/'`basicauth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-basicauth.Tpo $(DEPDIR)/libmicrohttpd_la-basicauth.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='basicauth.c' object='libmicrohttpd_la-basicauth.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-basicauth.lo `test -f 'basicauth.c' || echo '$(srcdir)/'`basicauth.c libmicrohttpd_la-connection_https.lo: connection_https.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -MT libmicrohttpd_la-connection_https.lo -MD -MP -MF $(DEPDIR)/libmicrohttpd_la-connection_https.Tpo -c -o libmicrohttpd_la-connection_https.lo `test -f 'connection_https.c' || echo '$(srcdir)/'`connection_https.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libmicrohttpd_la-connection_https.Tpo $(DEPDIR)/libmicrohttpd_la-connection_https.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='connection_https.c' object='libmicrohttpd_la-connection_https.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) $(libmicrohttpd_la_CFLAGS) $(CFLAGS) -c -o libmicrohttpd_la-connection_https.lo `test -f 'connection_https.c' || echo '$(srcdir)/'`connection_https.c test_auth_parse-test_auth_parse.o: test_auth_parse.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-test_auth_parse.o -MD -MP -MF $(DEPDIR)/test_auth_parse-test_auth_parse.Tpo -c -o test_auth_parse-test_auth_parse.o `test -f 'test_auth_parse.c' || echo '$(srcdir)/'`test_auth_parse.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-test_auth_parse.Tpo $(DEPDIR)/test_auth_parse-test_auth_parse.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_auth_parse.c' object='test_auth_parse-test_auth_parse.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-test_auth_parse.o `test -f 'test_auth_parse.c' || echo '$(srcdir)/'`test_auth_parse.c test_auth_parse-test_auth_parse.obj: test_auth_parse.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-test_auth_parse.obj -MD -MP -MF $(DEPDIR)/test_auth_parse-test_auth_parse.Tpo -c -o test_auth_parse-test_auth_parse.obj `if test -f 'test_auth_parse.c'; then $(CYGPATH_W) 'test_auth_parse.c'; else $(CYGPATH_W) '$(srcdir)/test_auth_parse.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-test_auth_parse.Tpo $(DEPDIR)/test_auth_parse-test_auth_parse.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_auth_parse.c' object='test_auth_parse-test_auth_parse.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-test_auth_parse.obj `if test -f 'test_auth_parse.c'; then $(CYGPATH_W) 'test_auth_parse.c'; else $(CYGPATH_W) '$(srcdir)/test_auth_parse.c'; fi` test_auth_parse-gen_auth.o: gen_auth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-gen_auth.o -MD -MP -MF $(DEPDIR)/test_auth_parse-gen_auth.Tpo -c -o test_auth_parse-gen_auth.o `test -f 'gen_auth.c' || echo '$(srcdir)/'`gen_auth.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-gen_auth.Tpo $(DEPDIR)/test_auth_parse-gen_auth.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='gen_auth.c' object='test_auth_parse-gen_auth.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-gen_auth.o `test -f 'gen_auth.c' || echo '$(srcdir)/'`gen_auth.c test_auth_parse-gen_auth.obj: gen_auth.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-gen_auth.obj -MD -MP -MF $(DEPDIR)/test_auth_parse-gen_auth.Tpo -c -o test_auth_parse-gen_auth.obj `if test -f 'gen_auth.c'; then $(CYGPATH_W) 'gen_auth.c'; else $(CYGPATH_W) '$(srcdir)/gen_auth.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-gen_auth.Tpo $(DEPDIR)/test_auth_parse-gen_auth.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='gen_auth.c' object='test_auth_parse-gen_auth.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-gen_auth.obj `if test -f 'gen_auth.c'; then $(CYGPATH_W) 'gen_auth.c'; else $(CYGPATH_W) '$(srcdir)/gen_auth.c'; fi` test_auth_parse-mhd_str.o: mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-mhd_str.o -MD -MP -MF $(DEPDIR)/test_auth_parse-mhd_str.Tpo -c -o test_auth_parse-mhd_str.o `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-mhd_str.Tpo $(DEPDIR)/test_auth_parse-mhd_str.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_str.c' object='test_auth_parse-mhd_str.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-mhd_str.o `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c test_auth_parse-mhd_str.obj: mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_auth_parse-mhd_str.obj -MD -MP -MF $(DEPDIR)/test_auth_parse-mhd_str.Tpo -c -o test_auth_parse-mhd_str.obj `if test -f 'mhd_str.c'; then $(CYGPATH_W) 'mhd_str.c'; else $(CYGPATH_W) '$(srcdir)/mhd_str.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_auth_parse-mhd_str.Tpo $(DEPDIR)/test_auth_parse-mhd_str.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_str.c' object='test_auth_parse-mhd_str.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_auth_parse_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_auth_parse-mhd_str.obj `if test -f 'mhd_str.c'; then $(CYGPATH_W) 'mhd_str.c'; else $(CYGPATH_W) '$(srcdir)/mhd_str.c'; fi` test_md5-test_md5.o: test_md5.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-test_md5.o -MD -MP -MF $(DEPDIR)/test_md5-test_md5.Tpo -c -o test_md5-test_md5.o `test -f 'test_md5.c' || echo '$(srcdir)/'`test_md5.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-test_md5.Tpo $(DEPDIR)/test_md5-test_md5.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_md5.c' object='test_md5-test_md5.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-test_md5.o `test -f 'test_md5.c' || echo '$(srcdir)/'`test_md5.c test_md5-test_md5.obj: test_md5.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-test_md5.obj -MD -MP -MF $(DEPDIR)/test_md5-test_md5.Tpo -c -o test_md5-test_md5.obj `if test -f 'test_md5.c'; then $(CYGPATH_W) 'test_md5.c'; else $(CYGPATH_W) '$(srcdir)/test_md5.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-test_md5.Tpo $(DEPDIR)/test_md5-test_md5.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_md5.c' object='test_md5-test_md5.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-test_md5.obj `if test -f 'test_md5.c'; then $(CYGPATH_W) 'test_md5.c'; else $(CYGPATH_W) '$(srcdir)/test_md5.c'; fi` test_md5-md5.o: md5.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-md5.o -MD -MP -MF $(DEPDIR)/test_md5-md5.Tpo -c -o test_md5-md5.o `test -f 'md5.c' || echo '$(srcdir)/'`md5.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-md5.Tpo $(DEPDIR)/test_md5-md5.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5.c' object='test_md5-md5.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-md5.o `test -f 'md5.c' || echo '$(srcdir)/'`md5.c test_md5-md5.obj: md5.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-md5.obj -MD -MP -MF $(DEPDIR)/test_md5-md5.Tpo -c -o test_md5-md5.obj `if test -f 'md5.c'; then $(CYGPATH_W) 'md5.c'; else $(CYGPATH_W) '$(srcdir)/md5.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-md5.Tpo $(DEPDIR)/test_md5-md5.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5.c' object='test_md5-md5.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-md5.obj `if test -f 'md5.c'; then $(CYGPATH_W) 'md5.c'; else $(CYGPATH_W) '$(srcdir)/md5.c'; fi` test_md5-md5_ext.o: md5_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-md5_ext.o -MD -MP -MF $(DEPDIR)/test_md5-md5_ext.Tpo -c -o test_md5-md5_ext.o `test -f 'md5_ext.c' || echo '$(srcdir)/'`md5_ext.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-md5_ext.Tpo $(DEPDIR)/test_md5-md5_ext.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5_ext.c' object='test_md5-md5_ext.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-md5_ext.o `test -f 'md5_ext.c' || echo '$(srcdir)/'`md5_ext.c test_md5-md5_ext.obj: md5_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -MT test_md5-md5_ext.obj -MD -MP -MF $(DEPDIR)/test_md5-md5_ext.Tpo -c -o test_md5-md5_ext.obj `if test -f 'md5_ext.c'; then $(CYGPATH_W) 'md5_ext.c'; else $(CYGPATH_W) '$(srcdir)/md5_ext.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_md5-md5_ext.Tpo $(DEPDIR)/test_md5-md5_ext.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='md5_ext.c' object='test_md5-md5_ext.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_md5_CPPFLAGS) $(CPPFLAGS) $(test_md5_CFLAGS) $(CFLAGS) -c -o test_md5-md5_ext.obj `if test -f 'md5_ext.c'; then $(CYGPATH_W) 'md5_ext.c'; else $(CYGPATH_W) '$(srcdir)/md5_ext.c'; fi` test_postprocessor-test_postprocessor.o: test_postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_CFLAGS) $(CFLAGS) -MT test_postprocessor-test_postprocessor.o -MD -MP -MF $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo -c -o test_postprocessor-test_postprocessor.o `test -f 'test_postprocessor.c' || echo '$(srcdir)/'`test_postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo $(DEPDIR)/test_postprocessor-test_postprocessor.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor.c' object='test_postprocessor-test_postprocessor.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_CFLAGS) $(CFLAGS) -c -o test_postprocessor-test_postprocessor.o `test -f 'test_postprocessor.c' || echo '$(srcdir)/'`test_postprocessor.c test_postprocessor-test_postprocessor.obj: test_postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_CFLAGS) $(CFLAGS) -MT test_postprocessor-test_postprocessor.obj -MD -MP -MF $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo -c -o test_postprocessor-test_postprocessor.obj `if test -f 'test_postprocessor.c'; then $(CYGPATH_W) 'test_postprocessor.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor-test_postprocessor.Tpo $(DEPDIR)/test_postprocessor-test_postprocessor.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor.c' object='test_postprocessor-test_postprocessor.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_CFLAGS) $(CFLAGS) -c -o test_postprocessor-test_postprocessor.obj `if test -f 'test_postprocessor.c'; then $(CYGPATH_W) 'test_postprocessor.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor.c'; fi` test_postprocessor_amp-test_postprocessor_amp.o: test_postprocessor_amp.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_amp_CFLAGS) $(CFLAGS) -MT test_postprocessor_amp-test_postprocessor_amp.o -MD -MP -MF $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo -c -o test_postprocessor_amp-test_postprocessor_amp.o `test -f 'test_postprocessor_amp.c' || echo '$(srcdir)/'`test_postprocessor_amp.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_amp.c' object='test_postprocessor_amp-test_postprocessor_amp.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_amp_CFLAGS) $(CFLAGS) -c -o test_postprocessor_amp-test_postprocessor_amp.o `test -f 'test_postprocessor_amp.c' || echo '$(srcdir)/'`test_postprocessor_amp.c test_postprocessor_amp-test_postprocessor_amp.obj: test_postprocessor_amp.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_amp_CFLAGS) $(CFLAGS) -MT test_postprocessor_amp-test_postprocessor_amp.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo -c -o test_postprocessor_amp-test_postprocessor_amp.obj `if test -f 'test_postprocessor_amp.c'; then $(CYGPATH_W) 'test_postprocessor_amp.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_amp.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Tpo $(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_amp.c' object='test_postprocessor_amp-test_postprocessor_amp.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_amp_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_amp_CFLAGS) $(CFLAGS) -c -o test_postprocessor_amp-test_postprocessor_amp.obj `if test -f 'test_postprocessor_amp.c'; then $(CYGPATH_W) 'test_postprocessor_amp.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_amp.c'; fi` test_postprocessor_large-test_postprocessor_large.o: test_postprocessor_large.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_large_CFLAGS) $(CFLAGS) -MT test_postprocessor_large-test_postprocessor_large.o -MD -MP -MF $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo -c -o test_postprocessor_large-test_postprocessor_large.o `test -f 'test_postprocessor_large.c' || echo '$(srcdir)/'`test_postprocessor_large.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_large.c' object='test_postprocessor_large-test_postprocessor_large.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_large_CFLAGS) $(CFLAGS) -c -o test_postprocessor_large-test_postprocessor_large.o `test -f 'test_postprocessor_large.c' || echo '$(srcdir)/'`test_postprocessor_large.c test_postprocessor_large-test_postprocessor_large.obj: test_postprocessor_large.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_large_CFLAGS) $(CFLAGS) -MT test_postprocessor_large-test_postprocessor_large.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo -c -o test_postprocessor_large-test_postprocessor_large.obj `if test -f 'test_postprocessor_large.c'; then $(CYGPATH_W) 'test_postprocessor_large.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_large.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Tpo $(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_large.c' object='test_postprocessor_large-test_postprocessor_large.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_large_CPPFLAGS) $(CPPFLAGS) $(test_postprocessor_large_CFLAGS) $(CFLAGS) -c -o test_postprocessor_large-test_postprocessor_large.obj `if test -f 'test_postprocessor_large.c'; then $(CYGPATH_W) 'test_postprocessor_large.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_large.c'; fi` test_postprocessor_md-test_postprocessor_md.o: test_postprocessor_md.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-test_postprocessor_md.o -MD -MP -MF $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Tpo -c -o test_postprocessor_md-test_postprocessor_md.o `test -f 'test_postprocessor_md.c' || echo '$(srcdir)/'`test_postprocessor_md.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Tpo $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_md.c' object='test_postprocessor_md-test_postprocessor_md.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-test_postprocessor_md.o `test -f 'test_postprocessor_md.c' || echo '$(srcdir)/'`test_postprocessor_md.c test_postprocessor_md-test_postprocessor_md.obj: test_postprocessor_md.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-test_postprocessor_md.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Tpo -c -o test_postprocessor_md-test_postprocessor_md.obj `if test -f 'test_postprocessor_md.c'; then $(CYGPATH_W) 'test_postprocessor_md.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_md.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Tpo $(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_postprocessor_md.c' object='test_postprocessor_md-test_postprocessor_md.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-test_postprocessor_md.obj `if test -f 'test_postprocessor_md.c'; then $(CYGPATH_W) 'test_postprocessor_md.c'; else $(CYGPATH_W) '$(srcdir)/test_postprocessor_md.c'; fi` test_postprocessor_md-postprocessor.o: postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-postprocessor.o -MD -MP -MF $(DEPDIR)/test_postprocessor_md-postprocessor.Tpo -c -o test_postprocessor_md-postprocessor.o `test -f 'postprocessor.c' || echo '$(srcdir)/'`postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-postprocessor.Tpo $(DEPDIR)/test_postprocessor_md-postprocessor.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='postprocessor.c' object='test_postprocessor_md-postprocessor.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-postprocessor.o `test -f 'postprocessor.c' || echo '$(srcdir)/'`postprocessor.c test_postprocessor_md-postprocessor.obj: postprocessor.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-postprocessor.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_md-postprocessor.Tpo -c -o test_postprocessor_md-postprocessor.obj `if test -f 'postprocessor.c'; then $(CYGPATH_W) 'postprocessor.c'; else $(CYGPATH_W) '$(srcdir)/postprocessor.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-postprocessor.Tpo $(DEPDIR)/test_postprocessor_md-postprocessor.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='postprocessor.c' object='test_postprocessor_md-postprocessor.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-postprocessor.obj `if test -f 'postprocessor.c'; then $(CYGPATH_W) 'postprocessor.c'; else $(CYGPATH_W) '$(srcdir)/postprocessor.c'; fi` test_postprocessor_md-internal.o: internal.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-internal.o -MD -MP -MF $(DEPDIR)/test_postprocessor_md-internal.Tpo -c -o test_postprocessor_md-internal.o `test -f 'internal.c' || echo '$(srcdir)/'`internal.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-internal.Tpo $(DEPDIR)/test_postprocessor_md-internal.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='internal.c' object='test_postprocessor_md-internal.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-internal.o `test -f 'internal.c' || echo '$(srcdir)/'`internal.c test_postprocessor_md-internal.obj: internal.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-internal.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_md-internal.Tpo -c -o test_postprocessor_md-internal.obj `if test -f 'internal.c'; then $(CYGPATH_W) 'internal.c'; else $(CYGPATH_W) '$(srcdir)/internal.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-internal.Tpo $(DEPDIR)/test_postprocessor_md-internal.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='internal.c' object='test_postprocessor_md-internal.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-internal.obj `if test -f 'internal.c'; then $(CYGPATH_W) 'internal.c'; else $(CYGPATH_W) '$(srcdir)/internal.c'; fi` test_postprocessor_md-mhd_str.o: mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-mhd_str.o -MD -MP -MF $(DEPDIR)/test_postprocessor_md-mhd_str.Tpo -c -o test_postprocessor_md-mhd_str.o `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-mhd_str.Tpo $(DEPDIR)/test_postprocessor_md-mhd_str.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_str.c' object='test_postprocessor_md-mhd_str.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-mhd_str.o `test -f 'mhd_str.c' || echo '$(srcdir)/'`mhd_str.c test_postprocessor_md-mhd_str.obj: mhd_str.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-mhd_str.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_md-mhd_str.Tpo -c -o test_postprocessor_md-mhd_str.obj `if test -f 'mhd_str.c'; then $(CYGPATH_W) 'mhd_str.c'; else $(CYGPATH_W) '$(srcdir)/mhd_str.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-mhd_str.Tpo $(DEPDIR)/test_postprocessor_md-mhd_str.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_str.c' object='test_postprocessor_md-mhd_str.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-mhd_str.obj `if test -f 'mhd_str.c'; then $(CYGPATH_W) 'mhd_str.c'; else $(CYGPATH_W) '$(srcdir)/mhd_str.c'; fi` test_postprocessor_md-mhd_panic.o: mhd_panic.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-mhd_panic.o -MD -MP -MF $(DEPDIR)/test_postprocessor_md-mhd_panic.Tpo -c -o test_postprocessor_md-mhd_panic.o `test -f 'mhd_panic.c' || echo '$(srcdir)/'`mhd_panic.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-mhd_panic.Tpo $(DEPDIR)/test_postprocessor_md-mhd_panic.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_panic.c' object='test_postprocessor_md-mhd_panic.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-mhd_panic.o `test -f 'mhd_panic.c' || echo '$(srcdir)/'`mhd_panic.c test_postprocessor_md-mhd_panic.obj: mhd_panic.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_postprocessor_md-mhd_panic.obj -MD -MP -MF $(DEPDIR)/test_postprocessor_md-mhd_panic.Tpo -c -o test_postprocessor_md-mhd_panic.obj `if test -f 'mhd_panic.c'; then $(CYGPATH_W) 'mhd_panic.c'; else $(CYGPATH_W) '$(srcdir)/mhd_panic.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_postprocessor_md-mhd_panic.Tpo $(DEPDIR)/test_postprocessor_md-mhd_panic.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='mhd_panic.c' object='test_postprocessor_md-mhd_panic.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_postprocessor_md_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_postprocessor_md-mhd_panic.obj `if test -f 'mhd_panic.c'; then $(CYGPATH_W) 'mhd_panic.c'; else $(CYGPATH_W) '$(srcdir)/mhd_panic.c'; fi` test_sha256-test_sha256.o: test_sha256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-test_sha256.o -MD -MP -MF $(DEPDIR)/test_sha256-test_sha256.Tpo -c -o test_sha256-test_sha256.o `test -f 'test_sha256.c' || echo '$(srcdir)/'`test_sha256.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-test_sha256.Tpo $(DEPDIR)/test_sha256-test_sha256.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_sha256.c' object='test_sha256-test_sha256.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-test_sha256.o `test -f 'test_sha256.c' || echo '$(srcdir)/'`test_sha256.c test_sha256-test_sha256.obj: test_sha256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-test_sha256.obj -MD -MP -MF $(DEPDIR)/test_sha256-test_sha256.Tpo -c -o test_sha256-test_sha256.obj `if test -f 'test_sha256.c'; then $(CYGPATH_W) 'test_sha256.c'; else $(CYGPATH_W) '$(srcdir)/test_sha256.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-test_sha256.Tpo $(DEPDIR)/test_sha256-test_sha256.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_sha256.c' object='test_sha256-test_sha256.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-test_sha256.obj `if test -f 'test_sha256.c'; then $(CYGPATH_W) 'test_sha256.c'; else $(CYGPATH_W) '$(srcdir)/test_sha256.c'; fi` test_sha256-sha256.o: sha256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-sha256.o -MD -MP -MF $(DEPDIR)/test_sha256-sha256.Tpo -c -o test_sha256-sha256.o `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-sha256.Tpo $(DEPDIR)/test_sha256-sha256.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256.c' object='test_sha256-sha256.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-sha256.o `test -f 'sha256.c' || echo '$(srcdir)/'`sha256.c test_sha256-sha256.obj: sha256.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-sha256.obj -MD -MP -MF $(DEPDIR)/test_sha256-sha256.Tpo -c -o test_sha256-sha256.obj `if test -f 'sha256.c'; then $(CYGPATH_W) 'sha256.c'; else $(CYGPATH_W) '$(srcdir)/sha256.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-sha256.Tpo $(DEPDIR)/test_sha256-sha256.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256.c' object='test_sha256-sha256.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-sha256.obj `if test -f 'sha256.c'; then $(CYGPATH_W) 'sha256.c'; else $(CYGPATH_W) '$(srcdir)/sha256.c'; fi` test_sha256-sha256_ext.o: sha256_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-sha256_ext.o -MD -MP -MF $(DEPDIR)/test_sha256-sha256_ext.Tpo -c -o test_sha256-sha256_ext.o `test -f 'sha256_ext.c' || echo '$(srcdir)/'`sha256_ext.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-sha256_ext.Tpo $(DEPDIR)/test_sha256-sha256_ext.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256_ext.c' object='test_sha256-sha256_ext.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-sha256_ext.o `test -f 'sha256_ext.c' || echo '$(srcdir)/'`sha256_ext.c test_sha256-sha256_ext.obj: sha256_ext.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -MT test_sha256-sha256_ext.obj -MD -MP -MF $(DEPDIR)/test_sha256-sha256_ext.Tpo -c -o test_sha256-sha256_ext.obj `if test -f 'sha256_ext.c'; then $(CYGPATH_W) 'sha256_ext.c'; else $(CYGPATH_W) '$(srcdir)/sha256_ext.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_sha256-sha256_ext.Tpo $(DEPDIR)/test_sha256-sha256_ext.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='sha256_ext.c' object='test_sha256-sha256_ext.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_sha256_CPPFLAGS) $(CPPFLAGS) $(test_sha256_CFLAGS) $(CFLAGS) -c -o test_sha256-sha256_ext.obj `if test -f 'sha256_ext.c'; then $(CYGPATH_W) 'sha256_ext.c'; else $(CYGPATH_W) '$(srcdir)/sha256_ext.c'; fi` test_shutdown_poll-test_shutdown_select.o: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_CFLAGS) $(CFLAGS) -MT test_shutdown_poll-test_shutdown_select.o -MD -MP -MF $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Tpo -c -o test_shutdown_poll-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_poll-test_shutdown_select.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_CFLAGS) $(CFLAGS) -c -o test_shutdown_poll-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c test_shutdown_poll-test_shutdown_select.obj: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_CFLAGS) $(CFLAGS) -MT test_shutdown_poll-test_shutdown_select.obj -MD -MP -MF $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Tpo -c -o test_shutdown_poll-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_poll-test_shutdown_select.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_CFLAGS) $(CFLAGS) -c -o test_shutdown_poll-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` test_shutdown_poll_ignore-test_shutdown_select.o: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_ignore_CFLAGS) $(CFLAGS) -MT test_shutdown_poll_ignore-test_shutdown_select.o -MD -MP -MF $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Tpo -c -o test_shutdown_poll_ignore-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_poll_ignore-test_shutdown_select.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_ignore_CFLAGS) $(CFLAGS) -c -o test_shutdown_poll_ignore-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c test_shutdown_poll_ignore-test_shutdown_select.obj: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_ignore_CFLAGS) $(CFLAGS) -MT test_shutdown_poll_ignore-test_shutdown_select.obj -MD -MP -MF $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Tpo -c -o test_shutdown_poll_ignore-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_poll_ignore-test_shutdown_select.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_poll_ignore_CFLAGS) $(CFLAGS) -c -o test_shutdown_poll_ignore-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` test_shutdown_select-test_shutdown_select.o: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_CFLAGS) $(CFLAGS) -MT test_shutdown_select-test_shutdown_select.o -MD -MP -MF $(DEPDIR)/test_shutdown_select-test_shutdown_select.Tpo -c -o test_shutdown_select-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_select-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_select-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_select-test_shutdown_select.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_CFLAGS) $(CFLAGS) -c -o test_shutdown_select-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c test_shutdown_select-test_shutdown_select.obj: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_CFLAGS) $(CFLAGS) -MT test_shutdown_select-test_shutdown_select.obj -MD -MP -MF $(DEPDIR)/test_shutdown_select-test_shutdown_select.Tpo -c -o test_shutdown_select-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_select-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_select-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_select-test_shutdown_select.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_CFLAGS) $(CFLAGS) -c -o test_shutdown_select-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` test_shutdown_select_ignore-test_shutdown_select.o: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_ignore_CFLAGS) $(CFLAGS) -MT test_shutdown_select_ignore-test_shutdown_select.o -MD -MP -MF $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Tpo -c -o test_shutdown_select_ignore-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_select_ignore-test_shutdown_select.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_ignore_CFLAGS) $(CFLAGS) -c -o test_shutdown_select_ignore-test_shutdown_select.o `test -f 'test_shutdown_select.c' || echo '$(srcdir)/'`test_shutdown_select.c test_shutdown_select_ignore-test_shutdown_select.obj: test_shutdown_select.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_ignore_CFLAGS) $(CFLAGS) -MT test_shutdown_select_ignore-test_shutdown_select.obj -MD -MP -MF $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Tpo -c -o test_shutdown_select_ignore-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Tpo $(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_shutdown_select.c' object='test_shutdown_select_ignore-test_shutdown_select.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_shutdown_select_ignore_CFLAGS) $(CFLAGS) -c -o test_shutdown_select_ignore-test_shutdown_select.obj `if test -f 'test_shutdown_select.c'; then $(CYGPATH_W) 'test_shutdown_select.c'; else $(CYGPATH_W) '$(srcdir)/test_shutdown_select.c'; fi` test_upgrade-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_CFLAGS) $(CFLAGS) -MT test_upgrade-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade-test_upgrade.Tpo -c -o test_upgrade-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade-test_upgrade.Tpo $(DEPDIR)/test_upgrade-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_CFLAGS) $(CFLAGS) -c -o test_upgrade-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_CFLAGS) $(CFLAGS) -MT test_upgrade-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade-test_upgrade.Tpo -c -o test_upgrade-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade-test_upgrade.Tpo $(DEPDIR)/test_upgrade-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_CFLAGS) $(CFLAGS) -c -o test_upgrade-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` test_upgrade_large-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_CFLAGS) $(CFLAGS) -MT test_upgrade_large-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade_large-test_upgrade.Tpo -c -o test_upgrade_large-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_large-test_upgrade.Tpo $(DEPDIR)/test_upgrade_large-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_large-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_CFLAGS) $(CFLAGS) -c -o test_upgrade_large-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade_large-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_CFLAGS) $(CFLAGS) -MT test_upgrade_large-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade_large-test_upgrade.Tpo -c -o test_upgrade_large-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_large-test_upgrade.Tpo $(DEPDIR)/test_upgrade_large-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_large-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_CFLAGS) $(CFLAGS) -c -o test_upgrade_large-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` test_upgrade_large_tls-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_large_tls-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Tpo -c -o test_upgrade_large_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_large_tls-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_large_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade_large_tls-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_large_tls-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Tpo -c -o test_upgrade_large_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_large_tls-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_large_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_large_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_large_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` test_upgrade_tls-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_tls-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade_tls-test_upgrade.Tpo -c -o test_upgrade_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_tls-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade_tls-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_tls-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade_tls-test_upgrade.Tpo -c -o test_upgrade_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_tls-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` test_upgrade_vlarge-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_CFLAGS) $(CFLAGS) -MT test_upgrade_vlarge-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Tpo -c -o test_upgrade_vlarge-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Tpo $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_vlarge-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_CFLAGS) $(CFLAGS) -c -o test_upgrade_vlarge-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade_vlarge-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_CFLAGS) $(CFLAGS) -MT test_upgrade_vlarge-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Tpo -c -o test_upgrade_vlarge-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Tpo $(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_vlarge-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_CFLAGS) $(CFLAGS) -c -o test_upgrade_vlarge-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` test_upgrade_vlarge_tls-test_upgrade.o: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_vlarge_tls-test_upgrade.o -MD -MP -MF $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Tpo -c -o test_upgrade_vlarge_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_vlarge_tls-test_upgrade.o' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_vlarge_tls-test_upgrade.o `test -f 'test_upgrade.c' || echo '$(srcdir)/'`test_upgrade.c test_upgrade_vlarge_tls-test_upgrade.obj: test_upgrade.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_tls_CFLAGS) $(CFLAGS) -MT test_upgrade_vlarge_tls-test_upgrade.obj -MD -MP -MF $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Tpo -c -o test_upgrade_vlarge_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Tpo $(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test_upgrade.c' object='test_upgrade_vlarge_tls-test_upgrade.obj' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_upgrade_vlarge_tls_CPPFLAGS) $(CPPFLAGS) $(test_upgrade_vlarge_tls_CFLAGS) $(CFLAGS) -c -o test_upgrade_vlarge_tls-test_upgrade.obj `if test -f 'test_upgrade.c'; then $(CYGPATH_W) 'test_upgrade.c'; else $(CYGPATH_W) '$(srcdir)/test_upgrade.c'; fi` mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ elif test -n "$$redo_logs"; then \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ output_system_information () \ { \ echo; \ { uname -a | $(AWK) '{ \ printf "System information (uname -a):"; \ for (i = 1; i < NF; ++i) \ { \ if (i != 2) \ printf " %s", $$i; \ } \ printf "\n"; \ }'; } 2>&1; \ if test -r /etc/os-release; then \ echo "Distribution information (/etc/os-release):"; \ sed 8q /etc/os-release; \ elif test -r /etc/issue; then \ echo "Distribution information (/etc/issue):"; \ cat /etc/issue; \ fi; \ }; \ please_report () \ { \ echo "Some test(s) failed. Please report this to $(PACKAGE_BUGREPORT),"; \ echo "together with the test-suite.log file (gzipped) and your system"; \ echo "information. Thanks."; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ output_system_information; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary"$(AM_TESTSUITE_SUMMARY_HEADER)"$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG) for debugging.$${std}";\ if test -n "$(PACKAGE_BUGREPORT)"; then \ please_report | sed -e "s/^/$${col}/" -e s/'$$'/"$${std}"/; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: $(check_PROGRAMS) @$(am__rm_f) $(RECHECK_LOGS) @$(am__rm_f) $(RECHECK_LOGS:.log=.trs) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @$(am__rm_f) $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? test_str_compare.log: test_str_compare$(EXEEXT) @p='test_str_compare$(EXEEXT)'; \ b='test_str_compare'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_to_value.log: test_str_to_value$(EXEEXT) @p='test_str_to_value$(EXEEXT)'; \ b='test_str_to_value'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_from_value.log: test_str_from_value$(EXEEXT) @p='test_str_from_value$(EXEEXT)'; \ b='test_str_from_value'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_token.log: test_str_token$(EXEEXT) @p='test_str_token$(EXEEXT)'; \ b='test_str_token'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_token_remove.log: test_str_token_remove$(EXEEXT) @p='test_str_token_remove$(EXEEXT)'; \ b='test_str_token_remove'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_tokens_remove.log: test_str_tokens_remove$(EXEEXT) @p='test_str_tokens_remove$(EXEEXT)'; \ b='test_str_tokens_remove'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_pct.log: test_str_pct$(EXEEXT) @p='test_str_pct$(EXEEXT)'; \ b='test_str_pct'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_bin_hex.log: test_str_bin_hex$(EXEEXT) @p='test_str_bin_hex$(EXEEXT)'; \ b='test_str_bin_hex'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_http_reasons.log: test_http_reasons$(EXEEXT) @p='test_http_reasons$(EXEEXT)'; \ b='test_http_reasons'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_sha1.log: test_sha1$(EXEEXT) @p='test_sha1$(EXEEXT)'; \ b='test_sha1'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_start_stop.log: test_start_stop$(EXEEXT) @p='test_start_stop$(EXEEXT)'; \ b='test_start_stop'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_daemon.log: test_daemon$(EXEEXT) @p='test_daemon$(EXEEXT)'; \ b='test_daemon'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_response_entries.log: test_response_entries$(EXEEXT) @p='test_response_entries$(EXEEXT)'; \ b='test_response_entries'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postprocessor_md.log: test_postprocessor_md$(EXEEXT) @p='test_postprocessor_md$(EXEEXT)'; \ b='test_postprocessor_md'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_shutdown.log: test_client_put_shutdown$(EXEEXT) @p='test_client_put_shutdown$(EXEEXT)'; \ b='test_client_put_shutdown'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_close.log: test_client_put_close$(EXEEXT) @p='test_client_put_close$(EXEEXT)'; \ b='test_client_put_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_hard_close.log: test_client_put_hard_close$(EXEEXT) @p='test_client_put_hard_close$(EXEEXT)'; \ b='test_client_put_hard_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_steps_shutdown.log: test_client_put_steps_shutdown$(EXEEXT) @p='test_client_put_steps_shutdown$(EXEEXT)'; \ b='test_client_put_steps_shutdown'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_steps_close.log: test_client_put_steps_close$(EXEEXT) @p='test_client_put_steps_close$(EXEEXT)'; \ b='test_client_put_steps_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_steps_hard_close.log: test_client_put_steps_hard_close$(EXEEXT) @p='test_client_put_steps_hard_close$(EXEEXT)'; \ b='test_client_put_steps_hard_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_shutdown.log: test_client_put_chunked_shutdown$(EXEEXT) @p='test_client_put_chunked_shutdown$(EXEEXT)'; \ b='test_client_put_chunked_shutdown'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_close.log: test_client_put_chunked_close$(EXEEXT) @p='test_client_put_chunked_close$(EXEEXT)'; \ b='test_client_put_chunked_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_hard_close.log: test_client_put_chunked_hard_close$(EXEEXT) @p='test_client_put_chunked_hard_close$(EXEEXT)'; \ b='test_client_put_chunked_hard_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_steps_shutdown.log: test_client_put_chunked_steps_shutdown$(EXEEXT) @p='test_client_put_chunked_steps_shutdown$(EXEEXT)'; \ b='test_client_put_chunked_steps_shutdown'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_steps_close.log: test_client_put_chunked_steps_close$(EXEEXT) @p='test_client_put_chunked_steps_close$(EXEEXT)'; \ b='test_client_put_chunked_steps_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_steps_hard_close.log: test_client_put_chunked_steps_hard_close$(EXEEXT) @p='test_client_put_chunked_steps_hard_close$(EXEEXT)'; \ b='test_client_put_chunked_steps_hard_close'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_options.log: test_options$(EXEEXT) @p='test_options$(EXEEXT)'; \ b='test_options'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_mhd_version.log: test_mhd_version$(EXEEXT) @p='test_mhd_version$(EXEEXT)'; \ b='test_mhd_version'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_set_panic.log: test_set_panic$(EXEEXT) @p='test_set_panic$(EXEEXT)'; \ b='test_set_panic'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_rq_shift_back.log: test_rq_shift_back$(EXEEXT) @p='test_rq_shift_back$(EXEEXT)'; \ b='test_rq_shift_back'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_chunked_ext.log: test_chunked_ext$(EXEEXT) @p='test_chunked_ext$(EXEEXT)'; \ b='test_chunked_ext'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_raw_requests.log: test_raw_requests$(EXEEXT) @p='test_raw_requests$(EXEEXT)'; \ b='test_raw_requests'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_option_matrix.log: test_option_matrix$(EXEEXT) @p='test_option_matrix$(EXEEXT)'; \ b='test_option_matrix'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_md5.log: test_md5$(EXEEXT) @p='test_md5$(EXEEXT)'; \ b='test_md5'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_sha256.log: test_sha256$(EXEEXT) @p='test_sha256$(EXEEXT)'; \ b='test_sha256'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_sha512_256.log: test_sha512_256$(EXEEXT) @p='test_sha512_256$(EXEEXT)'; \ b='test_sha512_256'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade.log: test_upgrade$(EXEEXT) @p='test_upgrade$(EXEEXT)'; \ b='test_upgrade'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade_large.log: test_upgrade_large$(EXEEXT) @p='test_upgrade_large$(EXEEXT)'; \ b='test_upgrade_large'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade_vlarge.log: test_upgrade_vlarge$(EXEEXT) @p='test_upgrade_vlarge$(EXEEXT)'; \ b='test_upgrade_vlarge'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade_tls.log: test_upgrade_tls$(EXEEXT) @p='test_upgrade_tls$(EXEEXT)'; \ b='test_upgrade_tls'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade_large_tls.log: test_upgrade_large_tls$(EXEEXT) @p='test_upgrade_large_tls$(EXEEXT)'; \ b='test_upgrade_large_tls'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_upgrade_vlarge_tls.log: test_upgrade_vlarge_tls$(EXEEXT) @p='test_upgrade_vlarge_tls$(EXEEXT)'; \ b='test_upgrade_vlarge_tls'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postprocessor.log: test_postprocessor$(EXEEXT) @p='test_postprocessor$(EXEEXT)'; \ b='test_postprocessor'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postprocessor_large.log: test_postprocessor_large$(EXEEXT) @p='test_postprocessor_large$(EXEEXT)'; \ b='test_postprocessor_large'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_postprocessor_amp.log: test_postprocessor_amp$(EXEEXT) @p='test_postprocessor_amp$(EXEEXT)'; \ b='test_postprocessor_amp'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_shutdown_select.log: test_shutdown_select$(EXEEXT) @p='test_shutdown_select$(EXEEXT)'; \ b='test_shutdown_select'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_shutdown_poll.log: test_shutdown_poll$(EXEEXT) @p='test_shutdown_poll$(EXEEXT)'; \ b='test_shutdown_poll'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_shutdown_select_ignore.log: test_shutdown_select_ignore$(EXEEXT) @p='test_shutdown_select_ignore$(EXEEXT)'; \ b='test_shutdown_select_ignore'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_shutdown_poll_ignore.log: test_shutdown_poll_ignore$(EXEEXT) @p='test_shutdown_poll_ignore$(EXEEXT)'; \ b='test_shutdown_poll_ignore'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_auth_parse.log: test_auth_parse$(EXEEXT) @p='test_auth_parse$(EXEEXT)'; \ b='test_auth_parse'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_quote.log: test_str_quote$(EXEEXT) @p='test_str_quote$(EXEEXT)'; \ b='test_str_quote'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_dauth_userdigest.log: test_dauth_userdigest$(EXEEXT) @p='test_dauth_userdigest$(EXEEXT)'; \ b='test_dauth_userdigest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_dauth_userhash.log: test_dauth_userhash$(EXEEXT) @p='test_dauth_userhash$(EXEEXT)'; \ b='test_dauth_userhash'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_dauth_malformed.log: test_dauth_malformed$(EXEEXT) @p='test_dauth_malformed$(EXEEXT)'; \ b='test_dauth_malformed'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_str_base64.log: test_str_base64$(EXEEXT) @p='test_str_base64$(EXEEXT)'; \ b='test_str_base64'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_hard_close_stress_os.log: test_client_put_hard_close_stress_os$(EXEEXT) @p='test_client_put_hard_close_stress_os$(EXEEXT)'; \ b='test_client_put_hard_close_stress_os'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_steps_hard_close_stress_os.log: test_client_put_steps_hard_close_stress_os$(EXEEXT) @p='test_client_put_steps_hard_close_stress_os$(EXEEXT)'; \ b='test_client_put_steps_hard_close_stress_os'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) test_client_put_chunked_steps_hard_close_stress_os.log: test_client_put_chunked_steps_hard_close_stress_os$(EXEEXT) @p='test_client_put_chunked_steps_hard_close_stress_os$(EXEEXT)'; \ b='test_client_put_chunked_steps_hard_close_stress_os'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile $(LTLIBRARIES) $(DATA) install-checkPROGRAMS: install-libLTLIBRARIES installdirs: for dir in "$(DESTDIR)$(libdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -$(am__rm_f) $(MOSTLYCLEANFILES) -$(am__rm_f) $(TEST_LOGS) -$(am__rm_f) $(TEST_LOGS:.log=.trs) -$(am__rm_f) $(TEST_SUITE_LOG) clean-generic: distclean-generic: -$(am__rm_f) $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool mostlyclean-am distclean: distclean-am -rm -f ./$(DEPDIR)/libmicrohttpd_la-basicauth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-connection.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-connection_https.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-daemon.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-digestauth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-gen_auth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-internal.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-md5.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-md5_ext.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-memorypool.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_compat.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_itc.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_panic.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_send.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_sockets.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_str.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_threads.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-postprocessor.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-response.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha256.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha256_ext.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha512_256.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-tsearch.Plo -rm -f ./$(DEPDIR)/mhd_opt_matrix.Po -rm -f ./$(DEPDIR)/mhd_str.Po -rm -f ./$(DEPDIR)/reason_phrase.Po -rm -f ./$(DEPDIR)/sha1.Po -rm -f ./$(DEPDIR)/sha512_256.Po -rm -f ./$(DEPDIR)/test_auth_parse-gen_auth.Po -rm -f ./$(DEPDIR)/test_auth_parse-mhd_str.Po -rm -f ./$(DEPDIR)/test_auth_parse-test_auth_parse.Po -rm -f ./$(DEPDIR)/test_chunked_ext.Po -rm -f ./$(DEPDIR)/test_client_put_stop.Po -rm -f ./$(DEPDIR)/test_daemon.Po -rm -f ./$(DEPDIR)/test_dauth_malformed.Po -rm -f ./$(DEPDIR)/test_dauth_userdigest.Po -rm -f ./$(DEPDIR)/test_dauth_userhash.Po -rm -f ./$(DEPDIR)/test_http_reasons.Po -rm -f ./$(DEPDIR)/test_md5-md5.Po -rm -f ./$(DEPDIR)/test_md5-md5_ext.Po -rm -f ./$(DEPDIR)/test_md5-test_md5.Po -rm -f ./$(DEPDIR)/test_mhd_version.Po -rm -f ./$(DEPDIR)/test_option_matrix.Po -rm -f ./$(DEPDIR)/test_options.Po -rm -f ./$(DEPDIR)/test_postprocessor-test_postprocessor.Po -rm -f ./$(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po -rm -f ./$(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-internal.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-mhd_panic.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-mhd_str.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-postprocessor.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po -rm -f ./$(DEPDIR)/test_raw_requests.Po -rm -f ./$(DEPDIR)/test_response_entries.Po -rm -f ./$(DEPDIR)/test_rq_shift_back.Po -rm -f ./$(DEPDIR)/test_set_panic.Po -rm -f ./$(DEPDIR)/test_sha1.Po -rm -f ./$(DEPDIR)/test_sha256-sha256.Po -rm -f ./$(DEPDIR)/test_sha256-sha256_ext.Po -rm -f ./$(DEPDIR)/test_sha256-test_sha256.Po -rm -f ./$(DEPDIR)/test_sha512_256.Po -rm -f ./$(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_select-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_start_stop.Po -rm -f ./$(DEPDIR)/test_str.Po -rm -f ./$(DEPDIR)/test_str_base64.Po -rm -f ./$(DEPDIR)/test_str_bin_hex.Po -rm -f ./$(DEPDIR)/test_str_pct.Po -rm -f ./$(DEPDIR)/test_str_quote.Po -rm -f ./$(DEPDIR)/test_str_token.Po -rm -f ./$(DEPDIR)/test_str_token_remove.Po -rm -f ./$(DEPDIR)/test_str_tokens_remove.Po -rm -f ./$(DEPDIR)/test_upgrade-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_large-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_tls-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f ./$(DEPDIR)/libmicrohttpd_la-basicauth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-connection.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-connection_https.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-daemon.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-digestauth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-gen_auth.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-internal.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-md5.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-md5_ext.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-memorypool.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_compat.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_itc.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_mono_clock.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_panic.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_send.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_sockets.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_str.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-mhd_threads.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-postprocessor.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-reason_phrase.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-response.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha256.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha256_ext.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sha512_256.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-sysfdsetsize.Plo -rm -f ./$(DEPDIR)/libmicrohttpd_la-tsearch.Plo -rm -f ./$(DEPDIR)/mhd_opt_matrix.Po -rm -f ./$(DEPDIR)/mhd_str.Po -rm -f ./$(DEPDIR)/reason_phrase.Po -rm -f ./$(DEPDIR)/sha1.Po -rm -f ./$(DEPDIR)/sha512_256.Po -rm -f ./$(DEPDIR)/test_auth_parse-gen_auth.Po -rm -f ./$(DEPDIR)/test_auth_parse-mhd_str.Po -rm -f ./$(DEPDIR)/test_auth_parse-test_auth_parse.Po -rm -f ./$(DEPDIR)/test_chunked_ext.Po -rm -f ./$(DEPDIR)/test_client_put_stop.Po -rm -f ./$(DEPDIR)/test_daemon.Po -rm -f ./$(DEPDIR)/test_dauth_malformed.Po -rm -f ./$(DEPDIR)/test_dauth_userdigest.Po -rm -f ./$(DEPDIR)/test_dauth_userhash.Po -rm -f ./$(DEPDIR)/test_http_reasons.Po -rm -f ./$(DEPDIR)/test_md5-md5.Po -rm -f ./$(DEPDIR)/test_md5-md5_ext.Po -rm -f ./$(DEPDIR)/test_md5-test_md5.Po -rm -f ./$(DEPDIR)/test_mhd_version.Po -rm -f ./$(DEPDIR)/test_option_matrix.Po -rm -f ./$(DEPDIR)/test_options.Po -rm -f ./$(DEPDIR)/test_postprocessor-test_postprocessor.Po -rm -f ./$(DEPDIR)/test_postprocessor_amp-test_postprocessor_amp.Po -rm -f ./$(DEPDIR)/test_postprocessor_large-test_postprocessor_large.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-internal.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-mhd_panic.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-mhd_str.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-postprocessor.Po -rm -f ./$(DEPDIR)/test_postprocessor_md-test_postprocessor_md.Po -rm -f ./$(DEPDIR)/test_raw_requests.Po -rm -f ./$(DEPDIR)/test_response_entries.Po -rm -f ./$(DEPDIR)/test_rq_shift_back.Po -rm -f ./$(DEPDIR)/test_set_panic.Po -rm -f ./$(DEPDIR)/test_sha1.Po -rm -f ./$(DEPDIR)/test_sha256-sha256.Po -rm -f ./$(DEPDIR)/test_sha256-sha256_ext.Po -rm -f ./$(DEPDIR)/test_sha256-test_sha256.Po -rm -f ./$(DEPDIR)/test_sha512_256.Po -rm -f ./$(DEPDIR)/test_shutdown_poll-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_poll_ignore-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_select-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_shutdown_select_ignore-test_shutdown_select.Po -rm -f ./$(DEPDIR)/test_start_stop.Po -rm -f ./$(DEPDIR)/test_str.Po -rm -f ./$(DEPDIR)/test_str_base64.Po -rm -f ./$(DEPDIR)/test_str_bin_hex.Po -rm -f ./$(DEPDIR)/test_str_pct.Po -rm -f ./$(DEPDIR)/test_str_quote.Po -rm -f ./$(DEPDIR)/test_str_token.Po -rm -f ./$(DEPDIR)/test_str_token_remove.Po -rm -f ./$(DEPDIR)/test_str_tokens_remove.Po -rm -f ./$(DEPDIR)/test_upgrade-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_large-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_large_tls-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_tls-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_vlarge-test_upgrade.Po -rm -f ./$(DEPDIR)/test_upgrade_vlarge_tls-test_upgrade.Po -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-libLTLIBRARIES .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am am--depfiles check check-TESTS \ check-am clean clean-checkPROGRAMS clean-generic \ clean-libLTLIBRARIES clean-libtool cscopelist-am ctags \ ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-libLTLIBRARIES install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am \ uninstall-libLTLIBRARIES .PRECIOUS: Makefile @W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.def: libmicrohttpd.la @W32_SHARED_LIB_EXP_TRUE@ $(AM_V_at)test -f $@ && touch $@ || \ @W32_SHARED_LIB_EXP_TRUE@ ( rm -f libmicrohttpd.la ; $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la && touch $@ ) @USE_EXPORT_FILE_TRUE@@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.exp: $(lt_cv_objdir)/libmicrohttpd.lib @USE_EXPORT_FILE_TRUE@@W32_SHARED_LIB_EXP_TRUE@ $(AM_V_at)test -f $@ && touch $@ || \ @USE_EXPORT_FILE_TRUE@@W32_SHARED_LIB_EXP_TRUE@ ( rm -f $(lt_cv_objdir)/libmicrohttpd.lib ; $(MAKE) $(AM_MAKEFLAGS) $(lt_cv_objdir)/libmicrohttpd.lib && touch $@ ) @USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) @USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@ $(AM_V_LIB) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ @USE_MS_LIB_TOOL_TRUE@@W32_SHARED_LIB_EXP_TRUE@ $(MS_LIB_TOOL) -nologo -def:libmicrohttpd.def -name:$$dll_name -out:libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -ignore:4221 @USE_EXPORT_FILE_TRUE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) @USE_EXPORT_FILE_TRUE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@ $(AM_V_DLLTOOL) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ @USE_EXPORT_FILE_TRUE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@ $(DLLTOOL) -d libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -e ./libmicrohttpd.exp @USE_EXPORT_FILE_FALSE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@$(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la @USE_EXPORT_FILE_FALSE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@ $(AM_V_DLLTOOL) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ @USE_EXPORT_FILE_FALSE@@USE_MS_LIB_TOOL_FALSE@@W32_SHARED_LIB_EXP_TRUE@ $(DLLTOOL) -d libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib @W32_STATIC_LIB_TRUE@$(lt_cv_objdir)/libmicrohttpd-static.lib: libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) @USE_MS_LIB_TOOL_TRUE@@W32_STATIC_LIB_TRUE@ $(AM_V_LIB) $(MS_LIB_TOOL) -nologo -out:$@ $(libmicrohttpd_la_OBJECTS:.lo=.o) @USE_MS_LIB_TOOL_FALSE@@W32_STATIC_LIB_TRUE@ $(AM_V_at)cp $(lt_cv_objdir)/libmicrohttpd.a $@ # General rule is not required, but keep it just in case # Note: windres does not understand '-isystem' flag, so all # possible '-isystem' flags are replaced by simple '-I' flags. .rc.lo: $(AM_V_RC) RC_ALL_CPPFLAGS=`echo ' $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) ' | $(SED) -e 's/ -isystem / -I /g'`; \ $(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_ALL_CPPFLAGS} $< -o $@ # Note: windres does not understand '-isystem' flag, so all # possible '-isystem' flags are replaced by simple '-I' flags. libmicrohttpd_la-microhttpd_dll_res.lo: $(builddir)/microhttpd_dll_res.rc $(AM_V_RC) RC_ALL_CPPFLAGS=`echo ' $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) ' | $(SED) -e 's/ -isystem / -I /g'`; \ $(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_ALL_CPPFLAGS} $(builddir)/microhttpd_dll_res.rc -o $@ update-po-POTFILES.in: $(top_srcdir)/po/POTFILES.in $(top_srcdir)/po/POTFILES.in: $(srcdir)/Makefile.am @echo "Creating $@" @echo src/include/microhttpd.h > "$@" && \ for src in $(am__libmicrohttpd_la_SOURCES_DIST) ; do \ echo "$(subdir)/$$src" >> "$@" ; \ done .PHONY: update-po-POTFILES.in # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: # Tell GNU make to disable its built-in pattern rules. %:: %,v %:: RCS/%,v %:: RCS/% %:: s.% %:: SCCS/s.% libmicrohttpd-1.0.10/src/microhttpd/connection.c0000664000175000017500000107723015232414241015377 /* This file is part of libmicrohttpd Copyright (C) 2007-2020 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2026 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file connection.c * @brief Methods for managing connections * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "internal.h" #include "mhd_limits.h" #include "connection.h" #include "memorypool.h" #include "response.h" #include "mhd_mono_clock.h" #include "mhd_str.h" #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #include "mhd_locks.h" #endif #include "mhd_sockets.h" #include "mhd_compat.h" #include "mhd_itc.h" #ifdef MHD_LINUX_SOLARIS_SENDFILE #include #endif /* MHD_LINUX_SOLARIS_SENDFILE */ #if defined(HAVE_FREEBSD_SENDFILE) || defined(HAVE_DARWIN_SENDFILE) #include #include #include #endif /* HAVE_FREEBSD_SENDFILE || HAVE_DARWIN_SENDFILE */ #ifdef HTTPS_SUPPORT #include "connection_https.h" #endif /* HTTPS_SUPPORT */ #ifdef HAVE_SYS_PARAM_H /* For FreeBSD version identification */ #include #endif /* HAVE_SYS_PARAM_H */ #include "mhd_send.h" #include "mhd_assert.h" #include "mhd_check.h" /** * Get whether bare LF in HTTP header and other protocol elements * should be treated as the line termination depending on the configured * strictness level. * RFC 9112, section 2.2 */ #define MHD_ALLOW_BARE_LF_AS_CRLF_(discp_lvl) (0 >= discp_lvl) /** * The reasonable length of the upload chunk "header" (the size specifier * with optional chunk extension). * MHD tries to keep the space in the read buffer large enough to read * the chunk "header" in one step. * The real "header" could be much larger, it will be handled correctly * anyway, however it may require several rounds of buffer grow. */ #define MHD_CHUNK_HEADER_REASONABLE_LEN 24 /** * Message to transmit when http 1.1 request is received */ #define HTTP_100_CONTINUE "HTTP/1.1 100 Continue\r\n\r\n" /** * Response text used when the request (http header) is too big to * be processed. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_TOO_BIG \ "" \ "Request too big" \ "Request HTTP header is too big for the memory constraints " \ "of this webserver." \ "" #else #define ERR_MSG_REQUEST_TOO_BIG "" #endif /** * Response text used when the request header is too big to be processed. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_HEADER_TOO_BIG \ "" \ "Request too big" \ "

    The total size of the request headers, which includes the " \ "request target and the request field lines, exceeds the memory " \ "constraints of this web server.

    " \ "

    The request could be re-tried with shorter field lines, a shorter " \ "request target or a shorter request method token.

    " \ "" #else #define ERR_MSG_REQUEST_HEADER_TOO_BIG "" #endif /** * Response text used when the request cookie header is too big to be processed. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_HEADER_WITH_COOKIES_TOO_BIG \ "" \ "Request too big" \ "

    The total size of the request headers, which includes the " \ "request target and the request field lines, exceeds the memory " \ "constraints of this web server.

    " \ "

    The request could be re-tried with smaller " \ ""Cookie:" field value, shorter other field lines, " \ "a shorter request target or a shorter request method token.

    " \ "" #else #define ERR_MSG_REQUEST_HEADER_WITH_COOKIES_TOO_BIG "" #endif /** * Response text used when the request chunk size line with chunk extension * cannot fit the buffer. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_CHUNK_LINE_EXT_TOO_BIG \ "" \ "Request too big" \ "

    The total size of the request target, the request field lines " \ "and the chunk size line exceeds the memory constraints of this web " \ "server.

    " \ "

    The request could be re-tried without chunk extensions, with a smaller " \ "chunk size, shorter field lines, a shorter request target or a shorter " \ "request method token.

    " \ "" #else #define ERR_MSG_REQUEST_CHUNK_LINE_EXT_TOO_BIG "" #endif /** * Response text used when the request chunk size line without chunk extension * cannot fit the buffer. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_CHUNK_LINE_TOO_BIG \ "" \ "Request too big" \ "

    The total size of the request target, the request field lines " \ "and the chunk size line exceeds the memory constraints of this web " \ "server.

    " \ "

    The request could be re-tried with a smaller " \ "chunk size, shorter field lines, a shorter request target or a shorter " \ "request method token.

    " \ "" #else #define ERR_MSG_REQUEST_CHUNK_LINE_TOO_BIG "" #endif /** * Response text used when the request header is too big to be processed. */ #ifdef HAVE_MESSAGES #define ERR_MSG_REQUEST_FOOTER_TOO_BIG \ "" \ "Request too big" \ "

    The total size of the request headers, which includes the " \ "request target, the request field lines and the chunked trailer " \ "section exceeds the memory constraints of this web server.

    " \ "

    The request could be re-tried with a shorter chunked trailer " \ "section, shorter field lines, a shorter request target or " \ "a shorter request method token.

    " \ "" #else #define ERR_MSG_REQUEST_FOOTER_TOO_BIG "" #endif /** * Response text used when the request line has more then two whitespaces. */ #ifdef HAVE_MESSAGES #define RQ_LINE_TOO_MANY_WSP \ "" \ "Request broken" \ "The request line has more then two whitespaces." \ "" #else #define RQ_LINE_TOO_MANY_WSP "" #endif /** * Response text used when the request HTTP header has bare CR character * without LF character (and CR is not allowed to be treated as whitespace). */ #ifdef HAVE_MESSAGES #define BARE_CR_IN_HEADER \ "" \ "Request broken" \ "Request HTTP header has bare CR character without " \ "following LF character." \ "" #else #define BARE_CR_IN_HEADER "" #endif /** * Response text used when the request HTTP footer has bare CR character * without LF character (and CR is not allowed to be treated as whitespace). */ #ifdef HAVE_MESSAGES #define BARE_CR_IN_FOOTER \ "" \ "Request broken" \ "Request HTTP footer has bare CR character without " \ "following LF character." \ "" #else #define BARE_CR_IN_FOOTER "" #endif /** * Response text used when the request HTTP header has bare LF character * without CR character. */ #ifdef HAVE_MESSAGES #define BARE_LF_IN_HEADER \ "" \ "Request broken" \ "Request HTTP header has bare LF character without " \ "preceding CR character." \ "" #else #define BARE_LF_IN_HEADER "" #endif /** * Response text used when the request HTTP footer has bare LF character * without CR character. */ #ifdef HAVE_MESSAGES #define BARE_LF_IN_FOOTER \ "" \ "Request broken" \ "Request HTTP footer has bare LF character without " \ "preceding CR character." \ "" #else #define BARE_LF_IN_FOOTER "" #endif /** * Response text used when the request line has invalid characters in URI. */ #ifdef HAVE_MESSAGES #define RQ_TARGET_INVALID_CHAR \ "" \ "Request broken" \ "HTTP request has invalid characters in " \ "the request-target." \ "" #else #define RQ_TARGET_INVALID_CHAR "" #endif /** * Response text used when line folding is used in request headers. */ #ifdef HAVE_MESSAGES #define ERR_RSP_OBS_FOLD \ "" \ "Request broken" \ "Obsolete line folding is used in HTTP request header." \ "" #else #define ERR_RSP_OBS_FOLD "" #endif /** * Response text used when line folding is used in request footers. */ #ifdef HAVE_MESSAGES #define ERR_RSP_OBS_FOLD_FOOTER \ "" \ "Request broken" \ "Obsolete line folding is used in HTTP request footer." \ "" #else #define ERR_RSP_OBS_FOLD_FOOTER "" #endif /** * Response text used when the request has whitespace at the start * of the first header line. */ #ifdef HAVE_MESSAGES #define ERR_RSP_WSP_BEFORE_HEADER \ "" \ "Request broken" \ "HTTP request has whitespace between the request line and " \ "the first header." \ "" #else #define ERR_RSP_WSP_BEFORE_HEADER "" #endif /** * Response text used when the request has whitespace at the start * of the first footer line. */ #ifdef HAVE_MESSAGES #define ERR_RSP_WSP_BEFORE_FOOTER \ "" \ "Request broken" \ "First HTTP footer line has whitespace at the first " \ "position." \ "" #else #define ERR_RSP_WSP_BEFORE_FOOTER "" #endif /** * Response text used when the whitespace found before colon (inside header * name or between header name and colon). */ #ifdef HAVE_MESSAGES #define ERR_RSP_WSP_IN_HEADER_NAME \ "" \ "Request broken" \ "HTTP request has whitespace before the first colon " \ "in header line." \ "" #else #define ERR_RSP_WSP_IN_HEADER_NAME "" #endif /** * Response text used when the whitespace found before colon (inside header * name or between header name and colon). */ #ifdef HAVE_MESSAGES #define ERR_RSP_WSP_IN_FOOTER_NAME \ "" \ "Request broken" \ "HTTP request has whitespace before the first colon " \ "in footer line." \ "" #else #define ERR_RSP_WSP_IN_FOOTER_NAME "" #endif /** * Response text used when the whitespace found before colon (inside header * name or between header name and colon). */ #ifdef HAVE_MESSAGES #define ERR_RSP_INVALID_CHAR_IN_FIELD_NAME \ "" \ "Request broken" \ "HTTP request has invalid character in field name." \ "" #else #define ERR_RSP_INVALID_CHAR_IN_FIELD_NAME "" #endif /** * Response text used when request header has invalid character. */ #ifdef HAVE_MESSAGES #define ERR_RSP_INVALID_CHR_IN_HEADER \ "" \ "Request broken" \ "HTTP request has invalid character in header." \ "" #else #define ERR_RSP_INVALID_CHR_IN_HEADER "" #endif /** * Response text used when request header has invalid character. */ #ifdef HAVE_MESSAGES #define ERR_RSP_INVALID_CHR_IN_FOOTER \ "" \ "Request broken" \ "HTTP request has invalid character in footer." \ "" #else #define ERR_RSP_INVALID_CHR_IN_FOOTER "" #endif /** * Response text used when request header has no colon character. */ #ifdef HAVE_MESSAGES #define ERR_RSP_HEADER_WITHOUT_COLON \ "" \ "Request broken" \ "HTTP request header line has no colon character." \ "" #else #define ERR_RSP_HEADER_WITHOUT_COLON "" #endif /** * Response text used when request footer has no colon character. */ #ifdef HAVE_MESSAGES #define ERR_RSP_FOOTER_WITHOUT_COLON \ "" \ "Request broken" \ "HTTP request footer line has no colon character." \ "" #else #define ERR_RSP_FOOTER_WITHOUT_COLON "" #endif /** * Response text used when request header has zero-length header (filed) name. */ #ifdef HAVE_MESSAGES #define ERR_RSP_EMPTY_HEADER_NAME \ "" \ "Request broken" \ "HTTP request header has empty header name." \ "" #else #define ERR_RSP_EMPTY_HEADER_NAME "" #endif /** * Response text used when request header has zero-length header (filed) name. */ #ifdef HAVE_MESSAGES #define ERR_RSP_EMPTY_FOOTER_NAME \ "" \ "Request broken" \ "HTTP request footer has empty footer name." \ "" #else #define ERR_RSP_EMPTY_FOOTER_NAME "" #endif /** * Response text used when the request (http header) does not * contain a "Host:" header and still claims to be HTTP 1.1. * * Intentionally empty here to keep our memory footprint * minimal. */ #ifdef HAVE_MESSAGES #define REQUEST_LACKS_HOST \ "" \ ""Host:" header required" \ "HTTP/1.1 request without "Host:"." \ "" #else #define REQUEST_LACKS_HOST "" #endif /** * Response text used when the request has multiple "Host:" headers */ #define REQUEST_MULTIPLE_HOST_HDR \ "" \ "Multiple "Host:" headers" \ "Request contains several "Host:" headers." \ "" /** * Response text used when the request (http header) has * multiple "Content-length" headers. */ #ifdef HAVE_MESSAGES #define REQUEST_AMBIGUOUS_CONTENT_LENGTH \ "" \ ""Content-Length:" header must be unique" \ "HTTP/1.1 request with multiple "Content-Length:" headers." \ "" #else #define REQUEST_AMBIGUOUS_CONTENT_LENGTH "" #endif /** * Response text used when the request has unsupported "Transfer-Encoding:". */ #ifdef HAVE_MESSAGES #define REQUEST_UNSUPPORTED_TR_ENCODING \ "" \ "Unsupported Transfer-Encoding" \ "The Transfer-Encoding used in request is not supported." \ "" #else #define REQUEST_UNSUPPORTED_TR_ENCODING "" #endif /** * Response text used when the request has unsupported both headers: * "Transfer-Encoding:" and "Content-Length:" */ #ifdef HAVE_MESSAGES #define REQUEST_LENGTH_WITH_TR_ENCODING \ "" \ "Malformed request" \ "Wrong combination of the request headers: both Transfer-Encoding " \ "and Content-Length headers are used at the same time." \ "" #else #define REQUEST_LENGTH_WITH_TR_ENCODING "" #endif /** * Response text used when the HTTP/1.0 request has "Transfer-Encoding:" header */ #define REQUEST_HTTP1_0_TR_ENCODING \ "Malformed request" \ ""Transfer-Encoding:" must not be used " \ "with HTTP/1.0." /** * Response text used when the request (http header) is * malformed. * * Intentionally empty here to keep our memory footprint * minimal. */ #ifdef HAVE_MESSAGES #define REQUEST_MALFORMED \ "Request malformed" \ "HTTP request is syntactically incorrect." #else #define REQUEST_MALFORMED "" #endif /** * Response text used when the request target path has %00 sequence. */ #define REQUEST_HAS_NUL_CHAR_IN_PATH \ "Bad Request Path" \ "The request path contains invalid characters." /** * Response text used when the request HTTP chunked encoding is * malformed. */ #ifdef HAVE_MESSAGES #define REQUEST_CHUNKED_MALFORMED \ "Request malformed" \ "HTTP chunked encoding is syntactically incorrect." #else #define REQUEST_CHUNKED_MALFORMED "" #endif /** * Response text used when the request HTTP chunk is too large. */ #ifdef HAVE_MESSAGES #define REQUEST_CHUNK_TOO_LARGE \ "Request content too large" \ "The chunk size used in HTTP chunked encoded " \ "request is too large." #else #define REQUEST_CHUNK_TOO_LARGE "" #endif /** * Response text used when the request HTTP content is too large. */ #ifdef HAVE_MESSAGES #define REQUEST_CONTENTLENGTH_TOOLARGE \ "Request content too large" \ "HTTP request has too large value for " \ "Content-Length header." #else #define REQUEST_CONTENTLENGTH_TOOLARGE "" #endif /** * Response text used when the request HTTP chunked encoding is * malformed. */ #ifdef HAVE_MESSAGES #define REQUEST_CONTENTLENGTH_MALFORMED \ "Request malformed" \ "HTTP request has wrong value for " \ "Content-Length header." #else #define REQUEST_CONTENTLENGTH_MALFORMED "" #endif /** * Response text used when there is an internal server error. * * Intentionally empty here to keep our memory footprint * minimal. */ #ifdef HAVE_MESSAGES #define ERROR_MSG_DATA_NOT_HANDLED_BY_APP \ "Internal server error" \ "Please ask the developer of this Web server to carefully " \ "read the GNU libmicrohttpd documentation about connection " \ "management and blocking." #else #define ERROR_MSG_DATA_NOT_HANDLED_BY_APP "" #endif /** * Response text used when the request HTTP version is too old. */ #ifdef HAVE_MESSAGES #define REQ_HTTP_VER_IS_TOO_OLD \ "Requested HTTP version is not supported" \ "Requested HTTP version is too old and not " \ "supported." #else #define REQ_HTTP_VER_IS_TOO_OLD "" #endif /** * Response text used when the request HTTP version is not supported. */ #ifdef HAVE_MESSAGES #define REQ_HTTP_VER_IS_NOT_SUPPORTED \ "Requested HTTP version is not supported" \ "Requested HTTP version is not supported." #else #define REQ_HTTP_VER_IS_NOT_SUPPORTED "" #endif /** * sendfile() chuck size */ #define MHD_SENFILE_CHUNK_ (0x20000) /** * sendfile() chuck size for thread-per-connection */ #define MHD_SENFILE_CHUNK_THR_P_C_ (0x200000) #ifdef HAVE_MESSAGES /** * Return text description for MHD_ERR_*_ codes * @param mhd_err_code the error code * @return pointer to static string with error description */ static const char * str_conn_error_ (ssize_t mhd_err_code) { switch (mhd_err_code) { case MHD_ERR_AGAIN_: return _ ("The operation would block, retry later"); case MHD_ERR_CONNRESET_: return _ ("The connection was forcibly closed by remote peer"); case MHD_ERR_NOTCONN_: return _ ("The socket is not connected"); case MHD_ERR_NOMEM_: return _ ("Not enough system resources to serve the request"); case MHD_ERR_BADF_: return _ ("Bad FD value"); case MHD_ERR_INVAL_: return _ ("Argument value is invalid"); case MHD_ERR_OPNOTSUPP_: return _ ("Argument value is not supported"); case MHD_ERR_PIPE_: return _ ("The socket is no longer available for sending"); case MHD_ERR_TLS_: return _ ("TLS encryption or decryption error"); default: break; /* Mute compiler warning */ } if (0 <= mhd_err_code) return _ ("Not an error code"); mhd_assert (0); /* Should never be reachable */ return _ ("Wrong error code value"); } #endif /* HAVE_MESSAGES */ /** * Allocate memory from connection's memory pool. * If memory pool doesn't have enough free memory but read or write buffer * have some unused memory, the size of the buffer will be reduced as needed. * @param connection the connection to use * @param size the size of allocated memory area * @return pointer to allocated memory region in the pool or * NULL if no memory is available */ void * MHD_connection_alloc_memory_ (struct MHD_Connection *connection, size_t size) { struct MHD_Connection *const c = connection; /* a short alias */ struct MemoryPool *const pool = c->pool; /* a short alias */ size_t need_to_be_freed = 0; /**< The required amount of additional free memory */ void *res; res = MHD_pool_try_alloc (pool, size, &need_to_be_freed); if (NULL != res) return res; if (MHD_pool_is_resizable_inplace (pool, c->write_buffer, c->write_buffer_size)) { if (c->write_buffer_size - c->write_buffer_append_offset >= need_to_be_freed) { char *buf; const size_t new_buf_size = c->write_buffer_size - need_to_be_freed; buf = MHD_pool_reallocate (pool, c->write_buffer, c->write_buffer_size, new_buf_size); mhd_assert (c->write_buffer == buf); mhd_assert (c->write_buffer_append_offset <= new_buf_size); mhd_assert (c->write_buffer_send_offset <= new_buf_size); c->write_buffer_size = new_buf_size; c->write_buffer = buf; } else return NULL; } else if (MHD_pool_is_resizable_inplace (pool, c->read_buffer, c->read_buffer_size)) { if (c->read_buffer_size - c->read_buffer_offset >= need_to_be_freed) { char *buf; const size_t new_buf_size = c->read_buffer_size - need_to_be_freed; buf = MHD_pool_reallocate (pool, c->read_buffer, c->read_buffer_size, new_buf_size); mhd_assert (c->read_buffer == buf); mhd_assert (c->read_buffer_offset <= new_buf_size); c->read_buffer_size = new_buf_size; c->read_buffer = buf; } else return NULL; } else return NULL; res = MHD_pool_allocate (pool, size, true); mhd_assert (NULL != res); /* It has been checked that pool has enough space */ return res; } /** * Callback for receiving data from the socket. * * @param connection the MHD connection structure * @param other where to write received data to * @param i maximum size of other (in bytes) * @return positive value for number of bytes actually received or * negative value for error number MHD_ERR_xxx_ */ static ssize_t recv_param_adapter (struct MHD_Connection *connection, void *other, size_t i) { ssize_t ret; if ( (MHD_INVALID_SOCKET == connection->socket_fd) || (MHD_CONNECTION_CLOSED == connection->state) ) { return MHD_ERR_NOTCONN_; } if (i > MHD_SCKT_SEND_MAX_SIZE_) i = MHD_SCKT_SEND_MAX_SIZE_; /* return value limit */ ret = MHD_recv_ (connection->socket_fd, other, i); if (0 > ret) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) { #ifdef EPOLL_SUPPORT /* Got EAGAIN --- no longer read-ready */ connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); #endif /* EPOLL_SUPPORT */ return MHD_ERR_AGAIN_; } if (MHD_SCKT_ERR_IS_EINTR_ (err)) return MHD_ERR_AGAIN_; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) return MHD_ERR_CONNRESET_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EOPNOTSUPP_)) return MHD_ERR_OPNOTSUPP_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_)) return MHD_ERR_NOTCONN_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINVAL_)) return MHD_ERR_INVAL_; if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) return MHD_ERR_NOMEM_; if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EBADF_)) return MHD_ERR_BADF_; /* Treat any other error as a hard error. */ return MHD_ERR_NOTCONN_; } #ifdef EPOLL_SUPPORT else if (i > (size_t) ret) connection->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); #endif /* EPOLL_SUPPORT */ return ret; } _MHD_EXTERN enum MHD_Result MHD_get_connection_URI_path_n (struct MHD_Connection *connection, const char **uri, size_t *uri_size) { if (NULL != uri) *uri = NULL; if (NULL != uri_size) *uri_size = 0u; if (connection->state < MHD_CONNECTION_REQ_LINE_RECEIVED) return MHD_NO; if (connection->state >= MHD_CONNECTION_START_REPLY) return MHD_NO; if (NULL == connection->rq.url) return MHD_NO; if (NULL != uri) *uri = connection->rq.url; if (NULL != uri_size) *uri_size = connection->rq.url_len; return MHD_YES; } /** * Get all of the headers from the request. * * @param connection connection to get values from * @param kind types of values to iterate over, can be a bitmask * @param iterator callback to call on each header; * maybe NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over * -1 if connection is NULL. * @ingroup request */ _MHD_EXTERN int MHD_get_connection_values (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIterator iterator, void *iterator_cls) { int ret; struct MHD_HTTP_Req_Header *pos; if (NULL == connection) return -1; ret = 0; for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) if (0 != (pos->kind & kind)) { ret++; if ( (NULL != iterator) && (MHD_NO == iterator (iterator_cls, pos->kind, pos->header, pos->value)) ) return ret; } return ret; } /** * Get all of the headers from the request. * * @param connection connection to get values from * @param kind types of values to iterate over, can be a bitmask * @param iterator callback to call on each header; * maybe NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over, * -1 if connection is NULL. * @ingroup request */ _MHD_EXTERN int MHD_get_connection_values_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIteratorN iterator, void *iterator_cls) { int ret; struct MHD_HTTP_Req_Header *pos; if (NULL == connection) return -1; ret = 0; if (NULL == iterator) for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if (0 != (kind & pos->kind)) ret++; } else for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) if (0 != (kind & pos->kind)) { ret++; if (MHD_NO == iterator (iterator_cls, pos->kind, pos->header, pos->header_size, pos->value, pos->value_size)) return ret; } return ret; } /** * This function can be used to add an arbitrary entry to connection. * Internal version of #MHD_set_connection_value_n() without checking * of arguments values. * * @param connection the connection for which a * value should be set * @param kind kind of the value * @param key key for the value, must be zero-terminated * @param key_size number of bytes in @a key (excluding 0-terminator) * @param value the value itself, must be zero-terminated * @param value_size number of bytes in @a value (excluding 0-terminator) * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @ingroup request */ static enum MHD_Result MHD_set_connection_value_n_nocheck_ (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct MHD_HTTP_Req_Header *pos; pos = MHD_connection_alloc_memory_ (connection, sizeof (struct MHD_HTTP_Req_Header)); if (NULL == pos) return MHD_NO; pos->header = key; pos->header_size = key_size; pos->value = value; pos->value_size = value_size; pos->kind = kind; pos->next = NULL; pos->prev = NULL; /* append 'pos' to the linked list of headers */ if (NULL == connection->rq.headers_received_tail) { mhd_assert (NULL == connection->rq.headers_received); connection->rq.headers_received = pos; connection->rq.headers_received_tail = pos; } else { mhd_assert (NULL != connection->rq.headers_received); mhd_assert (NULL == connection->rq.headers_received_tail->next); mhd_assert (pos != connection->rq.headers_received_tail); mhd_assert (pos != connection->rq.headers_received); connection->rq.headers_received_tail->next = pos; connection->rq.headers_received_tail = pos; } return MHD_YES; } /** * This function can be used to add an arbitrary entry to connection. * This function could add entry with binary zero, which is allowed * for #MHD_GET_ARGUMENT_KIND. For other kind on entries it is * recommended to use #MHD_set_connection_value. * * This function MUST only be called from within the * #MHD_AccessHandlerCallback (otherwise, access maybe improperly * synchronized). Furthermore, the client must guarantee that the key * and value arguments are 0-terminated strings that are NOT freed * until the connection is closed. (The easiest way to do this is by * passing only arguments to permanently allocated strings.). * * @param connection the connection for which a * value should be set * @param kind kind of the value * @param key key for the value, must be zero-terminated * @param key_size number of bytes in @a key (excluding 0-terminator) * @param value the value itself, must be zero-terminated * @param value_size number of bytes in @a value (excluding 0-terminator) * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_set_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { if ( (MHD_GET_ARGUMENT_KIND != kind) && ( ((key ? strlen (key) : 0) != key_size) || ((value ? strlen (value) : 0) != value_size) ) ) return MHD_NO; /* binary zero is allowed only in GET arguments */ return MHD_set_connection_value_n_nocheck_ (connection, kind, key, key_size, value, value_size); } /** * This function can be used to add an entry to the HTTP headers of a * connection (so that the #MHD_get_connection_values function will * return them -- and the `struct MHD_PostProcessor` will also see * them). This maybe required in certain situations (see Mantis * #1399) where (broken) HTTP implementations fail to supply values * needed by the post processor (or other parts of the application). * * This function MUST only be called from within the * #MHD_AccessHandlerCallback (otherwise, access maybe improperly * synchronized). Furthermore, the client must guarantee that the key * and value arguments are 0-terminated strings that are NOT freed * until the connection is closed. (The easiest way to do this is by * passing only arguments to permanently allocated strings.). * * @param connection the connection for which a * value should be set * @param kind kind of the value * @param key key for the value * @param value the value itself * @return #MHD_NO if the operation could not be * performed due to insufficient memory; * #MHD_YES on success * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_set_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, const char *value) { return MHD_set_connection_value_n_nocheck_ (connection, kind, key, NULL != key ? strlen (key) : 0, value, NULL != value ? strlen (value) : 0); } /** * Get a particular header value. If multiple * values match the kind, return any one of them. * * @param connection connection to get values from * @param kind what kind of value are we looking for * @param key the header to look for, NULL to lookup 'trailing' value without a key * @return NULL if no such item was found * @ingroup request */ _MHD_EXTERN const char * MHD_lookup_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key) { const char *value; value = NULL; (void) MHD_lookup_connection_value_n (connection, kind, key, (NULL == key) ? 0 : strlen (key), &value, NULL); return value; } /** * Get a particular header value. If multiple * values match the kind, return any one of them. * @note Since MHD_VERSION 0x00096304 * * @param connection connection to get values from * @param kind what kind of value are we looking for * @param key the header to look for, NULL to lookup 'trailing' value without a key * @param key_size the length of @a key in bytes * @param[out] value_ptr the pointer to variable, which will be set to found value, * will not be updated if key not found, * could be NULL to just check for presence of @a key * @param[out] value_size_ptr the pointer variable, which will set to found value, * will not be updated if key not found, * could be NULL * @return #MHD_YES if key is found, * #MHD_NO otherwise. * @ingroup request */ _MHD_EXTERN enum MHD_Result MHD_lookup_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char **value_ptr, size_t *value_size_ptr) { struct MHD_HTTP_Req_Header *pos; if (NULL == connection) return MHD_NO; if (NULL == key) { for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if ( (0 != (kind & pos->kind)) && (NULL == pos->header) ) break; } } else { for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if ( (0 != (kind & pos->kind)) && (key_size == pos->header_size) && ( (key == pos->header) || (MHD_str_equal_caseless_bin_n_ (key, pos->header, key_size) ) ) ) break; } } if (NULL == pos) return MHD_NO; if (NULL != value_ptr) *value_ptr = pos->value; if (NULL != value_size_ptr) *value_size_ptr = pos->value_size; return MHD_YES; } /** * Check whether request header contains particular token. * * Token could be surrounded by spaces and tabs and delimited by comma. * Case-insensitive match used for header names and tokens. * @param connection the connection to get values from * @param header the header name * @param header_len the length of header, not including optional * terminating null-character * @param token the token to find * @param token_len the length of token, not including optional * terminating null-character. * @return true if token is found in specified header, * false otherwise */ static bool MHD_lookup_header_token_ci (const struct MHD_Connection *connection, const char *header, size_t header_len, const char *token, size_t token_len) { struct MHD_HTTP_Req_Header *pos; if ((NULL == connection) || (NULL == header) || (0 == header[0]) || (NULL == token) || (0 == token[0])) return false; for (pos = connection->rq.headers_received; NULL != pos; pos = pos->next) { if ((0 != (pos->kind & MHD_HEADER_KIND)) && (header_len == pos->header_size) && ( (header == pos->header) || (MHD_str_equal_caseless_bin_n_ (header, pos->header, header_len)) ) && (MHD_str_has_token_caseless_ (pos->value, token, token_len))) return true; } return false; } /** * Check whether request header contains particular static @a tkn. * * Token could be surrounded by spaces and tabs and delimited by comma. * Case-insensitive match used for header names and tokens. * @param c the connection to get values from * @param h the static string of header name * @param tkn the static string of token to find * @return true if token is found in specified header, * false otherwise */ #define MHD_lookup_header_s_token_ci(c,h,tkn) \ MHD_lookup_header_token_ci ((c),(h),MHD_STATICSTR_LEN_ (h), \ (tkn),MHD_STATICSTR_LEN_ (tkn)) /** * Do we (still) need to send a 100 continue * message for this connection? * * @param connection connection to test * @return false if we don't need 100 CONTINUE, true if we do */ static bool need_100_continue (struct MHD_Connection *connection) { const char *expect; if (! MHD_IS_HTTP_VER_1_1_COMPAT (connection->rq.http_ver)) return false; if (0 == connection->rq.remaining_upload_size) return false; if (MHD_NO == MHD_lookup_connection_value_n (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_EXPECT, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_EXPECT), &expect, NULL)) return false; if (MHD_str_equal_caseless_ (expect, "100-continue")) return true; return false; } /** * Mark connection as "closed". * @remark To be called from any thread. * * @param connection connection to close */ void MHD_connection_mark_closed_ (struct MHD_Connection *connection) { const struct MHD_Daemon *daemon = connection->daemon; if (0 == (daemon->options & MHD_USE_TURBO)) { #ifdef HTTPS_SUPPORT /* For TLS connection use shutdown of TLS layer * and do not shutdown TCP socket. This give more * chances to send TLS closure data to remote side. * Closure of TLS layer will be interpreted by * remote side as end of transmission. */ if (0 != (daemon->options & MHD_USE_TLS)) { if (! MHD_tls_connection_shutdown (connection)) shutdown (connection->socket_fd, SHUT_WR); } else /* Combined with next 'shutdown()'. */ #endif /* HTTPS_SUPPORT */ shutdown (connection->socket_fd, SHUT_WR); } connection->state = MHD_CONNECTION_CLOSED; connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP; } /** * Close the given connection and give the * specified termination code to the user. * @remark To be called only from thread that * process connection's recv(), send() and response. * * @param connection connection to close * @param termination_code termination reason to give */ void MHD_connection_close_ (struct MHD_Connection *connection, enum MHD_RequestTerminationCode termination_code) { struct MHD_Daemon *daemon = connection->daemon; struct MHD_Response *resp = connection->rp.response; mhd_assert (! connection->suspended); #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); #endif /* MHD_USE_THREADS */ if ( (NULL != daemon->notify_completed) && (connection->rq.client_aware) ) daemon->notify_completed (daemon->notify_completed_cls, connection, &connection->rq.client_context, termination_code); connection->rq.client_aware = false; if (NULL != resp) { connection->rp.response = NULL; MHD_destroy_response (resp); } if (NULL != connection->pool) { MHD_pool_destroy (connection->pool); connection->pool = NULL; } MHD_connection_mark_closed_ (connection); } #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) /** * Stop TLS forwarding on upgraded connection and * reflect remote disconnect state to socketpair. * @remark In thread-per-connection mode this function * can be called from any thread, in other modes this * function must be called only from thread that process * daemon's select()/poll()/etc. * * @param connection the upgraded connection */ void MHD_connection_finish_forward_ (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; struct MHD_UpgradeResponseHandle *urh = connection->urh; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); #endif /* MHD_USE_THREADS */ if (0 == (daemon->options & MHD_USE_TLS)) return; /* Nothing to do with non-TLS connection. */ if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) DLL_remove (daemon->urh_head, daemon->urh_tail, urh); #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && (0 != epoll_ctl (daemon->epoll_upgrade_fd, EPOLL_CTL_DEL, connection->socket_fd, NULL)) ) { MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); } if (urh->in_eready_list) { EDLL_remove (daemon->eready_urh_head, daemon->eready_urh_tail, urh); urh->in_eready_list = false; } #endif /* EPOLL_SUPPORT */ if (MHD_INVALID_SOCKET != urh->mhd.socket) { #ifdef EPOLL_SUPPORT if (MHD_D_IS_USING_EPOLL_ (daemon) && (0 != epoll_ctl (daemon->epoll_upgrade_fd, EPOLL_CTL_DEL, urh->mhd.socket, NULL)) ) { MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); } #endif /* EPOLL_SUPPORT */ /* Reflect remote disconnect to application by breaking * socketpair connection. */ shutdown (urh->mhd.socket, SHUT_RDWR); } /* Socketpair sockets will remain open as they will be * used with MHD_UPGRADE_ACTION_CLOSE. They will be * closed by cleanup_upgraded_connection() during * connection's final cleanup. */ } #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT*/ /** * A serious error occurred, close the * connection (and notify the application). * * @param connection connection to close with error * @param emsg error message (can be NULL) */ static void connection_close_error (struct MHD_Connection *connection, const char *emsg) { connection->stop_with_error = true; connection->discard_request = true; #ifdef HAVE_MESSAGES if (NULL != emsg) MHD_DLOG (connection->daemon, "%s\n", emsg); #else /* ! HAVE_MESSAGES */ (void) emsg; /* Mute compiler warning. */ #endif /* ! HAVE_MESSAGES */ MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_WITH_ERROR); } /** * Macro to only include error message in call to * #connection_close_error() if we have HAVE_MESSAGES. */ #ifdef HAVE_MESSAGES #define CONNECTION_CLOSE_ERROR(c, emsg) connection_close_error (c, emsg) #else #define CONNECTION_CLOSE_ERROR(c, emsg) connection_close_error (c, NULL) #endif /** * Prepare the response buffer of this connection for * sending. Assumes that the response mutex is * already held. If the transmission is complete, * this function may close the socket (and return * #MHD_NO). * * @param connection the connection * @return #MHD_NO if readying the response failed (the * lock on the response will have been released already * in this case). */ static enum MHD_Result try_ready_normal_body (struct MHD_Connection *connection) { ssize_t ret; struct MHD_Response *response; response = connection->rp.response; mhd_assert (connection->rp.props.send_reply_body); if ( (0 == response->total_size) || /* TODO: replace the next check with assert */ (connection->rp.rsp_write_position == response->total_size) ) return MHD_YES; /* 0-byte response is always ready */ if (NULL != response->data_iov) { size_t copy_size; if (NULL != connection->rp.resp_iov.iov) return MHD_YES; copy_size = response->data_iovcnt * sizeof(MHD_iovec_); connection->rp.resp_iov.iov = MHD_connection_alloc_memory_ (connection, copy_size); if (NULL == connection->rp.resp_iov.iov) { MHD_mutex_unlock_chk_ (&response->mutex); /* not enough memory */ CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (out of memory).")); return MHD_NO; } memcpy (connection->rp.resp_iov.iov, response->data_iov, copy_size); connection->rp.resp_iov.cnt = response->data_iovcnt; connection->rp.resp_iov.sent = 0; return MHD_YES; } if (NULL == response->crc) return MHD_YES; if ( (response->data_start <= connection->rp.rsp_write_position) && (response->data_size + response->data_start > connection->rp.rsp_write_position) ) return MHD_YES; /* response already ready */ #if defined(_MHD_HAVE_SENDFILE) if (MHD_resp_sender_sendfile == connection->rp.resp_sender) { /* will use sendfile, no need to bother response crc */ return MHD_YES; } #endif /* _MHD_HAVE_SENDFILE */ ret = response->crc (response->crc_cls, connection->rp.rsp_write_position, (char *) response->data, (size_t) MHD_MIN ((uint64_t) response->data_buffer_size, response->total_size - connection->rp.rsp_write_position)); if (0 > ret) { /* either error or http 1.0 transfer, close socket! */ /* TODO: do not update total size, check whether response * was really with unknown size */ response->total_size = connection->rp.rsp_write_position; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif if (MHD_CONTENT_READER_END_OF_STREAM == ret) MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_COMPLETED_OK); else CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (application reported " \ "error generating data).")); return MHD_NO; } response->data_start = connection->rp.rsp_write_position; response->data_size = (size_t) ret; if (0 == ret) { connection->state = MHD_CONNECTION_NORMAL_BODY_UNREADY; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif return MHD_NO; } return MHD_YES; } /** * Prepare the response buffer of this connection for sending. * Assumes that the response mutex is already held. If the * transmission is complete, this function may close the socket (and * return #MHD_NO). * * @param connection the connection * @param[out] p_finished the pointer to variable that will be set to "true" * when application returned indication of the end * of the stream * @return #MHD_NO if readying the response failed */ static enum MHD_Result try_ready_chunked_body (struct MHD_Connection *connection, bool *p_finished) { ssize_t ret; struct MHD_Response *response; static const size_t max_chunk = 0xFFFFFF; char chunk_hdr[7]; /* 6: max strlen of "FFFFFF" */ /* "FFFFFF" + "\r\n" */ static const size_t max_chunk_hdr_len = sizeof(chunk_hdr) + 2; /* "FFFFFF" + "\r\n" + "\r\n" (chunk termination) */ static const size_t max_chunk_overhead = sizeof(chunk_hdr) + 2 + 2; size_t chunk_hdr_len; uint64_t left_to_send; size_t size_to_fill; response = connection->rp.response; mhd_assert (NULL != response->crc || NULL != response->data); mhd_assert (0 == connection->write_buffer_append_offset); /* The buffer must be reasonably large enough */ if (128 > connection->write_buffer_size) { size_t size; size = connection->write_buffer_size + MHD_pool_get_free (connection->pool); if (128 > size) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif /* not enough memory */ CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (out of memory).")); return MHD_NO; } /* Limit the buffer size to the largest usable size for chunks */ if ( (max_chunk + max_chunk_overhead) < size) size = max_chunk + max_chunk_overhead; mhd_assert ((NULL == connection->write_buffer) || \ MHD_pool_is_resizable_inplace (connection->pool, \ connection->write_buffer, \ connection->write_buffer_size)); connection->write_buffer = MHD_pool_reallocate (connection->pool, connection->write_buffer, connection->write_buffer_size, size); mhd_assert (NULL != connection->write_buffer); connection->write_buffer_size = size; } mhd_assert (max_chunk_overhead < connection->write_buffer_size); if (MHD_SIZE_UNKNOWN == response->total_size) left_to_send = MHD_SIZE_UNKNOWN; else left_to_send = response->total_size - connection->rp.rsp_write_position; size_to_fill = connection->write_buffer_size - max_chunk_overhead; /* Limit size for the callback to the max usable size */ if (max_chunk < size_to_fill) size_to_fill = max_chunk; if (left_to_send < size_to_fill) size_to_fill = (size_t) left_to_send; if (0 == left_to_send) /* nothing to send, don't bother calling crc */ ret = MHD_CONTENT_READER_END_OF_STREAM; else if ( (response->data_start <= connection->rp.rsp_write_position) && (response->data_start + response->data_size > connection->rp.rsp_write_position) ) { /* difference between rsp_write_position and data_start is less than data_size which is size_t type, no need to check for overflow */ const size_t data_write_offset = (size_t) (connection->rp.rsp_write_position - response->data_start); /* buffer already ready, use what is there for the chunk */ mhd_assert (SSIZE_MAX >= (response->data_size - data_write_offset)); mhd_assert (response->data_size >= data_write_offset); ret = (ssize_t) (response->data_size - data_write_offset); if ( ((size_t) ret) > size_to_fill) ret = (ssize_t) size_to_fill; memcpy (&connection->write_buffer[max_chunk_hdr_len], &response->data[data_write_offset], (size_t) ret); } else { if (NULL == response->crc) { /* There is no way to reach this code */ #if defined(MHD_USE_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif CONNECTION_CLOSE_ERROR (connection, _ ("No callback for the chunked data.")); return MHD_NO; } ret = response->crc (response->crc_cls, connection->rp.rsp_write_position, &connection->write_buffer[max_chunk_hdr_len], size_to_fill); } if (MHD_CONTENT_READER_END_WITH_ERROR == ret) { /* error, close socket! */ /* TODO: remove update of the response size */ response->total_size = connection->rp.rsp_write_position; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (application error " \ "generating response).")); return MHD_NO; } if (MHD_CONTENT_READER_END_OF_STREAM == ret) { *p_finished = true; /* TODO: remove update of the response size */ response->total_size = connection->rp.rsp_write_position; return MHD_YES; } if (0 == ret) { connection->state = MHD_CONNECTION_CHUNKED_BODY_UNREADY; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif return MHD_NO; } if (size_to_fill < (size_t) ret) { #if defined(MHD_USE_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (application returned " \ "more data than requested).")); return MHD_NO; } chunk_hdr_len = MHD_uint32_to_strx ((uint32_t) ret, chunk_hdr, sizeof(chunk_hdr)); mhd_assert (chunk_hdr_len != 0); mhd_assert (chunk_hdr_len <= sizeof(chunk_hdr)); /* This underflow would turn 'write_buffer_send_offset' into a huge value and make the following memcpy() write outside the write buffer. */ if (MHD_CHECK_FAILED_ ((chunk_hdr_len + 2) <= max_chunk_hdr_len)) { MHD_CHECK_LOG_ (connection->daemon, "(chunk_hdr_len + 2) <= max_chunk_hdr_len"); #if defined(MHD_USE_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif /* MHD_USE_THREADS */ connection_close_error (connection, NULL); return MHD_NO; } *p_finished = false; connection->write_buffer_send_offset = (max_chunk_hdr_len - (chunk_hdr_len + 2)); memcpy (connection->write_buffer + connection->write_buffer_send_offset, chunk_hdr, chunk_hdr_len); connection->write_buffer[max_chunk_hdr_len - 2] = '\r'; connection->write_buffer[max_chunk_hdr_len - 1] = '\n'; connection->write_buffer[max_chunk_hdr_len + (size_t) ret] = '\r'; connection->write_buffer[max_chunk_hdr_len + (size_t) ret + 1] = '\n'; connection->rp.rsp_write_position += (size_t) ret; connection->write_buffer_append_offset = max_chunk_hdr_len + (size_t) ret + 2; return MHD_YES; } /** * Are we allowed to keep the given connection alive? * We can use the TCP stream for a second request if the connection * is HTTP 1.1 and the "Connection" header either does not exist or * is not set to "close", or if the connection is HTTP 1.0 and the * "Connection" header is explicitly set to "keep-alive". * If no HTTP version is specified (or if it is not 1.0 or 1.1), we * definitively close the connection. If the "Connection" header is * not exactly "close" or "keep-alive", we proceed to use the default * for the respective HTTP version. * If response has HTTP/1.0 flag or has "Connection: close" header * then connection must be closed. * If full request has not been read then connection must be closed * as well. * * @param connection the connection to check for keepalive * @return MHD_CONN_USE_KEEPALIVE if (based on the request and the response), * a keepalive is legal, * MHD_CONN_MUST_CLOSE if connection must be closed after sending * complete reply, * MHD_CONN_MUST_UPGRADE if connection must be upgraded. */ static enum MHD_ConnKeepAlive keepalive_possible (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_Response *const r = c->rp.response; /**< a short alias */ mhd_assert (NULL != r); if (MHD_CONN_MUST_CLOSE == c->keepalive) return MHD_CONN_MUST_CLOSE; #ifdef UPGRADE_SUPPORT /* TODO: Move below the next check when MHD stops closing connections * when response is queued in first callback */ if (NULL != r->upgrade_handler) { /* No "close" token is enforced by 'add_response_header_connection()' */ mhd_assert (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)); /* Valid HTTP version is enforced by 'MHD_queue_response()' */ mhd_assert (MHD_IS_HTTP_VER_SUPPORTED (c->rq.http_ver)); mhd_assert (! c->stop_with_error); return MHD_CONN_MUST_UPGRADE; } #endif /* UPGRADE_SUPPORT */ mhd_assert ( (! c->stop_with_error) || (c->discard_request)); if ((c->read_closed) || (c->discard_request)) return MHD_CONN_MUST_CLOSE; if (0 != (r->flags & MHD_RF_HTTP_1_0_COMPATIBLE_STRICT)) return MHD_CONN_MUST_CLOSE; if (0 != (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)) return MHD_CONN_MUST_CLOSE; if (! MHD_IS_HTTP_VER_SUPPORTED (c->rq.http_ver)) return MHD_CONN_MUST_CLOSE; if (MHD_lookup_header_s_token_ci (c, MHD_HTTP_HEADER_CONNECTION, "close")) return MHD_CONN_MUST_CLOSE; if ((MHD_HTTP_VER_1_0 == connection->rq.http_ver) || (0 != (connection->rp.response->flags & MHD_RF_HTTP_1_0_SERVER))) { if (MHD_lookup_header_s_token_ci (connection, MHD_HTTP_HEADER_CONNECTION, "Keep-Alive")) return MHD_CONN_USE_KEEPALIVE; return MHD_CONN_MUST_CLOSE; } if (MHD_IS_HTTP_VER_1_1_COMPAT (c->rq.http_ver)) return MHD_CONN_USE_KEEPALIVE; return MHD_CONN_MUST_CLOSE; } /** * Produce time stamp. * * Result is NOT null-terminated. * Result is always 29 bytes long. * * @param[out] date where to write the time stamp, with * at least 29 bytes available space. */ static bool get_date_str (char *date) { static const char *const days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static const char *const mons[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static const size_t buf_len = 29; struct tm now; time_t t; const char *src; #if ! defined(HAVE_C11_GMTIME_S) && ! defined(HAVE_W32_GMTIME_S) && \ ! defined(HAVE_GMTIME_R) struct tm *pNow; #endif if ((time_t) -1 == time (&t)) return false; #if defined(HAVE_C11_GMTIME_S) if (NULL == gmtime_s (&t, &now)) return false; #elif defined(HAVE_W32_GMTIME_S) if (0 != gmtime_s (&now, &t)) return false; #elif defined(HAVE_GMTIME_R) if (NULL == gmtime_r (&t, &now)) return false; #else pNow = gmtime (&t); if (NULL == pNow) return false; now = *pNow; #endif /* Day of the week */ src = days[now.tm_wday % 7]; date[0] = src[0]; date[1] = src[1]; date[2] = src[2]; date[3] = ','; date[4] = ' '; /* Day of the month */ if (2 != MHD_uint8_to_str_pad ((uint8_t) now.tm_mday, 2, date + 5, buf_len - 5)) return false; date[7] = ' '; /* Month */ src = mons[now.tm_mon % 12]; date[8] = src[0]; date[9] = src[1]; date[10] = src[2]; date[11] = ' '; /* Year */ if (4 != MHD_uint16_to_str ((uint16_t) (1900 + now.tm_year), date + 12, buf_len - 12)) return false; date[16] = ' '; /* Time */ MHD_uint8_to_str_pad ((uint8_t) now.tm_hour, 2, date + 17, buf_len - 17); date[19] = ':'; MHD_uint8_to_str_pad ((uint8_t) now.tm_min, 2, date + 20, buf_len - 20); date[22] = ':'; MHD_uint8_to_str_pad ((uint8_t) now.tm_sec, 2, date + 23, buf_len - 23); date[25] = ' '; date[26] = 'G'; date[27] = 'M'; date[28] = 'T'; return true; } /** * Produce HTTP DATE header. * Result is always 37 bytes long (plus one terminating null). * * @param[out] header where to write the header, with * at least 38 bytes available space. */ static bool get_date_header (char *header) { if (! get_date_str (header + 6)) { header[0] = 0; return false; } header[0] = 'D'; header[1] = 'a'; header[2] = 't'; header[3] = 'e'; header[4] = ':'; header[5] = ' '; header[35] = '\r'; header[36] = '\n'; header[37] = 0; return true; } /** * Try growing the read buffer. We initially claim half the available * buffer space for the read buffer (the other half being left for * management data structures; the write buffer can in the end take * virtually everything as the read buffer can be reduced to the * minimum necessary at that point. * * @param connection the connection * @param required set to 'true' if grow is required, i.e. connection * will fail if no additional space is granted * @return 'true' on success, 'false' on failure */ static bool try_grow_read_buffer (struct MHD_Connection *connection, bool required) { size_t new_size; size_t avail_size; const size_t def_grow_size = connection->daemon->pool_increment; void *rb; avail_size = MHD_pool_get_free (connection->pool); if (0 == avail_size) return false; /* No more space available */ if (0 == connection->read_buffer_size) new_size = avail_size / 2; /* Use half of available buffer for reading */ else { size_t grow_size; grow_size = avail_size / 8; if (def_grow_size > grow_size) { /* Shortage of space */ const size_t left_free = connection->read_buffer_size - connection->read_buffer_offset; mhd_assert (connection->read_buffer_size >= \ connection->read_buffer_offset); if ((def_grow_size <= grow_size + left_free) && (left_free < def_grow_size)) grow_size = def_grow_size - left_free; /* Use precise 'def_grow_size' for new free space */ else if (! required) return false; /* Grow is not mandatory, leave some space in pool */ else { /* Shortage of space, but grow is mandatory */ const size_t small_inc = ((MHD_BUF_INC_SIZE > def_grow_size) ? def_grow_size : MHD_BUF_INC_SIZE) / 8; if (small_inc < avail_size) grow_size = small_inc; else grow_size = avail_size; } } new_size = connection->read_buffer_size + grow_size; } /* Make sure that read buffer will not be moved */ if ((NULL != connection->read_buffer) && ! MHD_pool_is_resizable_inplace (connection->pool, connection->read_buffer, connection->read_buffer_size)) { mhd_assert (0); return false; } /* we can actually grow the buffer, do it! */ rb = MHD_pool_reallocate (connection->pool, connection->read_buffer, connection->read_buffer_size, new_size); if (NULL == rb) { /* This should NOT be possible: we just computed 'new_size' so that it should fit. If it happens, somehow our read buffer is not in the right position in the pool, say because someone called MHD_pool_allocate() without 'from_end' set to 'true'? Anyway, should be investigated! (Ideally provide all data from *pool and connection->read_buffer and new_size for debugging). */ mhd_assert (0); return false; } mhd_assert (connection->read_buffer == rb); connection->read_buffer = rb; mhd_assert (NULL != connection->read_buffer); connection->read_buffer_size = new_size; return true; } /** * Shrink connection read buffer to the zero size of free space in the buffer * @param connection the connection whose read buffer is being manipulated */ static void connection_shrink_read_buffer (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ void *new_buf; if ((NULL == c->read_buffer) || (0 == c->read_buffer_size)) { mhd_assert (0 == c->read_buffer_size); mhd_assert (0 == c->read_buffer_offset); return; } mhd_assert (c->read_buffer_offset <= c->read_buffer_size); if (0 == c->read_buffer_offset) { MHD_pool_deallocate (c->pool, c->read_buffer, c->read_buffer_size); c->read_buffer = NULL; c->read_buffer_size = 0; } else { mhd_assert (MHD_pool_is_resizable_inplace (c->pool, c->read_buffer, \ c->read_buffer_size)); new_buf = MHD_pool_reallocate (c->pool, c->read_buffer, c->read_buffer_size, c->read_buffer_offset); mhd_assert (c->read_buffer == new_buf); c->read_buffer = new_buf; c->read_buffer_size = c->read_buffer_offset; } } /** * Allocate the maximum available amount of memory from MemoryPool * for write buffer. * @param connection the connection whose write buffer is being manipulated * @return the size of the free space in the write buffer */ static size_t connection_maximize_write_buffer (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MemoryPool *const pool = connection->pool; void *new_buf; size_t new_size; size_t free_size; mhd_assert ((NULL != c->write_buffer) || (0 == c->write_buffer_size)); mhd_assert (c->write_buffer_append_offset >= c->write_buffer_send_offset); mhd_assert (c->write_buffer_size >= c->write_buffer_append_offset); free_size = MHD_pool_get_free (pool); if (0 != free_size) { new_size = c->write_buffer_size + free_size; /* This function must not move the buffer position. * MHD_pool_reallocate () may return the new position only if buffer was * allocated 'from_end' or is not the last allocation, * which should not happen. */ mhd_assert ((NULL == c->write_buffer) || \ MHD_pool_is_resizable_inplace (pool, c->write_buffer, \ c->write_buffer_size)); new_buf = MHD_pool_reallocate (pool, c->write_buffer, c->write_buffer_size, new_size); mhd_assert ((c->write_buffer == new_buf) || (NULL == c->write_buffer)); c->write_buffer = new_buf; c->write_buffer_size = new_size; if (c->write_buffer_send_offset == c->write_buffer_append_offset) { /* All data have been sent, reset offsets to zero. */ c->write_buffer_send_offset = 0; c->write_buffer_append_offset = 0; } } return c->write_buffer_size - c->write_buffer_append_offset; } #if 0 /* disable unused function */ /** * Shrink connection write buffer to the size of unsent data. * * @note: The number of calls of this function should be limited to avoid extra * zeroing of the memory. * @param connection the connection whose write buffer is being manipulated * @param connection the connection to manipulate write buffer */ static void connection_shrink_write_buffer (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MemoryPool *const pool = connection->pool; void *new_buf; mhd_assert ((NULL != c->write_buffer) || (0 == c->write_buffer_size)); mhd_assert (c->write_buffer_append_offset >= c->write_buffer_send_offset); mhd_assert (c->write_buffer_size >= c->write_buffer_append_offset); if ( (NULL == c->write_buffer) || (0 == c->write_buffer_size)) { mhd_assert (0 == c->write_buffer_append_offset); mhd_assert (0 == c->write_buffer_send_offset); c->write_buffer = NULL; return; } if (c->write_buffer_append_offset == c->write_buffer_size) return; new_buf = MHD_pool_reallocate (pool, c->write_buffer, c->write_buffer_size, c->write_buffer_append_offset); mhd_assert ((c->write_buffer == new_buf) || \ (0 == c->write_buffer_append_offset)); c->write_buffer_size = c->write_buffer_append_offset; if (0 == c->write_buffer_size) c->write_buffer = NULL; else c->write_buffer = new_buf; } #endif /* unused function */ /** * Switch connection from recv mode to send mode. * * Current request header or body will not be read anymore, * response must be assigned to connection. * @param connection the connection to prepare for sending. */ static void connection_switch_from_recv_to_send (struct MHD_Connection *connection) { /* Read buffer is not needed for this request, shrink it.*/ connection_shrink_read_buffer (connection); } /** * This enum type describes requirements for reply body and reply bode-specific * headers (namely Content-Length, Transfer-Encoding). */ enum replyBodyUse { /** * No reply body allowed. * Reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked' are * not allowed as well. */ RP_BODY_NONE = 0, /** * Do not send reply body. * Reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked' are * allowed, but optional. */ RP_BODY_HEADERS_ONLY = 1, /** * Send reply body and * reply body headers 'Content-Length:' or 'Transfer-Encoding: chunked'. * Reply body headers are required. */ RP_BODY_SEND = 2 }; /** * Check whether reply body must be used. * * If reply body is needed, it could be zero-sized. * * @param connection the connection to check * @param rcode the response code * @return enum value indicating whether response body can be used and * whether response body length headers are allowed or required. * @sa is_reply_body_header_needed() */ static enum replyBodyUse is_reply_body_needed (struct MHD_Connection *connection, unsigned int rcode) { struct MHD_Connection *const c = connection; /**< a short alias */ mhd_assert (100 <= rcode); mhd_assert (999 >= rcode); if (199 >= rcode) return RP_BODY_NONE; if (MHD_HTTP_NO_CONTENT == rcode) return RP_BODY_NONE; #if 0 /* This check is not needed as upgrade handler is used only with code 101 */ #ifdef UPGRADE_SUPPORT if (NULL != rp.response->upgrade_handler) return RP_BODY_NONE; #endif /* UPGRADE_SUPPORT */ #endif #if 0 /* CONNECT is not supported by MHD */ /* Successful responses for connect requests are filtered by * MHD_queue_response() */ if ( (MHD_HTTP_MTHD_CONNECT == c->rq.http_mthd) && (2 == rcode / 100) ) return false; /* Actually pass-through CONNECT is not supported by MHD */ #endif /* Reply body headers could be used. * Check whether reply body itself must be used. */ if (MHD_HTTP_MTHD_HEAD == c->rq.http_mthd) return RP_BODY_HEADERS_ONLY; if (MHD_HTTP_NOT_MODIFIED == rcode) return RP_BODY_HEADERS_ONLY; /* Reply body must be sent. The body may have zero length, but body size * must be indicated by headers ('Content-Length:' or * 'Transfer-Encoding: chunked'). */ return RP_BODY_SEND; } /** * Setup connection reply properties. * * Reply properties include presence of reply body, transfer-encoding * type and other. * * @param connection to connection to process */ static void setup_reply_properties (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_Response *const r = c->rp.response; /**< a short alias */ enum replyBodyUse use_rp_body; bool use_chunked; mhd_assert (NULL != r); /* ** Adjust reply properties ** */ c->keepalive = keepalive_possible (c); use_rp_body = is_reply_body_needed (c, c->rp.responseCode); c->rp.props.send_reply_body = (use_rp_body > RP_BODY_HEADERS_ONLY); c->rp.props.use_reply_body_headers = (use_rp_body >= RP_BODY_HEADERS_ONLY); #ifdef UPGRADE_SUPPORT mhd_assert ( (NULL == r->upgrade_handler) || (RP_BODY_NONE == use_rp_body) ); #endif /* UPGRADE_SUPPORT */ if (c->rp.props.use_reply_body_headers) { if ((MHD_SIZE_UNKNOWN == r->total_size) || (0 != (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED))) { /* Use chunked reply encoding if possible */ /* Check whether chunked encoding is supported by the client */ if (! MHD_IS_HTTP_VER_1_1_COMPAT (c->rq.http_ver)) use_chunked = false; /* Check whether chunked encoding is allowed for the reply */ else if (0 != (r->flags & (MHD_RF_HTTP_1_0_COMPATIBLE_STRICT | MHD_RF_HTTP_1_0_SERVER))) use_chunked = false; else /* If chunked encoding is supported and allowed, and response size * is unknown, use chunked even for non-Keep-Alive connections. * See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.3 * Also use chunked if it is enforced by application and supported by * the client. */ use_chunked = true; } else use_chunked = false; if ( (MHD_SIZE_UNKNOWN == r->total_size) && (! use_chunked) ) { /* End of the stream is indicated by closure */ c->keepalive = MHD_CONN_MUST_CLOSE; } } else use_chunked = false; /* chunked encoding cannot be used without body */ c->rp.props.chunked = use_chunked; #ifdef _DEBUG c->rp.props.set = true; #endif /* _DEBUG */ } /** * Check whether queued response is suitable for @a connection. * @param connection to connection to check */ static void check_connection_reply (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_Response *const r = c->rp.response; /**< a short alias */ mhd_assert (c->rp.props.set); #ifdef HAVE_MESSAGES if ( (! c->rp.props.use_reply_body_headers) && (0 != r->total_size) ) { MHD_DLOG (c->daemon, _ ("This reply with response code %u cannot use reply body. " "Non-empty response body is ignored and not used.\n"), (unsigned) (c->rp.responseCode)); } if ( (! c->rp.props.use_reply_body_headers) && (0 != (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) ) { MHD_DLOG (c->daemon, _ ("This reply with response code %u cannot use reply body. " "Application defined \"Content-Length\" header violates" "HTTP specification.\n"), (unsigned) (c->rp.responseCode)); } #else (void) c; /* Mute compiler warning */ (void) r; /* Mute compiler warning */ #endif } /** * Append data to the buffer if enough space is available, * update position. * @param[out] buf the buffer to append data to * @param[in,out] ppos the pointer to position in the @a buffer * @param buf_size the size of the @a buffer * @param append the data to append * @param append_size the size of the @a append * @return true if data has been added and position has been updated, * false if not enough space is available */ static bool buffer_append (char *buf, size_t *ppos, size_t buf_size, const char *append, size_t append_size) { mhd_assert (NULL != buf); /* Mute static analyzer */ if (buf_size < *ppos + append_size) return false; memcpy (buf + *ppos, append, append_size); *ppos += append_size; return true; } /** * Append static string to the buffer if enough space is available, * update position. * @param[out] buf the buffer to append data to * @param[in,out] ppos the pointer to position in the @a buffer * @param buf_size the size of the @a buffer * @param str the static string to append * @return true if data has been added and position has been updated, * false if not enough space is available */ #define buffer_append_s(buf,ppos,buf_size,str) \ buffer_append (buf,ppos,buf_size,str, MHD_STATICSTR_LEN_ (str)) /** * Add user-defined headers from response object to * the text buffer. * * @param buf the buffer to add headers to * @param ppos the pointer to the position in the @a buf * @param buf_size the size of the @a buf * @param response the response * @param filter_transf_enc skip "Transfer-Encoding" header if any * @param filter_content_len skip "Content-Length" header if any * @param add_close add "close" token to the * "Connection:" header (if any), ignored if no "Connection:" * header was added by user or if "close" token is already * present in "Connection:" header * @param add_keep_alive add "Keep-Alive" token to the * "Connection:" header (if any) * @return true if succeed, * false if buffer is too small */ static bool add_user_headers (char *buf, size_t *ppos, size_t buf_size, struct MHD_Response *response, bool filter_transf_enc, bool filter_content_len, bool add_close, bool add_keep_alive) { struct MHD_Response *const r = response; /**< a short alias */ struct MHD_HTTP_Res_Header *hdr; /**< Iterates through User-specified headers */ size_t el_size; /**< the size of current element to be added to the @a buf */ mhd_assert (! add_close || ! add_keep_alive); if (0 == (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED)) filter_transf_enc = false; /* No such header */ if (0 == (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) filter_content_len = false; /* No such header */ if (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) { add_close = false; /* No such header */ add_keep_alive = false; /* No such header */ } else if (0 != (r->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)) add_close = false; /* "close" token was already set */ for (hdr = r->first_header; NULL != hdr; hdr = hdr->next) { size_t initial_pos = *ppos; if (MHD_HEADER_KIND != hdr->kind) continue; if (filter_transf_enc) { /* Need to filter-out "Transfer-Encoding" */ if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING) == hdr->header_size) && (MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_TRANSFER_ENCODING, hdr->header, hdr->header_size)) ) { filter_transf_enc = false; /* There is the only one such header */ continue; /* Skip "Transfer-Encoding" header */ } } if (filter_content_len) { /* Need to filter-out "Content-Length" */ if ((MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH) == hdr->header_size) && (MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_CONTENT_LENGTH, hdr->header, hdr->header_size)) ) { /* Reset filter flag if only one header is allowed */ filter_transf_enc = (0 == (r->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)); continue; /* Skip "Content-Length" header */ } } /* Add user header */ /* Check available space using subtractions to avoid integer overflow. '4' is two colons/space plus the final CRLF. */ if ( (buf_size - *ppos < 4) || (buf_size - *ppos - 4 < hdr->header_size) || (buf_size - *ppos - 4 - hdr->header_size < hdr->value_size) ) return false; el_size = hdr->header_size + 2 + hdr->value_size + 2; memcpy (buf + *ppos, hdr->header, hdr->header_size); (*ppos) += hdr->header_size; buf[(*ppos)++] = ':'; buf[(*ppos)++] = ' '; if (add_close || add_keep_alive) { /* "Connection:" header must be always the first one */ mhd_assert (MHD_str_equal_caseless_n_ (hdr->header, \ MHD_HTTP_HEADER_CONNECTION, \ hdr->header_size)); if (add_close) { el_size += MHD_STATICSTR_LEN_ ("close, "); if (buf_size < initial_pos + el_size) return false; memcpy (buf + *ppos, "close, ", MHD_STATICSTR_LEN_ ("close, ")); *ppos += MHD_STATICSTR_LEN_ ("close, "); } else { el_size += MHD_STATICSTR_LEN_ ("Keep-Alive, "); if (buf_size < initial_pos + el_size) return false; memcpy (buf + *ppos, "Keep-Alive, ", MHD_STATICSTR_LEN_ ("Keep-Alive, ")); *ppos += MHD_STATICSTR_LEN_ ("Keep-Alive, "); } add_close = false; add_keep_alive = false; } if (0 != hdr->value_size) memcpy (buf + *ppos, hdr->value, hdr->value_size); *ppos += hdr->value_size; buf[(*ppos)++] = '\r'; buf[(*ppos)++] = '\n'; mhd_assert (initial_pos + el_size == (*ppos)); } return true; } /** * Allocate the connection's write buffer and fill it with all of the * headers from the response. * Required headers are added here. * * @param connection the connection * @return #MHD_YES on success, #MHD_NO on failure (out of memory) */ static enum MHD_Result build_header_response (struct MHD_Connection *connection) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_Response *const r = c->rp.response; /**< a short alias */ char *buf; /**< the output buffer */ size_t pos; /**< append offset in the @a buf */ size_t buf_size; /**< the size of the @a buf */ size_t el_size; /**< the size of current element to be added to the @a buf */ unsigned rcode; /**< the response code */ bool use_conn_close; /**< Use "Connection: close" header */ bool use_conn_k_alive; /**< Use "Connection: Keep-Alive" header */ mhd_assert (NULL != r); /* ** Adjust response properties ** */ setup_reply_properties (c); mhd_assert (c->rp.props.set); mhd_assert ((MHD_CONN_MUST_CLOSE == c->keepalive) || \ (MHD_CONN_USE_KEEPALIVE == c->keepalive) || \ (MHD_CONN_MUST_UPGRADE == c->keepalive)); #ifdef UPGRADE_SUPPORT mhd_assert ((NULL == r->upgrade_handler) || \ (MHD_CONN_MUST_UPGRADE == c->keepalive)); #else /* ! UPGRADE_SUPPORT */ mhd_assert (MHD_CONN_MUST_UPGRADE != c->keepalive); #endif /* ! UPGRADE_SUPPORT */ mhd_assert ((! c->rp.props.chunked) || c->rp.props.use_reply_body_headers); mhd_assert ((! c->rp.props.send_reply_body) || \ c->rp.props.use_reply_body_headers); #ifdef UPGRADE_SUPPORT mhd_assert (NULL == r->upgrade_handler || \ ! c->rp.props.use_reply_body_headers); #endif /* UPGRADE_SUPPORT */ check_connection_reply (c); rcode = (unsigned) c->rp.responseCode; if (MHD_CONN_MUST_CLOSE == c->keepalive) { /* The closure of connection must be always indicated by header * to avoid hung connections */ use_conn_close = true; use_conn_k_alive = false; } else if (MHD_CONN_USE_KEEPALIVE == c->keepalive) { use_conn_close = false; /* Add "Connection: keep-alive" if request is HTTP/1.0 or * if reply is HTTP/1.0 * For HTTP/1.1 add header only if explicitly requested by app * (by response flag), as "Keep-Alive" is default for HTTP/1.1. */ if ((0 != (r->flags & MHD_RF_SEND_KEEP_ALIVE_HEADER)) || (MHD_HTTP_VER_1_0 == c->rq.http_ver) || (0 != (r->flags & MHD_RF_HTTP_1_0_SERVER))) use_conn_k_alive = true; else use_conn_k_alive = false; } else { use_conn_close = false; use_conn_k_alive = false; } /* ** Actually build the response header ** */ /* Get all space available */ connection_maximize_write_buffer (c); buf = c->write_buffer; pos = c->write_buffer_append_offset; buf_size = c->write_buffer_size; if (0 == buf_size) return MHD_NO; mhd_assert (NULL != buf); /* * The status line * */ /* The HTTP version */ if (! c->rp.responseIcy) { /* HTTP reply */ if (0 == (r->flags & MHD_RF_HTTP_1_0_SERVER)) { /* HTTP/1.1 reply */ /* Use HTTP/1.1 responses for HTTP/1.0 clients. * See https://datatracker.ietf.org/doc/html/rfc7230#section-2.6 */ if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_VERSION_1_1)) return MHD_NO; } else { /* HTTP/1.0 reply */ if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_VERSION_1_0)) return MHD_NO; } } else { /* ICY reply */ if (! buffer_append_s (buf, &pos, buf_size, "ICY")) return MHD_NO; } /* The response code */ if (buf_size < pos + 5) /* space + code + space */ return MHD_NO; buf[pos++] = ' '; pos += MHD_uint16_to_str ((uint16_t) rcode, buf + pos, buf_size - pos); buf[pos++] = ' '; /* The reason phrase */ el_size = MHD_get_reason_phrase_len_for (rcode); if (0 == el_size) { if (! buffer_append_s (buf, &pos, buf_size, "Non-Standard Status")) return MHD_NO; } else if (! buffer_append (buf, &pos, buf_size, MHD_get_reason_phrase_for (rcode), el_size)) return MHD_NO; /* The linefeed */ if (buf_size < pos + 2) return MHD_NO; buf[pos++] = '\r'; buf[pos++] = '\n'; /* * The headers * */ /* Main automatic headers */ /* The "Date:" header */ if ( (0 == (r->flags_auto & MHD_RAF_HAS_DATE_HDR)) && (0 == (c->daemon->options & MHD_USE_SUPPRESS_DATE_NO_CLOCK)) ) { /* Additional byte for unused zero-termination */ if (buf_size < pos + 38) return MHD_NO; if (get_date_header (buf + pos)) pos += 37; } /* The "Connection:" header */ mhd_assert (! use_conn_close || ! use_conn_k_alive); mhd_assert (! use_conn_k_alive || ! use_conn_close); if (0 == (r->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) { if (use_conn_close) { if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_HEADER_CONNECTION ": close\r\n")) return MHD_NO; } else if (use_conn_k_alive) { if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_HEADER_CONNECTION ": Keep-Alive\r\n")) return MHD_NO; } } /* User-defined headers */ if (! add_user_headers (buf, &pos, buf_size, r, ! c->rp.props.chunked, (! c->rp.props.use_reply_body_headers) && (0 == (r->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)), use_conn_close, use_conn_k_alive)) return MHD_NO; /* Other automatic headers */ if ( (c->rp.props.use_reply_body_headers) && (0 == (r->flags & MHD_RF_HEAD_ONLY_RESPONSE)) ) { /* Body-specific headers */ if (c->rp.props.chunked) { /* Chunked encoding is used */ if (0 == (r->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED)) { /* No chunked encoding header set by user */ if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_HEADER_TRANSFER_ENCODING ": " \ "chunked\r\n")) return MHD_NO; } } else /* Chunked encoding is not used */ { if (MHD_SIZE_UNKNOWN != r->total_size) { /* The size is known */ if (0 == (r->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) { /* The response does not have "Content-Length" header */ if (! buffer_append_s (buf, &pos, buf_size, MHD_HTTP_HEADER_CONTENT_LENGTH ": ")) return MHD_NO; el_size = MHD_uint64_to_str (r->total_size, buf + pos, buf_size - pos); if (0 == el_size) return MHD_NO; pos += el_size; if (buf_size < pos + 2) return MHD_NO; buf[pos++] = '\r'; buf[pos++] = '\n'; } } } } /* * Header termination * */ if (buf_size < pos + 2) return MHD_NO; buf[pos++] = '\r'; buf[pos++] = '\n'; c->write_buffer_append_offset = pos; return MHD_YES; } /** * Allocate the connection's write buffer (if necessary) and fill it * with response footers. * Works only for chunked responses as other responses do not need * and do not support any kind of footers. * * @param connection the connection * @return #MHD_YES on success, #MHD_NO on failure (out of memory) */ static enum MHD_Result build_connection_chunked_response_footer (struct MHD_Connection *connection) { char *buf; /**< the buffer to write footers to */ size_t buf_size; /**< the size of the @a buf */ size_t used_size; /**< the used size of the @a buf */ struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_HTTP_Res_Header *pos; mhd_assert (connection->rp.props.chunked); /* TODO: allow combining of the final footer with the last chunk, * modify the next assert. */ mhd_assert (MHD_CONNECTION_CHUNKED_BODY_SENT == connection->state); mhd_assert (NULL != c->rp.response); buf_size = connection_maximize_write_buffer (c); /* '5' is the minimal size of chunked footer ("0\r\n\r\n") */ if (buf_size < 5) return MHD_NO; mhd_assert (NULL != c->write_buffer); buf = c->write_buffer + c->write_buffer_append_offset; mhd_assert (NULL != buf); used_size = 0; buf[used_size++] = '0'; buf[used_size++] = '\r'; buf[used_size++] = '\n'; for (pos = c->rp.response->first_header; NULL != pos; pos = pos->next) { if (MHD_FOOTER_KIND == pos->kind) { size_t new_used_size; /* resulting size with this header */ /* '4' is colon, space, linefeeds */ /* Check available space using subtractions to avoid integer overflow. */ if ( (buf_size - used_size < 4) || (buf_size - used_size - 4 < pos->header_size) || (buf_size - used_size - 4 - pos->header_size < pos->value_size) ) return MHD_NO; new_used_size = used_size + pos->header_size + pos->value_size + 4; memcpy (buf + used_size, pos->header, pos->header_size); used_size += pos->header_size; buf[used_size++] = ':'; buf[used_size++] = ' '; memcpy (buf + used_size, pos->value, pos->value_size); used_size += pos->value_size; buf[used_size++] = '\r'; buf[used_size++] = '\n'; mhd_assert (used_size == new_used_size); } } if (used_size + 2 > buf_size) return MHD_NO; buf[used_size++] = '\r'; buf[used_size++] = '\n'; c->write_buffer_append_offset += used_size; mhd_assert (c->write_buffer_append_offset <= c->write_buffer_size); return MHD_YES; } /** * We encountered an error processing the request. * Handle it properly by stopping to read data * and sending the indicated response code and message. * * @param connection the connection * @param status_code the response code to send (400, 413 or 414) * @param message the error message to send * @param message_len the length of the @a message * @param header_name the name of the header, malloc()ed by the caller, * free() by this function, optional, can be NULL * @param header_name_len the length of the @a header_name * @param header_value the value of the header, malloc()ed by the caller, * free() by this function, optional, can be NULL * @param header_value_len the length of the @a header_value */ static void transmit_error_response_len (struct MHD_Connection *connection, unsigned int status_code, const char *message, size_t message_len, char *header_name, size_t header_name_len, char *header_value, size_t header_value_len) { struct MHD_Response *response; enum MHD_Result iret; mhd_assert (! connection->stop_with_error); /* Do not send error twice */ if (connection->stop_with_error) { /* Should not happen */ if (MHD_CONNECTION_CLOSED > connection->state) connection->state = MHD_CONNECTION_CLOSED; free (header_name); free (header_value); return; } connection->stop_with_error = true; connection->discard_request = true; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Error processing request (HTTP response code is %u ('%s')). " \ "Closing connection.\n"), status_code, message); #endif if (MHD_CONNECTION_START_REPLY < connection->state) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Too late to send an error response, " \ "response is being sent already.\n"), status_code, message); #endif CONNECTION_CLOSE_ERROR (connection, _ ("Too late for error response.")); free (header_name); free (header_value); return; } /* TODO: remove when special error queue function is implemented */ connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED; if (0 != connection->read_buffer_size) { /* Read buffer is not needed anymore, discard it * to free some space for error response. */ MHD_pool_deallocate (connection->pool, connection->read_buffer, connection->read_buffer_size); connection->read_buffer = NULL; connection->read_buffer_size = 0; connection->read_buffer_offset = 0; } if (NULL != connection->rp.response) { MHD_destroy_response (connection->rp.response); connection->rp.response = NULL; } response = MHD_create_response_from_buffer_static (message_len, message); if (NULL == response) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to create error response.\n"), status_code, message); #endif /* can't even send a reply, at least close the connection */ connection->state = MHD_CONNECTION_CLOSED; free (header_name); free (header_value); return; } mhd_assert ((0 == header_name_len) || (NULL != header_name)); mhd_assert ((NULL == header_name) || (0 != header_name_len)); mhd_assert ((0 == header_value_len) || (NULL != header_value)); mhd_assert ((NULL == header_value) || (0 != header_value_len)); mhd_assert ((NULL == header_name) || (NULL != header_value)); mhd_assert ((NULL != header_value) || (NULL == header_name)); if (NULL != header_name) { iret = MHD_add_response_entry_no_alloc_ (response, MHD_HEADER_KIND, header_name, header_name_len, header_value, header_value_len); if (MHD_NO == iret) { free (header_name); free (header_value); } } else iret = MHD_YES; if (MHD_NO != iret) { bool before = connection->in_access_handler; /* Fake the flag for the internal call */ connection->in_access_handler = true; iret = MHD_queue_response (connection, status_code, response); connection->in_access_handler = before; } MHD_destroy_response (response); if (MHD_NO == iret) { /* can't even send a reply, at least close the connection */ CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection " \ "(failed to queue error response).")); return; } mhd_assert (NULL != connection->rp.response); /* Do not reuse this connection. */ connection->keepalive = MHD_CONN_MUST_CLOSE; if (MHD_NO == build_header_response (connection)) { /* No memory. Release everything. */ connection->rq.version = NULL; connection->rq.method = NULL; connection->rq.url = NULL; connection->rq.url_len = 0; connection->rq.url_for_callback = NULL; connection->rq.headers_received = NULL; connection->rq.headers_received_tail = NULL; connection->write_buffer = NULL; connection->write_buffer_size = 0; connection->write_buffer_send_offset = 0; connection->write_buffer_append_offset = 0; connection->read_buffer = MHD_pool_reset (connection->pool, NULL, 0, 0); connection->read_buffer_size = 0; /* Retry with empty buffer */ if (MHD_NO == build_header_response (connection)) { CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection " \ "(failed to create error response header).")); return; } } connection->state = MHD_CONNECTION_HEADERS_SENDING; } /** * Transmit static string as error response */ #ifdef HAVE_MESSAGES # define transmit_error_response_static(c, code, msg) \ transmit_error_response_len (c, code, \ msg, MHD_STATICSTR_LEN_ (msg), \ NULL, 0, NULL, 0) #else /* ! HAVE_MESSAGES */ # define transmit_error_response_static(c, code, msg) \ transmit_error_response_len (c, code, \ "", 0, \ NULL, 0, NULL, 0) #endif /* ! HAVE_MESSAGES */ /** * Transmit static string as error response and add specified header */ #ifdef HAVE_MESSAGES # define transmit_error_response_header(c, code, m, hd_n, hd_n_l, hd_v, hd_v_l) \ transmit_error_response_len (c, code, \ m, MHD_STATICSTR_LEN_ (m), \ hd_n, hd_n_l, \ hd_v, hd_v_l) #else /* ! HAVE_MESSAGES */ # define transmit_error_response_header(c, code, m, hd_n, hd_n_l, hd_v, hd_v_l) \ transmit_error_response_len (c, code, \ "", 0, \ hd_n, hd_n_l, \ hd_v, hd_v_l) #endif /* ! HAVE_MESSAGES */ /** * Check whether the read buffer has any upload body data ready to * be processed. * Must be called only when connection is in MHD_CONNECTION_BODY_RECEIVING * state. * * @param c the connection to check * @return 'true' if upload body data is already in the read buffer, * 'false' if no upload data is received and not processed. */ static bool has_unprocessed_upload_body_data_in_buffer (struct MHD_Connection *c) { mhd_assert (MHD_CONNECTION_BODY_RECEIVING == c->state); if (! c->rq.have_chunked_upload) return 0 != c->read_buffer_offset; /* Chunked upload */ mhd_assert (0 != c->rq.remaining_upload_size); /* Must not be possible in MHD_CONNECTION_BODY_RECEIVING state */ if (c->rq.current_chunk_offset == c->rq.current_chunk_size) { /* 0 == c->rq.current_chunk_size: Waiting the chunk size (chunk header). 0 != c->rq.current_chunk_size: Waiting for chunk-closing CRLF. */ return false; } return 0 != c->read_buffer_offset; /* Chunk payload data in the read buffer */ } /** * The stage of input data processing. * Used for out-of-memory (in the pool) handling. */ enum MHD_ProcRecvDataStage { MHD_PROC_RECV_INIT, /**< No data HTTP request data have been processed yet */ MHD_PROC_RECV_METHOD, /**< Processing/receiving the request HTTP method */ MHD_PROC_RECV_URI, /**< Processing/receiving the request URI */ MHD_PROC_RECV_HTTPVER, /**< Processing/receiving the request HTTP version string */ MHD_PROC_RECV_HEADERS, /**< Processing/receiving the request HTTP headers */ MHD_PROC_RECV_COOKIE, /**< Processing the received request cookie header */ MHD_PROC_RECV_BODY_NORMAL, /**< Processing/receiving the request non-chunked body */ MHD_PROC_RECV_BODY_CHUNKED,/**< Processing/receiving the request chunked body */ MHD_PROC_RECV_FOOTERS /**< Processing/receiving the request footers */ }; #ifndef MHD_MAX_REASONABLE_HEADERS_SIZE_ /** * A reasonable headers size (excluding request line) that should be sufficient * for most requests. * If incoming data buffer free space is not enough to process the complete * header (the request line and all headers) and the headers size is larger than * this size then the status code 431 "Request Header Fields Too Large" is * returned to the client. * The larger headers are processed by MHD if enough space is available. */ # define MHD_MAX_REASONABLE_HEADERS_SIZE_ (6 * 1024) #endif /* ! MHD_MAX_REASONABLE_HEADERS_SIZE_ */ #ifndef MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ /** * A reasonable request target (the request URI) size that should be sufficient * for most requests. * If incoming data buffer free space is not enough to process the complete * header (the request line and all headers) and the request target size is * larger than this size then the status code 414 "URI Too Long" is * returned to the client. * The larger request targets are processed by MHD if enough space is available. * The value chosen according to RFC 9112 Section 3, paragraph 5 */ # define MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ 8000 #endif /* ! MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ */ #ifndef MHD_MIN_REASONABLE_HEADERS_SIZE_ /** * A reasonable headers size (excluding request line) that should be sufficient * for basic simple requests. * When no space left in the receiving buffer try to avoid replying with * the status code 431 "Request Header Fields Too Large" if headers size * is smaller then this value. */ # define MHD_MIN_REASONABLE_HEADERS_SIZE_ 26 #endif /* ! MHD_MIN_REASONABLE_HEADERS_SIZE_ */ #ifndef MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ /** * A reasonable request target (the request URI) size that should be sufficient * for basic simple requests. * When no space left in the receiving buffer try to avoid replying with * the status code 414 "URI Too Long" if the request target size is smaller then * this value. */ # define MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ 40 #endif /* ! MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ */ #ifndef MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ /** * A reasonable request method string size that should be sufficient * for basic simple requests. * When no space left in the receiving buffer try to avoid replying with * the status code 501 "Not Implemented" if the request method size is * smaller then this value. */ # define MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ 16 #endif /* ! MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ */ #ifndef MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ /** * A reasonable minimal chunk line length. * When no space left in the receiving buffer reply with 413 "Content Too Large" * if the chunk line length is larger than this value. */ # define MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ 4 #endif /* ! MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ */ /** * Select the HTTP error status code for "out of receive buffer space" error. * @param c the connection to process * @param stage the current stage of request receiving * @param add_element the optional pointer to the element failed to be processed * or added, the meaning of the element depends on * the @a stage. Could be not zero-terminated and can * contain binary zeros. Can be NULL. * @param add_element_size the size of the @a add_element * @return the HTTP error code to use in the error reply */ static unsigned int get_no_space_err_status_code (struct MHD_Connection *c, enum MHD_ProcRecvDataStage stage, const char *add_element, size_t add_element_size) { size_t method_size; size_t uri_size; size_t opt_headers_size; size_t host_field_line_size; mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVED < c->state); mhd_assert (MHD_PROC_RECV_HEADERS <= stage); mhd_assert ((0 == add_element_size) || (NULL != add_element)); if (MHD_CONNECTION_HEADERS_RECEIVED > c->state) { mhd_assert (NULL != c->rq.field_lines.start); opt_headers_size = (size_t) ((c->read_buffer + c->read_buffer_offset) - c->rq.field_lines.start); } else opt_headers_size = c->rq.field_lines.size; /* The read buffer is fully used by the request line, the field lines (headers) and internal information. The return status code works as a suggestion for the client to reduce one of the request elements. */ if ((MHD_PROC_RECV_BODY_CHUNKED == stage) && (MHD_MIN_REASONABLE_REQ_CHUNK_LINE_LENGTH_ < add_element_size)) { /* Request could be re-tried easily with smaller chunk sizes */ return MHD_HTTP_CONTENT_TOO_LARGE; } host_field_line_size = 0; /* The "Host:" field line is mandatory. The total size of the field lines (headers) cannot be smaller than the size of the "Host:" field line. */ if ((MHD_PROC_RECV_HEADERS == stage) && (0 != add_element_size)) { static const size_t header_host_key_len = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_HOST); const bool is_host_header = (header_host_key_len + 1 <= add_element_size) && ( (0 == add_element[header_host_key_len]) || (':' == add_element[header_host_key_len]) ) && MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_HOST, add_element, header_host_key_len); if (is_host_header) { const bool is_parsed = ! ( (MHD_CONNECTION_HEADERS_RECEIVED > c->state) && (add_element_size == c->read_buffer_offset) && (c->read_buffer == add_element) ); size_t actual_element_size; mhd_assert (! is_parsed || (0 == add_element[header_host_key_len])); /* The actual size should be larger due to CRLF or LF chars, however the exact termination sequence is not known here and as perfect precision is not required, to simplify the code assume the minimal length. */ if (is_parsed) actual_element_size = add_element_size + 1; /* "1" for LF */ else actual_element_size = add_element_size; host_field_line_size = actual_element_size; mhd_assert (opt_headers_size >= actual_element_size); opt_headers_size -= actual_element_size; } } if (0 == host_field_line_size) { static const size_t host_field_name_len = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_HOST); size_t host_field_name_value_len; if (MHD_NO != MHD_lookup_connection_value_n (c, MHD_HEADER_KIND, MHD_HTTP_HEADER_HOST, host_field_name_len, NULL, &host_field_name_value_len)) { /* Calculate the minimal size of the field line: no space between colon and the field value, line terminated by LR */ host_field_line_size = host_field_name_len + host_field_name_value_len + 2; /* "2" for ':' and LF */ /* The "Host:" field could be added by application */ if (opt_headers_size >= host_field_line_size) { opt_headers_size -= host_field_line_size; /* Take into account typical space after colon and CR at the end of the line */ if (opt_headers_size >= 2) opt_headers_size -= 2; } else host_field_line_size = 0; /* No "Host:" field line set by the client */ } } uri_size = c->rq.req_target_len; if (MHD_HTTP_MTHD_OTHER != c->rq.http_mthd) method_size = 0; /* Do not recommend shorter request method */ else { mhd_assert (NULL != c->rq.method); method_size = strlen (c->rq.method); } if ((size_t) MHD_MAX_REASONABLE_HEADERS_SIZE_ < opt_headers_size) { /* Typically the easiest way to reduce request header size is a removal of some optional headers. */ if (opt_headers_size > (uri_size / 8)) { if ((opt_headers_size / 2) > method_size) return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE; else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } else { /* Request target is MUCH larger than headers */ if ((uri_size / 16) > method_size) return MHD_HTTP_URI_TOO_LONG; else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } } if ((size_t) MHD_MAX_REASONABLE_REQ_TARGET_SIZE_ < uri_size) { /* If request target size if larger than maximum reasonable size recommend client to reduce the request target size (length). */ if ((uri_size / 16) > method_size) return MHD_HTTP_URI_TOO_LONG; /* Request target is MUCH larger than headers */ else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } /* The read buffer is too small to handle reasonably large requests */ if ((size_t) MHD_MIN_REASONABLE_HEADERS_SIZE_ < opt_headers_size) { /* Recommend application to retry with minimal headers */ if ((opt_headers_size * 4) > uri_size) { if (opt_headers_size > method_size) return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE; else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } else { /* Request target is significantly larger than headers */ if (uri_size > method_size * 4) return MHD_HTTP_URI_TOO_LONG; else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } } if ((size_t) MHD_MIN_REASONABLE_REQ_TARGET_SIZE_ < uri_size) { /* Recommend application to retry with a shorter request target */ if (uri_size > method_size * 4) return MHD_HTTP_URI_TOO_LONG; else return MHD_HTTP_NOT_IMPLEMENTED; /* The length of the HTTP request method is unreasonably large */ } if ((size_t) MHD_MIN_REASONABLE_REQ_METHOD_SIZE_ < method_size) { /* The request target (URI) and headers are (reasonably) very small. Some non-standard long request method is used. */ /* The last resort response as it means "the method is not supported by the server for any URI". */ return MHD_HTTP_NOT_IMPLEMENTED; } /* The almost impossible situation: all elements are small, but cannot fit the buffer. The application set the buffer size to critically low value? */ if ((1 < opt_headers_size) || (1 < uri_size)) { if (opt_headers_size >= uri_size) return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE; else return MHD_HTTP_URI_TOO_LONG; } /* Nothing to reduce in the request. Reply with some status. */ if (0 != host_field_line_size) return MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE; return MHD_HTTP_URI_TOO_LONG; } /** * Send error reply when receive buffer space exhausted while receiving or * storing the request headers * @param c the connection to handle * @param add_header the optional pointer to the current header string being * processed or the header failed to be added. * Could be not zero-terminated and can contain binary zeros. * Can be NULL. * @param add_header_size the size of the @a add_header */ static void handle_req_headers_no_space (struct MHD_Connection *c, const char *add_header, size_t add_header_size) { unsigned int err_code; err_code = get_no_space_err_status_code (c, MHD_PROC_RECV_HEADERS, add_header, add_header_size); transmit_error_response_static (c, err_code, ERR_MSG_REQUEST_HEADER_TOO_BIG); } #ifdef COOKIE_SUPPORT /** * Send error reply when the pool has no space to store 'cookie' header * parsing results. * @param c the connection to handle */ static void handle_req_cookie_no_space (struct MHD_Connection *c) { unsigned int err_code; err_code = get_no_space_err_status_code (c, MHD_PROC_RECV_COOKIE, NULL, 0); transmit_error_response_static (c, err_code, ERR_MSG_REQUEST_HEADER_WITH_COOKIES_TOO_BIG); } #endif /* COOKIE_SUPPORT */ /** * Send error reply when receive buffer space exhausted while receiving * the chunk size line. * @param c the connection to handle * @param add_header the optional pointer to the partially received * the current chunk size line. * Could be not zero-terminated and can contain binary zeros. * Can be NULL. * @param add_header_size the size of the @a add_header */ static void handle_req_chunk_size_line_no_space (struct MHD_Connection *c, const char *chunk_size_line, size_t chunk_size_line_size) { unsigned int err_code; if (NULL != chunk_size_line) { const char *semicol; /* Check for chunk extension */ semicol = memchr (chunk_size_line, ';', chunk_size_line_size); if (NULL != semicol) { /* Chunk extension present. It could be removed without any loss of the details of the request. */ transmit_error_response_static (c, MHD_HTTP_CONTENT_TOO_LARGE, ERR_MSG_REQUEST_CHUNK_LINE_EXT_TOO_BIG); return; /* The error response has been queued already */ } } err_code = get_no_space_err_status_code (c, MHD_PROC_RECV_BODY_CHUNKED, chunk_size_line, chunk_size_line_size); transmit_error_response_static (c, err_code, ERR_MSG_REQUEST_CHUNK_LINE_TOO_BIG); } /** * Send error reply when receive buffer space exhausted while receiving or * storing the request footers (for chunked requests). * @param c the connection to handle * @param add_footer the optional pointer to the current footer string being * processed or the footer failed to be added. * Could be not zero-terminated and can contain binary zeros. * Can be NULL. * @param add_footer_size the size of the @a add_footer */ static void handle_req_footers_no_space (struct MHD_Connection *c, const char *add_footer, size_t add_footer_size) { (void) add_footer; (void) add_footer_size; /* Unused */ mhd_assert (c->rq.have_chunked_upload); /* Footers should be optional */ transmit_error_response_static (c, MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, ERR_MSG_REQUEST_FOOTER_TOO_BIG); } /** * Handle situation with read buffer exhaustion. * Must be called when no more space left in the read buffer, no more * space left in the memory pool to grow the read buffer, but more data * need to be received from the client. * Could be called when the result of received data processing cannot be * stored in the memory pool (like some header). * @param c the connection to process * @param stage the receive stage where the exhaustion happens. */ static void handle_recv_no_space (struct MHD_Connection *c, enum MHD_ProcRecvDataStage stage) { mhd_assert (MHD_PROC_RECV_INIT <= stage); mhd_assert (MHD_PROC_RECV_FOOTERS >= stage); mhd_assert (MHD_CONNECTION_FULL_REQ_RECEIVED > c->state); mhd_assert ((MHD_PROC_RECV_INIT != stage) || \ (MHD_CONNECTION_INIT == c->state)); mhd_assert ((MHD_PROC_RECV_METHOD != stage) || \ (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_URI != stage) || \ (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_HTTPVER != stage) || \ (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_HEADERS != stage) || \ (MHD_CONNECTION_REQ_HEADERS_RECEIVING == c->state)); mhd_assert (MHD_PROC_RECV_COOKIE != stage); /* handle_req_cookie_no_space() must be called directly */ mhd_assert ((MHD_PROC_RECV_BODY_NORMAL != stage) || \ (MHD_CONNECTION_BODY_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) || \ (MHD_CONNECTION_BODY_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_FOOTERS != stage) || \ (MHD_CONNECTION_FOOTERS_RECEIVING == c->state)); mhd_assert ((MHD_PROC_RECV_BODY_NORMAL != stage) || \ (! c->rq.have_chunked_upload)); mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) || \ (c->rq.have_chunked_upload)); switch (stage) { case MHD_PROC_RECV_INIT: case MHD_PROC_RECV_METHOD: /* Some data has been received, but it is not clear yet whether * the received data is an valid HTTP request */ connection_close_error (c, _ ("No space left in the read buffer when " \ "receiving the initial part of " \ "the request line.")); return; case MHD_PROC_RECV_URI: case MHD_PROC_RECV_HTTPVER: /* Some data has been received, but the request line is incomplete */ mhd_assert (MHD_HTTP_MTHD_NO_METHOD != c->rq.http_mthd); mhd_assert (MHD_HTTP_VER_UNKNOWN == c->rq.http_ver); /* A quick simple check whether the incomplete line looks * like an HTTP request */ if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) && (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd)) { transmit_error_response_static (c, MHD_HTTP_URI_TOO_LONG, ERR_MSG_REQUEST_TOO_BIG); return; } connection_close_error (c, _ ("No space left in the read buffer when " \ "receiving the URI in " \ "the request line. " \ "The request uses non-standard HTTP request " \ "method token.")); return; case MHD_PROC_RECV_HEADERS: handle_req_headers_no_space (c, c->read_buffer, c->read_buffer_offset); return; case MHD_PROC_RECV_BODY_NORMAL: case MHD_PROC_RECV_BODY_CHUNKED: /* The 'some_payload_processed' flag reflects the *last* application callback only. After that callback more data may have been received from the network, in particular a chunk-size line with a chunk extension that does not fit into the read buffer. Therefore the flag alone does not imply that free space is available; it does so only as long as unprocessed payload is still sitting in the buffer. */ mhd_assert ((MHD_PROC_RECV_BODY_CHUNKED != stage) || \ (! c->rq.some_payload_processed) || \ (! has_unprocessed_upload_body_data_in_buffer (c))); if (has_unprocessed_upload_body_data_in_buffer (c)) { /* The connection must not be in MHD_EVENT_LOOP_INFO_READ state when external polling is used and some data left unprocessed. */ mhd_assert (MHD_D_IS_USING_THREADS_ (c->daemon)); /* failed to grow the read buffer, and the client which is supposed to handle the received data in a *blocking* fashion (in this mode) did not handle the data as it was supposed to! => we would either have to do busy-waiting (on the client, which would likely fail), or if we do nothing, we would just timeout on the connection (if a timeout is even set!). Solution: we kill the connection with an error */ transmit_error_response_static (c, MHD_HTTP_INTERNAL_SERVER_ERROR, ERROR_MSG_DATA_NOT_HANDLED_BY_APP); } else { if (MHD_PROC_RECV_BODY_NORMAL == stage) { /* A header probably has been added to a suspended connection and it took precisely all the space in the buffer. Very low probability. */ mhd_assert (! c->rq.have_chunked_upload); handle_req_headers_no_space (c, NULL, 0); } else { mhd_assert (c->rq.have_chunked_upload); if (c->rq.current_chunk_offset != c->rq.current_chunk_size) { /* Receiving content of the chunk */ /* A header probably has been added to a suspended connection and it took precisely all the space in the buffer. Very low probability. */ handle_req_headers_no_space (c, NULL, 0); } else { if (0 != c->rq.current_chunk_size) { /* Waiting for chunk-closing CRLF */ /* Not really possible as some payload should be processed and the space used by payload should be available. */ handle_req_headers_no_space (c, NULL, 0); } else { /* Reading the line with the chunk size */ handle_req_chunk_size_line_no_space (c, c->read_buffer, c->read_buffer_offset); } } } } return; case MHD_PROC_RECV_FOOTERS: handle_req_footers_no_space (c, c->read_buffer, c->read_buffer_offset); return; /* The next cases should not be possible */ case MHD_PROC_RECV_COOKIE: default: break; } mhd_assert (0); } /** * Check whether enough space is available in the read buffer for the next * operation. * Handles grow of the buffer if required and error conditions (when buffer * grow is required but not possible). * Must be called only when processing the event loop states and when * reading is required for the next phase. * @param c the connection to check * @return true if connection handled successfully and enough buffer * is available, * false if not enough buffer is available and the loop's states * must be processed again as connection is in the error state. */ static bool check_and_grow_read_buffer_space (struct MHD_Connection *c) { /** * The increase of read buffer size is desirable. */ bool rbuff_grow_desired; /** * The increase of read buffer size is a hard requirement. */ bool rbuff_grow_required; mhd_assert (0 != (MHD_EVENT_LOOP_INFO_READ & c->event_loop_info)); mhd_assert (! c->discard_request); rbuff_grow_required = (c->read_buffer_offset == c->read_buffer_size); if (rbuff_grow_required) rbuff_grow_desired = true; else { rbuff_grow_desired = (c->read_buffer_offset + c->daemon->pool_increment > c->read_buffer_size); if ((rbuff_grow_desired) && (MHD_CONNECTION_BODY_RECEIVING == c->state)) { if (! c->rq.have_chunked_upload) { mhd_assert (MHD_SIZE_UNKNOWN != c->rq.remaining_upload_size); /* Do not grow read buffer more than necessary to process the current request. */ rbuff_grow_desired = (c->rq.remaining_upload_size > c->read_buffer_size); } else { mhd_assert (MHD_SIZE_UNKNOWN == c->rq.remaining_upload_size); if (0 == c->rq.current_chunk_size) rbuff_grow_desired = /* Reading value of the next chunk size */ (MHD_CHUNK_HEADER_REASONABLE_LEN > c->read_buffer_size); else { const uint64_t cur_chunk_left = c->rq.current_chunk_size - c->rq.current_chunk_offset; /* Do not grow read buffer more than necessary to process the current chunk with terminating CRLF. */ mhd_assert (c->rq.current_chunk_offset <= c->rq.current_chunk_size); rbuff_grow_desired = ((cur_chunk_left + 2) > (uint64_t) (c->read_buffer_size)); } } } } if (! rbuff_grow_desired) return true; /* No need to increase the buffer */ if (try_grow_read_buffer (c, rbuff_grow_required)) return true; /* Buffer increase succeed */ if (! rbuff_grow_required) return true; /* Can continue without buffer increase */ /* Failed to increase the read buffer size, but need to read the data from the network. No more space left in the buffer, no more space to increase the buffer. */ /* 'PROCESS_READ' event state flag must be set only if the last application callback has processed some data. If any data is processed then some space in the read buffer must be available. */ mhd_assert (0 == (MHD_EVENT_LOOP_INFO_PROCESS & c->event_loop_info)); if ((! MHD_D_IS_USING_THREADS_ (c->daemon)) && (MHD_CONNECTION_BODY_RECEIVING == c->state) && has_unprocessed_upload_body_data_in_buffer (c)) { /* The application is handling processing cycles. The data could be processed later. */ c->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS; return true; } else { enum MHD_ProcRecvDataStage stage; switch (c->state) { case MHD_CONNECTION_INIT: stage = MHD_PROC_RECV_INIT; break; case MHD_CONNECTION_REQ_LINE_RECEIVING: if (MHD_HTTP_MTHD_NO_METHOD == c->rq.http_mthd) stage = MHD_PROC_RECV_METHOD; else if (0 == c->rq.req_target_len) stage = MHD_PROC_RECV_URI; else stage = MHD_PROC_RECV_HTTPVER; break; case MHD_CONNECTION_REQ_HEADERS_RECEIVING: stage = MHD_PROC_RECV_HEADERS; break; case MHD_CONNECTION_BODY_RECEIVING: stage = c->rq.have_chunked_upload ? MHD_PROC_RECV_BODY_CHUNKED : MHD_PROC_RECV_BODY_NORMAL; break; case MHD_CONNECTION_FOOTERS_RECEIVING: stage = MHD_PROC_RECV_FOOTERS; break; case MHD_CONNECTION_REQ_LINE_RECEIVED: case MHD_CONNECTION_HEADERS_RECEIVED: case MHD_CONNECTION_HEADERS_PROCESSED: case MHD_CONNECTION_CONTINUE_SENDING: case MHD_CONNECTION_BODY_RECEIVED: case MHD_CONNECTION_FOOTERS_RECEIVED: case MHD_CONNECTION_FULL_REQ_RECEIVED: case MHD_CONNECTION_START_REPLY: case MHD_CONNECTION_HEADERS_SENDING: case MHD_CONNECTION_HEADERS_SENT: case MHD_CONNECTION_NORMAL_BODY_UNREADY: case MHD_CONNECTION_NORMAL_BODY_READY: case MHD_CONNECTION_CHUNKED_BODY_UNREADY: case MHD_CONNECTION_CHUNKED_BODY_READY: case MHD_CONNECTION_CHUNKED_BODY_SENT: case MHD_CONNECTION_FOOTERS_SENDING: case MHD_CONNECTION_FULL_REPLY_SENT: case MHD_CONNECTION_CLOSED: #ifdef UPGRADE_SUPPORT case MHD_CONNECTION_UPGRADE: #endif default: stage = MHD_PROC_RECV_BODY_NORMAL; mhd_assert (0); } handle_recv_no_space (c, stage); } return false; } /** * Update the 'event_loop_info' field of this connection based on the state * that the connection is now in. May also close the connection or * perform other updates to the connection if needed to prepare for * the next round of the event loop. * * @param connection connection to get poll set for */ static void MHD_connection_update_event_loop_info (struct MHD_Connection *connection) { /* Do not update states of suspended connection */ if (connection->suspended) return; /* States will be updated after resume. */ #ifdef HTTPS_SUPPORT if (MHD_TLS_CONN_NO_TLS != connection->tls_state) { /* HTTPS connection. */ switch (connection->tls_state) { case MHD_TLS_CONN_INIT: connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; return; case MHD_TLS_CONN_HANDSHAKING: case MHD_TLS_CONN_WR_CLOSING: if (0 == gnutls_record_get_direction (connection->tls_session)) connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; else connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; return; case MHD_TLS_CONN_CONNECTED: break; /* Do normal processing */ case MHD_TLS_CONN_WR_CLOSED: case MHD_TLS_CONN_TLS_FAILED: connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP; return; case MHD_TLS_CONN_TLS_CLOSING: /* Not implemented yet */ case MHD_TLS_CONN_TLS_CLOSED: /* Not implemented yet */ case MHD_TLS_CONN_INVALID_STATE: case MHD_TLS_CONN_NO_TLS: /* Not possible */ default: MHD_PANIC (_ ("Invalid TLS state value.\n")); } } #endif /* HTTPS_SUPPORT */ while (1) { #if DEBUG_STATES MHD_DLOG (connection->daemon, _ ("In function %s handling connection at state: %s\n"), MHD_FUNC_, MHD_state_to_string (connection->state)); #endif switch (connection->state) { case MHD_CONNECTION_INIT: case MHD_CONNECTION_REQ_LINE_RECEIVING: connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; break; case MHD_CONNECTION_REQ_LINE_RECEIVED: mhd_assert (0); break; case MHD_CONNECTION_REQ_HEADERS_RECEIVING: connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; break; case MHD_CONNECTION_HEADERS_RECEIVED: case MHD_CONNECTION_HEADERS_PROCESSED: mhd_assert (0); break; case MHD_CONNECTION_CONTINUE_SENDING: connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; break; case MHD_CONNECTION_BODY_RECEIVING: if ((connection->rq.some_payload_processed) && has_unprocessed_upload_body_data_in_buffer (connection)) { /* Some data was processed, the buffer must have some free space */ mhd_assert (connection->read_buffer_offset < \ connection->read_buffer_size); if (! connection->rq.have_chunked_upload) { /* Not a chunked upload. Do not read more than necessary to process the current request. */ if (connection->rq.remaining_upload_size >= connection->read_buffer_offset) connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS; else connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS_READ; } else { /* Chunked upload. The size of the current request is unknown. Continue reading as the space in the read buffer is available. */ connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS_READ; } } else connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; break; case MHD_CONNECTION_BODY_RECEIVED: mhd_assert (0); break; case MHD_CONNECTION_FOOTERS_RECEIVING: connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; break; case MHD_CONNECTION_FOOTERS_RECEIVED: mhd_assert (0); break; case MHD_CONNECTION_FULL_REQ_RECEIVED: connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS; break; case MHD_CONNECTION_START_REPLY: mhd_assert (0); break; case MHD_CONNECTION_HEADERS_SENDING: /* headers in buffer, keep writing */ connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; break; case MHD_CONNECTION_HEADERS_SENT: mhd_assert (0); break; case MHD_CONNECTION_NORMAL_BODY_UNREADY: connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS; break; case MHD_CONNECTION_NORMAL_BODY_READY: connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; break; case MHD_CONNECTION_CHUNKED_BODY_UNREADY: connection->event_loop_info = MHD_EVENT_LOOP_INFO_PROCESS; break; case MHD_CONNECTION_CHUNKED_BODY_READY: connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; break; case MHD_CONNECTION_CHUNKED_BODY_SENT: mhd_assert (0); break; case MHD_CONNECTION_FOOTERS_SENDING: connection->event_loop_info = MHD_EVENT_LOOP_INFO_WRITE; break; case MHD_CONNECTION_FULL_REPLY_SENT: mhd_assert (0); break; case MHD_CONNECTION_CLOSED: connection->event_loop_info = MHD_EVENT_LOOP_INFO_CLEANUP; return; /* do nothing, not even reading */ #ifdef UPGRADE_SUPPORT case MHD_CONNECTION_UPGRADE: mhd_assert (0); break; #endif /* UPGRADE_SUPPORT */ default: mhd_assert (0); } if (0 != (MHD_EVENT_LOOP_INFO_READ & connection->event_loop_info)) { /* Check whether the space is available to receive data */ if (! check_and_grow_read_buffer_space (connection)) { mhd_assert (connection->discard_request); continue; } } break; /* Everything was processed. */ } } /** * Add an entry to the HTTP headers of a connection. If this fails, * transmit an error response (request too big). * * @param cls the context (connection) * @param kind kind of the value * @param key key for the value * @param key_size number of bytes in @a key * @param value the value itself * @param value_size number of bytes in @a value * @return #MHD_NO on failure (out of memory), #MHD_YES for success */ static enum MHD_Result connection_add_header (void *cls, const char *key, size_t key_size, const char *value, size_t value_size, enum MHD_ValueKind kind) { struct MHD_Connection *connection = (struct MHD_Connection *) cls; if (MHD_NO == MHD_set_connection_value_n (connection, kind, key, key_size, value, value_size)) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Not enough memory in pool to allocate header record!\n")); #endif transmit_error_response_static (connection, MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, ERR_MSG_REQUEST_TOO_BIG); return MHD_NO; } return MHD_YES; } #ifdef COOKIE_SUPPORT /** * Cookie parsing result */ enum _MHD_ParseCookie { MHD_PARSE_COOKIE_OK = MHD_YES, /**< Success or no cookies in headers */ MHD_PARSE_COOKIE_OK_LAX = 2, /**< Cookies parsed, but workarounds used */ MHD_PARSE_COOKIE_MALFORMED = -1, /**< Invalid cookie header */ MHD_PARSE_COOKIE_NO_MEMORY = MHD_NO /**< Not enough memory in the pool */ }; /** * Parse the cookies string (see RFC 6265). * * Try to parse the cookies string even if it is not strictly formed * as specified by RFC 6265. * * @param str the string to parse, without leading whitespaces * @param str_len the size of the @a str, not including mandatory * zero-termination * @param connection the connection to add parsed cookies * @return #MHD_PARSE_COOKIE_OK for success, error code otherwise */ static enum _MHD_ParseCookie parse_cookies_string (char *str, const size_t str_len, struct MHD_Connection *connection) { size_t i; bool non_strict; /* Skip extra whitespaces and empty cookies */ const bool allow_wsp_empty = (0 >= connection->daemon->client_discipline); /* Allow whitespaces around '=' character */ const bool wsp_around_eq = (-3 >= connection->daemon->client_discipline); /* Allow whitespaces in quoted cookie value */ const bool wsp_in_quoted = (-2 >= connection->daemon->client_discipline); /* Allow tab as space after semicolon between cookies */ const bool tab_as_sp = (0 >= connection->daemon->client_discipline); /* Allow no space after semicolon between cookies */ const bool allow_no_space = (0 >= connection->daemon->client_discipline); non_strict = false; i = 0; while (i < str_len) { size_t name_start; size_t name_len; size_t value_start; size_t value_len; bool val_quoted; /* Skip any whitespaces and empty cookies */ while (' ' == str[i] || '\t' == str[i] || ';' == str[i]) { if (! allow_wsp_empty) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; i++; if (i == str_len) return non_strict? MHD_PARSE_COOKIE_OK_LAX : MHD_PARSE_COOKIE_OK; } /* 'i' must point to the first char of cookie-name */ name_start = i; /* Find the end of the cookie-name */ do { const char l = str[i]; if (('=' == l) || (' ' == l) || ('\t' == l) || ('"' == l) || (',' == l) || (';' == l) || (0 == l)) break; } while (str_len > ++i); name_len = i - name_start; /* Skip any whitespaces */ while (str_len > i && (' ' == str[i] || '\t' == str[i])) { if (! wsp_around_eq) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; i++; } if ((str_len == i) || ('=' != str[i]) || (0 == name_len)) return MHD_PARSE_COOKIE_MALFORMED; /* Incomplete cookie name */ /* 'i' must point to the '=' char */ mhd_assert ('=' == str[i]); i++; /* Skip any whitespaces */ while (str_len > i && (' ' == str[i] || '\t' == str[i])) { if (! wsp_around_eq) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; i++; } /* 'i' must point to the first char of cookie-value */ if (str_len == i) { value_start = 0; value_len = 0; #ifdef _DEBUG val_quoted = false; /* This assignment used in assert */ #endif } else { bool valid_cookie; val_quoted = ('"' == str[i]); if (val_quoted) i++; value_start = i; /* Find the end of the cookie-value */ while (str_len > i) { const char l = str[i]; if ((';' == l) || ('"' == l) || (',' == l) || (';' == l) || ('\\' == l) || (0 == l)) break; if ((' ' == l) || ('\t' == l)) { if (! val_quoted) break; if (! wsp_in_quoted) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; } i++; } value_len = i - value_start; if (val_quoted) { if ((str_len == i) || ('"' != str[i])) return MHD_PARSE_COOKIE_MALFORMED; /* Incomplete cookie value, no closing quote */ i++; } /* Skip any whitespaces */ if ((str_len > i) && ((' ' == str[i]) || ('\t' == str[i]))) { do { i++; } while (str_len > i && (' ' == str[i] || '\t' == str[i])); /* Whitespace at the end? */ if (str_len > i) { if (! allow_wsp_empty) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; } } if (str_len == i) valid_cookie = true; else if (';' == str[i]) valid_cookie = true; else valid_cookie = false; if (! valid_cookie) return MHD_PARSE_COOKIE_MALFORMED; /* Garbage at the end of the cookie value */ } mhd_assert (0 != name_len); str[name_start + name_len] = 0; /* Zero-terminate the name */ if (0 != value_len) { mhd_assert (value_start + value_len <= str_len); str[value_start + value_len] = 0; /* Zero-terminate the value */ if (MHD_NO == MHD_set_connection_value_n_nocheck_ (connection, MHD_COOKIE_KIND, str + name_start, name_len, str + value_start, value_len)) return MHD_PARSE_COOKIE_NO_MEMORY; } else { if (MHD_NO == MHD_set_connection_value_n_nocheck_ (connection, MHD_COOKIE_KIND, str + name_start, name_len, "", 0)) return MHD_PARSE_COOKIE_NO_MEMORY; } if (str_len > i) { mhd_assert (0 == str[i] || ';' == str[i]); mhd_assert (! val_quoted || ';' == str[i]); mhd_assert (';' != str[i] || val_quoted || non_strict || 0 == value_len); i++; if (str_len == i) { /* No next cookie after semicolon */ if (! allow_wsp_empty) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; } else if (' ' != str[i]) {/* No space after semicolon */ if (('\t' == str[i]) && tab_as_sp) i++; else if (! allow_no_space) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; } else { i++; if (str_len == i) { if (! allow_wsp_empty) return MHD_PARSE_COOKIE_MALFORMED; non_strict = true; } } } } return non_strict? MHD_PARSE_COOKIE_OK_LAX : MHD_PARSE_COOKIE_OK; } /** * Parse the cookie header (see RFC 6265). * * @param connection connection to parse header of * @param hdr the value of the "Cookie:" header * @param hdr_len the length of the @a hdr string * @return #MHD_PARSE_COOKIE_OK for success, error code otherwise */ static enum _MHD_ParseCookie parse_cookie_header (struct MHD_Connection *connection, const char *hdr, size_t hdr_len) { char *cpy; size_t i; enum _MHD_ParseCookie parse_res; struct MHD_HTTP_Req_Header *const saved_tail = connection->rq.headers_received_tail; const bool allow_partially_correct_cookie = (1 >= connection->daemon->client_discipline); if (0 == hdr_len) return MHD_PARSE_COOKIE_OK; cpy = MHD_connection_alloc_memory_ (connection, hdr_len + 1); if (NULL == cpy) parse_res = MHD_PARSE_COOKIE_NO_MEMORY; else { memcpy (cpy, hdr, hdr_len); cpy[hdr_len] = '\0'; i = 0; /* Skip all initial whitespaces */ while (i < hdr_len && (' ' == cpy[i] || '\t' == cpy[i])) i++; parse_res = parse_cookies_string (cpy + i, hdr_len - i, connection); } switch (parse_res) { case MHD_PARSE_COOKIE_OK: break; case MHD_PARSE_COOKIE_OK_LAX: #ifdef HAVE_MESSAGES if (saved_tail != connection->rq.headers_received_tail) MHD_DLOG (connection->daemon, _ ("The Cookie header has been parsed, but it is not fully " "compliant with the standard.\n")); #endif /* HAVE_MESSAGES */ break; case MHD_PARSE_COOKIE_MALFORMED: if (saved_tail != connection->rq.headers_received_tail) { if (! allow_partially_correct_cookie) { /* Remove extracted values from partially broken cookie */ /* Memory remains allocated until the end of the request processing */ connection->rq.headers_received_tail = saved_tail; saved_tail->next = NULL; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The Cookie header has been ignored as it contains " "malformed data.\n")); #endif /* HAVE_MESSAGES */ } #ifdef HAVE_MESSAGES else MHD_DLOG (connection->daemon, _ ("The Cookie header has been only partially parsed as it " "contains malformed data.\n")); #endif /* HAVE_MESSAGES */ } #ifdef HAVE_MESSAGES else MHD_DLOG (connection->daemon, _ ("The Cookie header has malformed data.\n")); #endif /* HAVE_MESSAGES */ break; case MHD_PARSE_COOKIE_NO_MEMORY: #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Not enough memory in the connection pool to " "parse client cookies!\n")); #endif /* HAVE_MESSAGES */ break; default: mhd_assert (0); break; } #ifndef HAVE_MESSAGES (void) saved_tail; /* Mute compiler warning */ #endif /* ! HAVE_MESSAGES */ return parse_res; } #endif /* COOKIE_SUPPORT */ /** * The valid length of any HTTP version string */ #define HTTP_VER_LEN (MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1)) /** * Detect HTTP version, send error response if version is not supported * * @param connection the connection * @param http_string the pointer to HTTP version string * @param len the length of @a http_string in bytes * @return true if HTTP version is correct and supported, * false if HTTP version is not correct or unsupported. */ static bool parse_http_version (struct MHD_Connection *connection, const char *http_string, size_t len) { const char *const h = http_string; /**< short alias */ mhd_assert (NULL != http_string); /* String must start with 'HTTP/d.d', case-sensitive match. * See https://www.rfc-editor.org/rfc/rfc9112#name-http-version */ if ((HTTP_VER_LEN != len) || ('H' != h[0]) || ('T' != h[1]) || ('T' != h[2]) || ('P' != h[3]) || ('/' != h[4]) || ('.' != h[6]) || (('0' > h[5]) || ('9' < h[5])) || (('0' > h[7]) || ('9' < h[7]))) { connection->rq.http_ver = MHD_HTTP_VER_INVALID; transmit_error_response_static (connection, MHD_HTTP_BAD_REQUEST, REQUEST_MALFORMED); return false; } if (1 == h[5] - '0') { /* HTTP/1.x */ if (1 == h[7] - '0') connection->rq.http_ver = MHD_HTTP_VER_1_1; else if (0 == h[7] - '0') connection->rq.http_ver = MHD_HTTP_VER_1_0; else connection->rq.http_ver = MHD_HTTP_VER_1_2__1_9; return true; } if (0 == h[5] - '0') { /* Too old major version */ connection->rq.http_ver = MHD_HTTP_VER_TOO_OLD; transmit_error_response_static (connection, MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED, REQ_HTTP_VER_IS_TOO_OLD); return false; } connection->rq.http_ver = MHD_HTTP_VER_FUTURE; transmit_error_response_static (connection, MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED, REQ_HTTP_VER_IS_NOT_SUPPORTED); return false; } /** * Detect standard HTTP request method * * @param connection the connection * @param method the pointer to HTTP request method string * @param len the length of @a method in bytes */ static void parse_http_std_method (struct MHD_Connection *connection, const char *method, size_t len) { const char *const m = method; /**< short alias */ mhd_assert (NULL != m); mhd_assert (0 != len); if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_GET) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_GET, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_GET; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_HEAD) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_HEAD, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_HEAD; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_POST) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_POST, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_POST; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_PUT) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_PUT, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_PUT; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_DELETE) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_DELETE, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_DELETE; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_CONNECT) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_CONNECT, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_CONNECT; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_OPTIONS) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_OPTIONS, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_OPTIONS; else if ((MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_TRACE) == len) && (0 == memcmp (m, MHD_HTTP_METHOD_TRACE, len))) connection->rq.http_mthd = MHD_HTTP_MTHD_TRACE; else connection->rq.http_mthd = MHD_HTTP_MTHD_OTHER; } /** * Call the handler of the application for this * connection. Handles chunking of the upload * as well as normal uploads. * * @param connection connection we're processing */ static void call_connection_handler (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; size_t processed; if (NULL != connection->rp.response) return; /* already queued a response */ processed = 0; connection->rq.client_aware = true; connection->in_access_handler = true; if (MHD_NO == daemon->default_handler (daemon->default_handler_cls, connection, connection->rq.url_for_callback, connection->rq.method, connection->rq.version, NULL, &processed, &connection->rq.client_context)) { connection->in_access_handler = false; /* serious internal error, close connection */ CONNECTION_CLOSE_ERROR (connection, _ ("Application reported internal error, " \ "closing connection.")); return; } connection->in_access_handler = false; } /** * Call the handler of the application for this * connection. Handles chunking of the upload * as well as normal uploads. * * @param connection connection we're processing */ static void process_request_body (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; size_t available; bool instant_retry; char *buffer_head; const int discp_lvl = daemon->client_discipline; /* RFC does not allow LF as the line termination in chunk headers. See RFC 9112, section 7.1 and section 2.2-3 */ const bool bare_lf_as_crlf = (-2 > discp_lvl); /* Allow "Bad WhiteSpace" in chunk extension. RFC 9112, Section 7.1.1, Paragraph 2 */ const bool allow_bws = (2 > discp_lvl); mhd_assert (NULL == connection->rp.response); buffer_head = connection->read_buffer; available = connection->read_buffer_offset; do { size_t to_be_processed; size_t left_unprocessed; size_t processed_size; instant_retry = false; if (connection->rq.have_chunked_upload) { mhd_assert (MHD_SIZE_UNKNOWN == connection->rq.remaining_upload_size); if ( (connection->rq.current_chunk_offset == connection->rq.current_chunk_size) && (0 != connection->rq.current_chunk_size) ) { /* Skip CRLF chunk termination */ size_t i; mhd_assert (0 != available); /* skip new line at the *end* of a chunk */ i = 0; if ( (2 <= available) && ('\r' == buffer_head[0]) && ('\n' == buffer_head[1]) ) i += 2; /* skip CRLF */ else if (bare_lf_as_crlf && ('\n' == buffer_head[0])) i++; /* skip bare LF */ else if (2 > available) break; /* need more upload data */ if (0 == i) { /* malformed encoding */ transmit_error_response_static (connection, MHD_HTTP_BAD_REQUEST, REQUEST_CHUNKED_MALFORMED); return; } available -= i; buffer_head += i; connection->rq.current_chunk_offset = 0; connection->rq.current_chunk_size = 0; if (0 == available) break; } if (0 != connection->rq.current_chunk_size) { /* Process chunk "content" */ uint64_t cur_chunk_left; mhd_assert (connection->rq.current_chunk_offset < \ connection->rq.current_chunk_size); cur_chunk_left = connection->rq.current_chunk_size - connection->rq.current_chunk_offset; if (cur_chunk_left > available) to_be_processed = available; else { /* cur_chunk_left <= (size_t)available */ to_be_processed = (size_t) cur_chunk_left; if (available > to_be_processed) instant_retry = true; } } else { /* Need the parse the chunk size line */ /** The number of found digits in the chunk size number */ size_t num_dig; uint64_t chunk_size; bool broken; bool overflow; mhd_assert (0 != available); overflow = false; chunk_size = 0; /* Mute possible compiler warning. The real value will be set later. */ num_dig = MHD_strx_to_uint64_n_ (buffer_head, available, &chunk_size); mhd_assert (num_dig <= available); if (num_dig == available) continue; /* Need line delimiter */ broken = (0 == num_dig); if (broken) { uint64_t dummy; /* Check whether result is invalid due to uint64_t overflow */ overflow = (0 != MHD_strx_to_uint64_n_ (buffer_head, 1, &dummy)); } else { /** * The length of the string with the number of the chunk size, * including chunk extension */ size_t chunk_size_line_len; chunk_size_line_len = 0; if ((';' == buffer_head[num_dig]) || (allow_bws && ((' ' == buffer_head[num_dig]) || ('\t' == buffer_head[num_dig])))) { /* Chunk extension or "bad whitespace" after chunk length */ size_t i; /* Skip bad whitespaces (if any) */ for (i = num_dig; i < available; ++i) { if ((' ' != buffer_head[i]) && ('\t' != buffer_head[i])) break; } if (i == available) break; /* need more data */ if (';' == buffer_head[i]) { /* Chunk extension */ for (++i; i < available; ++i) { if (('\r' == buffer_head[i]) || ('\n' == buffer_head[i])) break; } if (i == available) break; /* need more data */ mhd_assert (i > num_dig); mhd_assert (1 <= i); if ('\r' == buffer_head[i]) { if (i + 1 == available) break; /* need more data */ if ('\n' == buffer_head[i + 1]) chunk_size_line_len = i + 2; /* Valid chunk header */ } else { mhd_assert ('\n' == buffer_head[i]); if (bare_lf_as_crlf) chunk_size_line_len = i + 1; /* Valid chunk header */ } /* The chunk header is broken if chunk_size_line_len is zero here. */ } else { /* No ';' after "bad whitespace" */ mhd_assert (allow_bws); mhd_assert (0 == chunk_size_line_len); } } else { /* No chunk extension */ mhd_assert (available >= num_dig); if ((2 <= (available - num_dig)) && ('\r' == buffer_head[num_dig]) && ('\n' == buffer_head[num_dig + 1])) chunk_size_line_len = num_dig + 2; else if (bare_lf_as_crlf && ('\n' == buffer_head[num_dig])) chunk_size_line_len = num_dig + 1; else if (2 > (available - num_dig)) break; /* need more data */ } if (0 != chunk_size_line_len) { /* Valid termination of the chunk size line */ mhd_assert (chunk_size_line_len <= available); /* Start reading payload data of the chunk */ connection->rq.current_chunk_offset = 0; connection->rq.current_chunk_size = chunk_size; available -= chunk_size_line_len; buffer_head += chunk_size_line_len; if (0 == chunk_size) { /* The final (termination) chunk */ connection->rq.remaining_upload_size = 0; break; } if (available > 0) instant_retry = true; continue; } /* Invalid chunk size line */ } if (! overflow) transmit_error_response_static (connection, MHD_HTTP_BAD_REQUEST, REQUEST_CHUNKED_MALFORMED); else transmit_error_response_static (connection, MHD_HTTP_CONTENT_TOO_LARGE, REQUEST_CHUNK_TOO_LARGE); return; } } else { /* no chunked encoding, give all to the client */ mhd_assert (MHD_SIZE_UNKNOWN != connection->rq.remaining_upload_size); mhd_assert (0 != connection->rq.remaining_upload_size); if (connection->rq.remaining_upload_size < available) to_be_processed = (size_t) connection->rq.remaining_upload_size; else to_be_processed = available; } left_unprocessed = to_be_processed; connection->rq.client_aware = true; connection->in_access_handler = true; if (MHD_NO == daemon->default_handler (daemon->default_handler_cls, connection, connection->rq.url_for_callback, connection->rq.method, connection->rq.version, buffer_head, &left_unprocessed, &connection->rq.client_context)) { connection->in_access_handler = false; /* serious internal error, close connection */ CONNECTION_CLOSE_ERROR (connection, _ ("Application reported internal error, " \ "closing connection.")); return; } connection->in_access_handler = false; if (left_unprocessed > to_be_processed) MHD_PANIC (_ ("libmicrohttpd API violation.\n")); connection->rq.some_payload_processed = (left_unprocessed != to_be_processed); if (0 != left_unprocessed) { instant_retry = false; /* client did not process everything */ #ifdef HAVE_MESSAGES if ((! connection->rq.some_payload_processed) && (! connection->suspended)) { /* client did not process any upload data, complain if the setup was incorrect, which may prevent us from handling the rest of the request */ if (MHD_D_IS_USING_THREADS_ (daemon)) MHD_DLOG (daemon, _ ("WARNING: Access Handler Callback has not processed " \ "any upload data and connection is not suspended. " \ "This may result in hung connection.\n")); } #endif /* HAVE_MESSAGES */ } processed_size = to_be_processed - left_unprocessed; /* dh left "processed" bytes in buffer for next time... */ buffer_head += processed_size; available -= processed_size; if (! connection->rq.have_chunked_upload) { mhd_assert (MHD_SIZE_UNKNOWN != connection->rq.remaining_upload_size); connection->rq.remaining_upload_size -= processed_size; } else { mhd_assert (MHD_SIZE_UNKNOWN == connection->rq.remaining_upload_size); connection->rq.current_chunk_offset += processed_size; } } while (instant_retry); /* TODO: zero out reused memory region */ if ( (available > 0) && (buffer_head != connection->read_buffer) ) memmove (connection->read_buffer, buffer_head, available); else mhd_assert ((0 == available) || \ (connection->read_buffer_offset == available)); connection->read_buffer_offset = available; } /** * Check if we are done sending the write-buffer. * If so, transition into "next_state". * * @param connection connection to check write status for * @param next_state the next state to transition to * @return #MHD_NO if we are not done, #MHD_YES if we are */ static enum MHD_Result check_write_done (struct MHD_Connection *connection, enum MHD_CONNECTION_STATE next_state) { if ( (connection->write_buffer_append_offset != connection->write_buffer_send_offset) /* || data_in_tls_buffers == true */ ) return MHD_NO; connection->write_buffer_append_offset = 0; connection->write_buffer_send_offset = 0; connection->state = next_state; return MHD_YES; } /** * Parse the various headers; figure out the size * of the upload and make sure the headers follow * the protocol. * * @param c the connection to process */ static void parse_connection_headers (struct MHD_Connection *c) { struct MHD_HTTP_Req_Header *pos; bool have_hdr_host; bool have_cntn_len; have_hdr_host = false; have_cntn_len = false; /* The presence of the request body is indicated by "Content-Length:" or "Transfer-Encoding:" request headers. See RFC 9112 section 6.1, 6.2, 6.3; RFC 9110 Section 8.6. */ mhd_assert (0 == c->rq.remaining_upload_size); mhd_assert (! c->rq.have_chunked_upload); for (pos = c->rq.headers_received; NULL != pos; pos = pos->next) { if (MHD_HEADER_KIND != pos->kind) continue; if (MHD_str_equal_caseless_s_bin_n_ (MHD_HTTP_HEADER_HOST, pos->header, pos->header_size)) { if (have_hdr_host) { if (-3 < c->daemon->client_discipline) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_MULTIPLE_HOST_HDR); return; } } have_hdr_host = true; } #ifdef COOKIE_SUPPORT else if (MHD_str_equal_caseless_s_bin_n_ (MHD_HTTP_HEADER_COOKIE, pos->header, pos->header_size)) { if (MHD_PARSE_COOKIE_NO_MEMORY == parse_cookie_header (c, pos->value, pos->value_size)) { handle_req_cookie_no_space (c); return; } } #endif /* COOKIE_SUPPORT */ else if (MHD_str_equal_caseless_s_bin_n_ (MHD_HTTP_HEADER_CONTENT_LENGTH, pos->header, pos->header_size)) { const char *clen; size_t val_len; size_t num_digits; uint64_t decoded_val; val_len = pos->value_size; clen = pos->value; mhd_assert ('\0' == clen[val_len]); if ((have_cntn_len) && (0 < c->daemon->client_discipline)) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_AMBIGUOUS_CONTENT_LENGTH); return; } num_digits = MHD_str_to_uint64_n_ (clen, val_len, &decoded_val); if ((0 == num_digits) || (val_len != num_digits) || (MHD_SIZE_UNKNOWN == decoded_val)) { /* Bad or too large value */ if (have_cntn_len) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_AMBIGUOUS_CONTENT_LENGTH); return; } if ((val_len != num_digits) || ('0' > clen[0]) || ('9' < clen[0])) { #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Malformed 'Content-Length' header. " \ "Closing connection.\n")); #endif transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_CONTENTLENGTH_MALFORMED); return; } #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Too large value of 'Content-Length' header. " \ "Closing connection.\n")); #endif transmit_error_response_static (c, MHD_HTTP_CONTENT_TOO_LARGE, REQUEST_CONTENTLENGTH_TOOLARGE); return; } if ((have_cntn_len) && (c->rq.remaining_upload_size != decoded_val)) { if (-3 < c->daemon->client_discipline) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_AMBIGUOUS_CONTENT_LENGTH); return; } /* The HTTP framing is broken. Use smallest (safest) length value and force-close after processing of this request. */ if (c->rq.remaining_upload_size > decoded_val) c->rq.remaining_upload_size = decoded_val; c->keepalive = MHD_CONN_MUST_CLOSE; } else c->rq.remaining_upload_size = decoded_val; have_cntn_len = true; } else if (MHD_str_equal_caseless_s_bin_n_ ( MHD_HTTP_HEADER_TRANSFER_ENCODING, pos->header, pos->header_size)) { if (MHD_HTTP_VER_1_1 > c->rq.http_ver) { /* RFC 9112, 6.1, last paragraph */ if (0 < c->daemon->client_discipline) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_HTTP1_0_TR_ENCODING); return; } /* HTTP framing potentially broken */ c->keepalive = MHD_CONN_MUST_CLOSE; } if (c->rq.have_chunked_upload || ! MHD_str_equal_caseless_s_bin_n_ ("chunked", pos->value, pos->value_size)) { transmit_error_response_static (c, c->rq.have_chunked_upload ? MHD_HTTP_BAD_REQUEST : MHD_HTTP_NOT_IMPLEMENTED, REQUEST_UNSUPPORTED_TR_ENCODING); return; } c->rq.have_chunked_upload = true; c->rq.remaining_upload_size = MHD_SIZE_UNKNOWN; } } if (c->rq.have_chunked_upload && have_cntn_len) { if (0 < c->daemon->client_discipline) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_LENGTH_WITH_TR_ENCODING); return; } else { #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("The 'Content-Length' request header is ignored " "as chunked Transfer-Encoding is set in the " "same request.\n")); #endif /* HAVE_MESSAGES */ c->rq.remaining_upload_size = MHD_SIZE_UNKNOWN; /* Must close connection after reply to prevent potential attack */ c->keepalive = MHD_CONN_MUST_CLOSE; } } mhd_assert (! c->rq.have_chunked_upload || (MHD_SIZE_UNKNOWN == c->rq.remaining_upload_size)); mhd_assert ((0 == c->rq.remaining_upload_size) || have_cntn_len || c->rq.have_chunked_upload); if (! have_hdr_host && (MHD_IS_HTTP_VER_1_1_COMPAT (c->rq.http_ver)) && (-3 < c->daemon->client_discipline)) { #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Received HTTP/1.1 request without `Host' header.\n")); #endif transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_LACKS_HOST); return; } } /** * Reset request header processing state. * * This function resets the processing state before processing the next header * (or footer) line. * @param c the connection to process */ _MHD_static_inline void reset_rq_header_processing_state (struct MHD_Connection *c) { memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr)); } /** * Switch to request headers (field lines) processing state. * @param c the connection to process */ _MHD_static_inline void switch_to_rq_headers_processing (struct MHD_Connection *c) { c->rq.field_lines.start = c->read_buffer; memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr)); c->state = MHD_CONNECTION_REQ_HEADERS_RECEIVING; } #ifndef MHD_MAX_EMPTY_LINES_SKIP /** * The maximum number of ignored empty line before the request line * at default "strictness" level. */ #define MHD_MAX_EMPTY_LINES_SKIP 1024 #endif /* ! MHD_MAX_EMPTY_LINES_SKIP */ /** * Find and parse the request line. * @param c the connection to process * @return true if request line completely processed (or unrecoverable error * found) and state is changed, * false if not enough data yet in the receive buffer */ static bool get_request_line_inner (struct MHD_Connection *c) { size_t p; /**< The current processing position */ const int discp_lvl = c->daemon->client_discipline; /* Allow to skip one or more empty lines before the request line. RFC 9112, section 2.2 */ const bool skip_empty_lines = (1 >= discp_lvl); /* Allow to skip more then one empty line before the request line. RFC 9112, section 2.2 */ const bool skip_several_empty_lines = (skip_empty_lines && (0 >= discp_lvl)); /* Allow to skip number of unlimited empty lines before the request line. RFC 9112, section 2.2 */ const bool skip_unlimited_empty_lines = (skip_empty_lines && (-3 >= discp_lvl)); /* Treat bare LF as the end of the line. RFC 9112, section 2.2 */ const bool bare_lf_as_crlf = MHD_ALLOW_BARE_LF_AS_CRLF_ (discp_lvl); /* Treat tab as whitespace delimiter. RFC 9112, section 3 */ const bool tab_as_wsp = (0 >= discp_lvl); /* Treat VT (vertical tab) and FF (form feed) as whitespace delimiters. RFC 9112, section 3 */ const bool other_wsp_as_wsp = (-1 >= discp_lvl); /* Treat continuous whitespace block as a single space. RFC 9112, section 3 */ const bool wsp_blocks = (-1 >= discp_lvl); /* Parse whitespace in URI, special parsing of the request line. RFC 9112, section 3.2 */ const bool wsp_in_uri = (0 >= discp_lvl); /* Keep whitespace in URI, give app URI with whitespace instead of automatic redirect to fixed URI. Violates RFC 9112, section 3.2 */ const bool wsp_in_uri_keep = (-2 >= discp_lvl); /* Keep bare CR character as is. Violates RFC 9112, section 2.2 */ const bool bare_cr_keep = (wsp_in_uri_keep && (-3 >= discp_lvl)); /* Treat bare CR as space; replace it with space before processing. RFC 9112, section 2.2 */ const bool bare_cr_as_sp = ((! bare_cr_keep) && (-1 >= discp_lvl)); mhd_assert (MHD_CONNECTION_INIT == c->state || \ MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (NULL == c->rq.method || \ MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (MHD_HTTP_MTHD_NO_METHOD == c->rq.http_mthd || \ MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (MHD_HTTP_MTHD_NO_METHOD == c->rq.http_mthd || \ 0 != c->rq.hdrs.rq_line.proc_pos); if (0 == c->read_buffer_offset) { mhd_assert (MHD_CONNECTION_INIT == c->state); return false; /* No data to process */ } p = c->rq.hdrs.rq_line.proc_pos; mhd_assert (p <= c->read_buffer_offset); /* Skip empty lines, if any (and if allowed) */ /* See RFC 9112, section 2.2 */ if ((0 == p) && (skip_empty_lines)) { /* Skip empty lines before the request line. See RFC 9112, section 2.2 */ bool is_empty_line; mhd_assert (MHD_CONNECTION_INIT == c->state); mhd_assert (NULL == c->rq.method); mhd_assert (NULL == c->rq.url); mhd_assert (0 == c->rq.url_len); mhd_assert (NULL == c->rq.hdrs.rq_line.rq_tgt); mhd_assert (0 == c->rq.req_target_len); mhd_assert (NULL == c->rq.version); do { is_empty_line = false; if ('\r' == c->read_buffer[0]) { if (1 == c->read_buffer_offset) return false; /* Not enough data yet */ if ('\n' == c->read_buffer[1]) { is_empty_line = true; c->read_buffer += 2; c->read_buffer_size -= 2; c->read_buffer_offset -= 2; c->rq.hdrs.rq_line.skipped_empty_lines++; } } else if (('\n' == c->read_buffer[0]) && (bare_lf_as_crlf)) { is_empty_line = true; c->read_buffer += 1; c->read_buffer_size -= 1; c->read_buffer_offset -= 1; c->rq.hdrs.rq_line.skipped_empty_lines++; } if (is_empty_line) { if ((! skip_unlimited_empty_lines) && (((unsigned int) ((skip_several_empty_lines) ? MHD_MAX_EMPTY_LINES_SKIP : 1)) < c->rq.hdrs.rq_line.skipped_empty_lines)) { connection_close_error (c, _ ("Too many meaningless extra empty lines " \ "received before the request")); return true; /* Process connection closure */ } if (0 == c->read_buffer_offset) return false; /* No more data to process */ } } while (is_empty_line); } /* All empty lines are skipped */ c->state = MHD_CONNECTION_REQ_LINE_RECEIVING; /* Read and parse the request line */ mhd_assert (1 <= c->read_buffer_offset); while (p < c->read_buffer_offset) { const char chr = c->read_buffer[p]; bool end_of_line; /* The processing logic is different depending on the configured strictness: When whitespace BLOCKS are NOT ALLOWED, the end of the whitespace is processed BEFORE processing of the current character. When whitespace BLOCKS are ALLOWED, the end of the whitespace is processed AFTER processing of the current character. When space char in the URI is ALLOWED, the delimiter between the URI and the HTTP version string is processed only at the END of the line. When space in the URI is NOT ALLOWED, the delimiter between the URI and the HTTP version string is processed as soon as the FIRST whitespace is found after URI start. */ end_of_line = false; mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_end) || \ (c->rq.hdrs.rq_line.last_ws_end > \ c->rq.hdrs.rq_line.last_ws_start)); mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_start) || \ (0 != c->rq.hdrs.rq_line.last_ws_end)); /* Check for the end of the line */ if ('\r' == chr) { if (p + 1 == c->read_buffer_offset) { c->rq.hdrs.rq_line.proc_pos = p; return false; /* Not enough data yet */ } else if ('\n' == c->read_buffer[p + 1]) end_of_line = true; else { /* Bare CR alone */ /* Must be rejected or replaced with space char. See RFC 9112, section 2.2 */ if (bare_cr_as_sp) { c->read_buffer[p] = ' '; c->rq.num_cr_sp_replaced++; continue; /* Re-start processing of the current character */ } else if (! bare_cr_keep) { /* A quick simple check whether this line looks like an HTTP request */ if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) && (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd)) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_CR_IN_HEADER); } else connection_close_error (c, _ ("Bare CR characters are not allowed " \ "in the request line.\n")); return true; /* Error in the request */ } } } else if ('\n' == chr) { /* Bare LF may be recognised as a line delimiter. See RFC 9112, section 2.2 */ if (bare_lf_as_crlf) end_of_line = true; else { /* While RFC does not enforce error for bare LF character, if this char is not treated as a line delimiter, it should be rejected to avoid any security weakness due to request smuggling. */ /* A quick simple check whether this line looks like an HTTP request */ if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) && (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd)) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_LF_IN_HEADER); } else connection_close_error (c, _ ("Bare LF characters are not allowed " \ "in the request line.\n")); return true; /* Error in the request */ } } if (end_of_line) { /* Handle the end of the request line */ if (NULL != c->rq.method) { if (wsp_in_uri) { /* The end of the URI and the start of the HTTP version string should be determined now. */ mhd_assert (NULL == c->rq.version); mhd_assert (0 == c->rq.req_target_len); if (0 != c->rq.hdrs.rq_line.last_ws_end) { /* Determine the end and the length of the URI */ if (NULL != c->rq.hdrs.rq_line.rq_tgt) { c->read_buffer [c->rq.hdrs.rq_line.last_ws_start] = 0; /* Zero terminate the URI */ c->rq.req_target_len = c->rq.hdrs.rq_line.last_ws_start - (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer); } else if ((c->rq.hdrs.rq_line.last_ws_start + 1 < c->rq.hdrs.rq_line.last_ws_end) && (HTTP_VER_LEN == (p - c->rq.hdrs.rq_line.last_ws_end))) { /* Found only HTTP method and HTTP version and more than one whitespace between them. Assume zero-length URI. */ mhd_assert (wsp_blocks); c->rq.hdrs.rq_line.last_ws_start++; c->read_buffer[c->rq.hdrs.rq_line.last_ws_start] = 0; /* Zero terminate the URI */ c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + c->rq.hdrs.rq_line.last_ws_start; c->rq.req_target_len = 0; c->rq.hdrs.rq_line.num_ws_in_uri = 0; c->rq.hdrs.rq_line.rq_tgt_qmark = NULL; } /* Determine the start of the HTTP version string */ if (NULL != c->rq.hdrs.rq_line.rq_tgt) { c->rq.version = c->read_buffer + c->rq.hdrs.rq_line.last_ws_end; } } } else { /* The end of the URI and the start of the HTTP version string should be already known. */ if ((NULL == c->rq.version) && (NULL != c->rq.hdrs.rq_line.rq_tgt) && (HTTP_VER_LEN == p - (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer)) && (0 != c->read_buffer[(size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer) - 1])) { /* Found only HTTP method and HTTP version and more than one whitespace between them. Assume zero-length URI. */ size_t uri_pos; mhd_assert (wsp_blocks); mhd_assert (0 == c->rq.req_target_len); uri_pos = (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer) - 1; mhd_assert (uri_pos < p); c->rq.version = c->rq.hdrs.rq_line.rq_tgt; c->read_buffer[uri_pos] = 0; /* Zero terminate the URI */ c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + uri_pos; c->rq.req_target_len = 0; c->rq.hdrs.rq_line.num_ws_in_uri = 0; c->rq.hdrs.rq_line.rq_tgt_qmark = NULL; } } if (NULL != c->rq.version) { mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt); if (! parse_http_version (c, c->rq.version, p - (size_t) (c->rq.version - c->read_buffer))) { mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING < c->state); return true; /* Unsupported / broken HTTP version */ } c->read_buffer[p] = 0; /* Zero terminate the HTTP version strings */ if ('\r' == chr) { p++; /* Consume CR */ mhd_assert (p < c->read_buffer_offset); /* The next character has been already checked */ } p++; /* Consume LF */ c->read_buffer += p; c->read_buffer_size -= p; c->read_buffer_offset -= p; mhd_assert (c->rq.hdrs.rq_line.num_ws_in_uri <= \ c->rq.req_target_len); mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \ (0 != c->rq.req_target_len)); mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \ ((size_t) (c->rq.hdrs.rq_line.rq_tgt_qmark \ - c->rq.hdrs.rq_line.rq_tgt) < \ c->rq.req_target_len)); mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \ (c->rq.hdrs.rq_line.rq_tgt_qmark >= \ c->rq.hdrs.rq_line.rq_tgt)); return true; /* The request line is successfully parsed */ } } /* Error in the request line */ /* A quick simple check whether this line looks like an HTTP request */ if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) && (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd)) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_MALFORMED); } else connection_close_error (c, _ ("The request line is malformed.\n")); return true; } /* Process possible end of the previously found whitespace delimiter */ if ((! wsp_blocks) && (p == c->rq.hdrs.rq_line.last_ws_end) && (0 != c->rq.hdrs.rq_line.last_ws_end)) { /* Previous character was a whitespace char and whitespace blocks are not allowed. */ /* The current position is the next character after a whitespace delimiter */ if (NULL == c->rq.hdrs.rq_line.rq_tgt) { /* The current position is the start of the URI */ mhd_assert (0 == c->rq.req_target_len); mhd_assert (NULL == c->rq.version); c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + p; /* Reset the whitespace marker */ c->rq.hdrs.rq_line.last_ws_start = 0; c->rq.hdrs.rq_line.last_ws_end = 0; } else { /* It was a whitespace after the start of the URI */ if (! wsp_in_uri) { mhd_assert ((0 != c->rq.req_target_len) || \ (c->rq.hdrs.rq_line.rq_tgt + 1 == c->read_buffer + p)); mhd_assert (NULL == c->rq.version); /* Too many whitespaces? This error is handled at whitespace start */ c->rq.version = c->read_buffer + p; /* Reset the whitespace marker */ c->rq.hdrs.rq_line.last_ws_start = 0; c->rq.hdrs.rq_line.last_ws_end = 0; } } } /* Process the current character. Is it not the end of the line. */ if ((' ' == chr) || (('\t' == chr) && (tab_as_wsp)) || ((other_wsp_as_wsp) && ((0xb == chr) || (0xc == chr)))) { /* A whitespace character */ if ((0 == c->rq.hdrs.rq_line.last_ws_end) || (p != c->rq.hdrs.rq_line.last_ws_end) || (! wsp_blocks)) { /* Found first whitespace char of the new whitespace block */ if (NULL == c->rq.method) { /* Found the end of the HTTP method string */ mhd_assert (0 == c->rq.hdrs.rq_line.last_ws_start); mhd_assert (0 == c->rq.hdrs.rq_line.last_ws_end); mhd_assert (NULL == c->rq.hdrs.rq_line.rq_tgt); mhd_assert (0 == c->rq.req_target_len); mhd_assert (NULL == c->rq.version); if (0 == p) { connection_close_error (c, _ ("The request line starts with " "a whitespace.\n")); return true; /* Error in the request */ } c->read_buffer[p] = 0; /* Zero-terminate the request method string */ c->rq.method = c->read_buffer; parse_http_std_method (c, c->rq.method, p); } else { /* A whitespace after the start of the URI */ if (! wsp_in_uri) { /* Whitespace in URI is not allowed to be parsed */ if (NULL == c->rq.version) { mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt); /* This is a delimiter between URI and HTTP version string */ c->read_buffer[p] = 0; /* Zero-terminate request URI string */ mhd_assert (((size_t) (c->rq.hdrs.rq_line.rq_tgt \ - c->read_buffer)) <= p); c->rq.req_target_len = p - (size_t) (c->rq.hdrs.rq_line.rq_tgt - c->read_buffer); } else { /* This is a delimiter AFTER version string */ /* A quick simple check whether this line looks like an HTTP request */ if ((MHD_HTTP_MTHD_GET <= c->rq.http_mthd) && (MHD_HTTP_MTHD_DELETE >= c->rq.http_mthd)) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, RQ_LINE_TOO_MANY_WSP); } else connection_close_error (c, _ ("The request line has more than " "two whitespaces.\n")); return true; /* Error in the request */ } } else { /* Whitespace in URI is allowed to be parsed */ if (0 != c->rq.hdrs.rq_line.last_ws_end) { /* The whitespace after the start of the URI has been found already */ c->rq.hdrs.rq_line.num_ws_in_uri += c->rq.hdrs.rq_line.last_ws_end - c->rq.hdrs.rq_line.last_ws_start; } } } c->rq.hdrs.rq_line.last_ws_start = p; c->rq.hdrs.rq_line.last_ws_end = p + 1; /* Will be updated on the next char parsing */ } else { /* Continuation of the whitespace block */ mhd_assert (0 != c->rq.hdrs.rq_line.last_ws_end); mhd_assert (0 != p); c->rq.hdrs.rq_line.last_ws_end = p + 1; } } else { /* Non-whitespace char, not the end of the line */ mhd_assert ((0 == c->rq.hdrs.rq_line.last_ws_end) || \ (c->rq.hdrs.rq_line.last_ws_end == p) || \ wsp_in_uri); if ((p == c->rq.hdrs.rq_line.last_ws_end) && (0 != c->rq.hdrs.rq_line.last_ws_end) && (wsp_blocks)) { /* The end of the whitespace block */ if (NULL == c->rq.hdrs.rq_line.rq_tgt) { /* This is the first character of the URI */ mhd_assert (0 == c->rq.req_target_len); mhd_assert (NULL == c->rq.version); c->rq.hdrs.rq_line.rq_tgt = c->read_buffer + p; /* Reset the whitespace marker */ c->rq.hdrs.rq_line.last_ws_start = 0; c->rq.hdrs.rq_line.last_ws_end = 0; } else { if (! wsp_in_uri) { /* This is the first character of the HTTP version */ mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt); mhd_assert ((0 != c->rq.req_target_len) || \ (c->rq.hdrs.rq_line.rq_tgt + 1 == c->read_buffer + p)); mhd_assert (NULL == c->rq.version); /* Handled at whitespace start */ c->rq.version = c->read_buffer + p; /* Reset the whitespace marker */ c->rq.hdrs.rq_line.last_ws_start = 0; c->rq.hdrs.rq_line.last_ws_end = 0; } } } /* Handle other special characters */ if ('?' == chr) { if ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) && (NULL != c->rq.hdrs.rq_line.rq_tgt)) { c->rq.hdrs.rq_line.rq_tgt_qmark = c->read_buffer + p; } } else if ((0xb == chr) || (0xc == chr)) { /* VT or LF characters */ mhd_assert (! other_wsp_as_wsp); if ((NULL != c->rq.hdrs.rq_line.rq_tgt) && (NULL == c->rq.version) && (wsp_in_uri)) { c->rq.hdrs.rq_line.num_ws_in_uri++; } else { connection_close_error (c, _ ("Invalid character is in the " "request line.\n")); return true; /* Error in the request */ } } else if (0 == chr) { /* NUL character */ connection_close_error (c, _ ("The NUL character is in the " "request line.\n")); return true; /* Error in the request */ } } p++; } c->rq.hdrs.rq_line.proc_pos = p; return false; /* Not enough data yet */ } #ifndef MHD_MAX_FIXED_URI_LEN /** * The maximum size of the fixed URI for automatic redirection */ #define MHD_MAX_FIXED_URI_LEN (64 * 1024) #endif /* ! MHD_MAX_FIXED_URI_LEN */ /** * Send the automatic redirection to fixed URI when received URI with * whitespaces. * If URI is too large, close connection with error. * * @param c the connection to process */ static void send_redirect_fixed_rq_target (struct MHD_Connection *c) { char *b; size_t fixed_uri_len; size_t i; size_t o; char *hdr_name; size_t hdr_name_len; mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (0 != c->rq.hdrs.rq_line.num_ws_in_uri); mhd_assert (c->rq.hdrs.rq_line.num_ws_in_uri <= \ c->rq.req_target_len); fixed_uri_len = c->rq.req_target_len + 2 * c->rq.hdrs.rq_line.num_ws_in_uri; if ( (fixed_uri_len + 200 > c->daemon->pool_size) || (fixed_uri_len > MHD_MAX_FIXED_URI_LEN) || (NULL == (b = malloc (fixed_uri_len + 1))) ) { connection_close_error (c, _ ("The request has whitespace character is " \ "in the URI and the URI is too large to " \ "send automatic redirect to fixed URI.\n")); return; } i = 0; o = 0; do { const char chr = c->rq.hdrs.rq_line.rq_tgt[i++]; /* The number of bytes that this iteration appends to the buffer. */ const size_t add_size = ((' ' == chr) || ('\t' == chr) || (0x0B == chr) || (0x0C == chr)) ? 3 : 1; mhd_assert ('\r' != chr); /* Replaced during request line parsing */ mhd_assert ('\n' != chr); /* Rejected during request line parsing */ mhd_assert (0 != chr); /* Rejected during request line parsing */ /* Check the remaining space before write. */ if (MHD_CHECK_FAILED_ (add_size <= fixed_uri_len - o)) { MHD_CHECK_LOG_ (c->daemon, "add_size <= fixed_uri_len - o"); free (b); connection_close_error (c, NULL); return; } switch (chr) { case ' ': b[o++] = '%'; b[o++] = '2'; b[o++] = '0'; break; case '\t': b[o++] = '%'; b[o++] = '0'; b[o++] = '9'; break; case 0x0B: /* VT (vertical tab) */ b[o++] = '%'; b[o++] = '0'; b[o++] = 'B'; break; case 0x0C: /* FF (form feed) */ b[o++] = '%'; b[o++] = '0'; b[o++] = 'C'; break; default: b[o++] = chr; break; } } while (i < c->rq.req_target_len); mhd_assert (fixed_uri_len == o); b[o] = 0; /* Zero-terminate the result */ hdr_name_len = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_LOCATION); hdr_name = malloc (hdr_name_len + 1); if (NULL != hdr_name) { memcpy (hdr_name, MHD_HTTP_HEADER_LOCATION, hdr_name_len + 1); /* hdr_name and b are free()d within this call */ transmit_error_response_header (c, MHD_HTTP_MOVED_PERMANENTLY, RQ_TARGET_INVALID_CHAR, hdr_name, hdr_name_len, b, o); return; } free (b); connection_close_error (c, _ ("The request has whitespace character is in the " \ "URI.\n")); return; } /** * Process request-target string, form URI and URI parameters * @param c the connection to process * @return true if request-target successfully processed, * false if error encountered */ static bool process_request_target (struct MHD_Connection *c) { #ifdef _DEBUG size_t params_len; #endif /* _DEBUG */ mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (NULL == c->rq.url); mhd_assert (0 == c->rq.url_len); mhd_assert (NULL == c->rq.url_for_callback); mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt); mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \ (c->rq.hdrs.rq_line.rq_tgt <= c->rq.hdrs.rq_line.rq_tgt_qmark)); mhd_assert ((NULL == c->rq.hdrs.rq_line.rq_tgt_qmark) || \ (c->rq.req_target_len > \ (size_t) (c->rq.hdrs.rq_line.rq_tgt_qmark \ - c->rq.hdrs.rq_line.rq_tgt))); /* Log callback before the request-target is modified/decoded */ if (NULL != c->daemon->uri_log_callback) { c->rq.client_aware = true; c->rq.client_context = c->daemon->uri_log_callback (c->daemon->uri_log_callback_cls, c->rq.hdrs.rq_line.rq_tgt, c); } if (NULL != c->rq.hdrs.rq_line.rq_tgt_qmark) { #ifdef _DEBUG params_len = c->rq.req_target_len - (size_t) (c->rq.hdrs.rq_line.rq_tgt_qmark - c->rq.hdrs.rq_line.rq_tgt); #endif /* _DEBUG */ c->rq.hdrs.rq_line.rq_tgt_qmark[0] = 0; /* Replace '?' with zero termination */ if (MHD_NO == MHD_parse_arguments_ (c, MHD_GET_ARGUMENT_KIND, c->rq.hdrs.rq_line.rq_tgt_qmark + 1, &connection_add_header, c)) { mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING != c->state); return false; } } #ifdef _DEBUG else params_len = 0; #endif /* _DEBUG */ mhd_assert (NULL == c->rq.url_for_callback); mhd_assert (strlen (c->rq.hdrs.rq_line.rq_tgt) == \ c->rq.req_target_len - params_len); /* Finally unescape URI itself */ c->rq.url_len = c->daemon->unescape_callback (c->daemon->unescape_callback_cls, c, c->rq.hdrs.rq_line.rq_tgt); c->rq.url = c->rq.hdrs.rq_line.rq_tgt; if (2 == c->daemon->allow_bzero_in_url) c->rq.url_for_callback = c->rq.url; else if (strlen (c->rq.url) == c->rq.url_len) c->rq.url_for_callback = c->rq.url; else if (0 == c->daemon->allow_bzero_in_url) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_HAS_NUL_CHAR_IN_PATH); return false; } return true; } /** * Find and parse the request line. * Advance to the next state when done, handle errors. * @param c the connection to process * @return true if request line completely processed and state is changed, * false if not enough data yet in the receive buffer */ static bool get_request_line (struct MHD_Connection *c) { const int discp_lvl = c->daemon->client_discipline; /* Parse whitespace in URI, special parsing of the request line */ const bool wsp_in_uri = (0 >= discp_lvl); /* Keep whitespace in URI, give app URI with whitespace instead of automatic redirect to fixed URI */ const bool wsp_in_uri_keep = (-2 >= discp_lvl); if (! get_request_line_inner (c)) { /* End of the request line has not been found yet */ mhd_assert ((! wsp_in_uri) || NULL == c->rq.version); if ((NULL != c->rq.version) && (HTTP_VER_LEN < (c->rq.hdrs.rq_line.proc_pos - (size_t) (c->rq.version - c->read_buffer)))) { c->rq.http_ver = MHD_HTTP_VER_INVALID; transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, REQUEST_MALFORMED); return true; /* Error in the request */ } return false; } if (MHD_CONNECTION_REQ_LINE_RECEIVING < c->state) return true; /* Error in the request */ mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING == c->state); mhd_assert (NULL == c->rq.url); mhd_assert (0 == c->rq.url_len); mhd_assert (NULL == c->rq.url_for_callback); mhd_assert (NULL != c->rq.hdrs.rq_line.rq_tgt); if (0 != c->rq.hdrs.rq_line.num_ws_in_uri) { if (! wsp_in_uri) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, RQ_TARGET_INVALID_CHAR); return true; /* Error in the request */ } if (! wsp_in_uri_keep) { send_redirect_fixed_rq_target (c); return true; /* Error in the request */ } } if (! process_request_target (c)) return true; /* Error in processing */ c->state = MHD_CONNECTION_REQ_LINE_RECEIVED; return true; } /** * Results of header line reading */ enum MHD_HdrLineReadRes_ { /** * Not enough data yet */ MHD_HDR_LINE_READING_NEED_MORE_DATA = 0, /** * New header line has been read */ MHD_HDR_LINE_READING_GOT_HEADER, /** * Error in header data, error response has been queued */ MHD_HDR_LINE_READING_DATA_ERROR, /** * Found the end of the request header (end of field lines) */ MHD_HDR_LINE_READING_GOT_END_OF_HEADER } _MHD_FIXED_ENUM; /** * Check if a character is legal inside of a field * name according to RFC 9110. * * @param chr character to test * @return true if character is allowed */ static bool char_legal_in_field_name (char chr) { switch (chr) { case '!': case '#': case '$': case '%': case '&': case '\'': case '*': case '+': case '-': case '.': case '^': case '_': case '`': case '|': case '~': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return true; default: return false; } } /** * Find the end of the request header line and make basic header parsing. * Handle errors and header folding. * @param c the connection to process * @param process_footers if true then footers are processed, * if false then headers are processed * @param[out] hdr_name the name of the parsed header (field) * @param[out] hdr_name the value of the parsed header (field) * @return true if request header line completely processed, * false if not enough data yet in the receive buffer */ static enum MHD_HdrLineReadRes_ get_req_header (struct MHD_Connection *c, bool process_footers, struct _MHD_str_w_len *hdr_name, struct _MHD_str_w_len *hdr_value) { const int discp_lvl = c->daemon->client_discipline; /* Treat bare LF as the end of the line. RFC 9112, section 2.2-3 Note: MHD never replaces bare LF with space (RFC 9110, section 5.5-5). Bare LF is processed as end of the line or rejected as broken request. */ const bool bare_lf_as_crlf = MHD_ALLOW_BARE_LF_AS_CRLF_ (discp_lvl); /* Keep bare CR character as is. Violates RFC 9112, section 2.2-4 */ const bool bare_cr_keep = (-3 >= discp_lvl); /* Treat bare CR as space; replace it with space before processing. RFC 9112, section 2.2-4 */ const bool bare_cr_as_sp = ((! bare_cr_keep) && (-1 >= discp_lvl)); /* Treat NUL as space; replace it with space before processing. RFC 9110, section 5.5-5 */ const bool nul_as_sp = (-1 >= discp_lvl); /* Allow folded header lines. RFC 9112, section 5.2-4 */ const bool allow_folded = (0 >= discp_lvl); /* Do not reject headers with the whitespace at the start of the first line. When allowed, the first line with whitespace character at the first position is ignored (as well as all possible line foldings of the first line). RFC 9112, section 2.2-8 */ const bool allow_wsp_at_start = allow_folded && (-1 >= discp_lvl); /* Allow whitespace in header (field) name. Violates RFC 9110, section 5.1-2 */ const bool allow_wsp_in_name = (-2 >= discp_lvl); /* Allow zero-length header (field) name. Violates RFC 9110, section 5.1-2 */ const bool allow_empty_name = (-2 >= discp_lvl); /* Allow non-tchar characters in header (field) name. Violates RFC 9110, section 5.1 */ const bool allow_extended_charset = (-2 >= discp_lvl); /* Allow whitespace before colon. Violates RFC 9112, section 5.1-2 */ const bool allow_wsp_before_colon = (-3 >= discp_lvl); /* Do not abort the request when header line has no colon, just skip such bad lines. RFC 9112, section 5-1 */ const bool allow_line_without_colon = (-2 >= discp_lvl); size_t p; /**< The position of the currently processed character */ #if ! defined (HAVE_MESSAGES) && ! defined(_DEBUG) (void) process_footers; /* Unused parameter */ #endif /* !HAVE_MESSAGES && !_DEBUG */ mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \ c->state); p = c->rq.hdrs.hdr.proc_pos; mhd_assert (p <= c->read_buffer_offset); while (p < c->read_buffer_offset) { const char chr = c->read_buffer[p]; bool end_of_line; mhd_assert ((0 == c->rq.hdrs.hdr.name_len) || \ (c->rq.hdrs.hdr.name_len < p)); mhd_assert ((0 == c->rq.hdrs.hdr.name_len) || (0 != p)); mhd_assert ((0 == c->rq.hdrs.hdr.name_len) || \ (c->rq.hdrs.hdr.name_end_found)); mhd_assert ((0 == c->rq.hdrs.hdr.value_start) || \ (c->rq.hdrs.hdr.name_len < c->rq.hdrs.hdr.value_start)); /* A zero-length header (field) name is possible in two deliberately non-conformant modes: a first line starting with whitespace (which is discarded as a whole when its end is reached) and an empty field name allowed by 'allow_empty_name'. */ mhd_assert ((0 == c->rq.hdrs.hdr.value_start) || \ (0 != c->rq.hdrs.hdr.name_len) || \ (c->rq.hdrs.hdr.starts_with_ws) || \ (allow_empty_name && c->rq.hdrs.hdr.name_end_found)); mhd_assert ((0 == c->rq.hdrs.hdr.ws_start) || \ (0 == c->rq.hdrs.hdr.name_len) || \ (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.name_len)); mhd_assert ((0 == c->rq.hdrs.hdr.ws_start) || \ (0 == c->rq.hdrs.hdr.value_start) || \ (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.value_start)); /* Check for the end of the line */ if ('\r' == chr) { if (0 != p) { /* Line is not empty, need to check for possible line folding */ if (p + 2 >= c->read_buffer_offset) break; /* Not enough data yet to check for folded line */ } else { /* Line is empty, no need to check for possible line folding */ if (p + 2 > c->read_buffer_offset) break; /* Not enough data yet to check for the end of the line */ } if ('\n' == c->read_buffer[p + 1]) end_of_line = true; else { /* Bare CR alone */ /* Must be rejected or replaced with space char. See RFC 9112, section 2.2-4 */ if (bare_cr_as_sp) { c->read_buffer[p] = ' '; c->rq.num_cr_sp_replaced++; continue; /* Re-start processing of the current character */ } else if (! bare_cr_keep) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_CR_IN_HEADER); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_CR_IN_FOOTER); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } end_of_line = false; } } else if ('\n' == chr) { /* Bare LF may be recognised as a line delimiter. See RFC 9112, section 2.2-3 */ if (bare_lf_as_crlf) { if (0 != p) { /* Line is not empty, need to check for possible line folding */ if (p + 1 >= c->read_buffer_offset) break; /* Not enough data yet to check for folded line */ } end_of_line = true; } else { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_LF_IN_HEADER); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, BARE_LF_IN_FOOTER); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } } else end_of_line = false; if (end_of_line) { /* Handle the end of the line */ /** * The full length of the line, including CRLF (or bare LF). */ const size_t line_len = p + (('\r' == chr) ? 2 : 1); char next_line_char; mhd_assert (line_len <= c->read_buffer_offset); if (0 == p) { /* Zero-length header line. This is the end of the request header section. RFC 9112, Section 2.1-1 */ mhd_assert (! c->rq.hdrs.hdr.starts_with_ws); mhd_assert (! c->rq.hdrs.hdr.name_end_found); mhd_assert (0 == c->rq.hdrs.hdr.name_len); mhd_assert (0 == c->rq.hdrs.hdr.ws_start); mhd_assert (0 == c->rq.hdrs.hdr.value_start); /* Consume the line with CRLF (or bare LF) */ c->read_buffer += line_len; c->read_buffer_offset -= line_len; c->read_buffer_size -= line_len; return MHD_HDR_LINE_READING_GOT_END_OF_HEADER; } mhd_assert (line_len < c->read_buffer_offset); mhd_assert (0 != line_len); mhd_assert ('\n' == c->read_buffer[line_len - 1]); next_line_char = c->read_buffer[line_len]; if ((' ' == next_line_char) || ('\t' == next_line_char)) { /* Folded line */ if (! allow_folded) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_OBS_FOLD); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_OBS_FOLD_FOOTER); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } /* Replace CRLF (or bare LF) character(s) with space characters. See RFC 9112, Section 5.2-4 */ c->read_buffer[p] = ' '; if ('\r' == chr) c->read_buffer[p + 1] = ' '; continue; /* Re-start processing of the current character */ } else { /* It is not a folded line, it's the real end of the non-empty line */ bool skip_line = false; mhd_assert (0 != p); if (c->rq.hdrs.hdr.starts_with_ws) { /* This is the first line and it starts with whitespace. This line must be discarded completely. See RFC 9112, Section 2.2-8 */ mhd_assert (allow_wsp_at_start); #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Whitespace-prefixed first header line " \ "has been skipped.\n")); #endif /* HAVE_MESSAGES */ skip_line = true; } else if (! c->rq.hdrs.hdr.name_end_found) { if (! allow_line_without_colon) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_HEADER_WITHOUT_COLON); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_FOOTER_WITHOUT_COLON); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } /* Skip broken line completely */ c->rq.skipped_broken_lines++; skip_line = true; } if (skip_line) { /* Skip the entire line */ c->read_buffer += line_len; c->read_buffer_offset -= line_len; c->read_buffer_size -= line_len; p = 0; /* Reset processing state */ memset (&c->rq.hdrs.hdr, 0, sizeof(c->rq.hdrs.hdr)); /* Start processing of the next line */ continue; } else { /* This line should be valid header line */ size_t value_len; mhd_assert ((0 != c->rq.hdrs.hdr.name_len) || allow_empty_name); hdr_name->str = c->read_buffer + 0; /* The name always starts at the first character */ hdr_name->len = c->rq.hdrs.hdr.name_len; mhd_assert (0 == hdr_name->str[hdr_name->len]); if (0 == c->rq.hdrs.hdr.value_start) { c->rq.hdrs.hdr.value_start = p; c->read_buffer[p] = 0; value_len = 0; } else if (0 != c->rq.hdrs.hdr.ws_start) { mhd_assert (p > c->rq.hdrs.hdr.ws_start); mhd_assert (c->rq.hdrs.hdr.ws_start > c->rq.hdrs.hdr.value_start); c->read_buffer[c->rq.hdrs.hdr.ws_start] = 0; value_len = c->rq.hdrs.hdr.ws_start - c->rq.hdrs.hdr.value_start; } else { mhd_assert (p > c->rq.hdrs.hdr.ws_start); c->read_buffer[p] = 0; value_len = p - c->rq.hdrs.hdr.value_start; } hdr_value->str = c->read_buffer + c->rq.hdrs.hdr.value_start; hdr_value->len = value_len; mhd_assert (0 == hdr_value->str[hdr_value->len]); /* Consume the entire line */ c->read_buffer += line_len; c->read_buffer_offset -= line_len; c->read_buffer_size -= line_len; return MHD_HDR_LINE_READING_GOT_HEADER; } } } else if ((' ' == chr) || ('\t' == chr)) { if (0 == p) { if (! allow_wsp_at_start) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_BEFORE_HEADER); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_BEFORE_FOOTER); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } c->rq.hdrs.hdr.starts_with_ws = true; } else if ((! c->rq.hdrs.hdr.name_end_found) && (! c->rq.hdrs.hdr.starts_with_ws)) { /* Whitespace in header name / between header name and colon */ if (allow_wsp_in_name || allow_wsp_before_colon) { if (0 == c->rq.hdrs.hdr.ws_start) c->rq.hdrs.hdr.ws_start = p; } else { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_HEADER_NAME); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_FOOTER_NAME); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } } else { /* Whitespace before/inside/after header (field) value */ if (0 == c->rq.hdrs.hdr.ws_start) c->rq.hdrs.hdr.ws_start = p; } } else if (0 == chr) { if (! nul_as_sp) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_INVALID_CHR_IN_HEADER); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_INVALID_CHR_IN_FOOTER); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } c->read_buffer[p] = ' '; continue; /* Re-start processing of the current character */ } else { /* Not a whitespace, not the end of the header line */ /* A bare CR reaches this point when it is kept as an ordinary character ('bare_cr_keep', MHD_OPTION_CLIENT_DISCIPLINE_LVL -3); in every other mode it is either replaced with a space or rejected before. */ mhd_assert (('\r' != chr) || bare_cr_keep); mhd_assert ('\n' != chr); mhd_assert ('\0' != chr); if ( (! c->rq.hdrs.hdr.name_end_found) && (! c->rq.hdrs.hdr.starts_with_ws) ) { /* Processing the header (field) name */ if ( (! allow_extended_charset) && (':' != chr) && (! char_legal_in_field_name (chr)) ) { transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_INVALID_CHAR_IN_FIELD_NAME); return MHD_HDR_LINE_READING_DATA_ERROR; } if (':' == chr) { if (0 == c->rq.hdrs.hdr.ws_start) c->rq.hdrs.hdr.name_len = p; else { mhd_assert (allow_wsp_in_name || allow_wsp_before_colon); if (! allow_wsp_before_colon) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_HEADER_NAME); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_FOOTER_NAME); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } c->rq.hdrs.hdr.name_len = c->rq.hdrs.hdr.ws_start; #ifndef MHD_FAVOR_SMALL_CODE c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */ #endif /* ! MHD_FAVOR_SMALL_CODE */ } if ((0 == c->rq.hdrs.hdr.name_len) && ! allow_empty_name) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_EMPTY_HEADER_NAME); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_EMPTY_FOOTER_NAME); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } c->rq.hdrs.hdr.name_end_found = true; c->read_buffer[c->rq.hdrs.hdr.name_len] = 0; /* Zero-terminate the name */ } else { if (0 != c->rq.hdrs.hdr.ws_start) { /* End of the whitespace in header (field) name */ mhd_assert (allow_wsp_in_name || allow_wsp_before_colon); if (! allow_wsp_in_name) { if (! process_footers) transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_HEADER_NAME); else transmit_error_response_static (c, MHD_HTTP_BAD_REQUEST, ERR_RSP_WSP_IN_FOOTER_NAME); return MHD_HDR_LINE_READING_DATA_ERROR; /* Error in the request */ } #ifndef MHD_FAVOR_SMALL_CODE c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */ #endif /* ! MHD_FAVOR_SMALL_CODE */ } } } else { /* Processing the header (field) value */ if (0 == c->rq.hdrs.hdr.value_start) c->rq.hdrs.hdr.value_start = p; #ifndef MHD_FAVOR_SMALL_CODE c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */ #endif /* ! MHD_FAVOR_SMALL_CODE */ } #ifdef MHD_FAVOR_SMALL_CODE c->rq.hdrs.hdr.ws_start = 0; /* Not on whitespace anymore */ #endif /* MHD_FAVOR_SMALL_CODE */ } p++; } c->rq.hdrs.hdr.proc_pos = p; return MHD_HDR_LINE_READING_NEED_MORE_DATA; /* Not enough data yet */ } /** * Find the end of the request headers and make basic header parsing. * Advance to the next state when done, handle errors. * @param c the connection to process * @param process_footers if true then footers are processed, * if false then headers are processed * @return true if request headers reading finished (either successfully * or with error), * false if not enough data yet in the receive buffer */ static bool get_req_headers (struct MHD_Connection *c, bool process_footers) { do { struct _MHD_str_w_len hdr_name; struct _MHD_str_w_len hdr_value; enum MHD_HdrLineReadRes_ res; mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \ c->state); #ifdef _DEBUG hdr_name.str = NULL; hdr_value.str = NULL; #endif /* _DEBUG */ res = get_req_header (c, process_footers, &hdr_name, &hdr_value); if (MHD_HDR_LINE_READING_GOT_HEADER == res) { mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \ c->state); mhd_assert (NULL != hdr_name.str); mhd_assert (NULL != hdr_value.str); /* Values must be zero-terminated and must not have binary zeros */ mhd_assert (strlen (hdr_name.str) == hdr_name.len); mhd_assert (strlen (hdr_value.str) == hdr_value.len); /* Values must not have whitespaces at the start or at the end */ mhd_assert ((hdr_name.len == 0) || (hdr_name.str[0] != ' ')); mhd_assert ((hdr_name.len == 0) || (hdr_name.str[0] != '\t')); mhd_assert ((hdr_name.len == 0) || \ (hdr_name.str[hdr_name.len - 1] != ' ')); mhd_assert ((hdr_name.len == 0) || \ (hdr_name.str[hdr_name.len - 1] != '\t')); mhd_assert ((hdr_value.len == 0) || (hdr_value.str[0] != ' ')); mhd_assert ((hdr_value.len == 0) || (hdr_value.str[0] != '\t')); mhd_assert ((hdr_value.len == 0) || \ (hdr_value.str[hdr_value.len - 1] != ' ')); mhd_assert ((hdr_value.len == 0) || \ (hdr_value.str[hdr_value.len - 1] != '\t')); if (MHD_NO == MHD_set_connection_value_n_nocheck_ (c, (! process_footers) ? MHD_HEADER_KIND : MHD_FOOTER_KIND, hdr_name.str, hdr_name.len, hdr_value.str, hdr_value.len)) { size_t add_element_size; mhd_assert (hdr_name.str < hdr_value.str); #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Failed to allocate memory in the connection memory " \ "pool to store %s.\n"), (! process_footers) ? _ ("header") : _ ("footer")); #endif /* HAVE_MESSAGES */ add_element_size = hdr_value.len + (size_t) (hdr_value.str - hdr_name.str); if (! process_footers) handle_req_headers_no_space (c, hdr_name.str, add_element_size); else handle_req_footers_no_space (c, hdr_name.str, add_element_size); mhd_assert (MHD_CONNECTION_FULL_REQ_RECEIVED < c->state); return true; } /* Reset processing state */ reset_rq_header_processing_state (c); mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \ c->state); /* Read the next header (field) line */ continue; } else if (MHD_HDR_LINE_READING_NEED_MORE_DATA == res) { mhd_assert ((process_footers ? MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) == \ c->state); return false; } else if (MHD_HDR_LINE_READING_DATA_ERROR == res) { mhd_assert ((process_footers ? \ MHD_CONNECTION_FOOTERS_RECEIVING : \ MHD_CONNECTION_REQ_HEADERS_RECEIVING) < c->state); mhd_assert (c->stop_with_error); mhd_assert (c->discard_request); return true; } mhd_assert (MHD_HDR_LINE_READING_GOT_END_OF_HEADER == res); break; } while (1); #ifdef HAVE_MESSAGES if (1 == c->rq.num_cr_sp_replaced) { MHD_DLOG (c->daemon, _ ("One bare CR character has been replaced with space " \ "in %s.\n"), (! process_footers) ? _ ("the request line or in the request headers") : _ ("the request footers")); } else if (0 != c->rq.num_cr_sp_replaced) { MHD_DLOG (c->daemon, _ ("%" PRIu64 " bare CR characters have been replaced with " \ "spaces in the request line and/or in the request %s.\n"), (uint64_t) c->rq.num_cr_sp_replaced, (! process_footers) ? _ ("headers") : _ ("footers")); } if (1 == c->rq.skipped_broken_lines) { MHD_DLOG (c->daemon, _ ("One %s line without colon has been skipped.\n"), (! process_footers) ? _ ("header") : _ ("footer")); } else if (0 != c->rq.skipped_broken_lines) { MHD_DLOG (c->daemon, _ ("%" PRIu64 " %s lines without colons has been skipped.\n"), (uint64_t) c->rq.skipped_broken_lines, (! process_footers) ? _ ("header") : _ ("footer")); } #endif /* HAVE_MESSAGES */ mhd_assert (c->rq.method < c->read_buffer); if (! process_footers) { c->rq.header_size = (size_t) (c->read_buffer - c->rq.method); mhd_assert (NULL != c->rq.field_lines.start); c->rq.field_lines.size = (size_t) ((c->read_buffer - c->rq.field_lines.start) - 1); if ('\r' == *(c->read_buffer - 2)) c->rq.field_lines.size--; c->state = MHD_CONNECTION_HEADERS_RECEIVED; if (MHD_BUF_INC_SIZE > c->read_buffer_size) { /* Try to re-use some of the last bytes of the request header */ /* Do this only if space in the read buffer is limited AND amount of read ahead data is small. */ /** * The position of the terminating NUL after the last character of * the last header element. */ const char *last_elmnt_end; size_t shift_back_size; if (NULL != c->rq.headers_received_tail) { if (NULL == c->rq.headers_received_tail->value) { /* Tailing query argument without '=', we only have the header */ last_elmnt_end = c->rq.headers_received_tail->header + c->rq.headers_received_tail->header_size; } else { last_elmnt_end = c->rq.headers_received_tail->value + c->rq.headers_received_tail->value_size; } } else { last_elmnt_end = c->rq.version + HTTP_VER_LEN; } /* The request line strings (method, url, version) remain visible to the application for the whole request, and the last received header is not necessarily above them: when it is not, reclaiming down to the header end puts the read buffer on top of the version string, and the next recv() overwrites the terminator the application is about to read through. Never reclaim below the end of the request line. */ if ((NULL != c->rq.version) && (last_elmnt_end < c->rq.version + HTTP_VER_LEN)) last_elmnt_end = c->rq.version + HTTP_VER_LEN; /* Check that @a last_elmnt_end points into the request that has just been parsed, which lives entirely between the start of the request line and the current read buffer position. */ MHD_CHECK_CONN_CLOSE_RET_ (c, (NULL != last_elmnt_end) && (c->rq.method <= last_elmnt_end) && (last_elmnt_end < c->read_buffer - 1), true); shift_back_size = (size_t) (c->read_buffer - (last_elmnt_end + 1)); if (0 != c->read_buffer_offset) memmove (c->read_buffer - shift_back_size, c->read_buffer, c->read_buffer_offset); c->read_buffer -= shift_back_size; c->read_buffer_size += shift_back_size; } } else c->state = MHD_CONNECTION_FOOTERS_RECEIVED; return true; } /** * Update the 'last_activity' field of the connection to the current time * and move the connection to the head of the 'normal_timeout' list if * the timeout for the connection uses the default value. * * @param connection the connection that saw some activity */ void MHD_update_last_activity_ (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; #if defined(MHD_USE_THREADS) mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ if (0 == connection->connection_timeout_ms) return; /* Skip update of activity for connections without timeout timer. */ if (connection->suspended) return; /* no activity on suspended connections */ connection->last_activity = MHD_monotonic_msec_counter (); if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) return; /* each connection has personal timeout */ if (connection->connection_timeout_ms != daemon->connection_timeout_ms) return; /* custom timeout, no need to move it in "normal" DLL */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif /* move connection to head of timeout list (by remove + add operation) */ XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); XDLL_insert (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif } /** * This function handles a particular connection when it has been * determined that there is data to be read off a socket. All * implementations (multithreaded, external polling, internal polling) * call this function to handle reads. * * @param connection connection to handle * @param socket_error set to true if socket error was detected */ void MHD_connection_handle_read (struct MHD_Connection *connection, bool socket_error) { ssize_t bytes_read; if ( (MHD_CONNECTION_CLOSED == connection->state) || (connection->suspended) ) return; #ifdef HTTPS_SUPPORT if (MHD_TLS_CONN_NO_TLS != connection->tls_state) { /* HTTPS connection. */ if (MHD_TLS_CONN_CONNECTED > connection->tls_state) { if (! MHD_run_tls_handshake_ (connection)) return; } } #endif /* HTTPS_SUPPORT */ mhd_assert (NULL != connection->read_buffer); if (connection->read_buffer_size == connection->read_buffer_offset) return; /* No space for receiving data. */ bytes_read = connection->recv_cls (connection, &connection->read_buffer [connection->read_buffer_offset], connection->read_buffer_size - connection->read_buffer_offset); if ((bytes_read < 0) || socket_error) { if ((MHD_ERR_AGAIN_ == bytes_read) && ! socket_error) return; /* No new data to process. */ if ((bytes_read > 0) && connection->sk_nonblck) { /* Try to detect the socket error */ int dummy; bytes_read = connection->recv_cls (connection, &dummy, sizeof (dummy)); } if (MHD_ERR_CONNRESET_ == bytes_read) { if ( (MHD_CONNECTION_INIT < connection->state) && (MHD_CONNECTION_FULL_REQ_RECEIVED > connection->state) ) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Socket has been disconnected when reading request.\n")); #endif connection->discard_request = true; } MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_READ_ERROR); return; } #ifdef HAVE_MESSAGES if (MHD_CONNECTION_INIT != connection->state) MHD_DLOG (connection->daemon, _ ("Connection socket is closed when reading " \ "request due to the error: %s\n"), (bytes_read < 0) ? str_conn_error_ (bytes_read) : "detected connection closure"); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } if (0 == bytes_read) { /* Remote side closed connection. */ connection->read_closed = true; if ( (MHD_CONNECTION_INIT < connection->state) && (MHD_CONNECTION_FULL_REQ_RECEIVED > connection->state) ) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Connection was closed by remote side with incomplete " "request.\n")); #endif connection->discard_request = true; MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_CLIENT_ABORT); } else if (MHD_CONNECTION_INIT == connection->state) /* This termination code cannot be reported to the application * because application has not been informed yet about this request */ MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_COMPLETED_OK); else MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_WITH_ERROR); return; } connection->read_buffer_offset += (size_t) bytes_read; MHD_update_last_activity_ (connection); #if DEBUG_STATES MHD_DLOG (connection->daemon, _ ("In function %s handling connection at state: %s\n"), MHD_FUNC_, MHD_state_to_string (connection->state)); #endif /* TODO: check whether the next 'switch()' really needed */ switch (connection->state) { case MHD_CONNECTION_INIT: case MHD_CONNECTION_REQ_LINE_RECEIVING: case MHD_CONNECTION_REQ_HEADERS_RECEIVING: case MHD_CONNECTION_BODY_RECEIVING: case MHD_CONNECTION_FOOTERS_RECEIVING: case MHD_CONNECTION_FULL_REQ_RECEIVED: /* nothing to do but default action */ if (connection->read_closed) { /* TODO: check whether this really needed */ MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_READ_ERROR); } return; case MHD_CONNECTION_CLOSED: return; #ifdef UPGRADE_SUPPORT case MHD_CONNECTION_UPGRADE: mhd_assert (0); return; #endif /* UPGRADE_SUPPORT */ case MHD_CONNECTION_START_REPLY: /* shrink read buffer to how much is actually used */ /* TODO: remove shrink as it handled in special function */ if ((0 != connection->read_buffer_size) && (connection->read_buffer_size != connection->read_buffer_offset)) { mhd_assert (NULL != connection->read_buffer); connection->read_buffer = MHD_pool_reallocate (connection->pool, connection->read_buffer, connection->read_buffer_size, connection->read_buffer_offset); connection->read_buffer_size = connection->read_buffer_offset; } break; case MHD_CONNECTION_REQ_LINE_RECEIVED: case MHD_CONNECTION_HEADERS_RECEIVED: case MHD_CONNECTION_HEADERS_PROCESSED: case MHD_CONNECTION_BODY_RECEIVED: case MHD_CONNECTION_FOOTERS_RECEIVED: /* Milestone state, no data should be read */ mhd_assert (0); /* Should not be possible */ break; case MHD_CONNECTION_CONTINUE_SENDING: case MHD_CONNECTION_HEADERS_SENDING: case MHD_CONNECTION_HEADERS_SENT: case MHD_CONNECTION_NORMAL_BODY_UNREADY: case MHD_CONNECTION_NORMAL_BODY_READY: case MHD_CONNECTION_CHUNKED_BODY_UNREADY: case MHD_CONNECTION_CHUNKED_BODY_READY: case MHD_CONNECTION_CHUNKED_BODY_SENT: case MHD_CONNECTION_FOOTERS_SENDING: case MHD_CONNECTION_FULL_REPLY_SENT: default: mhd_assert (0); /* Should not be possible */ break; } return; } /** * This function was created to handle writes to sockets when it has * been determined that the socket can be written to. All * implementations (multithreaded, external select, internal select) * call this function * * @param connection connection to handle */ void MHD_connection_handle_write (struct MHD_Connection *connection) { struct MHD_Response *response; ssize_t ret; if (connection->suspended) return; #ifdef HTTPS_SUPPORT if (MHD_TLS_CONN_NO_TLS != connection->tls_state) { /* HTTPS connection. */ if (MHD_TLS_CONN_CONNECTED > connection->tls_state) { if (! MHD_run_tls_handshake_ (connection)) return; } } #endif /* HTTPS_SUPPORT */ #if DEBUG_STATES MHD_DLOG (connection->daemon, _ ("In function %s handling connection at state: %s\n"), MHD_FUNC_, MHD_state_to_string (connection->state)); #endif switch (connection->state) { case MHD_CONNECTION_INIT: case MHD_CONNECTION_REQ_LINE_RECEIVING: case MHD_CONNECTION_REQ_LINE_RECEIVED: case MHD_CONNECTION_REQ_HEADERS_RECEIVING: case MHD_CONNECTION_HEADERS_RECEIVED: case MHD_CONNECTION_HEADERS_PROCESSED: mhd_assert (0); return; case MHD_CONNECTION_CONTINUE_SENDING: ret = MHD_send_data_ (connection, &HTTP_100_CONTINUE [connection->continue_message_write_offset], MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE) - connection->continue_message_write_offset, true); if (ret < 0) { if (MHD_ERR_AGAIN_ == ret) return; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to send data in request for %s.\n"), connection->rq.url); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } #if _MHD_DEBUG_SEND_DATA fprintf (stderr, _ ("Sent 100 continue response: `%.*s'\n"), (int) ret, &HTTP_100_CONTINUE[connection->continue_message_write_offset]); #endif connection->continue_message_write_offset += (size_t) ret; MHD_update_last_activity_ (connection); return; case MHD_CONNECTION_BODY_RECEIVING: case MHD_CONNECTION_BODY_RECEIVED: case MHD_CONNECTION_FOOTERS_RECEIVING: case MHD_CONNECTION_FOOTERS_RECEIVED: case MHD_CONNECTION_FULL_REQ_RECEIVED: mhd_assert (0); return; case MHD_CONNECTION_START_REPLY: mhd_assert (0); return; case MHD_CONNECTION_HEADERS_SENDING: { struct MHD_Response *const resp = connection->rp.response; const size_t wb_ready = connection->write_buffer_append_offset - connection->write_buffer_send_offset; mhd_assert (connection->write_buffer_append_offset >= \ connection->write_buffer_send_offset); mhd_assert (NULL != resp); mhd_assert ( (0 == resp->data_size) || \ (0 == resp->data_start) || \ (NULL != resp->crc) ); mhd_assert ( (0 == connection->rp.rsp_write_position) || \ (resp->total_size == connection->rp.rsp_write_position) ); mhd_assert ((MHD_CONN_MUST_UPGRADE != connection->keepalive) || \ (! connection->rp.props.send_reply_body)); if ( (connection->rp.props.send_reply_body) && (NULL == resp->crc) && (NULL == resp->data_iov) && /* TODO: remove the next check as 'send_reply_body' is used */ (0 == connection->rp.rsp_write_position) && (! connection->rp.props.chunked) ) { mhd_assert (resp->total_size >= resp->data_size); mhd_assert (0 == resp->data_start); /* Send response headers alongside the response body, if the body * data is available. */ ret = MHD_send_hdr_and_body_ (connection, &connection->write_buffer [connection->write_buffer_send_offset], wb_ready, false, resp->data, resp->data_size, (resp->total_size == resp->data_size)); } else { /* This is response for HEAD request or reply body is not allowed * for any other reason or reply body is dynamically generated. */ /* Do not send the body data even if it's available. */ ret = MHD_send_hdr_and_body_ (connection, &connection->write_buffer [connection->write_buffer_send_offset], wb_ready, false, NULL, 0, ((0 == resp->total_size) || (! connection->rp.props.send_reply_body) )); } if (ret < 0) { if (MHD_ERR_AGAIN_ == ret) return; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to send the response headers for the " \ "request for `%s'. Error: %s\n"), connection->rq.url, str_conn_error_ (ret)); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } /* 'ret' is not negative, it's safe to cast it to 'size_t'. */ if (((size_t) ret) > wb_ready) { /* The complete header and some response data have been sent, * update both offsets. */ mhd_assert (0 == connection->rp.rsp_write_position); mhd_assert (! connection->rp.props.chunked); mhd_assert (connection->rp.props.send_reply_body); connection->write_buffer_send_offset += wb_ready; connection->rp.rsp_write_position = ((size_t) ret) - wb_ready; } else connection->write_buffer_send_offset += (size_t) ret; MHD_update_last_activity_ (connection); if (MHD_CONNECTION_HEADERS_SENDING != connection->state) return; check_write_done (connection, MHD_CONNECTION_HEADERS_SENT); return; } case MHD_CONNECTION_HEADERS_SENT: return; case MHD_CONNECTION_NORMAL_BODY_READY: response = connection->rp.response; if (connection->rp.rsp_write_position < connection->rp.response->total_size) { uint64_t data_write_offset; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != response->crc) MHD_mutex_lock_chk_ (&response->mutex); #endif if (MHD_NO == try_ready_normal_body (connection)) { /* mutex was already unlocked by try_ready_normal_body */ return; } #if defined(_MHD_HAVE_SENDFILE) if (MHD_resp_sender_sendfile == connection->rp.resp_sender) { mhd_assert (NULL == response->data_iov); ret = MHD_send_sendfile_ (connection); } else /* combined with the next 'if' */ #endif /* _MHD_HAVE_SENDFILE */ if (NULL != response->data_iov) { ret = MHD_send_iovec_ (connection, &connection->rp.resp_iov, true); } else { data_write_offset = connection->rp.rsp_write_position - response->data_start; if (data_write_offset > (uint64_t) SIZE_MAX) MHD_PANIC (_ ("Data offset exceeds limit.\n")); ret = MHD_send_data_ (connection, &response->data [(size_t) data_write_offset], response->data_size - (size_t) data_write_offset, true); #if _MHD_DEBUG_SEND_DATA if (ret > 0) fprintf (stderr, _ ("Sent %d-byte DATA response: `%.*s'\n"), (int) ret, (int) ret, &rp.response->data[connection->rp.rsp_write_position - rp.response->data_start]); #endif } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != response->crc) MHD_mutex_unlock_chk_ (&response->mutex); #endif if (ret < 0) { if (MHD_ERR_AGAIN_ == ret) return; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to send the response body for the " \ "request for `%s'. Error: %s\n"), connection->rq.url, str_conn_error_ (ret)); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } connection->rp.rsp_write_position += (size_t) ret; MHD_update_last_activity_ (connection); } if (connection->rp.rsp_write_position == connection->rp.response->total_size) connection->state = MHD_CONNECTION_FULL_REPLY_SENT; return; case MHD_CONNECTION_NORMAL_BODY_UNREADY: mhd_assert (0); return; case MHD_CONNECTION_CHUNKED_BODY_READY: ret = MHD_send_data_ (connection, &connection->write_buffer [connection->write_buffer_send_offset], connection->write_buffer_append_offset - connection->write_buffer_send_offset, true); if (ret < 0) { if (MHD_ERR_AGAIN_ == ret) return; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to send the chunked response body for the " \ "request for `%s'. Error: %s\n"), connection->rq.url, str_conn_error_ (ret)); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } connection->write_buffer_send_offset += (size_t) ret; MHD_update_last_activity_ (connection); if (MHD_CONNECTION_CHUNKED_BODY_READY != connection->state) return; check_write_done (connection, (connection->rp.response->total_size == connection->rp.rsp_write_position) ? MHD_CONNECTION_CHUNKED_BODY_SENT : MHD_CONNECTION_CHUNKED_BODY_UNREADY); return; case MHD_CONNECTION_CHUNKED_BODY_UNREADY: case MHD_CONNECTION_CHUNKED_BODY_SENT: mhd_assert (0); return; case MHD_CONNECTION_FOOTERS_SENDING: ret = MHD_send_data_ (connection, &connection->write_buffer [connection->write_buffer_send_offset], connection->write_buffer_append_offset - connection->write_buffer_send_offset, true); if (ret < 0) { if (MHD_ERR_AGAIN_ == ret) return; #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Failed to send the footers for the " \ "request for `%s'. Error: %s\n"), connection->rq.url, str_conn_error_ (ret)); #endif CONNECTION_CLOSE_ERROR (connection, NULL); return; } connection->write_buffer_send_offset += (size_t) ret; MHD_update_last_activity_ (connection); if (MHD_CONNECTION_FOOTERS_SENDING != connection->state) return; check_write_done (connection, MHD_CONNECTION_FULL_REPLY_SENT); return; case MHD_CONNECTION_FULL_REPLY_SENT: mhd_assert (0); return; case MHD_CONNECTION_CLOSED: return; #ifdef UPGRADE_SUPPORT case MHD_CONNECTION_UPGRADE: mhd_assert (0); return; #endif /* UPGRADE_SUPPORT */ default: mhd_assert (0); CONNECTION_CLOSE_ERROR (connection, _ ("Internal error.\n")); break; } return; } /** * Check whether connection has timed out. * @param c the connection to check * @return true if connection has timeout and needs to be closed, * false otherwise. */ static bool connection_check_timedout (struct MHD_Connection *c) { const uint64_t timeout = c->connection_timeout_ms; uint64_t now; uint64_t since_actv; if (c->suspended) return false; if (0 == timeout) return false; now = MHD_monotonic_msec_counter (); since_actv = now - c->last_activity; /* Keep the next lines in sync with #connection_get_wait() to avoid * undesired side-effects like busy-waiting. */ if (timeout < since_actv) { if (UINT64_MAX / 2 < since_actv) { const uint64_t jump_back = c->last_activity - now; /* Very unlikely that it is more than quarter-million years pause. * More likely that system clock jumps back. */ if (5000 >= jump_back) { #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Detected system clock %u milliseconds jump back.\n"), (unsigned int) jump_back); #endif return false; } #ifdef HAVE_MESSAGES MHD_DLOG (c->daemon, _ ("Detected too large system clock %" PRIu64 " milliseconds " "jump back.\n"), jump_back); #endif } return true; } return false; } /** * Clean up the state of the given connection and move it into the * clean up queue for final disposal. * @remark To be called only from thread that process connection's * recv(), send() and response. * * @param connection handle for the connection to clean up */ static void cleanup_connection (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); mhd_assert (NULL == daemon->worker_pool); #endif /* MHD_USE_THREADS */ if (connection->in_cleanup) return; /* Prevent double cleanup. */ connection->in_cleanup = true; if (NULL != connection->rp.response) { MHD_destroy_response (connection->rp.response); connection->rp.response = NULL; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif if (connection->suspended) { DLL_remove (daemon->suspended_connections_head, daemon->suspended_connections_tail, connection); connection->suspended = false; } else { if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { if (connection->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); else XDLL_remove (daemon->manual_timeout_head, daemon->manual_timeout_tail, connection); } DLL_remove (daemon->connections_head, daemon->connections_tail, connection); } DLL_insert (daemon->cleanup_head, daemon->cleanup_tail, connection); connection->resuming = false; connection->in_idle = false; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { /* if we were at the connection limit before and are in thread-per-connection mode, signal the main thread to resume accepting connections */ if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && (! MHD_itc_activate_ (daemon->itc, "c")) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to signal end of connection via inter-thread " \ "communication channel.\n")); #endif } } } /** * Set initial internal states for the connection to start reading and * processing incoming data. * @param c the connection to process */ void MHD_connection_set_initial_state_ (struct MHD_Connection *c) { size_t read_buf_size; #ifdef HTTPS_SUPPORT mhd_assert ( (0 == (c->daemon->options & MHD_USE_TLS)) || \ (MHD_TLS_CONN_INIT == c->tls_state) ); mhd_assert ( (0 != (c->daemon->options & MHD_USE_TLS)) || \ (MHD_TLS_CONN_NO_TLS == c->tls_state) ); #endif /* HTTPS_SUPPORT */ mhd_assert (MHD_CONNECTION_INIT == c->state); c->keepalive = MHD_CONN_KEEPALIVE_UNKOWN; c->event_loop_info = MHD_EVENT_LOOP_INFO_READ; memset (&c->rq, 0, sizeof(c->rq)); memset (&c->rp, 0, sizeof(c->rp)); c->write_buffer = NULL; c->write_buffer_size = 0; c->write_buffer_send_offset = 0; c->write_buffer_append_offset = 0; c->continue_message_write_offset = 0; c->read_buffer_offset = 0; read_buf_size = c->daemon->pool_size / 2; c->read_buffer = MHD_pool_allocate (c->pool, read_buf_size, false); c->read_buffer_size = read_buf_size; } /** * Reset connection after request-reply cycle. * @param connection the connection to process * @param reuse the flag to choose whether to close connection or * prepare connection for the next request processing */ static void connection_reset (struct MHD_Connection *connection, bool reuse) { struct MHD_Connection *const c = connection; /**< a short alias */ struct MHD_Daemon *const d = connection->daemon; if (! reuse) { /* Next function will destroy response, notify client, * destroy memory pool, and set connection state to "CLOSED" */ MHD_connection_close_ (c, c->stop_with_error ? MHD_REQUEST_TERMINATED_WITH_ERROR : MHD_REQUEST_TERMINATED_COMPLETED_OK); c->read_buffer = NULL; c->read_buffer_size = 0; c->read_buffer_offset = 0; c->write_buffer = NULL; c->write_buffer_size = 0; c->write_buffer_send_offset = 0; c->write_buffer_append_offset = 0; } else { /* Reset connection to process the next request */ size_t new_read_buf_size; mhd_assert (! c->stop_with_error); mhd_assert (! c->discard_request); if ( (NULL != d->notify_completed) && (c->rq.client_aware) ) d->notify_completed (d->notify_completed_cls, c, &c->rq.client_context, MHD_REQUEST_TERMINATED_COMPLETED_OK); c->rq.client_aware = false; if (NULL != c->rp.response) MHD_destroy_response (c->rp.response); c->rp.response = NULL; c->keepalive = MHD_CONN_KEEPALIVE_UNKOWN; c->state = MHD_CONNECTION_INIT; c->event_loop_info = (0 == c->read_buffer_offset) ? MHD_EVENT_LOOP_INFO_READ : MHD_EVENT_LOOP_INFO_PROCESS; memset (&c->rq, 0, sizeof(c->rq)); /* iov (if any) will be deallocated by MHD_pool_reset */ memset (&c->rp, 0, sizeof(c->rp)); c->write_buffer = NULL; c->write_buffer_size = 0; c->write_buffer_send_offset = 0; c->write_buffer_append_offset = 0; c->continue_message_write_offset = 0; /* Reset the read buffer to the starting size, preserving the bytes we have already read. */ new_read_buf_size = c->daemon->pool_size / 2; if (c->read_buffer_offset > new_read_buf_size) new_read_buf_size = c->read_buffer_offset; c->read_buffer = MHD_pool_reset (c->pool, c->read_buffer, c->read_buffer_offset, new_read_buf_size); c->read_buffer_size = new_read_buf_size; } c->rq.client_context = NULL; } /** * This function was created to handle per-connection processing that * has to happen even if the socket cannot be read or written to. * All implementations (multithreaded, external select, internal select) * call this function. * @remark To be called only from thread that process connection's * recv(), send() and response. * * @param connection connection to handle * @return #MHD_YES if we should continue to process the * connection (not dead yet), #MHD_NO if it died */ enum MHD_Result MHD_connection_handle_idle (struct MHD_Connection *connection) { struct MHD_Daemon *daemon = connection->daemon; enum MHD_Result ret; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); #endif /* MHD_USE_THREADS */ /* 'daemon' is not used if epoll is not available and asserts are disabled */ (void) daemon; /* Mute compiler warning */ connection->in_idle = true; while (! connection->suspended) { #ifdef HTTPS_SUPPORT if (MHD_TLS_CONN_NO_TLS != connection->tls_state) { /* HTTPS connection. */ if ((MHD_TLS_CONN_INIT <= connection->tls_state) && (MHD_TLS_CONN_CONNECTED > connection->tls_state)) break; } #endif /* HTTPS_SUPPORT */ #if DEBUG_STATES MHD_DLOG (daemon, _ ("In function %s handling connection at state: %s\n"), MHD_FUNC_, MHD_state_to_string (connection->state)); #endif switch (connection->state) { case MHD_CONNECTION_INIT: case MHD_CONNECTION_REQ_LINE_RECEIVING: if (get_request_line (connection)) { mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING < connection->state); mhd_assert ((MHD_IS_HTTP_VER_SUPPORTED (connection->rq.http_ver)) \ || (connection->discard_request)); continue; } mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVING >= connection->state); break; case MHD_CONNECTION_REQ_LINE_RECEIVED: switch_to_rq_headers_processing (connection); mhd_assert (MHD_CONNECTION_REQ_LINE_RECEIVED != connection->state); continue; case MHD_CONNECTION_REQ_HEADERS_RECEIVING: if (get_req_headers (connection, false)) { mhd_assert (MHD_CONNECTION_REQ_HEADERS_RECEIVING < connection->state); mhd_assert ((MHD_CONNECTION_HEADERS_RECEIVED == connection->state) || \ (connection->discard_request)); continue; } mhd_assert (MHD_CONNECTION_REQ_HEADERS_RECEIVING == connection->state); break; case MHD_CONNECTION_HEADERS_RECEIVED: parse_connection_headers (connection); if (MHD_CONNECTION_HEADERS_RECEIVED != connection->state) continue; connection->state = MHD_CONNECTION_HEADERS_PROCESSED; if (connection->suspended) break; continue; case MHD_CONNECTION_HEADERS_PROCESSED: call_connection_handler (connection); /* first call */ if (MHD_CONNECTION_HEADERS_PROCESSED != connection->state) continue; if (connection->suspended) continue; if ( (NULL == connection->rp.response) && (need_100_continue (connection)) && /* If the client is already sending the payload (body) there is no need to send "100 Continue" */ (0 == connection->read_buffer_offset) ) { connection->state = MHD_CONNECTION_CONTINUE_SENDING; break; } if ( (NULL != connection->rp.response) && (0 != connection->rq.remaining_upload_size) ) { /* we refused (no upload allowed!) */ connection->rq.remaining_upload_size = 0; /* force close, in case client still tries to upload... */ connection->discard_request = true; } connection->state = (0 == connection->rq.remaining_upload_size) ? MHD_CONNECTION_FULL_REQ_RECEIVED : MHD_CONNECTION_BODY_RECEIVING; if (connection->suspended) break; continue; case MHD_CONNECTION_CONTINUE_SENDING: if (connection->continue_message_write_offset == MHD_STATICSTR_LEN_ (HTTP_100_CONTINUE)) { connection->state = MHD_CONNECTION_BODY_RECEIVING; continue; } break; case MHD_CONNECTION_BODY_RECEIVING: mhd_assert (0 != connection->rq.remaining_upload_size); mhd_assert (! connection->discard_request); mhd_assert (NULL == connection->rp.response); if (0 != connection->read_buffer_offset) { process_request_body (connection); /* loop call */ if (MHD_CONNECTION_BODY_RECEIVING != connection->state) continue; } /* Modify here when queueing of the response during data processing will be supported */ mhd_assert (! connection->discard_request); mhd_assert (NULL == connection->rp.response); if (0 == connection->rq.remaining_upload_size) { connection->state = MHD_CONNECTION_BODY_RECEIVED; continue; } break; case MHD_CONNECTION_BODY_RECEIVED: mhd_assert (! connection->discard_request); mhd_assert (NULL == connection->rp.response); if (0 == connection->rq.remaining_upload_size) { if (connection->rq.have_chunked_upload) { /* Reset counter variables reused for footers */ connection->rq.num_cr_sp_replaced = 0; connection->rq.skipped_broken_lines = 0; reset_rq_header_processing_state (connection); connection->state = MHD_CONNECTION_FOOTERS_RECEIVING; } else connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED; continue; } break; case MHD_CONNECTION_FOOTERS_RECEIVING: if (get_req_headers (connection, true)) { mhd_assert (MHD_CONNECTION_FOOTERS_RECEIVING < connection->state); mhd_assert ((MHD_CONNECTION_FOOTERS_RECEIVED == connection->state) || \ (connection->discard_request)); continue; } mhd_assert (MHD_CONNECTION_FOOTERS_RECEIVING == connection->state); break; case MHD_CONNECTION_FOOTERS_RECEIVED: /* The header, the body, and the footers of the request has been received, * switch to the final processing of the request. */ connection->state = MHD_CONNECTION_FULL_REQ_RECEIVED; continue; case MHD_CONNECTION_FULL_REQ_RECEIVED: call_connection_handler (connection); /* "final" call */ if (connection->state != MHD_CONNECTION_FULL_REQ_RECEIVED) continue; if (NULL == connection->rp.response) break; /* try again next time */ /* Response is ready, start reply */ connection->state = MHD_CONNECTION_START_REPLY; continue; case MHD_CONNECTION_START_REPLY: mhd_assert (NULL != connection->rp.response); connection_switch_from_recv_to_send (connection); if (MHD_NO == build_header_response (connection)) { /* oops - close! */ CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (failed to create " "response header).\n")); continue; } connection->state = MHD_CONNECTION_HEADERS_SENDING; break; case MHD_CONNECTION_HEADERS_SENDING: /* no default action */ break; case MHD_CONNECTION_HEADERS_SENT: #ifdef UPGRADE_SUPPORT if (NULL != connection->rp.response->upgrade_handler) { connection->state = MHD_CONNECTION_UPGRADE; /* This connection is "upgraded". Pass socket to application. */ if (MHD_NO == MHD_response_execute_upgrade_ (connection->rp.response, connection)) { /* upgrade failed, fail hard */ CONNECTION_CLOSE_ERROR (connection, NULL); continue; } /* Response is not required anymore for this connection. */ if (1) { struct MHD_Response *const resp = connection->rp.response; connection->rp.response = NULL; MHD_destroy_response (resp); } continue; } #endif /* UPGRADE_SUPPORT */ if (connection->rp.props.send_reply_body) { if (connection->rp.props.chunked) connection->state = MHD_CONNECTION_CHUNKED_BODY_UNREADY; else connection->state = MHD_CONNECTION_NORMAL_BODY_UNREADY; } else connection->state = MHD_CONNECTION_FULL_REPLY_SENT; continue; case MHD_CONNECTION_NORMAL_BODY_READY: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (! connection->rp.props.chunked); /* nothing to do here */ break; case MHD_CONNECTION_NORMAL_BODY_UNREADY: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (! connection->rp.props.chunked); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_lock_chk_ (&connection->rp.response->mutex); #endif if (0 == connection->rp.response->total_size) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_unlock_chk_ (&connection->rp.response->mutex); #endif if (connection->rp.props.chunked) connection->state = MHD_CONNECTION_CHUNKED_BODY_SENT; else connection->state = MHD_CONNECTION_FULL_REPLY_SENT; continue; } if (MHD_NO != try_ready_normal_body (connection)) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_unlock_chk_ (&connection->rp.response->mutex); #endif connection->state = MHD_CONNECTION_NORMAL_BODY_READY; /* Buffering for flushable socket was already enabled*/ break; } /* mutex was already unlocked by "try_ready_normal_body */ /* not ready, no socket action */ break; case MHD_CONNECTION_CHUNKED_BODY_READY: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (connection->rp.props.chunked); /* nothing to do here */ break; case MHD_CONNECTION_CHUNKED_BODY_UNREADY: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (connection->rp.props.chunked); #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_lock_chk_ (&connection->rp.response->mutex); #endif if ( (0 == connection->rp.response->total_size) || (connection->rp.rsp_write_position == connection->rp.response->total_size) ) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_unlock_chk_ (&connection->rp.response->mutex); #endif connection->state = MHD_CONNECTION_CHUNKED_BODY_SENT; continue; } if (1) { /* pseudo-branch for local variables scope */ bool finished; if (MHD_NO != try_ready_chunked_body (connection, &finished)) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (NULL != connection->rp.response->crc) MHD_mutex_unlock_chk_ (&connection->rp.response->mutex); #endif connection->state = finished ? MHD_CONNECTION_CHUNKED_BODY_SENT : MHD_CONNECTION_CHUNKED_BODY_READY; continue; } /* mutex was already unlocked by try_ready_chunked_body */ } break; case MHD_CONNECTION_CHUNKED_BODY_SENT: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (connection->rp.props.chunked); mhd_assert (connection->write_buffer_send_offset <= \ connection->write_buffer_append_offset); if (MHD_NO == build_connection_chunked_response_footer (connection)) { /* oops - close! */ CONNECTION_CLOSE_ERROR (connection, _ ("Closing connection (failed to create " \ "response footer).")); continue; } mhd_assert (connection->write_buffer_send_offset < \ connection->write_buffer_append_offset); connection->state = MHD_CONNECTION_FOOTERS_SENDING; continue; case MHD_CONNECTION_FOOTERS_SENDING: mhd_assert (connection->rp.props.send_reply_body); mhd_assert (connection->rp.props.chunked); /* no default action */ break; case MHD_CONNECTION_FULL_REPLY_SENT: if (MHD_HTTP_PROCESSING == connection->rp.responseCode) { /* After this type of response, we allow sending another! */ connection->state = MHD_CONNECTION_HEADERS_PROCESSED; MHD_destroy_response (connection->rp.response); connection->rp.response = NULL; /* FIXME: maybe partially reset memory pool? */ continue; } /* Reset connection after complete reply */ connection_reset (connection, MHD_CONN_USE_KEEPALIVE == connection->keepalive && ! connection->read_closed && ! connection->discard_request); continue; case MHD_CONNECTION_CLOSED: cleanup_connection (connection); connection->in_idle = false; return MHD_NO; #ifdef UPGRADE_SUPPORT case MHD_CONNECTION_UPGRADE: connection->in_idle = false; return MHD_YES; /* keep open */ #endif /* UPGRADE_SUPPORT */ default: mhd_assert (0); break; } break; } if (connection_check_timedout (connection)) { MHD_connection_close_ (connection, MHD_REQUEST_TERMINATED_TIMEOUT_REACHED); connection->in_idle = false; return MHD_YES; } MHD_connection_update_event_loop_info (connection); ret = MHD_YES; #ifdef EPOLL_SUPPORT if ( (! connection->suspended) && MHD_D_IS_USING_EPOLL_ (daemon) ) { ret = MHD_connection_epoll_update_ (connection); } #endif /* EPOLL_SUPPORT */ connection->in_idle = false; return ret; } #ifdef EPOLL_SUPPORT /** * Perform epoll() processing, possibly moving the connection back into * the epoll() set if needed. * * @param connection connection to process * @return #MHD_YES if we should continue to process the * connection (not dead yet), #MHD_NO if it died */ enum MHD_Result MHD_connection_epoll_update_ (struct MHD_Connection *connection) { struct MHD_Daemon *const daemon = connection->daemon; mhd_assert (MHD_D_IS_USING_EPOLL_ (daemon)); if ((0 != (MHD_EVENT_LOOP_INFO_PROCESS & connection->event_loop_info)) && (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))) { /* Make sure that connection waiting for processing will be processed */ EDLL_insert (daemon->eready_head, daemon->eready_tail, connection); connection->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; } if ( (0 == (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) && (0 == (connection->epoll_state & MHD_EPOLL_STATE_SUSPENDED)) && ( ( (MHD_EVENT_LOOP_INFO_WRITE == connection->event_loop_info) && (0 == (connection->epoll_state & MHD_EPOLL_STATE_WRITE_READY))) || ( (0 != (MHD_EVENT_LOOP_INFO_READ & connection->event_loop_info)) && (0 == (connection->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) ) ) { /* add to epoll set */ struct epoll_event event; event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET; event.data.ptr = connection; if (0 != epoll_ctl (daemon->epoll_fd, EPOLL_CTL_ADD, connection->socket_fd, &event)) { #ifdef HAVE_MESSAGES if (0 != (daemon->options & MHD_USE_ERROR_LOG)) MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif connection->state = MHD_CONNECTION_CLOSED; cleanup_connection (connection); return MHD_NO; } connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET; } return MHD_YES; } #endif /** * Set callbacks for this connection to those for HTTP. * * @param connection connection to initialize */ void MHD_set_http_callbacks_ (struct MHD_Connection *connection) { connection->recv_cls = &recv_param_adapter; } /** * Obtain information about the given connection. * The returned pointer is invalidated with the next call of this function or * when the connection is closed. * * @param connection what connection to get information about * @param info_type what information is desired? * @param ... depends on @a info_type * @return NULL if this information is not available * (or if the @a info_type is unknown) * @ingroup specialized */ _MHD_EXTERN const union MHD_ConnectionInfo * MHD_get_connection_info (struct MHD_Connection *connection, enum MHD_ConnectionInfoType info_type, ...) { switch (info_type) { #ifdef HTTPS_SUPPORT case MHD_CONNECTION_INFO_CIPHER_ALGO: if (NULL == connection->tls_session) return NULL; if (1) { /* Workaround to mute compiler warning */ gnutls_cipher_algorithm_t res; res = gnutls_cipher_get (connection->tls_session); connection->connection_info_dummy.cipher_algorithm = (int) res; } return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_PROTOCOL: if (NULL == connection->tls_session) return NULL; if (1) { /* Workaround to mute compiler warning */ gnutls_protocol_t res; res = gnutls_protocol_get_version (connection->tls_session); connection->connection_info_dummy.protocol = (int) res; } return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_GNUTLS_SESSION: if (NULL == connection->tls_session) return NULL; connection->connection_info_dummy.tls_session = connection->tls_session; return &connection->connection_info_dummy; #else /* ! HTTPS_SUPPORT */ case MHD_CONNECTION_INFO_CIPHER_ALGO: case MHD_CONNECTION_INFO_PROTOCOL: case MHD_CONNECTION_INFO_GNUTLS_SESSION: #endif /* ! HTTPS_SUPPORT */ case MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT: return NULL; /* Not implemented */ case MHD_CONNECTION_INFO_CLIENT_ADDRESS: if (0 < connection->addr_len) { mhd_assert (sizeof (connection->addr) == \ sizeof (connection->connection_info_dummy.client_addr)); memcpy (&connection->connection_info_dummy.client_addr, &connection->addr, sizeof(connection->addr)); return &connection->connection_info_dummy; } return NULL; case MHD_CONNECTION_INFO_DAEMON: connection->connection_info_dummy.daemon = MHD_get_master (connection->daemon); return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_CONNECTION_FD: connection->connection_info_dummy.connect_fd = connection->socket_fd; return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_SOCKET_CONTEXT: connection->connection_info_dummy.socket_context = connection->socket_context; return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_CONNECTION_SUSPENDED: connection->connection_info_dummy.suspended = connection->suspended ? MHD_YES : MHD_NO; return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_CONNECTION_TIMEOUT: #if SIZEOF_UNSIGNED_INT <= (SIZEOF_UINT64_T - 2) if (UINT_MAX < connection->connection_timeout_ms / 1000) connection->connection_info_dummy.connection_timeout = UINT_MAX; else #endif /* SIZEOF_UNSIGNED_INT <=(SIZEOF_UINT64_T - 2) */ connection->connection_info_dummy.connection_timeout = (unsigned int) (connection->connection_timeout_ms / 1000); return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE: if ( (MHD_CONNECTION_HEADERS_RECEIVED > connection->state) || (MHD_CONNECTION_CLOSED == connection->state) ) return NULL; /* invalid, too early! */ connection->connection_info_dummy.header_size = connection->rq.header_size; return &connection->connection_info_dummy; case MHD_CONNECTION_INFO_HTTP_STATUS: if (NULL == connection->rp.response) return NULL; connection->connection_info_dummy.http_status = connection->rp.responseCode; return &connection->connection_info_dummy; default: return NULL; } } /** * Set a custom option for the given connection, overriding defaults. * * @param connection connection to modify * @param option option to set * @param ... arguments to the option, depending on the option type * @return #MHD_YES on success, #MHD_NO if setting the option failed * @ingroup specialized */ _MHD_EXTERN enum MHD_Result MHD_set_connection_option (struct MHD_Connection *connection, enum MHD_CONNECTION_OPTION option, ...) { va_list ap; struct MHD_Daemon *daemon; unsigned int ui_val; daemon = connection->daemon; switch (option) { case MHD_CONNECTION_OPTION_TIMEOUT: if (0 == connection->connection_timeout_ms) connection->last_activity = MHD_monotonic_msec_counter (); va_start (ap, option); ui_val = va_arg (ap, unsigned int); va_end (ap); #if (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT if ((UINT64_MAX / 4000 - 1) < ui_val) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The specified connection timeout (%u) is too " \ "large. Maximum allowed value (%" PRIu64 ") will be used " \ "instead.\n"), ui_val, (UINT64_MAX / 4000 - 1)); #endif ui_val = UINT64_MAX / 4000 - 1; } #endif /* (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT */ if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { #if defined(MHD_USE_THREADS) MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); #endif if (! connection->suspended) { if (connection->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_remove (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); else XDLL_remove (daemon->manual_timeout_head, daemon->manual_timeout_tail, connection); connection->connection_timeout_ms = ((uint64_t) ui_val) * 1000; if (connection->connection_timeout_ms == daemon->connection_timeout_ms) XDLL_insert (daemon->normal_timeout_head, daemon->normal_timeout_tail, connection); else XDLL_insert (daemon->manual_timeout_head, daemon->manual_timeout_tail, connection); } #if defined(MHD_USE_THREADS) MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); #endif } return MHD_YES; default: return MHD_NO; } } /** * Queue a response to be transmitted to the client (as soon as * possible but after #MHD_AccessHandlerCallback returns). * * For any active connection this function must be called * only by #MHD_AccessHandlerCallback callback. * * For suspended connection this function can be called at any moment (this * behaviour is deprecated and will be removed!). Response will be sent * as soon as connection is resumed. * * For single thread environment, when MHD is used in "external polling" mode * (without MHD_USE_SELECT_INTERNALLY) this function can be called any * time (this behaviour is deprecated and will be removed!). * * If HTTP specifications require use no body in reply, like @a status_code with * value 1xx, the response body is automatically not sent even if it is present * in the response. No "Content-Length" or "Transfer-Encoding" headers are * generated and added. * * When the response is used to respond HEAD request or used with @a status_code * #MHD_HTTP_NOT_MODIFIED, then response body is not sent, but "Content-Length" * header is added automatically based the size of the body in the response. * If body size it set to #MHD_SIZE_UNKNOWN or chunked encoding is enforced * then "Transfer-Encoding: chunked" header (for HTTP/1.1 only) is added instead * of "Content-Length" header. For example, if response with zero-size body is * used for HEAD request, then "Content-Length: 0" is added automatically to * reply headers. * @sa #MHD_RF_HEAD_ONLY_RESPONSE * * In situations, where reply body is required, like answer for the GET request * with @a status_code #MHD_HTTP_OK, headers "Content-Length" (for known body * size) or "Transfer-Encoding: chunked" (for #MHD_SIZE_UNKNOWN with HTTP/1.1) * are added automatically. * In practice, the same response object can be used to respond to both HEAD and * GET requests. * * @param connection the connection identifying the client * @param status_code HTTP status code (i.e. #MHD_HTTP_OK) * @param response response to transmit, the NULL is tolerated * @return #MHD_NO on error (reply already sent, response is NULL), * #MHD_YES on success or if message has been queued * @ingroup response * @sa #MHD_AccessHandlerCallback */ _MHD_EXTERN enum MHD_Result MHD_queue_response (struct MHD_Connection *connection, unsigned int status_code, struct MHD_Response *response) { struct MHD_Daemon *daemon; bool reply_icy; if ((NULL == connection) || (NULL == response)) return MHD_NO; daemon = connection->daemon; if ((! connection->in_access_handler) && (! connection->suspended) && MHD_D_IS_USING_THREADS_ (daemon)) return MHD_NO; reply_icy = (0 != (status_code & MHD_ICY_FLAG)); status_code &= ~MHD_ICY_FLAG; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if ( (! connection->suspended) && MHD_D_IS_USING_THREADS_ (daemon) && (! MHD_thread_handle_ID_is_current_thread_ (connection->tid)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Attempted to queue response on wrong thread!\n")); #endif return MHD_NO; } #endif if (NULL != connection->rp.response) return MHD_NO; /* The response was already set */ if ( (MHD_CONNECTION_HEADERS_PROCESSED != connection->state) && (MHD_CONNECTION_FULL_REQ_RECEIVED != connection->state) ) return MHD_NO; /* Wrong connection state */ if (daemon->shutdown) return MHD_NO; #ifdef UPGRADE_SUPPORT if (NULL != response->upgrade_handler) { if (0 == (daemon->options & MHD_ALLOW_UPGRADE)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Attempted 'upgrade' connection on daemon without" \ " MHD_ALLOW_UPGRADE option!\n")); #endif return MHD_NO; } if (MHD_HTTP_SWITCHING_PROTOCOLS != status_code) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Application used invalid status code for" \ " 'upgrade' response!\n")); #endif return MHD_NO; } if (0 == (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Application used invalid response" \ " without \"Connection\" header!\n")); #endif return MHD_NO; } /* MHD_add_response_header() keeps the "Connection" header first, so response->first_header could be read directly here; look it up by name instead, so that this does not silently break if that ever stops being true. */ mhd_assert (NULL != response->first_header); mhd_assert (MHD_str_equal_caseless_ (response->first_header->header, MHD_HTTP_HEADER_CONNECTION)); if (! MHD_check_response_header_s_token_ci (response, MHD_HTTP_HEADER_CONNECTION, "upgrade")) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Application used invalid response" \ " without \"upgrade\" token in" \ " \"Connection\" header!\n")); #endif return MHD_NO; } if (! MHD_IS_HTTP_VER_1_1_COMPAT (connection->rq.http_ver)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Connection \"Upgrade\" can be used only " \ "with HTTP/1.1 connections!\n")); #endif return MHD_NO; } if (MHD_CONN_MUST_CLOSE == connection->keepalive) { /* MHD has already decided, while parsing the request, that this * connection cannot be reused; 'keepalive_possible()' therefore * returns MHD_CONN_MUST_CLOSE rather than MHD_CONN_MUST_UPGRADE * for it, and 'build_header_response()' asserts that an upgrade * reply is only ever built for MHD_CONN_MUST_UPGRADE. Refuse the * response here instead of aborting there. * * The application cannot test for this itself: the request that * triggers it looks perfectly well-formed to the access handler. * A request carrying both "Content-Length" and * "Transfer-Encoding: chunked" is the shortest way in and needs * no non-default daemon options at all. */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Connection cannot be upgraded: it has already been " \ "marked as \"must close\" while the request was " \ "being parsed.\n")); #endif return MHD_NO; } } #endif /* UPGRADE_SUPPORT */ if (MHD_HTTP_SWITCHING_PROTOCOLS == status_code) { #ifdef UPGRADE_SUPPORT if (NULL == response->upgrade_handler) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Application used status code 101 \"Switching Protocols\" " \ "with non-'upgrade' response!\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; } #else /* ! UPGRADE_SUPPORT */ #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Application used status code 101 \"Switching Protocols\", " \ "but this MHD was built without \"Upgrade\" support!\n")); #endif /* HAVE_MESSAGES */ return MHD_NO; #endif /* ! UPGRADE_SUPPORT */ } if ( (100 > status_code) || (999 < status_code) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Refused wrong status code (%u). " \ "HTTP requires three digits status code!\n"), status_code); #endif return MHD_NO; } if (200 > status_code) { if (MHD_HTTP_VER_1_0 == connection->rq.http_ver) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Wrong status code (%u) refused. " \ "HTTP/1.0 clients do not support 1xx status codes!\n"), (status_code)); #endif return MHD_NO; } if (0 != (response->flags & (MHD_RF_HTTP_1_0_COMPATIBLE_STRICT | MHD_RF_HTTP_1_0_SERVER))) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Wrong status code (%u) refused. " \ "HTTP/1.0 reply mode does not support 1xx status codes!\n"), (status_code)); #endif return MHD_NO; } } if ( (MHD_HTTP_MTHD_CONNECT == connection->rq.http_mthd) && (2 == status_code / 100) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Successful (%u) response code cannot be used to answer " \ "\"CONNECT\" request!\n"), (status_code)); #endif return MHD_NO; } if ( (0 != (MHD_RF_HEAD_ONLY_RESPONSE & response->flags)) && (RP_BODY_HEADERS_ONLY < is_reply_body_needed (connection, status_code)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("HEAD-only response cannot be used when the request requires " "reply body to be sent!\n")); #endif return MHD_NO; } #ifdef HAVE_MESSAGES if ( (0 != (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) && (0 != (MHD_RAF_HAS_CONTENT_LENGTH & response->flags_auto)) ) { MHD_DLOG (daemon, _ ("The response has application-defined \"Content-Length\" " \ "header. The reply to the request will be not " \ "HTTP-compliant and may result in hung connection or " \ "other problems!\n")); } #endif MHD_increment_response_rc (response); connection->rp.response = response; connection->rp.responseCode = status_code; connection->rp.responseIcy = reply_icy; #if defined(_MHD_HAVE_SENDFILE) if ( (response->fd == -1) || (response->is_pipe) || (0 != (connection->daemon->options & MHD_USE_TLS)) #if defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) && \ defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) || (! daemon->sigpipe_blocked && ! connection->sk_spipe_suppress) #endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED && MHD_SEND_SPIPE_SUPPRESS_POSSIBLE */ ) connection->rp.resp_sender = MHD_resp_sender_std; else connection->rp.resp_sender = MHD_resp_sender_sendfile; #endif /* _MHD_HAVE_SENDFILE */ /* FIXME: if 'is_pipe' is set, TLS is off, and we have *splice*, we could use splice() to avoid two user-space copies... */ if ( (MHD_HTTP_MTHD_HEAD == connection->rq.http_mthd) || (MHD_HTTP_OK > status_code) || (MHD_HTTP_NO_CONTENT == status_code) || (MHD_HTTP_NOT_MODIFIED == status_code) ) { /* if this is a "HEAD" request, or a status code for which a body is not allowed, pretend that we have already sent the full message body. */ /* TODO: remove the next assignment, use 'rp_props.send_reply_body' in * checks */ connection->rp.rsp_write_position = response->total_size; } if (MHD_CONNECTION_HEADERS_PROCESSED == connection->state) { /* response was queued "early", refuse to read body / footers or further requests! */ connection->discard_request = true; connection->state = MHD_CONNECTION_START_REPLY; connection->rq.remaining_upload_size = 0; } if (! connection->in_idle) (void) MHD_connection_handle_idle (connection); MHD_update_last_activity_ (connection); return MHD_YES; } /* end of connection.c */ libmicrohttpd-1.0.10/src/microhttpd/sha256_ext.h0000644000175000017500000000567015035214301015125 /* This file is part of GNU libmicrohttpd Copyright (C) 2022 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/sha256_ext.h * @brief Wrapper declarations for SHA-256 calculation performed by TLS library * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA256_EXT_H #define MHD_SHA256_EXT_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * Size of SHA-256 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define SHA256_DIGEST_SIZE (32) /* Actual declaration is in GnuTLS lib header */ struct hash_hd_st; /** * Indicates that struct Sha256CtxExt has 'ext_error' */ #define MHD_SHA256_HAS_EXT_ERROR 1 /** * SHA-256 calculation context */ struct Sha256CtxExt { struct hash_hd_st *handle; /**< Hash calculation handle */ int ext_error; /**< Non-zero if external error occurs during init or hashing */ }; /** * Indicates that MHD_SHA256_init_one_time() function is present. */ #define MHD_SHA256_HAS_INIT_ONE_TIME 1 /** * Initialise structure for SHA-256 calculation, allocate resources. * * This function must not be called more than one time for @a ctx. * * @param ctx the calculation context */ void MHD_SHA256_init_one_time (struct Sha256CtxExt *ctx); /** * SHA-256 process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA256_update (struct Sha256CtxExt *ctx, const uint8_t *data, size_t length); /** * Indicates that MHD_SHA256_finish_reset() function is available */ #define MHD_SHA256_HAS_FINISH_RESET 1 /** * Finalise SHA-256 calculation, return digest, reset hash calculation. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #SHA256_DIGEST_SIZE bytes */ void MHD_SHA256_finish_reset (struct Sha256CtxExt *ctx, uint8_t digest[SHA256_DIGEST_SIZE]); /** * Indicates that MHD_SHA256_deinit() function is present */ #define MHD_SHA256_HAS_DEINIT 1 /** * Free allocated resources. * * @param ctx the calculation context */ void MHD_SHA256_deinit (struct Sha256CtxExt *ctx); #endif /* MHD_SHA256_EXT_H */ libmicrohttpd-1.0.10/src/microhttpd/response.h0000644000175000017500000001066614760713577015123 /* This file is part of libmicrohttpd Copyright (C) 2007 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file response.h * @brief Methods for managing response objects * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef RESPONSE_H #define RESPONSE_H /** * Increments the reference counter for the @a response. * * @param response object to modify */ void MHD_increment_response_rc (struct MHD_Response *response); /** * We are done sending the header of a given response * to the client. Now it is time to perform the upgrade * and hand over the connection to the application. * @remark To be called only from thread that process connection's * recv(), send() and response. Must be called right after sending * response headers. * * @param response the response that was created for an upgrade * @param connection the specific connection we are upgrading * @return #MHD_YES on success, #MHD_NO on failure (will cause * connection to be closed) */ enum MHD_Result MHD_response_execute_upgrade_ (struct MHD_Response *response, struct MHD_Connection *connection); /** * Get a particular header (or footer) element from the response. * * Function returns the first found element. * @param response response to query * @param kind the kind of element: header or footer * @param key the key which header to get * @param key_len the length of the @a key * @return NULL if header element does not exist * @ingroup response */ struct MHD_HTTP_Res_Header * MHD_get_response_element_n_ (struct MHD_Response *response, enum MHD_ValueKind kind, const char *key, size_t key_len); /** * Add a header or footer line to the response without checking. * * It is assumed that parameters are correct. * * @param response response to add a header to * @param kind header or footer * @param header the header to add, does not need to be zero-terminated * @param header_len the length of the @a header * @param content value to add, does not need to be zero-terminated * @param content_len the length of the @a content * @return false on error (like out-of-memory), * true if succeed */ bool MHD_add_response_entry_no_check_ (struct MHD_Response *response, enum MHD_ValueKind kind, const char *header, size_t header_len, const char *content, size_t content_len); /** * Add preallocated strings a header or footer line to the response without * checking. * * Header/footer strings are not checked and assumed to be correct. * * The string must not be statically allocated! * The strings must be malloc()'ed and zero terminated. The strings will * be free()'ed when the response is destroyed. * * @param response response to add a header to * @param kind header or footer * @param header the header string to add, must be malloc()'ed and * zero-terminated * @param header_len the length of the @a header * @param content the value string to add, must be malloc()'ed and * zero-terminated * @param content_len the length of the @a content */ bool MHD_add_response_entry_no_alloc_ (struct MHD_Response *response, enum MHD_ValueKind kind, char *header, size_t header_len, char *content, size_t content_len); #endif libmicrohttpd-1.0.10/src/microhttpd/test_chunked_ext.c0000664000175000017500000007102415232103064016570 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_chunked_ext.c * @brief Regression test for the handling of the chunk-extension part of * the chunk size line of a chunked request body. * * When a chunk size line carries a chunk-extension (RFC 9112, Section 7.1.1) * the length of that line used to be computed as the position of the CR (or * of the bare LF) instead of the position just after the line delimiter. * As a result the line delimiter was not consumed and became part of the * chunk data, shifting all the following body parsing by two (or one) bytes. * That both corrupts the data given to the application and de-synchronises * the request/response stream, which can be abused for HTTP request * smuggling. * * Every sub-case sends, in a single write, a chunked request using a * chunk-extension immediately followed by a pipelined second request on the * same connection. The test verifies the exact bytes received by the * request handler, that exactly one chunked request was processed and that * the pipelined request was parsed correctly. * * The test honours the daemon option matrix of mhd_opt_matrix.h: when one of * the MHD_TEST_* environment variables selects a profile, its connection * memory limit, threading mode and polling backend are applied to every * daemon this test starts. The *client discipline level* is deliberately * NOT taken from the profile: it is the very thing each sub-case varies (a * bare LF is accepted as the chunk size line delimiter only at level -3), so * the per-sub-case value always wins. Without those environment variables * nothing changes. As the sub-cases need a pool that can still hold the * request and the reply, a profile asking for less than #MIN_POOL_FOR_TEST * bytes is raised to that value and the adjustment is reported. * * @author Christian Grothoff */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifndef WINDOWS #include #endif /* ! WINDOWS */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif /* _WIN32 */ #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #include "mhd_sockets.h" /* only macros used */ #include "mhd_opt_matrix.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" /** * The smallest connection memory pool this test can work with: the sub-cases * send a chunked request plus a pipelined second request and expect two * complete replies, which does not fit into a smaller pool. */ #define MIN_POOL_FOR_TEST 1024 #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #if MHD_VERSION >= 0x00097701 #define TEST_MK_RESPONSE(len,str) \ MHD_create_response_from_buffer_static ((len), (str)) #else /* MHD_VERSION < 0x00097701 */ #define TEST_MK_RESPONSE(len,str) \ MHD_create_response_from_buffer ((len), (void *) (str), \ MHD_RESPMEM_PERSISTENT) #endif /* MHD_VERSION < 0x00097701 */ /** * The exit code for a failed test. */ #define EXIT_FAILED_TEST 1 /** * The exit code for a failure of the test framework itself. */ #define EXIT_HARD_ERROR 99 /** * The maximum time (in seconds) to wait for any single socket operation. */ #define TEST_SOCKET_TIMEOUT_SEC 5 /** * The time (in milliseconds) to wait between the two parts of a request * which is intentionally sent in two writes. */ #define TEST_SPLIT_DELAY_MS 50 /** * The body of the response sent by the test daemon. */ #define RESP_BODY "OK" /** * The URL of the chunked request. */ #define URL_FIRST "/first" /** * The URL of the pipelined request. */ #define URL_SECOND "/second" /** * The head of the chunked request, the chunked body is appended to it. */ #define REQ_FIRST_HEAD \ "POST " URL_FIRST " HTTP/1.1\r\nHost: h\r\n" \ "Transfer-Encoding: chunked\r\n\r\n" /** * The complete pipelined request, appended after the chunked body. */ #define REQ_SECOND \ "GET " URL_SECOND " HTTP/1.1\r\nHost: h\r\nConnection: close\r\n\r\n" /** * The number of the requests that could be tracked. */ #define MAX_TRACKED_REQS 8 /** * The maximum size of the tracked request body. */ #define MAX_TRACKED_BODY 256 /** * The data tracked for a single request. */ struct ReqTrack { /** * The URL of the request. */ char url[64]; /** * The body of the request as given to the request handler. */ char body[MAX_TRACKED_BODY]; /** * The number of bytes in @a body. */ size_t body_size; /** * Non-zero if the body of the request did not fit in @a body. */ int body_overflow; /** * Non-zero if the request has been fully received. */ int completed; }; /** * The tracked requests. * Written by the daemon thread only, read by the main thread only after * MHD_stop_daemon() (which joins the daemon thread) has returned. */ static struct ReqTrack tracked[MAX_TRACKED_REQS]; /** * The number of the used elements in #tracked. */ static unsigned int num_tracked; /** * Be verbose. */ static int verbose; /** * The profile selected by the environment, NULL if the built-in daemon * configuration is used (which is the case for a stock "make check"). */ static const struct MHD_OptMatrixProfile *test_prof; /** * The (possibly adjusted) copy of the profile @a test_prof points to. */ static struct MHD_OptMatrixProfile test_prof_copy; _MHD_NORETURN static void hard_error (const char *desc, int line_num) { fprintf (stderr, "HARD ERROR: %s at line %d. Last errno: %d (%s).\n", desc, line_num, (int) errno, strerror (errno)); fflush (stderr); exit (EXIT_HARD_ERROR); } #define hardErrorExit(desc) hard_error ((desc), __LINE__) /** * Pause the execution for the specified number of milliseconds. * * @param ms the number of the milliseconds to sleep */ static void test_sleep_ms (unsigned int ms) { #if defined(_WIN32) && ! defined(__CYGWIN__) Sleep ((DWORD) ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp; struct timespec rmn; int num_retries = 0; slp.tv_sec = (time_t) (ms / 1000); slp.tv_nsec = (long) ((ms % 1000) * 1000000); while (0 != nanosleep (&slp, &rmn)) { if (EINTR != errno) break; if (8 < num_retries++) break; slp = rmn; } #elif defined(HAVE_USLEEP) usleep (((unsigned long) ms) * 1000); #else /* ! HAVE_NANOSLEEP && ! HAVE_USLEEP */ (void) ms; /* Mute compiler warning, the test works without the delay */ #endif /* ! HAVE_NANOSLEEP && ! HAVE_USLEEP */ } /** * The handler of the requests, tracks the URL and the exact body bytes. */ static enum MHD_Result ahc_track (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct ReqTrack *trk = (struct ReqTrack *) *req_cls; struct MHD_Response *resp; enum MHD_Result ret; (void) cls; (void) method; (void) version; if (NULL == trk) { if (MAX_TRACKED_REQS <= num_tracked) return MHD_NO; /* Too many requests, the check in the main thread fails */ trk = tracked + num_tracked++; memset (trk, 0, sizeof (*trk)); if (sizeof (trk->url) <= strlen (url)) return MHD_NO; memcpy (trk->url, url, strlen (url) + 1); *req_cls = trk; return MHD_YES; } if (0 != *upload_data_size) { if (sizeof (trk->body) < trk->body_size + *upload_data_size) trk->body_overflow = 1; else { memcpy (trk->body + trk->body_size, upload_data, *upload_data_size); trk->body_size += *upload_data_size; } *upload_data_size = 0; return MHD_YES; } trk->completed = 1; resp = TEST_MK_RESPONSE (MHD_STATICSTR_LEN_ (RESP_BODY), RESP_BODY); if (NULL == resp) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_OK, resp); MHD_destroy_response (resp); return ret; } /** * Set send and receive timeouts on the socket so that the test cannot * block indefinitely. * * @param sk the socket to set the timeouts on * @return non-zero if succeed, zero if failed */ static int set_socket_timeouts (MHD_socket sk) { #if defined(MHD_WINSOCK_SOCKETS) DWORD tv = (DWORD) (TEST_SOCKET_TIMEOUT_SEC * 1000); #else /* ! MHD_WINSOCK_SOCKETS */ struct timeval tv; tv.tv_sec = (time_t) TEST_SOCKET_TIMEOUT_SEC; tv.tv_usec = 0; #endif /* ! MHD_WINSOCK_SOCKETS */ if (0 != setsockopt (sk, SOL_SOCKET, SO_RCVTIMEO, (const void *) &tv, (socklen_t) sizeof (tv))) return 0; if (0 != setsockopt (sk, SOL_SOCKET, SO_SNDTIMEO, (const void *) &tv, (socklen_t) sizeof (tv))) return 0; return ! 0; } /** * Open a TCP connection to the given port on the loopback interface. * * @param port the port to connect to * @return the connected socket, MHD_INVALID_SOCKET on failure */ static MHD_socket connect_to_port (uint16_t port) { MHD_socket sk; struct sockaddr_in sa; sk = socket (PF_INET, SOCK_STREAM, 0); if (MHD_INVALID_SOCKET == sk) return MHD_INVALID_SOCKET; if (! set_socket_timeouts (sk)) { (void) MHD_socket_close_ (sk); return MHD_INVALID_SOCKET; } memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != connect (sk, (const struct sockaddr *) &sa, (socklen_t) sizeof (sa))) { (void) MHD_socket_close_ (sk); return MHD_INVALID_SOCKET; } return sk; } /** * Send all the given data over the socket. * * @param sk the socket to use * @param buf the data to send * @param size the size of @a buf * @return non-zero if succeed, zero if failed */ static int send_all (MHD_socket sk, const char *buf, size_t size) { size_t off = 0; while (off < size) { ssize_t res; res = MHD_send_ (sk, buf + off, size - off); if (0 > res) { if (MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) continue; return 0; } if (0 == res) return 0; off += (size_t) res; } return ! 0; } /** * Receive data from the socket until the remote side closes the connection, * the buffer is full or the receive timeout expires. * * @param sk the socket to use * @param[out] buf the buffer to fill * @param buf_size the size of @a buf, the result is always zero-terminated, * therefore at most @a buf_size minus one bytes are received * @return the number of the received bytes */ static size_t recv_all (MHD_socket sk, char *buf, size_t buf_size) { size_t off = 0; while (off + 1 < buf_size) { ssize_t res; res = MHD_recv_ (sk, buf + off, buf_size - 1 - off); if (0 > res) { if (MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) continue; break; /* Timeout or error */ } if (0 == res) break; /* The remote side closed the connection */ off += (size_t) res; } buf[off] = 0; return off; } /** * Count the number of the non-overlapping occurrences of @a needle * in @a haystack. * * @param haystack the zero-terminated string to search in * @param needle the zero-terminated string to search for * @return the number of the found occurrences */ static unsigned int count_substr (const char *haystack, const char *needle) { const size_t needle_len = strlen (needle); unsigned int num = 0; const char *pos = haystack; if (0 == needle_len) return 0; while (NULL != (pos = strstr (pos, needle))) { ++num; pos += needle_len; } return num; } /** * Print the data to the standard error stream, replacing the non-printable * characters with their escaped hexadecimal form. * * @param data the data to print * @param size the size of @a data */ static void print_escaped (const char *data, size_t size) { size_t i; for (i = 0; i < size; ++i) { const unsigned char chr = (unsigned char) data[i]; if ((0x20 <= chr) && (0x7e >= chr) && ('\\' != chr)) fputc ((int) chr, stderr); else if ('\\' == chr) fputs ("\\\\", stderr); else if ('\r' == chr) fputs ("\\r", stderr); else if ('\n' == chr) fputs ("\\n", stderr); else if ('\t' == chr) fputs ("\\t", stderr); else fprintf (stderr, "\\x%02X", (unsigned int) chr); } } /** * The description of a single sub-case. */ struct ChunkCase { /** * The human readable name of the sub-case. */ const char *name; /** * The chunked body of the request, including the terminating chunk and * the (empty) trailer section. */ const char *chunked; /** * The exact bytes that the request handler must receive. */ const char *expected; /** * The number of the bytes in @a expected. */ size_t expected_size; /** * If non-zero, the request is sent in two writes and this is the number of * the bytes of @a chunked included in the first write. */ size_t split_at; /** * The value for MHD_OPTION_CLIENT_DISCIPLINE_LVL. */ int discipline; /** * Non-zero if the sub-case requires the support of the bare LF as the * line delimiter of the chunk size line. */ int need_bare_lf; }; #define CHUNK_CASE(nm,ch,exp,spl,dsc,blf) \ { (nm), (ch), (exp), MHD_STATICSTR_LEN_ (exp), (spl), (dsc), (blf) } /** * The sub-cases. * All of them must be processed identically: the handler must receive * exactly the expected bytes, and the pipelined request must be processed * as the second (and the last) request on the connection. */ static const struct ChunkCase chunkcases[] = { CHUNK_CASE ("no chunk-extension (control)", "5\r\nHELLO\r\n0\r\n\r\n", "HELLO", 0, 0, 0), CHUNK_CASE ("chunk-extension with a value", "5;ext=val\r\nHELLO\r\n0\r\n\r\n", "HELLO", 0, 0, 0), CHUNK_CASE ("chunk-extension without a value", "5;ext\r\nHELLO\r\n0\r\n\r\n", "HELLO", 0, 0, 0), CHUNK_CASE ("chunk-extension after a bad whitespace (space)", "5 ;ext=val\r\nHELLO\r\n0\r\n\r\n", "HELLO", 0, 0, 0), CHUNK_CASE ("chunk-extension after a bad whitespace (tab)", "5\t;ext\r\nHELLO\r\n0\r\n\r\n", "HELLO", 0, 0, 0), CHUNK_CASE ("chunk-extension with a quoted-string value", "5;ext=\"quoted; value\"\r\nHELLO\r\n0\r\n\r\n", "HELLO", 0, 0, 0), CHUNK_CASE ("several chunk-extensions", "5;e1=v1;e2=\"v 2\";e3\r\nHELLO\r\n0\r\n\r\n", "HELLO", 0, 0, 0), CHUNK_CASE ("two chunks, both with a chunk-extension", "3;a=b\r\nabc\r\n4;c=d\r\ndefg\r\n0\r\n\r\n", "abcdefg", 0, 0, 0), CHUNK_CASE ("two chunks, only the first with a chunk-extension", "3;a=b\r\nabc\r\n4\r\ndefg\r\n0\r\n\r\n", "abcdefg", 0, 0, 0), CHUNK_CASE ("two chunks, only the second with a chunk-extension", "3\r\nabc\r\n4;c=d\r\ndefg\r\n0\r\n\r\n", "abcdefg", 0, 0, 0), CHUNK_CASE ("chunk-extension on the terminating chunk as well", "3;a=b\r\nabc\r\n4;c=d\r\ndefg\r\n0;last=1\r\n\r\n", "abcdefg", 0, 0, 0), CHUNK_CASE ("chunk data with an embedded CRLF", "7;ext=val\r\nAB\r\nCDE\r\n0\r\n\r\n", "AB\r\nCDE", 0, 0, 0), CHUNK_CASE ("chunk-extension line split between two writes", "5;ext=val\r\nHELLO\r\n0\r\n\r\n", "HELLO", 4, 0, 0), CHUNK_CASE ("chunk-extension line delimiter split between two writes", "5;ext=val\r\nHELLO\r\n0\r\n\r\n", "HELLO", 10, 0, 0), CHUNK_CASE ("chunk-extension with a bare LF line delimiter", "5;ext=val\nHELLO\r\n0\r\n\r\n", "HELLO", 0, -3, 1), CHUNK_CASE ("two chunks with a bare LF line delimiter", "3;a=b\nabc\r\n4;c=d\ndefg\r\n0\r\n\r\n", "abcdefg", 0, -3, 1) }; /** * The sub-case used to detect whether this build accepts the bare LF as the * line delimiter of the chunk size line. It does not use any * chunk-extension, therefore it is not affected by the tested bug. */ static const struct ChunkCase bare_lf_probe = CHUNK_CASE ("bare LF support probe", "5\nHELLO\r\n0\r\n\r\n", "HELLO", 0, -3, 0); /** * Run a single sub-case. * * @param cc the sub-case to run * @param quiet if non-zero, do not report the failures * @return non-zero if the sub-case succeeded, zero if it failed */ static int run_subcase (const struct ChunkCase *cc, int quiet) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; uint16_t port; MHD_socket sk; char req[1024]; char resp[4096]; size_t req_size; size_t chunked_size; size_t resp_size; int failed = 0; int sent_ok; struct MHD_OptMatrixProfile prof; struct MHD_OptionItem ops[8]; unsigned int flags; chunked_size = strlen (cc->chunked); req_size = MHD_STATICSTR_LEN_ (REQ_FIRST_HEAD) + chunked_size + MHD_STATICSTR_LEN_ (REQ_SECOND); if (sizeof (req) <= req_size) hardErrorExit ("The request does not fit in the buffer"); memcpy (req, REQ_FIRST_HEAD, MHD_STATICSTR_LEN_ (REQ_FIRST_HEAD)); memcpy (req + MHD_STATICSTR_LEN_ (REQ_FIRST_HEAD), cc->chunked, chunked_size); memcpy (req + MHD_STATICSTR_LEN_ (REQ_FIRST_HEAD) + chunked_size, REQ_SECOND, MHD_STATICSTR_LEN_ (REQ_SECOND) + 1); num_tracked = 0; memset (tracked, 0, sizeof (tracked)); /* The profile (if any) supplies the memory limit, the threading mode and the polling backend. The client discipline level always comes from the sub-case, see the file comment. */ if (NULL != test_prof) prof = *test_prof; else { memset (&prof, 0, sizeof (prof)); prof.name = "built-in"; prof.threading = MHD_OPT_MATRIX_THR_INTERNAL; prof.poll_backend = MHD_OPT_MATRIX_POLL_SELECT; } prof.discipline_lvl = 0; prof.use_legacy_strict = 0; if (0 == mhd_opt_matrix_fill_options (&prof, ops, (unsigned int) (sizeof (ops) / sizeof (ops[0])))) hardErrorExit ("The daemon option array is too small"); /* The client of this test is a plain blocking socket client, so external polling is served with an internal polling thread instead. */ flags = mhd_opt_matrix_daemon_flags (&prof, MHD_USE_ERROR_LOG, 0); d = MHD_start_daemon (flags, 0, NULL, NULL, &ahc_track, NULL, MHD_OPTION_ARRAY, ops, MHD_OPTION_CLIENT_DISCIPLINE_LVL, cc->discipline, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) TEST_SOCKET_TIMEOUT_SEC, MHD_OPTION_END); if (NULL == d) hardErrorExit ("Cannot start the test daemon"); dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port)) { MHD_stop_daemon (d); hardErrorExit ("Cannot detect the port used by the test daemon"); } port = (uint16_t) dinfo->port; sk = connect_to_port (port); if (MHD_INVALID_SOCKET == sk) { MHD_stop_daemon (d); hardErrorExit ("Cannot connect to the test daemon"); } if (0 == cc->split_at) sent_ok = send_all (sk, req, req_size); else { const size_t first_part = MHD_STATICSTR_LEN_ (REQ_FIRST_HEAD) + cc->split_at; if (first_part >= req_size) hardErrorExit ("Wrong 'split_at' value in the sub-case"); sent_ok = send_all (sk, req, first_part); if (sent_ok) { test_sleep_ms (TEST_SPLIT_DELAY_MS); sent_ok = send_all (sk, req + first_part, req_size - first_part); } } if (! sent_ok) { if (! quiet) fprintf (stderr, "FAILED: sub-case '%s': cannot send the request.\n", cc->name); (void) MHD_socket_close_ (sk); MHD_stop_daemon (d); return 0; } resp_size = recv_all (sk, resp, sizeof (resp)); (void) MHD_socket_close_ (sk); /* MHD_stop_daemon() joins the daemon thread, therefore all the data tracked by the request handler is safely visible afterwards. */ MHD_stop_daemon (d); if (2 != num_tracked) { if (! quiet) fprintf (stderr, "FAILED: sub-case '%s': the number of the processed requests " "is %u, while exactly 2 requests are expected.\n", cc->name, num_tracked); failed = 1; } if (1 <= num_tracked) { const struct ReqTrack *const trk = tracked + 0; if (0 != strcmp (trk->url, URL_FIRST)) { if (! quiet) fprintf (stderr, "FAILED: sub-case '%s': the URL of the first request is " "'%s', while '%s' is expected.\n", cc->name, trk->url, URL_FIRST); failed = 1; } if (0 != trk->body_overflow) { if (! quiet) fprintf (stderr, "FAILED: sub-case '%s': the body of the first request is " "too large.\n", cc->name); failed = 1; } else if ((cc->expected_size != trk->body_size) || (0 != memcmp (cc->expected, trk->body, cc->expected_size))) { if (! quiet) { fprintf (stderr, "FAILED: sub-case '%s': the body of the first request is '", cc->name); print_escaped (trk->body, trk->body_size); fprintf (stderr, "' (%u bytes), while '", (unsigned) trk->body_size); print_escaped (cc->expected, cc->expected_size); fprintf (stderr, "' (%u bytes) is expected.\n", (unsigned) cc->expected_size); } failed = 1; } if (0 == trk->completed) { if (! quiet) fprintf (stderr, "FAILED: sub-case '%s': the first request has not been " "completed.\n", cc->name); failed = 1; } } if (2 <= num_tracked) { const struct ReqTrack *const trk = tracked + 1; if (0 != strcmp (trk->url, URL_SECOND)) { if (! quiet) fprintf (stderr, "FAILED: sub-case '%s': the URL of the pipelined request is " "'%s', while '%s' is expected. The request stream has been " "de-synchronised.\n", cc->name, trk->url, URL_SECOND); failed = 1; } if ((0 != trk->body_size) || (0 != trk->body_overflow)) { if (! quiet) fprintf (stderr, "FAILED: sub-case '%s': the pipelined request has a body of " "%u bytes, while no body is expected.\n", cc->name, (unsigned) trk->body_size); failed = 1; } if (0 == trk->completed) { if (! quiet) fprintf (stderr, "FAILED: sub-case '%s': the pipelined request has not been " "completed.\n", cc->name); failed = 1; } } if (2 != count_substr (resp, "HTTP/1.1 ")) { if (! quiet) fprintf (stderr, "FAILED: sub-case '%s': the number of the replies is %u, " "while exactly 2 replies are expected. The reply stream is:\n" "%.*s\n", cc->name, count_substr (resp, "HTTP/1.1 "), (int) resp_size, resp); failed = 1; } else if (2 != count_substr (resp, "HTTP/1.1 200 ")) { if (! quiet) fprintf (stderr, "FAILED: sub-case '%s': not all replies have the '200' status " "code. The reply stream is:\n%.*s\n", cc->name, (int) resp_size, resp); failed = 1; } if ((0 == failed) && verbose) printf ("PASSED: %s\n", cc->name); return ! failed; } int main (int argc, char *const *argv) { unsigned int num_failed = 0; unsigned int num_skipped = 0; int bare_lf_supported; size_t i; verbose = 0; for (i = 1; i < (size_t) argc; ++i) { if ((0 == strcmp (argv[i], "-v")) || (0 == strcmp (argv[i], "--verbose"))) verbose = 1; } if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE)) { #if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) hardErrorExit ("Cannot suppress the SIGPIPE signal"); #else /* ! HAVE_SIGNAL_H || ! SIGPIPE */ fprintf (stderr, "Cannot suppress the SIGPIPE signal.\n"); #endif /* ! HAVE_SIGNAL_H || ! SIGPIPE */ } mhd_opt_matrix_print_notice ("test_chunked_ext"); test_prof = mhd_opt_matrix_from_env (); if (NULL != test_prof) { char desc[256]; test_prof_copy = *test_prof; test_prof = &test_prof_copy; if (! mhd_opt_matrix_profile_supported (test_prof)) { printf ("test_chunked_ext: the selected profile %s is not supported by " "this build, the test is skipped.\n", mhd_opt_matrix_describe (test_prof, desc, sizeof (desc))); return 77; } if (mhd_opt_matrix_raise_mem_limit (&test_prof_copy, MIN_POOL_FOR_TEST)) printf ("test_chunked_ext: the connection memory limit of the profile " "was raised to %u, the smallest pool this test can work " "with.\n", (unsigned) MIN_POOL_FOR_TEST); } /* Detect whether the bare LF is accepted as the line delimiter of the chunk size line with the lowest client discipline level. */ bare_lf_supported = run_subcase (&bare_lf_probe, 1); if ((! bare_lf_supported) && verbose) printf ("The bare LF as the chunk size line delimiter is not supported " "by this build, the related sub-cases are skipped.\n"); for (i = 0; i < sizeof (chunkcases) / sizeof (chunkcases[0]); ++i) { const struct ChunkCase *const cc = chunkcases + i; if ((0 != cc->need_bare_lf) && (! bare_lf_supported)) { ++num_skipped; continue; } /* Report the sub-case before running it, so that the failing sub-case can be identified even if the daemon aborts the process. */ fprintf (stderr, "Running sub-case: %s\n", cc->name); fflush (stderr); if (! run_subcase (cc, 0)) ++num_failed; } if (0 != num_failed) { fprintf (stderr, "FAILED: %u sub-case(s) failed.\n", num_failed); return EXIT_FAILED_TEST; } if (verbose) printf ("All sub-cases passed (%u sub-case(s) skipped).\n", num_skipped); return 0; } libmicrohttpd-1.0.10/src/microhttpd/mhd_itc.c0000644000175000017500000000356015035214301014633 /* This file is part of libmicrohttpd Copyright (C) 2016 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_itc.c * @brief Implementation of inter-thread communication functions * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "mhd_itc.h" #ifdef HAVE_UNISTD_H #include #endif /* HAVE_UNISTD_H */ #include #include "internal.h" #if defined(_MHD_ITC_PIPE) #if ! defined(_WIN32) || defined(__CYGWIN__) #ifndef HAVE_PIPE2_FUNC /** * Change itc FD options to be non-blocking. * * @param itc the inter-thread communication primitive to manipulate * @return non-zero if succeeded, zero otherwise */ int MHD_itc_nonblocking_ (struct MHD_itc_ itc) { unsigned int i; for (i = 0; i<2; i++) { int flags; flags = fcntl (itc.fd[i], F_GETFL); if (-1 == flags) return 0; if ( ((flags | O_NONBLOCK) != flags) && (0 != fcntl (itc.fd[i], F_SETFL, flags | O_NONBLOCK)) ) return 0; } return ! 0; } #endif /* ! HAVE_PIPE2_FUNC */ #endif /* !_WIN32 || __CYGWIN__ */ #endif /* _MHD_ITC_EVENTFD || _MHD_ITC_PIPE */ libmicrohttpd-1.0.10/src/microhttpd/test_sha256.c0000664000175000017500000005022215232103064015274 /* This file is part of libmicrohttpd Copyright (C) 2019-2023 Evgeny Grin (Karlson2k) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_sha256.h * @brief Unit tests for SHA-256 functions * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include "mhd_sha256_wrap.h" #include "test_helpers.h" #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #if defined(MHD_SHA256_TLSLIB) && defined(MHD_HTTPS_REQUIRE_GCRYPT) #define NEED_GCRYP_INIT 1 #include #endif /* MHD_SHA256_TLSLIB && MHD_HTTPS_REQUIRE_GCRYPT */ static int verbose = 0; /* verbose level (0-1)*/ struct str_with_len { const char *const str; const size_t len; }; #define D_STR_W_LEN(s) {(s), (sizeof((s)) / sizeof(char)) - 1} struct data_unit1 { const struct str_with_len str_l; const uint8_t digest[SHA256_DIGEST_SIZE]; }; static const struct data_unit1 data_units1[] = { {D_STR_W_LEN ("abc"), {0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad}}, {D_STR_W_LEN ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), {0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1}}, {D_STR_W_LEN (""), {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}}, {D_STR_W_LEN ("1234567890!@~%&$@#{}[]\\/!?`."), {0x2f, 0xad, 0x7a, 0xff, 0x7d, 0xfe, 0xcd, 0x78, 0xe4, 0xa6, 0xf3, 0x85, 0x97, 0x9d, 0xdc, 0x39, 0x55, 0x24, 0x35, 0x4a, 0x00, 0x6f, 0x42, 0x72, 0x41, 0xc1, 0x52, 0xa7, 0x01, 0x0b, 0x2c, 0x41}}, {D_STR_W_LEN ("Simple string."), {0x01, 0x73, 0x17, 0xc4, 0x0a, 0x9a, 0x0e, 0x81, 0xb3, 0xa4, 0xb1, 0x8e, 0xe9, 0xd6, 0xc2, 0xdf, 0xfa, 0x7d, 0x53, 0x4e, 0xa1, 0xda, 0xb2, 0x5a, 0x75, 0xbb, 0x2c, 0x30, 0x2f, 0x5f, 0x7a, 0xf4}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyz"), {0x71, 0xc4, 0x80, 0xdf, 0x93, 0xd6, 0xae, 0x2f, 0x1e, 0xfa, 0xd1, 0x44, 0x7c, 0x66, 0xc9, 0x52, 0x5e, 0x31, 0x62, 0x18, 0xcf, 0x51, 0xfc, 0x8d, 0x9e, 0xd8, 0x32, 0xf2, 0xda, 0xf1, 0x8b, 0x73}}, {D_STR_W_LEN ("zyxwvutsrqponMLKJIHGFEDCBA"), {0xce, 0x7d, 0xde, 0xb6, 0x1f, 0x7c, 0x1d, 0x83, 0x7c, 0x60, 0xd8, 0x36, 0x73, 0x82, 0xac, 0x92, 0xca, 0x37, 0xfd, 0x72, 0x8b, 0x0c, 0xd1, 0x6c, 0x55, 0xd5, 0x88, 0x98, 0x24, 0xfa, 0x16, 0xf2}}, {D_STR_W_LEN ("abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA" \ "abcdefghijklmnopqrstuvwxyzzyxwvutsrqponMLKJIHGFEDCBA"), {0x27, 0xd1, 0xe8, 0xbc, 0x6a, 0x79, 0x16, 0x83, 0x61, 0x73, 0xa9, 0xa8, 0x9b, 0xaf, 0xaf, 0xcf, 0x47, 0x4d, 0x09, 0xef, 0x6d, 0x50, 0x35, 0x12, 0x25, 0x72, 0xd8, 0x68, 0xdc, 0x1f, 0xd2, 0xf4}}, {D_STR_W_LEN ("/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/long/long/long/long/long/long/long" \ "/long/long/long/long/path?with%20some=parameters"), {0x73, 0x85, 0xc5, 0xb9, 0x8f, 0xaf, 0x7d, 0x5e, 0xad, 0xd8, 0x0b, 0x8e, 0x12, 0xdb, 0x28, 0x60, 0xc7, 0xc7, 0x55, 0x05, 0x2f, 0x7c, 0x6f, 0xfa, 0xd1, 0xe3, 0xe1, 0x7b, 0x04, 0xd4, 0xb0, 0x21}} }; static const size_t units1_num = sizeof(data_units1) / sizeof(data_units1[0]); struct bin_with_len { const uint8_t bin[512]; const size_t len; }; struct data_unit2 { const struct bin_with_len bin_l; const uint8_t digest[SHA256_DIGEST_SIZE]; }; /* Size must be less than 512 bytes! */ static const struct data_unit2 data_units2[] = { { { {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}, 26}, /* a..z ASCII sequence */ {0x71, 0xc4, 0x80, 0xdf, 0x93, 0xd6, 0xae, 0x2f, 0x1e, 0xfa, 0xd1, 0x44, 0x7c, 0x66, 0xc9, 0x52, 0x5e, 0x31, 0x62, 0x18, 0xcf, 0x51, 0xfc, 0x8d, 0x9e, 0xd8, 0x32, 0xf2, 0xda, 0xf1, 0x8b, 0x73}}, { { {65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65}, 72 },/* 'A' x 72 times */ {0x6a, 0x6d, 0x69, 0x1a, 0xc9, 0xba, 0x70, 0x95, 0x50, 0x46, 0x75, 0x7c, 0xd6, 0x85, 0xb6, 0x25, 0x77, 0x73, 0xff, 0x3a, 0xd9, 0x3f, 0x43, 0xd4, 0xd4, 0x81, 0x2c, 0x5b, 0x10, 0x6f, 0x4b, 0x5b}}, { { {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73}, 55}, /* 19..73 sequence */ {0x06, 0xe4, 0xb3, 0x9e, 0xf1, 0xfb, 0x6c, 0xcf, 0xd7, 0x3f, 0x50, 0x9e, 0xf4, 0x16, 0x17, 0xd4, 0x63, 0x7c, 0x39, 0x1e, 0xa8, 0x0f, 0xa9, 0x88, 0x03, 0x44, 0x98, 0x0e, 0x95, 0x81, 0xf0, 0x2a}}, { { {7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69}, 63}, /* 7..69 sequence */ {0x4a, 0xd3, 0xc6, 0x87, 0x1f, 0xd1, 0xc5, 0xe2, 0x3e, 0x52, 0xdc, 0x22, 0xd1, 0x10, 0xd2, 0x05, 0x15, 0x23, 0xcd, 0x15, 0xac, 0x24, 0x88, 0x26, 0x02, 0x00, 0x70, 0x78, 0x9f, 0x17, 0xf8, 0xd9}}, { { {38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92}, 55}, /* 38..92 sequence */ {0xe6, 0x03, 0x0f, 0xc9, 0x0d, 0xca, 0x0c, 0x26, 0x41, 0xcf, 0x43, 0x27, 0xec, 0xd6, 0x28, 0x2a, 0x98, 0x24, 0x55, 0xd3, 0x5a, 0xed, 0x8b, 0x32, 0x19, 0x78, 0xeb, 0x83, 0x1d, 0x19, 0x92, 0x79}}, { { {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72}, 72},/* 1..72 sequence */ {0x87, 0xa2, 0xfa, 0x2e, 0xec, 0x53, 0x05, 0x3c, 0xb1, 0xee, 0x07, 0xd7, 0x59, 0x70, 0xf6, 0x50, 0xcd, 0x9d, 0xc5, 0x8b, 0xdc, 0xb8, 0x65, 0x30, 0x4f, 0x70, 0x82, 0x9e, 0xbd, 0xe2, 0x7d, 0xac}}, { { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255}, 256}, /* 0..255 sequence */ {0x40, 0xaf, 0xf2, 0xe9, 0xd2, 0xd8, 0x92, 0x2e, 0x47, 0xaf, 0xd4, 0x64, 0x8e, 0x69, 0x67, 0x49, 0x71, 0x58, 0x78, 0x5f, 0xbd, 0x1d, 0xa8, 0x70, 0xe7, 0x11, 0x02, 0x66, 0xbf, 0x94, 0x48, 0x80}}, { { {199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139}, 61}, /* 199..139 sequence */ {0x85, 0xf8, 0xa2, 0x83, 0xd6, 0x3c, 0x76, 0x8e, 0xea, 0x8f, 0x1c, 0x57, 0x2d, 0x85, 0xb6, 0xff, 0xd8, 0x33, 0x57, 0x62, 0x1d, 0x37, 0xae, 0x0e, 0xfc, 0x22, 0xd3, 0xd5, 0x8f, 0x53, 0x21, 0xb7}}, { { {255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, 223, 222, 221, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, 207, 206, 205, 204, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, 111, 110, 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, 255}, /* 255..1 sequence */ {0x61, 0x86, 0x96, 0xab, 0x3e, 0xaa, 0x0e, 0x64, 0xb2, 0xf7, 0x2d, 0x75, 0x47, 0x5a, 0x14, 0x97, 0xa3, 0x3d, 0x59, 0xa4, 0x08, 0xd9, 0x9e, 0x73, 0xf2, 0x78, 0x00, 0x5b, 0x4b, 0x55, 0xca, 0x43}}, { { {41, 35, 190, 132, 225, 108, 214, 174, 82, 144, 73, 241, 241, 187, 233, 235, 179, 166, 219, 60, 135, 12, 62, 153, 36, 94, 13, 28, 6, 183, 71, 222, 179, 18, 77, 200, 67, 187, 139, 166, 31, 3, 90, 125, 9, 56, 37, 31, 93, 212, 203, 252, 150, 245, 69, 59, 19, 13, 137, 10, 28, 219, 174, 50, 32, 154, 80, 238, 64, 120, 54, 253, 18, 73, 50, 246, 158, 125, 73, 220, 173, 79, 20, 242, 68, 64, 102, 208, 107, 196, 48, 183, 50, 59, 161, 34, 246, 34, 145, 157, 225, 139, 31, 218, 176, 202, 153, 2, 185, 114, 157, 73, 44, 128, 126, 197, 153, 213, 233, 128, 178, 234, 201, 204, 83, 191, 103, 214, 191, 20, 214, 126, 45, 220, 142, 102, 131, 239, 87, 73, 97, 255, 105, 143, 97, 205, 209, 30, 157, 156, 22, 114, 114, 230, 29, 240, 132, 79, 74, 119, 2, 215, 232, 57, 44, 83, 203, 201, 18, 30, 51, 116, 158, 12, 244, 213, 212, 159, 212, 164, 89, 126, 53, 207, 50, 34, 244, 204, 207, 211, 144, 45, 72, 211, 143, 117, 230, 217, 29, 42, 229, 192, 247, 43, 120, 129, 135, 68, 14, 95, 80, 0, 212, 97, 141, 190, 123, 5, 21, 7, 59, 51, 130, 31, 24, 112, 146, 218, 100, 84, 206, 177, 133, 62, 105, 21, 248, 70, 106, 4, 150, 115, 14, 217, 22, 47, 103, 104, 212, 247, 74, 74, 208, 87, 104}, 255}, /* pseudo-random data */ {0x08, 0x7f, 0x86, 0xac, 0xe2, 0x2e, 0x28, 0x56, 0x74, 0x53, 0x4f, 0xc0, 0xfb, 0xb8, 0x79, 0x57, 0xc5, 0xc8, 0xd1, 0xb7, 0x47, 0xb7, 0xd9, 0xea, 0x97, 0xa8, 0x67, 0xe9, 0x26, 0x93, 0xee, 0xa3}} }; static const size_t units2_num = sizeof(data_units2) / sizeof(data_units2[0]); /* * Helper functions */ /** * Print bin as hex * * @param bin binary data * @param len number of bytes in bin * @param hex pointer to len*2+1 bytes buffer */ static void bin2hex (const uint8_t *bin, size_t len, char *hex) { while (len-- > 0) { unsigned int b1, b2; b1 = (*bin >> 4) & 0xf; *hex++ = (char) ((b1 > 9) ? (b1 + 'A' - 10) : (b1 + '0')); b2 = *bin++ & 0xf; *hex++ = (char) ((b2 > 9) ? (b2 + 'A' - 10) : (b2 + '0')); } *hex = 0; } static int check_result (const char *test_name, unsigned int check_num, const uint8_t calculated[SHA256_DIGEST_SIZE], const uint8_t expected[SHA256_DIGEST_SIZE]) { int failed = memcmp (calculated, expected, SHA256_DIGEST_SIZE); check_num++; /* Print 1-based numbers */ if (failed) { char calc_str[SHA256_DIGEST_STRING_SIZE]; char expc_str[SHA256_DIGEST_STRING_SIZE]; bin2hex (calculated, SHA256_DIGEST_SIZE, calc_str); bin2hex (expected, SHA256_DIGEST_SIZE, expc_str); fprintf (stderr, "FAILED: %s check %u: calculated digest %s, expected digest %s.\n", test_name, check_num, calc_str, expc_str); fflush (stderr); } else if (verbose) { char calc_str[SHA256_DIGEST_STRING_SIZE]; bin2hex (calculated, SHA256_DIGEST_SIZE, calc_str); printf ("PASSED: %s check %u: calculated digest %s " "matches expected digest.\n", test_name, check_num, calc_str); fflush (stdout); } return failed ? 1 : 0; } /* * Tests */ /* Calculated SHA-256 as one pass for whole data */ static int test1_str (void) { int num_failed = 0; unsigned int i; struct Sha256CtxWr ctx; MHD_SHA256_init_one_time (&ctx); for (i = 0; i < units1_num; i++) { uint8_t digest[SHA256_DIGEST_SIZE]; MHD_SHA256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, data_units1[i].str_l.len); MHD_SHA256_finish_reset (&ctx, digest); #ifdef MHD_SHA256_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif /* MHD_SHA256_HAS_EXT_ERROR */ num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } MHD_SHA256_deinit (&ctx); return num_failed; } static int test1_bin (void) { int num_failed = 0; unsigned int i; struct Sha256CtxWr ctx; MHD_SHA256_init_one_time (&ctx); for (i = 0; i < units2_num; i++) { uint8_t digest[SHA256_DIGEST_SIZE]; MHD_SHA256_update (&ctx, data_units2[i].bin_l.bin, data_units2[i].bin_l.len); MHD_SHA256_finish_reset (&ctx, digest); #ifdef MHD_SHA256_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif /* MHD_SHA256_HAS_EXT_ERROR */ num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } MHD_SHA256_deinit (&ctx); return num_failed; } /* Calculated SHA-256 as two iterations for whole data */ static int test2_str (void) { int num_failed = 0; unsigned int i; struct Sha256CtxWr ctx; MHD_SHA256_init_one_time (&ctx); for (i = 0; i < units1_num; i++) { uint8_t digest[SHA256_DIGEST_SIZE]; size_t part_s = data_units1[i].str_l.len / 4; MHD_SHA256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str, part_s); MHD_SHA256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA256_update (&ctx, (const uint8_t *) data_units1[i].str_l.str + part_s, data_units1[i].str_l.len - part_s); MHD_SHA256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA256_finish_reset (&ctx, digest); #ifdef MHD_SHA256_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif /* MHD_SHA256_HAS_EXT_ERROR */ num_failed += check_result (MHD_FUNC_, i, digest, data_units1[i].digest); } MHD_SHA256_deinit (&ctx); return num_failed; } static int test2_bin (void) { int num_failed = 0; unsigned int i; struct Sha256CtxWr ctx; MHD_SHA256_init_one_time (&ctx); for (i = 0; i < units2_num; i++) { uint8_t digest[SHA256_DIGEST_SIZE]; size_t part_s = data_units2[i].bin_l.len * 2 / 3; MHD_SHA256_update (&ctx, data_units2[i].bin_l.bin, part_s); MHD_SHA256_update (&ctx, (const uint8_t *) "", 0); MHD_SHA256_update (&ctx, data_units2[i].bin_l.bin + part_s, data_units2[i].bin_l.len - part_s); MHD_SHA256_finish_reset (&ctx, digest); #ifdef MHD_SHA256_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif /* MHD_SHA256_HAS_EXT_ERROR */ num_failed += check_result (MHD_FUNC_, i, digest, data_units2[i].digest); } MHD_SHA256_deinit (&ctx); return num_failed; } /* Use data set number 7 as it has the longest sequence */ #define DATA_POS 6 #define MAX_OFFSET 31 static int test_unaligned (void) { int num_failed = 0; unsigned int offset; uint8_t *buf; uint8_t *digest_buf; struct Sha256CtxWr ctx; const struct data_unit2 *const tdata = data_units2 + DATA_POS; MHD_SHA256_init_one_time (&ctx); buf = malloc (tdata->bin_l.len + MAX_OFFSET); digest_buf = malloc (SHA256_DIGEST_SIZE + MAX_OFFSET); if ((NULL == buf) || (NULL == digest_buf)) exit (99); for (offset = MAX_OFFSET; offset >= 1; --offset) { uint8_t *unaligned_digest; uint8_t *unaligned_buf; unaligned_buf = buf + offset; memcpy (unaligned_buf, tdata->bin_l.bin, tdata->bin_l.len); unaligned_digest = digest_buf + MAX_OFFSET - offset; memset (unaligned_digest, 0, SHA256_DIGEST_SIZE); MHD_SHA256_update (&ctx, unaligned_buf, tdata->bin_l.len); MHD_SHA256_finish_reset (&ctx, unaligned_digest); #ifdef MHD_SHA256_HAS_EXT_ERROR if (0 != ctx.ext_error) { fprintf (stderr, "External hashing error: %d.\n", ctx.ext_error); exit (99); } #endif /* MHD_SHA256_HAS_EXT_ERROR */ num_failed += check_result (MHD_FUNC_, MAX_OFFSET - offset, unaligned_digest, tdata->digest); } free (digest_buf); free (buf); MHD_SHA256_deinit (&ctx); return num_failed; } int main (int argc, char *argv[]) { int num_failed = 0; (void) has_in_name; /* Mute compiler warning. */ if (has_param (argc, argv, "-v") || has_param (argc, argv, "--verbose")) verbose = 1; #ifdef NEED_GCRYP_INIT gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); #ifdef GCRYCTL_INITIALIZATION_FINISHED gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif /* GCRYCTL_INITIALIZATION_FINISHED */ #endif /* NEED_GCRYP_INIT */ num_failed += test1_str (); num_failed += test1_bin (); num_failed += test2_str (); num_failed += test2_bin (); num_failed += test_unaligned (); return num_failed ? 1 : 0; } libmicrohttpd-1.0.10/src/microhttpd/md5_ext.h0000644000175000017500000000552215035214301014576 /* This file is part of GNU libmicrohttpd Copyright (C) 2022-2024 Evgeny Grin (Karlson2k) GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with GNU libmicrohttpd. If not, see . */ /** * @file microhttpd/md5_ext.h * @brief Wrapper declarations for MD5 calculation performed by TLS library * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_MD5_EXT_H #define MHD_MD5_EXT_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * Size of MD5 resulting digest in bytes * This is the final digest size, not intermediate hash. */ #define MD5_DIGEST_SIZE (16) /* Actual declaration is in GnuTLS lib header */ struct hash_hd_st; /** * Indicates that struct Md5CtxExt has 'ext_error' */ #define MHD_MD5_HAS_EXT_ERROR 1 /** * MD5 calculation context */ struct Md5CtxExt { struct hash_hd_st *handle; /**< Hash calculation handle */ int ext_error; /**< Non-zero if external error occurs during init or hashing */ }; /** * Indicates that MHD_MD5_init_one_time() function is present. */ #define MHD_MD5_HAS_INIT_ONE_TIME 1 /** * Initialise structure for MD5 calculation, allocate resources. * * This function must not be called more than one time for @a ctx. * * @param ctx the calculation context */ void MHD_MD5_init_one_time (struct Md5CtxExt *ctx); /** * MD5 process portion of bytes. * * @param ctx the calculation context * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_MD5_update (struct Md5CtxExt *ctx, const uint8_t *data, size_t length); /** * Indicates that MHD_MD5_finish_reset() function is available */ #define MHD_MD5_HAS_FINISH_RESET 1 /** * Finalise MD5 calculation, return digest, reset hash calculation. * * @param ctx the calculation context * @param[out] digest set to the hash, must be #MD5_DIGEST_SIZE bytes */ void MHD_MD5_finish_reset (struct Md5CtxExt *ctx, uint8_t digest[MD5_DIGEST_SIZE]); /** * Indicates that MHD_MD5_deinit() function is present */ #define MHD_MD5_HAS_DEINIT 1 /** * Free allocated resources. * * @param ctx the calculation context */ void MHD_MD5_deinit (struct Md5CtxExt *ctx); #endif /* MHD_MD5_EXT_H */ libmicrohttpd-1.0.10/src/microhttpd/internal.h0000664000175000017500000023044715235436227015074 /* This file is part of libmicrohttpd Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff Copyright (C) 2014-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/internal.h * @brief MHD internal shared structures * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef INTERNAL_H #define INTERNAL_H #include "mhd_options.h" #include "platform.h" #include "microhttpd.h" #include "mhd_assert.h" #ifdef HTTPS_SUPPORT #include #if GNUTLS_VERSION_MAJOR >= 3 #include #endif #endif /* HTTPS_SUPPORT */ #ifdef HAVE_STDBOOL_H #include #endif #ifdef HAVE_INTTYPES_H #include #endif /* HAVE_INTTYPES_H */ #ifndef PRIu64 #define PRIu64 "llu" #endif /* ! PRIu64 */ /* Must be included before other internal headers! */ #include "mhd_panic.h" #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) #include "mhd_threads.h" #endif #include "mhd_locks.h" #include "mhd_sockets.h" #include "mhd_itc_types.h" #include "mhd_str_types.h" #if defined(BAUTH_SUPPORT) || defined(DAUTH_SUPPORT) #include "gen_auth.h" #endif /* BAUTH_SUPPORT || DAUTH_SUPPORT*/ /** * Macro to drop 'const' qualifier from pointer without compiler warning. * To be used *only* to deal with broken external APIs, which require non-const * pointer to unmodifiable data. * Must not be used to transform pointers for MHD needs. */ #define _MHD_DROP_CONST(ptr) ((void *) ((uintptr_t) ((const void *) (ptr)))) /** * @def _MHD_MACRO_NO * "Negative answer"/"false" for use in macros, meaningful for precompiler */ #define _MHD_MACRO_NO 0 /** * @def _MHD_MACRO_YES * "Positive answer"/"true" for use in macros, meaningful for precompiler */ #define _MHD_MACRO_YES 1 /** * Close FD and abort execution if error is detected. * @param fd the FD to close */ #define MHD_fd_close_chk_(fd) do { \ if ( (0 != close ((fd)) && (EBADF == errno)) ) { \ MHD_PANIC (_ ("Failed to close FD.\n")); \ } \ } while (0) /* #define EXTRA_CHECKS _MHD_MACRO_NO * Not used. Behaviour is controlled by _DEBUG/NDEBUG macros. */ #ifndef _MHD_DEBUG_CONNECT /** * Print extra messages when establishing * connections? (only adds non-error messages). */ #define _MHD_DEBUG_CONNECT _MHD_MACRO_NO #endif /* ! _MHD_DEBUG_CONNECT */ #ifndef _MHD_DEBUG_SEND_DATA /** * Should all data send be printed to stderr? */ #define _MHD_DEBUG_SEND_DATA _MHD_MACRO_NO #endif /* ! _MHD_DEBUG_SEND_DATA */ #ifndef _MHD_DEBUG_CLOSE /** * Add extra debug messages with reasons for closing connections * (non-error reasons). */ #define _MHD_DEBUG_CLOSE _MHD_MACRO_NO #endif /* ! _MHD_DEBUG_CLOSE */ #define MHD_MAX(a,b) (((a)<(b)) ? (b) : (a)) #define MHD_MIN(a,b) (((a)<(b)) ? (a) : (b)) /** * Minimum reasonable size by which MHD tries to increment read/write buffers. * We usually begin with half the available pool space for the * IO-buffer, but if absolutely needed we additively grow by the * number of bytes given here (up to -- theoretically -- the full pool * space). * * Currently set to reasonable maximum MSS size. */ #define MHD_BUF_INC_SIZE 1500 #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /** * Tri-state on/off/unknown */ enum MHD_tristate { _MHD_UNKNOWN = -1, /**< State is not yet checked nor set */ _MHD_OFF = false, /**< State is "off" / "disabled" */ _MHD_NO = false, /**< State is "off" / "disabled" */ _MHD_ON = true, /**< State is "on" / "enabled" */ _MHD_YES = true /**< State is "on" / "enabled" */ } _MHD_FIXED_ENUM; /** * State of the socket with respect to epoll (bitmask). */ enum MHD_EpollState { /** * The socket is not involved with a defined state in epoll() right * now. */ MHD_EPOLL_STATE_UNREADY = 0, /** * epoll() told us that data was ready for reading, and we did * not consume all of it yet. */ MHD_EPOLL_STATE_READ_READY = 1, /** * epoll() told us that space was available for writing, and we did * not consume all of it yet. */ MHD_EPOLL_STATE_WRITE_READY = 2, /** * Is this connection currently in the 'eready' EDLL? */ MHD_EPOLL_STATE_IN_EREADY_EDLL = 4, /** * Is this connection currently in the epoll() set? */ MHD_EPOLL_STATE_IN_EPOLL_SET = 8, /** * Is this connection currently suspended? */ MHD_EPOLL_STATE_SUSPENDED = 16, /** * Is this connection in some error state? */ MHD_EPOLL_STATE_ERROR = 128 } _MHD_FIXED_FLAGS_ENUM; /** * What is this connection waiting for? */ enum MHD_ConnectionEventLoopInfo { /** * We are waiting to be able to read. */ MHD_EVENT_LOOP_INFO_READ = 1 << 0, /** * We are waiting to be able to write. */ MHD_EVENT_LOOP_INFO_WRITE = 1 << 1, /** * We are waiting for the application to provide data. */ MHD_EVENT_LOOP_INFO_PROCESS = 1 << 2, /** * Some data is ready to be processed, but more data could * be read. */ MHD_EVENT_LOOP_INFO_PROCESS_READ = MHD_EVENT_LOOP_INFO_READ | MHD_EVENT_LOOP_INFO_PROCESS, /** * We are finished and are awaiting cleanup. */ MHD_EVENT_LOOP_INFO_CLEANUP = 1 << 3 } _MHD_FIXED_ENUM; /** * Additional test value for enum MHD_FLAG to check only for MHD_ALLOW_SUSPEND_RESUME and * NOT for MHD_USE_ITC. */ #define MHD_TEST_ALLOW_SUSPEND_RESUME 8192 /** * Maximum length of a nonce in digest authentication. 64(SHA-256 Hex) + * 12(Timestamp Hex) + 1(NULL); hence 77 should suffice, but Opera * (already) takes more (see Mantis #1633), so we've increased the * value to support something longer... */ #define MAX_CLIENT_NONCE_LENGTH 129 /** * The maximum size of MHD-generated nonce when printed with hexadecimal chars. * * This is equal to "(32 bytes for SHA-256 (or SHA-512/256) nonce plus 6 bytes * for timestamp) multiplied by two hex chars per byte". * Please keep it in sync with digestauth.c */ #if defined(MHD_SHA256_SUPPORT) || defined(MHD_SHA512_256_SUPPORT) #define MAX_DIGEST_NONCE_LENGTH ((32 + 6) * 2) #else /* !MHD_SHA256_SUPPORT && !MHD_SHA512_256_SUPPORT */ #define MAX_DIGEST_NONCE_LENGTH ((16 + 6) * 2) #endif /* !MHD_SHA256_SUPPORT && !MHD_SHA512_256_SUPPORT */ /** * A structure representing the internal holder of the * nonce-nc map. */ struct MHD_NonceNc { /** * Nonce counter, a value that increases for each subsequent * request for the same nonce. Matches the largest last received * 'nc' value. * This 'nc' value was already used by the client. */ uint32_t nc; /** * Bitmask over the previous 64 nonce counter values (down to to nc-64). * Used to allow out-of-order 'nc'. * If bit in the bitmask is set to one, then this 'nc' value was already used * by the client. */ uint64_t nmask; /** * Nonce value */ char nonce[MAX_DIGEST_NONCE_LENGTH + 1]; }; #ifdef HAVE_MESSAGES /** * fprintf()-like helper function for logging debug * messages. */ void MHD_DLOG (const struct MHD_Daemon *daemon, const char *format, ...); #endif /** * Header or footer for HTTP response. */ struct MHD_HTTP_Res_Header { /** * Headers are kept in a double-linked list. */ struct MHD_HTTP_Res_Header *next; /** * Headers are kept in a double-linked list. */ struct MHD_HTTP_Res_Header *prev; /** * The name of the header (key), without the colon. */ char *header; /** * The length of the @a header, not including the final zero termination. */ size_t header_size; /** * The value of the header. */ char *value; /** * The length of the @a value, not including the final zero termination. */ size_t value_size; /** * Type of the value. */ enum MHD_ValueKind kind; }; /** * Header, footer, or cookie for HTTP request. */ struct MHD_HTTP_Req_Header { /** * Headers are kept in a double-linked list. */ struct MHD_HTTP_Req_Header *next; /** * Headers are kept in a double-linked list. */ struct MHD_HTTP_Req_Header *prev; /** * The name of the header (key), without the colon. */ const char *header; /** * The length of the @a header, not including the final zero termination. */ size_t header_size; /** * The value of the header. */ const char *value; /** * The length of the @a value, not including the final zero termination. */ size_t value_size; /** * Type of the value. */ enum MHD_ValueKind kind; }; /** * Automatically assigned flags */ enum MHD_ResponseAutoFlags { MHD_RAF_NO_FLAGS = 0, /**< No auto flags */ MHD_RAF_HAS_CONNECTION_HDR = 1 << 0, /**< Has "Connection" header */ MHD_RAF_HAS_CONNECTION_CLOSE = 1 << 1, /**< Has "Connection: close" */ MHD_RAF_HAS_TRANS_ENC_CHUNKED = 1 << 2, /**< Has "Transfer-Encoding: chunked" */ MHD_RAF_HAS_CONTENT_LENGTH = 1 << 3, /**< Has "Content-Length" header */ MHD_RAF_HAS_DATE_HDR = 1 << 4 /**< Has "Date" header */ } _MHD_FIXED_FLAGS_ENUM; #if defined(MHD_WINSOCK_SOCKETS) /** * Internally used I/O vector type for use with winsock. * Binary matches system "WSABUF". */ typedef struct _MHD_W32_iovec { unsigned long iov_len; char *iov_base; } MHD_iovec_; #define MHD_IOV_ELMN_MAX_SIZE ULONG_MAX typedef unsigned long MHD_iov_size_; #elif defined(HAVE_SENDMSG) || defined(HAVE_WRITEV) /** * Internally used I/O vector type for use when writev or sendmsg * is available. Matches system "struct iovec". */ typedef struct iovec MHD_iovec_; #define MHD_IOV_ELMN_MAX_SIZE SIZE_MAX typedef size_t MHD_iov_size_; #else /** * Internally used I/O vector type for use when writev or sendmsg * is not available. */ typedef struct MHD_IoVec MHD_iovec_; #define MHD_IOV_ELMN_MAX_SIZE SIZE_MAX typedef size_t MHD_iov_size_; #endif struct MHD_iovec_track_ { /** * The copy of array of iovec elements. * The copy of elements are updated during sending. * The number of elements is not changed during lifetime. */ MHD_iovec_ *iov; /** * The number of elements in @a iov. * This value is not changed during lifetime. */ size_t cnt; /** * The number of sent elements. * At the same time, it is the index of the next (or current) element * to send. */ size_t sent; }; /** * Representation of a response. */ struct MHD_Response { /** * Head of double-linked list of headers to send for the response. */ struct MHD_HTTP_Res_Header *first_header; /** * Tail of double-linked list of headers to send for the response. */ struct MHD_HTTP_Res_Header *last_header; /** * Buffer pointing to data that we are supposed * to send as a response. */ const char *data; /** * Closure to give to the content reader @e crc * and content reader free callback @e crfc. */ void *crc_cls; /** * How do we get more data? NULL if we are * given all of the data up front. */ MHD_ContentReaderCallback crc; /** * NULL if data must not be freed, otherwise * either user-specified callback or "&free". */ MHD_ContentReaderFreeCallback crfc; #ifdef UPGRADE_SUPPORT /** * Application function to call once we are done sending the headers * of the response; NULL unless this is a response created with * #MHD_create_response_for_upgrade(). */ MHD_UpgradeHandler upgrade_handler; /** * Closure for @e uh. */ void *upgrade_handler_cls; #endif /* UPGRADE_SUPPORT */ #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Mutex to synchronize access to @e data, @e size and * @e reference_count. */ MHD_mutex_ mutex; #endif /** * The size of the response body. * Set to #MHD_SIZE_UNKNOWN if size is not known. */ uint64_t total_size; /** * At what offset in the stream is the * beginning of @e data located? */ uint64_t data_start; /** * Offset to start reading from when using @e fd. */ uint64_t fd_off; /** * Number of bytes ready in @e data (buffer may be larger * than what is filled with payload). */ size_t data_size; /** * Size of the writable data buffer @e data. */ size_t data_buffer_size; /** * Reference count for this response. Free once the counter hits * zero. */ unsigned int reference_count; /** * File-descriptor if this response is FD-backed. */ int fd; /** * Flags set for the MHD response. */ enum MHD_ResponseFlags flags; /** * Automatic flags set for the MHD response. */ enum MHD_ResponseAutoFlags flags_auto; /** * If the @e fd is a pipe (no sendfile()). */ bool is_pipe; /** * I/O vector used with MHD_create_response_from_iovec. */ MHD_iovec_ *data_iov; /** * Number of elements in data_iov. */ unsigned int data_iovcnt; }; /** * States in a state machine for a connection. * * The main transitions are any-state to #MHD_CONNECTION_CLOSED, any * state to state+1, #MHD_CONNECTION_FOOTERS_SENT to * #MHD_CONNECTION_INIT. #MHD_CONNECTION_CLOSED is the terminal state * and #MHD_CONNECTION_INIT the initial state. * * Note that transitions for *reading* happen only after the input has * been processed; transitions for *writing* happen after the * respective data has been put into the write buffer (the write does * not have to be completed yet). A transition to * #MHD_CONNECTION_CLOSED or #MHD_CONNECTION_INIT requires the write * to be complete. */ enum MHD_CONNECTION_STATE { /** * Connection just started (no headers received). * Waiting for the line with the request type, URL and version. */ MHD_CONNECTION_INIT = 0, /** * Part of the request line was received. * Wait for complete line. */ MHD_CONNECTION_REQ_LINE_RECEIVING = MHD_CONNECTION_INIT + 1, /** * We got the URL (and request type and version). Wait for a header line. * * A milestone state. No received data is processed in this state. */ MHD_CONNECTION_REQ_LINE_RECEIVED = MHD_CONNECTION_REQ_LINE_RECEIVING + 1, /** * Receiving request headers. Wait for the rest of the headers. */ MHD_CONNECTION_REQ_HEADERS_RECEIVING = MHD_CONNECTION_REQ_LINE_RECEIVED + 1, /** * We got the request headers. Process them. */ MHD_CONNECTION_HEADERS_RECEIVED = MHD_CONNECTION_REQ_HEADERS_RECEIVING + 1, /** * We have processed the request headers. Call application callback. */ MHD_CONNECTION_HEADERS_PROCESSED = MHD_CONNECTION_HEADERS_RECEIVED + 1, /** * We have processed the headers and need to send 100 CONTINUE. */ MHD_CONNECTION_CONTINUE_SENDING = MHD_CONNECTION_HEADERS_PROCESSED + 1, /** * We have sent 100 CONTINUE (or do not need to). Read the message body. */ MHD_CONNECTION_BODY_RECEIVING = MHD_CONNECTION_CONTINUE_SENDING + 1, /** * We got the request body. * * A milestone state. No received data is processed in this state. */ MHD_CONNECTION_BODY_RECEIVED = MHD_CONNECTION_BODY_RECEIVING + 1, /** * We are reading the request footers. */ MHD_CONNECTION_FOOTERS_RECEIVING = MHD_CONNECTION_BODY_RECEIVED + 1, /** * We received the entire footer. * * A milestone state. No received data is processed in this state. */ MHD_CONNECTION_FOOTERS_RECEIVED = MHD_CONNECTION_FOOTERS_RECEIVING + 1, /** * We received the entire request. * Wait for a response to be queued. */ MHD_CONNECTION_FULL_REQ_RECEIVED = MHD_CONNECTION_FOOTERS_RECEIVED + 1, /** * Finished reading of the request and the response is ready. * Switch internal logic from receiving to sending, prepare connection * sending the reply and build the reply header. */ MHD_CONNECTION_START_REPLY = MHD_CONNECTION_FULL_REQ_RECEIVED + 1, /** * We have prepared the response headers in the write buffer. * Send the response headers. */ MHD_CONNECTION_HEADERS_SENDING = MHD_CONNECTION_START_REPLY + 1, /** * We have sent the response headers. Get ready to send the body. */ MHD_CONNECTION_HEADERS_SENT = MHD_CONNECTION_HEADERS_SENDING + 1, /** * We are waiting for the client to provide more * data of a non-chunked body. */ MHD_CONNECTION_NORMAL_BODY_UNREADY = MHD_CONNECTION_HEADERS_SENT + 1, /** * We are ready to send a part of a non-chunked body. Send it. */ MHD_CONNECTION_NORMAL_BODY_READY = MHD_CONNECTION_NORMAL_BODY_UNREADY + 1, /** * We are waiting for the client to provide a chunk of the body. */ MHD_CONNECTION_CHUNKED_BODY_UNREADY = MHD_CONNECTION_NORMAL_BODY_READY + 1, /** * We are ready to send a chunk. */ MHD_CONNECTION_CHUNKED_BODY_READY = MHD_CONNECTION_CHUNKED_BODY_UNREADY + 1, /** * We have sent the chunked response body. Prepare the footers. */ MHD_CONNECTION_CHUNKED_BODY_SENT = MHD_CONNECTION_CHUNKED_BODY_READY + 1, /** * We have prepared the response footer. Send it. */ MHD_CONNECTION_FOOTERS_SENDING = MHD_CONNECTION_CHUNKED_BODY_SENT + 1, /** * We have sent the entire reply. * Shutdown connection or restart processing to get a new request. */ MHD_CONNECTION_FULL_REPLY_SENT = MHD_CONNECTION_FOOTERS_SENDING + 1, /** * This connection is to be closed. */ MHD_CONNECTION_CLOSED = MHD_CONNECTION_FULL_REPLY_SENT + 1 #ifdef UPGRADE_SUPPORT , /** * Connection was "upgraded" and socket is now under the * control of the application. */ MHD_CONNECTION_UPGRADE = MHD_CONNECTION_CLOSED + 1 #endif /* UPGRADE_SUPPORT */ } _MHD_FIXED_ENUM; /** * States of TLS transport layer. */ enum MHD_TLS_CONN_STATE { MHD_TLS_CONN_NO_TLS = 0, /**< Not a TLS connection (plain socket). */ MHD_TLS_CONN_INIT, /**< TLS connection is not established yet. */ MHD_TLS_CONN_HANDSHAKING, /**< TLS is in handshake process. */ MHD_TLS_CONN_CONNECTED, /**< TLS is established. */ MHD_TLS_CONN_WR_CLOSING, /**< Closing WR side of TLS layer. */ MHD_TLS_CONN_WR_CLOSED, /**< WR side of TLS layer is closed. */ MHD_TLS_CONN_TLS_CLOSING, /**< TLS session is terminating. */ MHD_TLS_CONN_TLS_CLOSED, /**< TLS session is terminated. */ MHD_TLS_CONN_TLS_FAILED, /**< TLS session failed. */ MHD_TLS_CONN_INVALID_STATE/**< Sentinel. Not a valid value. */ } _MHD_FIXED_ENUM; /** * Should all state transitions be printed to stderr? */ #define DEBUG_STATES _MHD_MACRO_NO #ifdef HAVE_MESSAGES #if DEBUG_STATES const char * MHD_state_to_string (enum MHD_CONNECTION_STATE state); #endif #endif /** * Function to receive plaintext data. * * @param conn the connection struct * @param write_to where to write received data * @param max_bytes maximum number of bytes to receive * @return number of bytes written to @a write_to */ typedef ssize_t (*ReceiveCallback) (struct MHD_Connection *conn, void *write_to, size_t max_bytes); /** * Function to transmit plaintext data. * * @param conn the connection struct * @param read_from where to read data to transmit * @param max_bytes maximum number of bytes to transmit * @return number of bytes transmitted */ typedef ssize_t (*TransmitCallback) (struct MHD_Connection *conn, const void *read_from, size_t max_bytes); /** * Ability to use same connection for next request */ enum MHD_ConnKeepAlive { /** * Connection must be closed after sending response. */ MHD_CONN_MUST_CLOSE = -1, /** * KeelAlive state is not yet determined */ MHD_CONN_KEEPALIVE_UNKOWN = 0, /** * Connection can be used for serving next request */ MHD_CONN_USE_KEEPALIVE = 1, /** * Connection will be upgraded */ MHD_CONN_MUST_UPGRADE = 2 } _MHD_FIXED_ENUM; enum MHD_HTTP_Version { /** * Not a HTTP protocol or HTTP version is invalid. */ MHD_HTTP_VER_INVALID = -1, /** * HTTP version is not yet received from the client. */ MHD_HTTP_VER_UNKNOWN = 0, /** * HTTP version before 1.0, unsupported. */ MHD_HTTP_VER_TOO_OLD = 1, /** * HTTP version 1.0 */ MHD_HTTP_VER_1_0 = 2, /** * HTTP version 1.1 */ MHD_HTTP_VER_1_1 = 3, /** * HTTP version 1.2-1.9, must be used as 1.1 */ MHD_HTTP_VER_1_2__1_9 = 4, /** * HTTP future version. Unsupported. */ MHD_HTTP_VER_FUTURE = 100 } _MHD_FIXED_ENUM; /** * Returns boolean 'true' if HTTP version is supported by MHD */ #define MHD_IS_HTTP_VER_SUPPORTED(ver) (MHD_HTTP_VER_1_0 <= (ver) && \ MHD_HTTP_VER_1_2__1_9 >= (ver)) /** * Protocol should be used as HTTP/1.1 protocol. * * See the last paragraph of * https://datatracker.ietf.org/doc/html/rfc7230#section-2.6 */ #define MHD_IS_HTTP_VER_1_1_COMPAT(ver) (MHD_HTTP_VER_1_1 == (ver) || \ MHD_HTTP_VER_1_2__1_9 == (ver)) /** * The HTTP method. * * Only primary methods (specified in RFC9110) are defined here. */ enum MHD_HTTP_Method { /** * No request string has been received yet */ MHD_HTTP_MTHD_NO_METHOD = 0, /** * HTTP method GET */ MHD_HTTP_MTHD_GET = 1, /** * HTTP method HEAD */ MHD_HTTP_MTHD_HEAD = 2, /** * HTTP method POST */ MHD_HTTP_MTHD_POST = 3, /** * HTTP method PUT */ MHD_HTTP_MTHD_PUT = 4, /** * HTTP method DELETE */ MHD_HTTP_MTHD_DELETE = 5, /** * HTTP method CONNECT */ MHD_HTTP_MTHD_CONNECT = 6, /** * HTTP method OPTIONS */ MHD_HTTP_MTHD_OPTIONS = 7, /** * HTTP method TRACE */ MHD_HTTP_MTHD_TRACE = 8, /** * Other HTTP method. Check the string value. */ MHD_HTTP_MTHD_OTHER = 1000 } _MHD_FIXED_ENUM; /** * The request line processing data */ struct MHD_RequestLineProcessing { /** * The position of the next character to be processed */ size_t proc_pos; /** * The number of empty lines skipped */ unsigned int skipped_empty_lines; /** * The position of the start of the current/last found whitespace block, * zero if not found yet. */ size_t last_ws_start; /** * The position of the next character after the last known whitespace * character in the current/last found whitespace block, * zero if not found yet. */ size_t last_ws_end; /** * The pointer to the request target. * The request URI will be formed based on it. */ char *rq_tgt; /** * The pointer to the first question mark in the @a rq_tgt. */ char *rq_tgt_qmark; /** * The number of whitespace characters in the request URI */ size_t num_ws_in_uri; }; /** * The request header processing data */ struct MHD_HeaderProcessing { /** * The position of the last processed character */ size_t proc_pos; /** * The position of the first whitespace character in current contiguous * whitespace block. * Zero when no whitespace found or found non-whitespace character after * whitespace. * Must be zero, if the current character is not whitespace. */ size_t ws_start; /** * Indicates that end of the header (field) name found. * Must be false until the first colon in line is found. */ bool name_end_found; /** * The length of the header name. * Must be zero until the first colon in line is found. * Name always starts at zero position. */ size_t name_len; /** * The position of the first character of the header value. * Zero when the first character has not been found yet. */ size_t value_start; /** * Line starts with whitespace. * It's meaningful only for the first line, as other lines should be handled * as "folded". */ bool starts_with_ws; }; /** * The union of request line and header processing data */ union MHD_HeadersProcessing { /** * The request line processing data */ struct MHD_RequestLineProcessing rq_line; /** * The request header processing data */ struct MHD_HeaderProcessing hdr; }; /** * The union of text staring point and the size of the text */ union MHD_StartOrSize { /** * The starting point of the text. * Valid when the text is being processed and the end of the text * is not yet determined. */ const char *start; /** * The size of the text. * Valid when the text has been processed and the end of the text * is known. */ size_t size; }; /** * Request-specific values. * * Meaningful for the current request only. */ struct MHD_Request { /** * HTTP version string (i.e. http/1.1). Allocated * in pool. */ const char *version; /** * HTTP protocol version as enum. */ enum MHD_HTTP_Version http_ver; /** * Request method. Should be GET/POST/etc. Allocated in pool. */ const char *method; /** * The request method as enum. */ enum MHD_HTTP_Method http_mthd; /** * Requested URL (everything after "GET" only). Allocated * in pool. */ const char *url; /** * The length of the @a url in characters, not including the terminating zero. */ size_t url_len; /** * The original length of the request target. */ size_t req_target_len; /** * Requested URL (everything after "GET" only). * Depending on daemon setting either the same as @a URL or NULL. */ const char *url_for_callback; /** * Linked list of parsed headers. */ struct MHD_HTTP_Req_Header *headers_received; /** * Tail of linked list of parsed headers. */ struct MHD_HTTP_Req_Header *headers_received_tail; /** * Number of bytes we had in the HTTP header, set once we * pass #MHD_CONNECTION_HEADERS_RECEIVED. * This includes the request line, all request headers, the header section * terminating empty line, with all CRLF (or LF) characters. */ size_t header_size; /** * The union of the size of all request field lines (headers) and * the starting point of the first request field line (the first header). * Until #MHD_CONNECTION_HEADERS_RECEIVED the @a start member is valid, * staring with #MHD_CONNECTION_HEADERS_RECEIVED the @a size member is valid. * The size includes CRLF (or LR) characters, but does not include * the terminating empty line. */ union MHD_StartOrSize field_lines; /** * How many more bytes of the body do we expect * to read? #MHD_SIZE_UNKNOWN for unknown. */ uint64_t remaining_upload_size; /** * Are we receiving with chunked encoding? * This will be set to #MHD_YES after we parse the headers and * are processing the body with chunks. * After we are done with the body and we are processing the footers; * once the footers are also done, this will be set to #MHD_NO again * (before the final call to the handler). * It is used only for requests, chunked encoding for response is * indicated by @a rp_props. */ bool have_chunked_upload; /** * If we are receiving with chunked encoding, where are we right * now? * Set to 0 if we are waiting to receive the chunk size; * otherwise, this is the size of the current chunk. * A value of zero is also used when we're at the end of the chunks. */ uint64_t current_chunk_size; /** * If we are receiving with chunked encoding, where are we currently * with respect to the current chunk (at what offset / position)? */ uint64_t current_chunk_offset; /** * Indicate that some of the upload payload data (from the currently * processed chunk for chunked uploads) have been processed by the * last call of the connection handler. * If any data have been processed, but some data left in the buffer * for further processing, then MHD will use zero timeout before the * next data processing round. This allow the application handler * process the data by the fixed portions or other way suitable for * application developer. * If no data have been processed, than MHD will wait for more data * to come (as it makes no sense to call the same connection handler * under the same conditions). However this is dangerous as if buffer * is completely used then connection is aborted. Connection * suspension should be used in such case. */ bool some_payload_processed; /** * We allow the main application to associate some pointer with the * HTTP request, which is passed to each #MHD_AccessHandlerCallback * and some other API calls. Here is where we store it. (MHD does * not know or care what it is). */ void *client_context; /** * Did we ever call the "default_handler" on this request? * This flag determines if we have called the #MHD_OPTION_NOTIFY_COMPLETED * handler when the request finishes. */ bool client_aware; #ifdef BAUTH_SUPPORT /** * Basic Authorization parameters. * The result of Basic Authorization header parsing. * Allocated in the connection's pool. */ const struct MHD_RqBAuth *bauth; /** * Set to true if current request headers are checked for Basic Authorization */ bool bauth_tried; #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /** * Digest Authorization parameters. * The result of Digest Authorization header parsing. * Allocated in the connection's pool. */ const struct MHD_RqDAuth *dauth; /** * Set to true if current request headers are checked for Digest Authorization */ bool dauth_tried; #endif /* DAUTH_SUPPORT */ /** * Number of bare CR characters that were replaced with space characters * in the request line or in the headers (field lines). */ size_t num_cr_sp_replaced; /** * The number of header lines skipped because they have no colon */ size_t skipped_broken_lines; /** * The data of the request line / request headers processing */ union MHD_HeadersProcessing hdrs; }; /** * Reply-specific properties. */ struct MHD_Reply_Properties { #ifdef _DEBUG bool set; /**< Indicates that other members are set and valid */ #endif /* _DEBUG */ bool use_reply_body_headers; /**< Use reply body-specific headers */ bool send_reply_body; /**< Send reply body (can be zero-sized) */ bool chunked; /**< Use chunked encoding for reply */ }; #if defined(_MHD_HAVE_SENDFILE) enum MHD_resp_sender_ { MHD_resp_sender_std = 0, MHD_resp_sender_sendfile }; #endif /* _MHD_HAVE_SENDFILE */ /** * Reply-specific values. * * Meaningful for the current reply only. */ struct MHD_Reply { /** * Response to transmit (initially NULL). */ struct MHD_Response *response; /** * HTTP response code. Only valid if response object * is already set. */ unsigned int responseCode; /** * The "ICY" response. * Reply begins with the SHOUTcast "ICY" line instead of "HTTP". */ bool responseIcy; /** * Current write position in the actual response * (excluding headers, content only; should be 0 * while sending headers). */ uint64_t rsp_write_position; /** * The copy of iov response. * Valid if iovec response is used. * Updated during send. * Members are allocated in the pool. */ struct MHD_iovec_track_ resp_iov; #if defined(_MHD_HAVE_SENDFILE) enum MHD_resp_sender_ resp_sender; #endif /* _MHD_HAVE_SENDFILE */ /** * Reply-specific properties */ struct MHD_Reply_Properties props; }; /** * State kept for each HTTP request. */ struct MHD_Connection { #ifdef EPOLL_SUPPORT /** * Next pointer for the EDLL listing connections that are epoll-ready. */ struct MHD_Connection *nextE; /** * Previous pointer for the EDLL listing connections that are epoll-ready. */ struct MHD_Connection *prevE; #endif /** * Next pointer for the DLL describing our IO state. */ struct MHD_Connection *next; /** * Previous pointer for the DLL describing our IO state. */ struct MHD_Connection *prev; /** * Next pointer for the XDLL organizing connections by timeout. * This DLL can be either the * 'manual_timeout_head/manual_timeout_tail' or the * 'normal_timeout_head/normal_timeout_tail', depending on whether a * custom timeout is set for the connection. */ struct MHD_Connection *nextX; /** * Previous pointer for the XDLL organizing connections by timeout. */ struct MHD_Connection *prevX; /** * Reference to the MHD_Daemon struct. */ struct MHD_Daemon *daemon; /** * Request-specific data */ struct MHD_Request rq; /** * Reply-specific data */ struct MHD_Reply rp; /** * The memory pool is created whenever we first read from the TCP * stream and destroyed at the end of each request (and re-created * for the next request). In the meantime, this pointer is NULL. * The pool is used for all connection-related data except for the * response (which maybe shared between connections) and the IP * address (which persists across individual requests). */ struct MemoryPool *pool; /** * We allow the main application to associate some pointer with the * TCP connection (which may span multiple HTTP requests). Here is * where we store it. (MHD does not know or care what it is). * The location is given to the #MHD_NotifyConnectionCallback and * also accessible via #MHD_CONNECTION_INFO_SOCKET_CONTEXT. */ void *socket_context; /** * Close connection after sending response? * Functions may change value from "Unknown" or "KeepAlive" to "Must close", * but no functions reset value "Must Close" to any other value. */ enum MHD_ConnKeepAlive keepalive; /** * Buffer for reading requests. Allocated in pool. Actually one * byte larger than @e read_buffer_size (if non-NULL) to allow for * 0-termination. */ char *read_buffer; /** * Buffer for writing response (headers only). Allocated * in pool. */ char *write_buffer; /** * Foreign address (of length @e addr_len). MALLOCED (not * in pool!). */ struct sockaddr_storage *addr; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Thread handle for this connection (if we are using * one thread per connection). */ MHD_thread_handle_ID_ tid; #endif /** * Size of @e read_buffer (in bytes). * This value indicates how many bytes we're willing to read * into the buffer. */ size_t read_buffer_size; /** * Position where we currently append data in @e read_buffer (the * next char after the last valid position). */ size_t read_buffer_offset; /** * Size of @e write_buffer (in bytes). */ size_t write_buffer_size; /** * Offset where we are with sending from @e write_buffer. */ size_t write_buffer_send_offset; /** * Last valid location in write_buffer (where do we * append and up to where is it safe to send?) */ size_t write_buffer_append_offset; /** * Position in the 100 CONTINUE message that * we need to send when receiving http 1.1 requests. */ size_t continue_message_write_offset; /** * Length of the foreign address. */ socklen_t addr_len; /** * Last time this connection had any activity * (reading or writing). */ uint64_t last_activity; /** * After how many milliseconds of inactivity should * this connection time out? * Zero for no timeout. */ uint64_t connection_timeout_ms; /** * Socket for this connection. Set to #MHD_INVALID_SOCKET if * this connection has died (daemon should clean * up in that case). */ MHD_socket socket_fd; /** * true if @e socket_fd is not TCP/IP (a UNIX domain socket, a pipe), * false (TCP/IP) otherwise. */ enum MHD_tristate is_nonip; /** * true if #socket_fd is non-blocking, false otherwise. */ bool sk_nonblck; /** * true if connection socket has set SIGPIPE suppression */ bool sk_spipe_suppress; /** * Tracks TCP_CORK / TCP_NOPUSH of the connection socket. */ enum MHD_tristate sk_corked; /** * Tracks TCP_NODELAY state of the connection socket. */ enum MHD_tristate sk_nodelay; /** * Has this socket been closed for reading (i.e. other side closed * the connection)? If so, we must completely close the connection * once we are done sending our response (and stop trying to read * from this socket). */ bool read_closed; /** * Some error happens during processing the connection therefore this * connection must be closed. * The error may come from the client side (like wrong request format), * from the application side (like data callback returned error), or from * the OS side (like out-of-memory). */ bool stop_with_error; /** * Response queued early, before the request is fully processed, * the client upload is rejected. * The connection cannot be reused for additional requests as the current * request is incompletely read and it is unclear where is the initial * byte of the next request. */ bool discard_request; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Set to `true` if the thread has been joined. */ bool thread_joined; #endif /** * Are we currently inside the "idle" handler (to avoid recursively * invoking it). */ bool in_idle; /** * Connection is in the cleanup DL-linked list. */ bool in_cleanup; #ifdef EPOLL_SUPPORT /** * What is the state of this socket in relation to epoll? */ enum MHD_EpollState epoll_state; #endif /** * State in the FSM for this connection. */ enum MHD_CONNECTION_STATE state; /** * What is this connection waiting for? */ enum MHD_ConnectionEventLoopInfo event_loop_info; /** * Function used for reading HTTP request stream. */ ReceiveCallback recv_cls; #ifdef UPGRADE_SUPPORT /** * If this connection was upgraded, this points to * the upgrade response details such that the * #thread_main_connection_upgrade()-logic can perform the * bi-directional forwarding. */ struct MHD_UpgradeResponseHandle *urh; #endif /* UPGRADE_SUPPORT */ #ifdef HTTPS_SUPPORT /** * State required for HTTPS/SSL/TLS support. */ gnutls_session_t tls_session; /** * State of connection's TLS layer */ enum MHD_TLS_CONN_STATE tls_state; /** * Could it be that we are ready to read due to TLS buffers * even though the socket is not? */ bool tls_read_ready; #endif /* HTTPS_SUPPORT */ /** * Is the connection suspended? */ bool suspended; /** * Are we currently in the #MHD_AccessHandlerCallback * for this connection (and thus eligible to receive * calls to #MHD_queue_response()?). */ bool in_access_handler; /** * Is the connection wanting to resume? */ volatile bool resuming; /** * Has the connection been resumed without its states having been * updated since? * * #MHD_connection_update_event_loop_info() deliberately does not * touch a suspended connection, so whatever the application did * while the connection was suspended -- queueing a response, or the * content reader reporting that it has no data yet and moving the * connection to #MHD_CONNECTION_NORMAL_BODY_UNREADY -- leaves * @e event_loop_info describing the state from before the * suspension. The event loop must not act on that stale value; see * the use in call_handlers(). */ bool resumed; /** * Inter-thread communication channel used to wake up the thread that * handles this connection when the connection is resumed. * * Only initialised in thread-per-connection mode with * #MHD_ALLOW_SUSPEND_RESUME enabled, invalid otherwise. * * The daemon-wide ITC cannot serve this purpose: the daemon's own * thread waits on it as well, and #MHD_itc_clear_() drains it, so * whichever of the two threads runs first consumes the notification * and the other one sleeps through it. A channel that only this * connection's thread ever reads cannot lose the wake-up that way. */ struct MHD_itc_ resume_itc; /** * Special member to be returned by #MHD_get_connection_info() */ union MHD_ConnectionInfo connection_info_dummy; }; #ifdef UPGRADE_SUPPORT /** * Buffer we use for upgrade response handling in the unlikely * case where the memory pool was so small it had no buffer * capacity left. Note that we don't expect to _ever_ use this * buffer, so it's mostly wasted memory (except that it allows * us to handle a tricky error condition nicely). So no need to * make this one big. Applications that want to perform well * should just pick an adequate size for the memory pools. */ #define RESERVE_EBUF_SIZE 8 /** * Context we pass to epoll() for each of the two sockets * of a `struct MHD_UpgradeResponseHandle`. We need to do * this so we can distinguish the two sockets when epoll() * gives us event notifications. */ struct UpgradeEpollHandle { /** * Reference to the overall response handle this struct is * included within. */ struct MHD_UpgradeResponseHandle *urh; /** * The socket this event is kind-of about. Note that this is NOT * necessarily the socket we are polling on, as for when we read * from TLS, we epoll() on the connection's socket * (`urh->connection->socket_fd`), while this then the application's * socket (where the application will read from). Nevertheless, for * the application to read, we need to first read from TLS, hence * the two are related. * * Similarly, for writing to TLS, this epoll() will be on the * connection's `socket_fd`, and this will merely be the FD which * the application would write to. Hence this struct must always be * interpreted based on which field in `struct * MHD_UpgradeResponseHandle` it is (`app` or `mhd`). */ MHD_socket socket; /** * IO-state of the @e socket (or the connection's `socket_fd`). */ enum MHD_EpollState celi; }; /** * Handle given to the application to manage special * actions relating to MHD responses that "upgrade" * the HTTP protocol (i.e. to WebSockets). */ struct MHD_UpgradeResponseHandle { /** * The connection for which this is an upgrade handle. Note that * because a response may be shared over many connections, this may * not be the only upgrade handle for the response of this connection. */ struct MHD_Connection *connection; #ifdef HTTPS_SUPPORT /** * Kept in a DLL per daemon. */ struct MHD_UpgradeResponseHandle *next; /** * Kept in a DLL per daemon. */ struct MHD_UpgradeResponseHandle *prev; #ifdef EPOLL_SUPPORT /** * Next pointer for the EDLL listing urhs that are epoll-ready. */ struct MHD_UpgradeResponseHandle *nextE; /** * Previous pointer for the EDLL listing urhs that are epoll-ready. */ struct MHD_UpgradeResponseHandle *prevE; /** * Specifies whether urh already in EDLL list of ready connections. */ bool in_eready_list; #endif /** * The buffer for receiving data from TLS to * be passed to the application. Contains @e in_buffer_size * bytes (unless @e in_buffer_size is zero). Do not free! */ char *in_buffer; /** * The buffer for receiving data from the application to * be passed to TLS. Contains @e out_buffer_size * bytes (unless @e out_buffer_size is zero). Do not free! */ char *out_buffer; /** * Size of the @e in_buffer. * Set to 0 if the TLS connection went down for reading or socketpair * went down for writing. */ size_t in_buffer_size; /** * Size of the @e out_buffer. * Set to 0 if the TLS connection went down for writing or socketpair * went down for reading. */ size_t out_buffer_size; /** * Number of bytes actually in use in the @e in_buffer. Can be larger * than @e in_buffer_size if and only if @a in_buffer_size is zero and * we still have bytes that can be forwarded. * Reset to zero if all data was forwarded to socketpair or * if socketpair went down for writing. */ size_t in_buffer_used; /** * Number of bytes actually in use in the @e out_buffer. Can be larger * than @e out_buffer_size if and only if @a out_buffer_size is zero and * we still have bytes that can be forwarded. * Reset to zero if all data was forwarded to TLS connection or * if TLS connection went down for writing. */ size_t out_buffer_used; /** * The socket we gave to the application (r/w). */ struct UpgradeEpollHandle app; /** * If @a app_sock was a socketpair, our end of it, otherwise * #MHD_INVALID_SOCKET; (r/w). */ struct UpgradeEpollHandle mhd; /** * Emergency IO buffer we use in case the memory pool has literally * nothing left. */ char e_buf[RESERVE_EBUF_SIZE]; #endif /* HTTPS_SUPPORT */ /** * Set to true after the application finished with the socket * by #MHD_UPGRADE_ACTION_CLOSE. * * When BOTH @e was_closed (changed by command from application) * AND @e clean_ready (changed internally by MHD) are set to * #MHD_YES, function #MHD_resume_connection() will move this * connection to cleanup list. * @remark This flag could be changed from any thread. */ volatile bool was_closed; /** * Set to true if connection is ready for cleanup. * * In TLS mode functions #MHD_connection_finish_forward_() must * be called before setting this flag to true. * * In thread-per-connection mode, true in this flag means * that connection's thread exited or about to exit and will * not use MHD_Connection::urh data anymore. * * In any mode true in this flag also means that * MHD_Connection::urh data will not be used for socketpair * forwarding and forwarding itself is finished. * * When BOTH @e was_closed (changed by command from application) * AND @e clean_ready (changed internally by MHD) are set to * true, function #MHD_resume_connection() will move this * connection to cleanup list. * @remark This flag could be changed from thread that process * connection's recv(), send() and response. */ volatile bool clean_ready; }; #endif /* UPGRADE_SUPPORT */ /** * Signature of function called to log URI accesses. * * @param cls closure * @param uri uri being accessed * @param con connection handle * @return new closure */ typedef void * (*LogCallback)(void *cls, const char *uri, struct MHD_Connection *con); /** * Signature of function called to unescape URIs. See also * #MHD_http_unescape(). * * @param cls closure * @param conn connection handle * @param uri 0-terminated string to unescape (should be updated) * @return length of the resulting string */ typedef size_t (*UnescapeCallback)(void *cls, struct MHD_Connection *conn, char *uri); /** * State kept for each MHD daemon. All connections are kept in two * doubly-linked lists. The first one reflects the state of the * connection in terms of what operations we are waiting for (read, * write, locally blocked, cleanup) whereas the second is about its * timeout state (default or custom). */ struct MHD_Daemon { /** * Callback function for all requests. */ MHD_AccessHandlerCallback default_handler; /** * Closure argument to default_handler. */ void *default_handler_cls; /** * Daemon's flags (bitfield). * * @remark Keep this member after pointer value to keep it * properly aligned as it will be used as member of union MHD_DaemonInfo. */ enum MHD_FLAG options; /** * Head of doubly-linked list of new, externally added connections. */ struct MHD_Connection *new_connections_head; /** * Tail of doubly-linked list of new, externally added connections. */ struct MHD_Connection *new_connections_tail; /** * Head of doubly-linked list of our current, active connections. */ struct MHD_Connection *connections_head; /** * Tail of doubly-linked list of our current, active connections. */ struct MHD_Connection *connections_tail; /** * Head of doubly-linked list of our current but suspended connections. */ struct MHD_Connection *suspended_connections_head; /** * Tail of doubly-linked list of our current but suspended connections. */ struct MHD_Connection *suspended_connections_tail; /** * Head of doubly-linked list of connections to clean up. */ struct MHD_Connection *cleanup_head; /** * Tail of doubly-linked list of connections to clean up. */ struct MHD_Connection *cleanup_tail; /** * _MHD_YES if the @e listen_fd socket is a UNIX domain socket. */ enum MHD_tristate listen_is_unix; #ifdef EPOLL_SUPPORT /** * Head of EDLL of connections ready for processing (in epoll mode). */ struct MHD_Connection *eready_head; /** * Tail of EDLL of connections ready for processing (in epoll mode) */ struct MHD_Connection *eready_tail; /** * File descriptor associated with our epoll loop. * * @remark Keep this member after pointer value to keep it * properly aligned as it will be used as member of union MHD_DaemonInfo. */ int epoll_fd; /** * true if the @e listen_fd socket is in the 'epoll' set, * false if not. */ bool listen_socket_in_epoll; #ifdef UPGRADE_SUPPORT #ifdef HTTPS_SUPPORT /** * File descriptor associated with the #run_epoll_for_upgrade() loop. * Only available if #MHD_USE_HTTPS_EPOLL_UPGRADE is set. */ int epoll_upgrade_fd; /** * true if @e epoll_upgrade_fd is in the 'epoll' set, * false if not. */ bool upgrade_fd_in_epoll; #endif /* HTTPS_SUPPORT */ /** * Head of EDLL of upgraded connections ready for processing (in epoll mode). */ struct MHD_UpgradeResponseHandle *eready_urh_head; /** * Tail of EDLL of upgraded connections ready for processing (in epoll mode) */ struct MHD_UpgradeResponseHandle *eready_urh_tail; #endif /* UPGRADE_SUPPORT */ #endif /* EPOLL_SUPPORT */ /** * Head of the XDLL of ALL connections with a default ('normal') * timeout, sorted by timeout (earliest at the tail, most recently * used connection at the head). MHD can just look at the tail of * this list to determine the timeout for all of its elements; * whenever there is an event of a connection, the connection is * moved back to the tail of the list. * * All connections by default start in this list; if a custom * timeout that does not match @e connection_timeout_ms is set, they * are moved to the @e manual_timeout_head-XDLL. * Not used in MHD_USE_THREAD_PER_CONNECTION mode as each thread * needs only one connection-specific timeout. */ struct MHD_Connection *normal_timeout_head; /** * Tail of the XDLL of ALL connections with a default timeout, * sorted by timeout (earliest timeout at the tail). * Not used in MHD_USE_THREAD_PER_CONNECTION mode. */ struct MHD_Connection *normal_timeout_tail; /** * Head of the XDLL of ALL connections with a non-default/custom * timeout, unsorted. MHD will do a O(n) scan over this list to * determine the current timeout. * Not used in MHD_USE_THREAD_PER_CONNECTION mode. */ struct MHD_Connection *manual_timeout_head; /** * Tail of the XDLL of ALL connections with a non-default/custom * timeout, unsorted. * Not used in MHD_USE_THREAD_PER_CONNECTION mode. */ struct MHD_Connection *manual_timeout_tail; /** * Function to call to check if we should accept or reject an * incoming request. May be NULL. */ MHD_AcceptPolicyCallback apc; /** * Closure argument to apc. */ void *apc_cls; /** * Function to call when we are done processing * a particular request. May be NULL. */ MHD_RequestCompletedCallback notify_completed; /** * Closure argument to @e notify_completed. */ void *notify_completed_cls; /** * Function to call when we are starting/stopping * a connection. May be NULL. */ MHD_NotifyConnectionCallback notify_connection; /** * Closure argument to @e notify_connection. */ void *notify_connection_cls; /** * Function to call with the full URI at the * beginning of request processing. May be NULL. *

    * Returns the initial pointer to internal state * kept by the client for the request. */ LogCallback uri_log_callback; /** * Closure argument to @e uri_log_callback. */ void *uri_log_callback_cls; /** * Function to call when we unescape escape sequences. */ UnescapeCallback unescape_callback; /** * Closure for @e unescape_callback. */ void *unescape_callback_cls; /** * Listen port. * * @remark Keep this member after pointer value to keep it * properly aligned as it will be used as member of union MHD_DaemonInfo. */ uint16_t port; #ifdef HAVE_MESSAGES /** * Function for logging error messages (if we * support error reporting). */ MHD_LogCallback custom_error_log; /** * Closure argument to @e custom_error_log. */ void *custom_error_log_cls; #endif /** * Pointer to master daemon (NULL if this is the master) */ struct MHD_Daemon *master; /** * Listen socket. * * @remark Keep this member after pointer value to keep it * properly aligned as it will be used as member of union MHD_DaemonInfo. */ MHD_socket listen_fd; /** * Listen socket is non-blocking. */ bool listen_nonblk; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Worker daemons (one per thread) */ struct MHD_Daemon *worker_pool; #endif /** * Table storing number of connections per IP */ void *per_ip_connection_count; /** * Number of active parallel connections. * * @remark Keep this member after pointer value to keep it * properly aligned as it will be used as member of union MHD_DaemonInfo. */ unsigned int connections; /** * Size of the per-connection memory pools. */ size_t pool_size; /** * Increment for growth of the per-connection memory pools. */ size_t pool_increment; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * Size of threads created by MHD. */ size_t thread_stack_size; /** * Number of worker daemons */ unsigned int worker_pool_size; /** * The select thread handle (if we have internal select) */ MHD_thread_handle_ID_ tid; /** * Mutex for per-IP connection counts. */ MHD_mutex_ per_ip_connection_mutex; /** * Mutex for (modifying) access to the "cleanup", "normal_timeout" and * "manual_timeout" DLLs. */ MHD_mutex_ cleanup_connection_mutex; /** * Mutex for any access to the "new connections" DL-list. */ MHD_mutex_ new_connections_mutex; /** * Mutex serialising the listening socket's membership of the epoll * set: @a listen_socket_in_epoll, @a was_quiesced and the * epoll_ctl() calls that act on them. * * MHD_epoll() runs on the polling thread and MHD_quiesce_daemon() on * the application's; both test those flags and then add or remove the * listening socket, and without this lock the test and the act are * two steps, so both can decide to remove it and the loser gets * ENOENT. A dedicated mutex rather than @a cleanup_connection_mutex: * that one is held across an application callback * (@a notify_completed, in resume_suspended_connections()), so reusing * it would let an application deadlock itself by calling * MHD_quiesce_daemon() from that callback. */ MHD_mutex_ epoll_listen_mutex; #endif /** * Our #MHD_OPTION_SERVER_INSANITY level, bits indicating * which sanity checks are off. */ enum MHD_DisableSanityCheck insanity_level; /** * Whether to allow/disallow/ignore reuse of listening address. * The semantics is the following: * 0: ignore (user did not ask for neither allow/disallow, use SO_REUSEADDR * except W32) * >0: allow (use SO_REUSEPORT on most platforms, SO_REUSEADDR on Windows) * <0: disallow (mostly no action, SO_EXCLUSIVEADDRUSE on Windows or SO_EXCLBIND * on Solaris) */ int listening_address_reuse; /** * Inter-thread communication channel (also used to unblock * select() in non-threaded code). */ struct MHD_itc_ itc; /** * Are we shutting down? */ volatile bool shutdown; /** * Has this daemon been quiesced via #MHD_quiesce_daemon()? * If so, we should no longer use the @e listen_fd (including * removing it from the @e epoll_fd when possible). */ volatile bool was_quiesced; /** * Did we hit some system or process-wide resource limit while * trying to accept() the last time? If so, we don't accept new * connections until we close an existing one. This effectively * temporarily lowers the "connection_limit" to the current * number of connections. */ bool at_limit; /* * Do we need to process resuming connections? */ volatile bool resuming; /** * Indicate that new connections in @e new_connections_head list * need to be processed. */ volatile bool have_new; /** * 'True' if some data is already waiting to be processed. * If set to 'true' - zero timeout for select()/poll*() * is used. * Should be reset each time before processing connections * and raised by any connection which require additional * immediately processing (application does not provide * data for response, data waiting in TLS buffers etc.) */ bool data_already_pending; /** * Limit on the number of parallel connections. */ unsigned int connection_limit; /** * After how many milliseconds of inactivity should * this connection time out? * Zero for no timeout. */ uint64_t connection_timeout_ms; /** * Maximum number of connections per IP, or 0 for * unlimited. */ unsigned int per_ip_connection_limit; /** * The strictness level for parsing of incoming data. * @see #MHD_OPTION_CLIENT_DISCIPLINE_LVL */ int client_discipline; /** * Allow binary zero in the URI (excluding query part). * When set to '1' then @a url parameter must be NULL, when binary zero * is used in URI. */ int allow_bzero_in_url; #ifdef HAS_FD_SETSIZE_OVERRIDABLE /** * The value of FD_SETSIZE used by the daemon. * For external sockets polling this is the value provided by the application * via MHD_OPTION_APP_FD_SETSIZE or current FD_SETSIZE value. * For internal threads modes this is always current FD_SETSIZE value. */ int fdset_size; /** * Indicates whether @a fdset_size value was set by application. * 'false' if default value is used. */ bool fdset_size_set_by_app; #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ /** * True if SIGPIPE is blocked */ bool sigpipe_blocked; #ifdef HTTPS_SUPPORT #ifdef UPGRADE_SUPPORT /** * Head of DLL of upgrade response handles we are processing. * Used for upgraded TLS connections when thread-per-connection * is not used. */ struct MHD_UpgradeResponseHandle *urh_head; /** * Tail of DLL of upgrade response handles we are processing. * Used for upgraded TLS connections when thread-per-connection * is not used. */ struct MHD_UpgradeResponseHandle *urh_tail; #endif /* UPGRADE_SUPPORT */ /** * Desired cipher algorithms. */ gnutls_priority_t priority_cache; /** * What kind of credentials are we offering * for SSL/TLS? */ gnutls_credentials_type_t cred_type; /** * Server x509 credentials */ gnutls_certificate_credentials_t x509_cred; /** * Diffie-Hellman parameters */ gnutls_dh_params_t dh_params; /** * Server PSK credentials */ gnutls_psk_server_credentials_t psk_cred; #if GNUTLS_VERSION_MAJOR >= 3 /** * Function that can be used to obtain the certificate. Needed * for SNI support. See #MHD_OPTION_HTTPS_CERT_CALLBACK. */ gnutls_certificate_retrieve_function2 *cert_callback; /** * Function that can be used to obtain the shared key. */ MHD_PskServerCredentialsCallback cred_callback; /** * Closure for @e cred_callback. */ void *cred_callback_cls; #endif #if GNUTLS_VERSION_NUMBER >= 0x030603 /** * Function that can be used to obtain the certificate. Needed * for OCSP stapling support. See #MHD_OPTION_HTTPS_CERT_CALLBACK2. */ gnutls_certificate_retrieve_function3 *cert_callback2; #endif /** * Pointer to our SSL/TLS key (in ASCII) in memory. */ const char *https_mem_key; /** * Pointer to our SSL/TLS certificate (in ASCII) in memory. */ const char *https_mem_cert; /** * Pointer to 0-terminated HTTPS passphrase in memory. */ const char *https_key_password; /** * Pointer to our SSL/TLS certificate authority (in ASCII) in memory. */ const char *https_mem_trust; /** * Our Diffie-Hellman parameters in memory. */ gnutls_dh_params_t https_mem_dhparams; /** * true if we have initialized @e https_mem_dhparams. */ bool have_dhparams; /** * true if ALPN is disabled. */ bool disable_alpn; #endif /* HTTPS_SUPPORT */ #ifdef DAUTH_SUPPORT /** * Character array of random values. */ const char *digest_auth_random; /** * Size of @a digest_auth_random. */ size_t digest_auth_rand_size; /** * The malloc'ed copy of the @a digest_auth_random. */ void *digest_auth_random_copy; /** * An array that contains the map nonce-nc. */ struct MHD_NonceNc *nnc; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) /** * A rw-lock for synchronizing access to @e nnc. */ MHD_mutex_ nnc_lock; #endif /** * Size of the nonce-nc array. */ unsigned int nonce_nc_size; /** * Nonce bind type. */ unsigned int dauth_bind_type; /** * Default nonce validity length. */ unsigned int dauth_def_nonce_timeout; /** * Default maximum nc (nonce count) value. */ uint32_t dauth_def_max_nc; #endif #ifdef TCP_FASTOPEN /** * The queue size for incoming SYN + DATA packets. */ unsigned int fastopen_queue_size; #endif /** * The size of queue for listen socket. */ unsigned int listen_backlog_size; /* TODO: replace with a single member */ /** * The value to be returned by #MHD_get_daemon_info() */ union MHD_DaemonInfo daemon_info_dummy_listen_fd; #ifdef EPOLL_SUPPORT /** * The value to be returned by #MHD_get_daemon_info() */ union MHD_DaemonInfo daemon_info_dummy_epoll_fd; #endif /* EPOLL_SUPPORT */ /** * The value to be returned by #MHD_get_daemon_info() */ union MHD_DaemonInfo daemon_info_dummy_num_connections; /** * The value to be returned by #MHD_get_daemon_info() */ union MHD_DaemonInfo daemon_info_dummy_flags; /** * The value to be returned by #MHD_get_daemon_info() */ union MHD_DaemonInfo daemon_info_dummy_port; #if defined(_DEBUG) && defined(HAVE_ACCEPT4) /** * If set to 'true', accept() function will be used instead of accept4() even * if accept4() is available. * This is a workaround for zzuf, which does not support sockets created * by accept4() function. * There is no API to change the value of this member, it can be flipped * only by direct access to the struct member. */ bool avoid_accept4; #endif /* _DEBUG */ }; #if defined(HAVE_POLL) && defined(EPOLL_SUPPORT) /** * Checks whether the @a d daemon is using select() */ #define MHD_D_IS_USING_SELECT_(d) \ (0 == (d->options & (MHD_USE_POLL | MHD_USE_EPOLL))) /** * Checks whether the @a d daemon is using poll() */ #define MHD_D_IS_USING_POLL_(d) (0 != ((d)->options & MHD_USE_POLL)) /** * Checks whether the @a d daemon is using epoll */ #define MHD_D_IS_USING_EPOLL_(d) (0 != ((d)->options & MHD_USE_EPOLL)) #elif defined(HAVE_POLL) /** * Checks whether the @a d daemon is using select() */ #define MHD_D_IS_USING_SELECT_(d) (0 == ((d)->options & MHD_USE_POLL)) /** * Checks whether the @a d daemon is using poll() */ #define MHD_D_IS_USING_POLL_(d) (0 != ((d)->options & MHD_USE_POLL)) /** * Checks whether the @a d daemon is using epoll */ #define MHD_D_IS_USING_EPOLL_(d) ((void) (d), 0) #elif defined(EPOLL_SUPPORT) /** * Checks whether the @a d daemon is using select() */ #define MHD_D_IS_USING_SELECT_(d) (0 == ((d)->options & MHD_USE_EPOLL)) /** * Checks whether the @a d daemon is using poll() */ #define MHD_D_IS_USING_POLL_(d) ((void) (d), 0) /** * Checks whether the @a d daemon is using epoll */ #define MHD_D_IS_USING_EPOLL_(d) (0 != ((d)->options & MHD_USE_EPOLL)) #else /* select() only */ /** * Checks whether the @a d daemon is using select() */ #define MHD_D_IS_USING_SELECT_(d) ((void) (d), ! 0) /** * Checks whether the @a d daemon is using poll() */ #define MHD_D_IS_USING_POLL_(d) ((void) (d), 0) /** * Checks whether the @a d daemon is using epoll */ #define MHD_D_IS_USING_EPOLL_(d) ((void) (d), 0) #endif /* select() only */ #if defined(MHD_USE_THREADS) /** * Checks whether the @a d daemon is using internal polling thread */ #define MHD_D_IS_USING_THREADS_(d) \ (0 != (d->options & (MHD_USE_INTERNAL_POLLING_THREAD))) /** * Checks whether the @a d daemon is using thread-per-connection mode */ #define MHD_D_IS_USING_THREAD_PER_CONN_(d) \ (0 != ((d)->options & MHD_USE_THREAD_PER_CONNECTION)) /** * Check whether the @a d daemon has thread-safety enabled. */ #define MHD_D_IS_THREAD_SAFE_(d) \ (0 == ((d)->options & MHD_USE_NO_THREAD_SAFETY)) #else /* ! MHD_USE_THREADS */ /** * Checks whether the @a d daemon is using internal polling thread */ #define MHD_D_IS_USING_THREADS_(d) ((void) d, 0) /** * Checks whether the @a d daemon is using thread-per-connection mode */ #define MHD_D_IS_USING_THREAD_PER_CONN_(d) ((void) d, 0) /** * Check whether the @a d daemon has thread-safety enabled. */ #define MHD_D_IS_THREAD_SAFE_(d) ((void) d, 0) #endif /* ! MHD_USE_THREADS */ #ifdef HAS_FD_SETSIZE_OVERRIDABLE /** * Get FD_SETSIZE used by the daemon @a d */ #define MHD_D_GET_FD_SETSIZE_(d) ((d)->fdset_size) #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ /** * Get FD_SETSIZE used by the daemon @a d */ #define MHD_D_GET_FD_SETSIZE_(d) (FD_SETSIZE) #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ /** * Check whether socket @a sckt fits fd_sets used by the daemon @a d */ #define MHD_D_DOES_SCKT_FIT_FDSET_(sckt,d) \ MHD_SCKT_FD_FITS_FDSET_SETSIZE_(sckt,NULL,MHD_D_GET_FD_SETSIZE_(d)) #ifdef DAUTH_SUPPORT /** * Parameter of request's Digest Authorization header */ struct MHD_RqDAuthParam { /** * The string with length, NOT zero-terminated */ struct _MHD_str_w_len value; /** * True if string must be "unquoted" before processing. * This member is false if the string is used in DQUOTE marks, but no * backslash-escape is used in the string. */ bool quoted; }; /** * Request client's Digest Authorization header parameters */ struct MHD_RqDAuth { struct MHD_RqDAuthParam nonce; struct MHD_RqDAuthParam opaque; struct MHD_RqDAuthParam response; struct MHD_RqDAuthParam username; struct MHD_RqDAuthParam username_ext; struct MHD_RqDAuthParam realm; struct MHD_RqDAuthParam uri; /* The raw QOP value, used in the 'response' calculation */ struct MHD_RqDAuthParam qop_raw; struct MHD_RqDAuthParam cnonce; struct MHD_RqDAuthParam nc; /* Decoded values are below */ bool userhash; /* True if 'userhash' parameter has value 'true'. */ enum MHD_DigestAuthAlgo3 algo3; enum MHD_DigestAuthQOP qop; }; #endif /* DAUTH_SUPPORT */ /** * Insert an element at the head of a DLL. Assumes that head, tail and * element are structs with prev and next fields. * * @param head pointer to the head of the DLL * @param tail pointer to the tail of the DLL * @param element element to insert */ #define DLL_insert(head,tail,element) do { \ mhd_assert (NULL == (element)->next); \ mhd_assert (NULL == (element)->prev); \ (element)->next = (head); \ (element)->prev = NULL; \ if ((tail) == NULL) { \ (tail) = element; \ } else { \ (head)->prev = element; \ } \ (head) = (element); } while (0) /** * Remove an element from a DLL. Assumes * that head, tail and element are structs * with prev and next fields. * * @param head pointer to the head of the DLL * @param tail pointer to the tail of the DLL * @param element element to remove */ #define DLL_remove(head,tail,element) do { \ mhd_assert ( (NULL != (element)->next) || ((element) == (tail))); \ mhd_assert ( (NULL != (element)->prev) || ((element) == (head))); \ if ((element)->prev == NULL) { \ (head) = (element)->next; \ } else { \ (element)->prev->next = (element)->next; \ } \ if ((element)->next == NULL) { \ (tail) = (element)->prev; \ } else { \ (element)->next->prev = (element)->prev; \ } \ (element)->next = NULL; \ (element)->prev = NULL; } while (0) /** * Insert an element at the head of a XDLL. Assumes that head, tail and * element are structs with prevX and nextX fields. * * @param head pointer to the head of the XDLL * @param tail pointer to the tail of the XDLL * @param element element to insert */ #define XDLL_insert(head,tail,element) do { \ mhd_assert (NULL == (element)->nextX); \ mhd_assert (NULL == (element)->prevX); \ (element)->nextX = (head); \ (element)->prevX = NULL; \ if (NULL == (tail)) { \ (tail) = element; \ } else { \ (head)->prevX = element; \ } \ (head) = (element); } while (0) /** * Remove an element from a XDLL. Assumes * that head, tail and element are structs * with prevX and nextX fields. * * @param head pointer to the head of the XDLL * @param tail pointer to the tail of the XDLL * @param element element to remove */ #define XDLL_remove(head,tail,element) do { \ mhd_assert ( (NULL != (element)->nextX) || ((element) == (tail))); \ mhd_assert ( (NULL != (element)->prevX) || ((element) == (head))); \ if (NULL == (element)->prevX) { \ (head) = (element)->nextX; \ } else { \ (element)->prevX->nextX = (element)->nextX; \ } \ if (NULL == (element)->nextX) { \ (tail) = (element)->prevX; \ } else { \ (element)->nextX->prevX = (element)->prevX; \ } \ (element)->nextX = NULL; \ (element)->prevX = NULL; } while (0) /** * Insert an element at the head of a EDLL. Assumes that head, tail and * element are structs with prevE and nextE fields. * * @param head pointer to the head of the EDLL * @param tail pointer to the tail of the EDLL * @param element element to insert */ #define EDLL_insert(head,tail,element) do { \ (element)->nextE = (head); \ (element)->prevE = NULL; \ if ((tail) == NULL) { \ (tail) = element; \ } else { \ (head)->prevE = element; \ } \ (head) = (element); } while (0) /** * Remove an element from a EDLL. Assumes * that head, tail and element are structs * with prevE and nextE fields. * * @param head pointer to the head of the EDLL * @param tail pointer to the tail of the EDLL * @param element element to remove */ #define EDLL_remove(head,tail,element) do { \ if ((element)->prevE == NULL) { \ (head) = (element)->nextE; \ } else { \ (element)->prevE->nextE = (element)->nextE; \ } \ if ((element)->nextE == NULL) { \ (tail) = (element)->prevE; \ } else { \ (element)->nextE->prevE = (element)->prevE; \ } \ (element)->nextE = NULL; \ (element)->prevE = NULL; } while (0) /** * Convert all occurrences of '+' to ' '. * * @param arg string that is modified (in place), must be 0-terminated */ void MHD_unescape_plus (char *arg); /** * Callback invoked when iterating over @a key / @a value * argument pairs during parsing. * * @param cls context of the iteration * @param key 0-terminated key string, never NULL * @param key_size number of bytes in key * @param value 0-terminated binary data, may include binary zeros, may be NULL * @param value_size number of bytes in value * @param kind origin of the key-value pair * @return #MHD_YES on success (continue to iterate) * #MHD_NO to signal failure (and abort iteration) */ typedef enum MHD_Result (*MHD_ArgumentIterator_)(void *cls, const char *key, size_t key_size, const char *value, size_t value_size, enum MHD_ValueKind kind); /** * Parse and unescape the arguments given by the client * as part of the HTTP request URI. * * @param kind header kind to pass to @a cb * @param connection connection to add headers to * @param[in,out] args argument URI string (after "?" in URI), * clobbered in the process! * @param cb function to call on each key-value pair found * @param cls the iterator context * @return #MHD_NO on failure (@a cb returned #MHD_NO), * #MHD_YES for success (parsing succeeded, @a cb always * returned #MHD_YES) */ enum MHD_Result MHD_parse_arguments_ (struct MHD_Connection *connection, enum MHD_ValueKind kind, char *args, MHD_ArgumentIterator_ cb, void *cls); /** * Check whether response header contains particular token. * * Token could be surrounded by spaces and tabs and delimited by comma. * Case-insensitive match used for header names and tokens. * * @param response the response to query * @param key header name * @param key_len the length of @a key, not including optional * terminating null-character. * @param token the token to find * @param token_len the length of @a token, not including optional * terminating null-character. * @return true if token is found in specified header, * false otherwise */ bool MHD_check_response_header_token_ci (const struct MHD_Response *response, const char *key, size_t key_len, const char *token, size_t token_len); /** * Check whether response header contains particular static @a tkn. * * Token could be surrounded by spaces and tabs and delimited by comma. * Case-insensitive match used for header names and tokens. * @param r the response to query * @param k header name * @param tkn the static string of token to find * @return true if token is found in specified header, * false otherwise */ #define MHD_check_response_header_s_token_ci(r,k,tkn) \ MHD_check_response_header_token_ci ((r),(k),MHD_STATICSTR_LEN_ (k), \ (tkn),MHD_STATICSTR_LEN_ (tkn)) /** * Internal version of #MHD_suspend_connection(). * * @remark In thread-per-connection mode: can be called from any thread, * in any other mode: to be called only from thread that process * daemon's select()/poll()/etc. * * @param connection the connection to suspend */ void internal_suspend_connection_ (struct MHD_Connection *connection); /** * Trace up to and return master daemon. If the supplied daemon * is a master, then return the daemon itself. * * @param daemon handle to a daemon * @return master daemon handle */ _MHD_static_inline struct MHD_Daemon * MHD_get_master (struct MHD_Daemon *const daemon) { struct MHD_Daemon *ret; if (NULL != daemon->master) ret = daemon->master; else ret = daemon; mhd_assert (NULL == ret->master); return ret; } #ifdef UPGRADE_SUPPORT /** * Mark upgraded connection as closed by application. * * The @a connection pointer must not be used after call of this function * as it may be freed in other thread immediately. * @param connection the upgraded connection to mark as closed by application */ void MHD_upgraded_connection_mark_app_closed_ (struct MHD_Connection *connection); #endif /* UPGRADE_SUPPORT */ #endif libmicrohttpd-1.0.10/src/microhttpd/test_option_matrix.c0000664000175000017500000013054315232103064017165 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_option_matrix.c * @brief A battery of raw HTTP requests replayed against every supported * point of the daemon option matrix. * @author Christian Grothoff * * ## Why this test exists * * Every other test in this directory pins one daemon configuration, so the * suite as a whole only ever visits a single point of a fairly large * configuration space: connection memory limit x client discipline level x * threading mode x polling backend. Yet the code that a request travels * through depends on all four: a small connection pool unlocks the read * buffer "shift back" and buffer-grow paths, the discipline level switches * whole families of parser leniency, and the threading/polling mode decides * which of the four event loops re-enters the parser. * * This test walks the matrix defined in mhd_opt_matrix.c and replays the same * small battery of hand-written raw requests against every point of it. The * requests are sent over raw sockets because several of them (chunk * extensions, pipelining, a whitespace-prefixed header line, an early close * in the middle of a request) cannot be produced with libcurl. * * Every failure names the profile it came from, so a report is directly * actionable. * * ## Command line * * * `-v` - report every profile and every scenario; * * `-v -v` - additionally print the MHD error log; * * `--profile=N` - restrict the run to one profile (name or index), the * same as MHD_TEST_PROFILE=N in the environment; * * `--list-profiles` - print one profile name per line and exit; this is * what contrib/run-option-matrix.sh uses, so that the * matrix is defined in exactly one place; * * `--scenario=NAME` - restrict the run to one scenario. Useful to walk * the whole battery of a profile that aborts the process * in the middle of it. * * Exit codes: 0 = pass, 77 = skip, 99 = hard setup error, 1 = test failure. */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #include #include #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #include #include "mhd_sockets.h" /* only macros used */ #include "mhd_opt_matrix.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /** * Convenience shorthand used all over the scenario table. */ #define CRLF "\r\n" /** * The Host header used by (almost) every scenario. */ #define H_LOCAL "Host: localhost" CRLF /** * Size of the textual observation buffer. */ #define OBS_SIZE 4096 /** * Size of the client receive buffer. */ #define RX_SIZE 8192 /** * Hard upper bound (ms) for reading the complete server answer. */ #define READ_DEADLINE_MS 700 /** * Silence (ms) accepted as "the server is done and keeps the connection * alive". */ #define READ_GRACE_MS 10 /** * Milliseconds to wait for the server side to finish tearing down the * connection, so that the observations become stable. */ #define CLOSE_WAIT_MS 1500 /** * Milliseconds the daemon is left running after a scenario that closes the * connection without reading an answer, so that a wrongly parsed request * still has a chance to show up. */ #define SETTLE_MS 60 /** * The connection timeout of the test daemons, in seconds. */ #define DAEMON_TIMEOUT 8 /** * Give up after that many reported failures. */ #define MAX_FAILURES 12 /* ------------------------------------------------------------------ */ /* Error exits */ /* ------------------------------------------------------------------ */ /* Forward declaration, needed by the error exit helpers. */ static void print_context (FILE *out); _MHD_NORETURN static void external_error_exit (const char *desc, int line) { fprintf (stderr, "%s at line %d.\nLast errno value: %d (%s)\n", (NULL != desc) ? desc : "System or external library call failed", line, (int) errno, strerror (errno)); print_context (stderr); fflush (stderr); exit (99); } #define hard_error(desc) external_error_exit (desc, __LINE__) /** * Pause execution for the given number of milliseconds. * * @param ms the number of milliseconds to sleep */ static void sleep_ms (unsigned int ms) { #if defined(_WIN32) Sleep (ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp = {(time_t) (ms / 1000), (long) ((ms % 1000) * 1000000)}; struct timespec rmn; int num_retries = 0; while (0 != nanosleep (&slp, &rmn)) { if (EINTR != errno) hard_error ("nanosleep() failed"); if (num_retries++ > 8) break; slp = rmn; } #elif defined(HAVE_USLEEP) usleep ((useconds_t) (ms * 1000)); #else hard_error ("No sleep function available on this system"); #endif } /** * Monotonic-ish millisecond clock. */ static uint64_t now_ms (void) { #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) struct timespec ts; if (0 == clock_gettime (CLOCK_MONOTONIC, &ts)) return ((uint64_t) ts.tv_sec) * 1000 + (uint64_t) (ts.tv_nsec / 1000000); #endif /* HAVE_CLOCK_GETTIME && CLOCK_MONOTONIC */ return ((uint64_t) time (NULL)) * 1000; } /* ------------------------------------------------------------------ */ /* Textual observation buffer */ /* ------------------------------------------------------------------ */ /** * A bounded, always NUL-terminated text accumulator. Both the expected and * the actual observation are rendered into such a buffer, so that a single * strcmp() performs the whole check and also yields readable diagnostics. */ struct obs_buf { char d[OBS_SIZE]; size_t len; int overflow; }; static void obs_reset (struct obs_buf *b) { b->len = 0; b->overflow = 0; b->d[0] = 0; } static void obs_addf (struct obs_buf *b, const char *fmt, ...) { va_list ap; int r; size_t space; if (b->len >= sizeof(b->d) - 1) { b->overflow = 1; return; } space = sizeof(b->d) - b->len; va_start (ap, fmt); r = vsnprintf (b->d + b->len, space, fmt, ap); va_end (ap); if (0 > r) { b->overflow = 1; return; } if ((size_t) r >= space) { b->len = sizeof(b->d) - 1; b->overflow = 1; return; } b->len += (size_t) r; } /** * Append @a data with all non-printable bytes escaped as \\xNN. */ static void obs_add_escaped (struct obs_buf *b, const char *data, size_t size) { size_t i; for (i = 0; i < size; ++i) { const unsigned char c = (unsigned char) data[i]; if ((0x20 <= c) && (0x7e >= c) && ('\\' != c)) obs_addf (b, "%c", (char) c); else if ('\\' == c) obs_addf (b, "\\\\"); else obs_addf (b, "\\x%02x", (unsigned int) c); } } /* ------------------------------------------------------------------ */ /* The scenario battery */ /* ------------------------------------------------------------------ */ /** * One request scenario. * * The expectation @e exp is the concatenation of one line per request that * MHD must parse, in the format * * "METHOD URL [BODY] {ARG=VAL,ARG=VAL}\n" * * with every byte outside the printable ASCII range escaped as \\xNN and a * query argument without a value rendered as "ARG=". */ struct scenario { /** * Short identifier, printed on failure. */ const char *name; /** * One line saying which behaviour this scenario pins down. */ const char *desc; /** * The raw request byte stream (may hold several pipelined requests). */ const char *raw; /** * The number of complete requests MHD must parse out of @e raw. */ unsigned int n_req; /** * The number of complete responses the client must see. */ unsigned int n_resp; /** * The expected status code of the first response, zero for "any". */ int status; /** * 1 if the connection must stay alive afterwards, 0 if MHD must close it. */ int alive; /** * If non-zero, the client closes the connection right after sending and * does not read any answer at all. */ int close_after_send; /** * If non-zero, the only requirement is that the daemon survives: neither * the number of parsed requests nor the answer is checked. Used by the * probes whose declared purpose is to reach a defect. */ int loose; /** * The lowest client discipline level at which this scenario is meaningful. */ int min_discp; /** * The highest client discipline level at which this scenario is * meaningful. */ int max_discp; /** * The expected server side observation, see above. */ const char *exp; }; /** * A header block of ten headers with values of moderate length. Kept small * enough to still fit into a connection memory pool of * 1024 bytes, so that the scenario is a real check rather than a permanent * "degraded by the pool" case. */ #define MANY_HDRS \ "A-One: 1" CRLF "B-Two: 22" CRLF "C-Three: 333" CRLF \ "D-Four: 4444" CRLF "E-Five: 55555" CRLF "F-Six: 666666" CRLF \ "G-Seven: 7777777" CRLF "H-Eight: 88888888" CRLF \ "I-Nine: 999999999" CRLF "J-Ten: aaaaaaaaaa" CRLF /** * Forty characters of chunk-extension filler. */ #define EXT_40 "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq" /** * Four hundred characters of chunk-extension filler: longer than the whole * read buffer of a connection memory pool of 512 bytes, so that MHD has to * take the "chunk-size line does not fit" path, and comfortably shorter than * the read buffer of a 1024-byte pool, where the line still fits. */ #define EXT_400 \ EXT_40 EXT_40 EXT_40 EXT_40 EXT_40 \ EXT_40 EXT_40 EXT_40 EXT_40 EXT_40 /** * The expected rendering of #MANY_HDRS as GET arguments: none, the block is * a header block. Only listed here to keep the table readable. */ #define E_MANY "GET /h [] {}\n" static const struct scenario scenarios[] = { { "get_plain", "baseline: request line, one header, empty reply", "GET / HTTP/1.1" CRLF H_LOCAL CRLF, 1, 1, 200, 1, 0, 0, -3, 3, "GET / [] {}\n" }, { "get_query", "query arguments: '=' value, bare argument, '+' decoding", "GET /q?a=1&b&c=x+y HTTP/1.1" CRLF H_LOCAL CRLF, 1, 1, 200, 1, 0, 0, -3, 3, "GET /q [] {a=1,b=,c=x y}\n" }, { "post_cl", "Content-Length body, delivered incrementally to the handler", "POST /p HTTP/1.1" CRLF H_LOCAL "Content-Length: 11" CRLF CRLF "Hello World", 1, 1, 200, 1, 0, 0, -3, 3, "POST /p [Hello World] {}\n" }, { "post_chunked", "chunked body without any chunk extension", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5" CRLF "Hello" CRLF "6" CRLF " World" CRLF "0" CRLF CRLF, 1, 1, 200, 1, 0, 0, -3, 3, "POST /c [Hello World] {}\n" }, { "post_chunk_ext", "chunk extensions, incl. a quoted value holding a ';' (commit c13f4c64)", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5;a=b" CRLF "Hello" CRLF "6;q=\"x;y\"" CRLF " World" CRLF "0;z" CRLF CRLF, 1, 1, 200, 1, 0, 0, -3, 3, "POST /c [Hello World] {}\n" }, /* With a connection memory limit of about 512 or less this chunk-size line does not fit into the read buffer. */ { "post_chunk_ext_long", "chunk extension longer than the space reserved for the chunk header", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5;ext=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"" CRLF "Hello" CRLF "0" CRLF CRLF, 1, 1, 200, 1, 0, 0, -3, 3, "POST /c [Hello] {}\n" }, /* Regression test for commits 68c83f22 and e04eb218: the chunk-size line is longer than the read buffer of a small connection memory pool, so MHD has to take handle_req_chunk_size_line_no_space(). With a pool of 1024 bytes or more the line fits and the scenario is an ordinary chunk-extension check. */ { "post_chunk_ext_huge", "chunk extension longer than the whole read buffer of a small pool", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5;ext=\"" EXT_400 "\"" CRLF "Hello" CRLF "0" CRLF CRLF, 1, 1, 200, 1, 0, 0, -3, 3, "POST /c [Hello] {}\n" }, /* The same, but with the over-long chunk-size line on the *second* chunk, so that the upload callback has already run once when MHD runs out of read buffer space. That is the extra precondition of the assertion fixed in 68c83f22 (rq.some_payload_processed still describes the previous read). */ { "post_chunk_ext_huge_2nd", "over-long chunk-size line after a chunk that was already delivered", "POST /c HTTP/1.1" CRLF H_LOCAL "Transfer-Encoding: chunked" CRLF CRLF "5" CRLF "Hello" CRLF "5;ext=\"" EXT_400 "\"" CRLF "World" CRLF "0" CRLF CRLF, 1, 1, 200, 1, 0, 0, -3, 3, "POST /c [HelloWorld] {}\n" }, { "pipelined", "two pipelined requests must yield exactly two parsed requests", "GET /1 HTTP/1.1" CRLF H_LOCAL CRLF "GET /2?x=1 HTTP/1.1" CRLF H_LOCAL CRLF, 2, 2, 200, 1, 0, 0, -3, 3, "GET /1 [] {}\nGET /2 [] {x=1}\n" }, { "many_headers", "ten header lines: pool allocation and read buffer growth", "GET /h HTTP/1.1" CRLF H_LOCAL MANY_HDRS CRLF, 1, 1, 200, 1, 0, 0, -3, 3, E_MANY }, { "early_close", "the client vanishes in the middle of the request header", "GET /e HTTP/1.1" CRLF H_LOCAL "X-Partial: abc", 0, 0, 0, 0, 1, 0, -3, 3, "" }, /* ---- probes for the relaxed client discipline levels ------------ */ /* The three "strict" variants below are the control cases: at the discipline levels at which MHD promises to reject the input, it must really answer 400 and must not parse a request. The three "lax" variants are the regression tests for the assertions fixed in commits 0b750975 and 6fcdfd43; they only require that the daemon survives, since what those modes do with the input is deliberately unspecified beyond "do not abort". */ { "wsp_first_hdr_strict", "whitespace-prefixed first header line is rejected at level 0 and above", "GET / HTTP/1.1" CRLF " " H_LOCAL "X-A: b" CRLF CRLF, 0, 1, 400, 0, 0, 0, 0, 3, "" }, { "wsp_first_hdr_lax", "whitespace-prefixed first header line at level -1 or below (0b750975)", "GET / HTTP/1.1" CRLF " " H_LOCAL "X-A: b" CRLF CRLF, 0, 0, 0, 0, 0, 1, -3, -1, "" }, { "empty_hdr_name_strict", "an empty header name is rejected at level -1 and above", "GET / HTTP/1.1" CRLF H_LOCAL ": value" CRLF CRLF, 0, 1, 400, 0, 0, 0, -1, 3, "" }, { "empty_hdr_name_lax", "an empty header name at level -2 or below (0b750975)", "GET / HTTP/1.1" CRLF H_LOCAL ": value" CRLF CRLF, 0, 0, 0, 0, 0, 1, -3, -2, "" }, { "bare_cr_strict", "a bare CR in a header value is rejected at level 0 and above", "GET / HTTP/1.1" CRLF H_LOCAL "X-Cr: va\rlue" CRLF CRLF, 0, 1, 400, 0, 0, 0, 0, 3, "" }, { "bare_cr_as_sp", "a bare CR becomes a space at level -1 and -2", "GET / HTTP/1.1" CRLF H_LOCAL "X-Cr: va\rlue" CRLF CRLF, 1, 1, 200, 1, 0, 0, -2, -1, "GET / [] {}\n" }, { "bare_cr_keep", "a bare CR is kept in the header value at level -3 (6fcdfd43)", "GET / HTTP/1.1" CRLF H_LOCAL "X-Cr: va\rlue" CRLF CRLF, 0, 0, 0, 0, 0, 1, -3, -3, "" } }; #define NUM_SCENARIOS (sizeof(scenarios) / sizeof(scenarios[0])) /* ------------------------------------------------------------------ */ /* Global state */ /* ------------------------------------------------------------------ */ static int verbose; /** The profile currently under test. */ static const struct MHD_OptMatrixProfile *cur_prof; /** Rendered description of @a cur_prof. */ static char cur_prof_desc[256]; /** The scenario currently under test. */ static const struct scenario *cur_scen; /** If not NULL, only the scenario with this name is run. */ static const char *only_scen; /** The port of the running daemon. */ static uint16_t global_port; /** The running daemon, only set when it has to be driven with MHD_run(). */ static struct MHD_Daemon *extern_daemon; /** Server side observations of the connection currently under test. */ static struct obs_buf srv_obs; /** Number of completed requests seen by the request handler. */ static volatile unsigned int srv_n_req; /** Set if the handler noticed something structurally impossible. */ static volatile unsigned int srv_error; static volatile unsigned int conn_started; static volatile unsigned int conn_closed; /** Number of (profile x scenario) combinations executed. */ static unsigned long combos; /** Number of combinations that could not fit into the memory pool. */ static unsigned long combos_degraded; /** Number of scenarios skipped because of the discipline level. */ static unsigned long scen_skipped; /** Number of profiles skipped because this build cannot provide them. */ static unsigned long prof_skipped; /** Number of failures found. */ static unsigned long failures; static void print_context (FILE *out) { fprintf (out, " context: profile %s scenario='%s'\n", cur_prof_desc, (NULL != cur_scen) ? cur_scen->name : "(none)"); if (NULL != cur_scen) fprintf (out, " scenario purpose: %s\n", cur_scen->desc); } #if defined(HAVE_SIGNAL_H) && defined(SIGABRT) /** * Report the profile and the scenario when the library aborts (e.g. from an * internal assertion) instead of dying anonymously. */ static void abort_handler (int sig) { (void) sig; fprintf (stderr, "\nFATAL: the library aborted while running a scenario.\n"); print_context (stderr); fflush (stderr); _exit (1); } #endif /* HAVE_SIGNAL_H && SIGABRT */ /** * Panic callback: a library panic is a test failure that names the profile * and the scenario. */ static void test_panic (void *cls, const char *file, unsigned int line, const char *reason) { (void) cls; fprintf (stderr, "\nFATAL: MHD panic at %s:%u: %s\n", (NULL != file) ? file : "(unknown)", line, (NULL != reason) ? reason : "(no reason given)"); print_context (stderr); fflush (stderr); _exit (1); } /* ------------------------------------------------------------------ */ /* Request handler: records the observations */ /* ------------------------------------------------------------------ */ struct req_state { struct obs_buf body; }; struct iter_ctx { struct obs_buf *out; unsigned int num; }; static enum MHD_Result value_iterator (void *cls, enum MHD_ValueKind kind, const char *key, size_t key_size, const char *value, size_t value_size) { struct iter_ctx *const ctx = (struct iter_ctx *) cls; (void) kind; if (0 != ctx->num) obs_addf (ctx->out, ","); ctx->num++; if (NULL != key) obs_add_escaped (ctx->out, key, key_size); else obs_addf (ctx->out, ""); obs_addf (ctx->out, "="); if (NULL == value) obs_addf (ctx->out, ""); else obs_add_escaped (ctx->out, value, value_size); return MHD_YES; } static enum MHD_Result ahc_record (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { /* The reply body is intentionally empty, which keeps the response framing on the client side trivial. */ static const char rp_data[] = ""; struct req_state *rs; struct MHD_Response *response; struct iter_ctx ctx; enum MHD_Result ret; (void) cls; (void) version; if (NULL == *req_cls) { rs = (struct req_state *) malloc (sizeof (struct req_state)); if (NULL == rs) hard_error ("malloc() failed"); obs_reset (&rs->body); *req_cls = rs; return MHD_YES; } rs = (struct req_state *) *req_cls; if (0 != *upload_data_size) { obs_add_escaped (&rs->body, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } /* The request is complete: record everything that is observable. */ obs_addf (&srv_obs, "%s ", (NULL != method) ? method : "(null)"); if (NULL != url) obs_add_escaped (&srv_obs, url, strlen (url)); else obs_addf (&srv_obs, "(null)"); obs_addf (&srv_obs, " [%s] {", rs->body.d); ctx.out = &srv_obs; ctx.num = 0; MHD_get_connection_values_n (connection, MHD_GET_ARGUMENT_KIND, &value_iterator, &ctx); obs_addf (&srv_obs, "}\n"); free (rs); *req_cls = NULL; srv_n_req++; response = MHD_create_response_from_buffer (MHD_STATICSTR_LEN_ (rp_data), (void *) rp_data, MHD_RESPMEM_PERSISTENT); if (NULL == response) { srv_error++; return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) srv_error++; return ret; } /** * The MHD error log, only printed with '-v -v': the matrix visits several * deliberately hostile configurations and the library complains a lot. */ static void test_log (void *cls, const char *fmt, va_list ap) { (void) cls; if (1 < verbose) { vfprintf (stderr, fmt, ap); fflush (stderr); } } static void conn_notify (void *cls, struct MHD_Connection *c, void **socket_context, enum MHD_ConnectionNotificationCode toe) { (void) cls; (void) c; (void) socket_context; if (MHD_CONNECTION_NOTIFY_STARTED == toe) conn_started++; else if (MHD_CONNECTION_NOTIFY_CLOSED == toe) conn_closed++; } static void req_completed (void *cls, struct MHD_Connection *c, void **req_cls, enum MHD_RequestTerminationCode term_code) { (void) cls; (void) c; (void) term_code; if ((NULL != req_cls) && (NULL != *req_cls)) { free (*req_cls); *req_cls = NULL; } } /* ------------------------------------------------------------------ */ /* Raw client */ /* ------------------------------------------------------------------ */ struct client_result { unsigned int n_resp; int first_status; int peer_closed; int timed_out; size_t rx_len; char rx[RX_SIZE]; }; /** * Case-insensitive comparison of @a size bytes (ASCII only). */ static int mem_equal_ci (const char *a, const char *b, size_t size) { size_t i; for (i = 0; i < size; ++i) { char ca = a[i]; char cb = b[i]; if (('A' <= ca) && ('Z' >= ca)) ca = (char) (ca - 'A' + 'a'); if (('A' <= cb) && ('Z' >= cb)) cb = (char) (cb - 'A' + 'a'); if (ca != cb) return 0; } return 1; } /** * Count the number of complete HTTP responses in @a buf. * * @param buf the received bytes * @param len the number of bytes in @a buf * @param[out] first_status set to the status code of the first response * @return the number of *complete* responses found */ static unsigned int count_responses (const char *buf, size_t len, int *first_status) { size_t pos = 0; unsigned int num = 0; *first_status = 0; while (pos < len) { const char *hdr_end; const char *cl; size_t hdr_len; size_t body_len = 0; int status; size_t i; if (7 > len - pos) break; if (0 != memcmp (buf + pos, "HTTP/1.", 7)) break; /* Not a well-formed response */ hdr_end = NULL; for (i = pos; i + 3 < len; ++i) { if (('\r' == buf[i]) && ('\n' == buf[i + 1]) && ('\r' == buf[i + 2]) && ('\n' == buf[i + 3])) { hdr_end = buf + i + 4; break; } } if (NULL == hdr_end) break; /* Incomplete header */ hdr_len = (size_t) (hdr_end - (buf + pos)); status = 0; if ((pos + 12 <= len) && ('0' <= buf[pos + 9]) && ('9' >= buf[pos + 9])) status = (buf[pos + 9] - '0') * 100 + (buf[pos + 10] - '0') * 10 + (buf[pos + 11] - '0'); if (0 == num) *first_status = status; cl = NULL; for (i = pos; i + 15 <= pos + hdr_len; ++i) { if (mem_equal_ci (buf + i, "content-length:", 15)) { cl = buf + i + 15; break; } } if (NULL != cl) { while ((cl < buf + pos + hdr_len) && (' ' == *cl)) cl++; body_len = 0; while ((cl < buf + pos + hdr_len) && ('0' <= *cl) && ('9' >= *cl)) { body_len = body_len * 10 + (size_t) (*cl - '0'); cl++; } } if (pos + hdr_len + body_len > len) break; /* Body incomplete */ pos += hdr_len + body_len; num++; } return num; } /** * Switch a socket to the non-blocking mode. * * @param sk the socket to modify * @return non-zero on success */ static int set_nonblocking (MHD_socket sk) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (sk, F_GETFL); if (-1 == flags) return 0; return (-1 != fcntl (sk, F_SETFL, flags | O_NONBLOCK)) ? ! 0 : 0; #else /* ! MHD_POSIX_SOCKETS */ unsigned long mode = 1; return (0 == ioctlsocket (sk, FIONBIO, &mode)) ? ! 0 : 0; #endif /* ! MHD_POSIX_SOCKETS */ } static MHD_socket client_connect (void) { MHD_socket sk; struct sockaddr_in sa; const MHD_SCKT_OPT_BOOL_ on_val = 1; sk = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == sk) hard_error ("Cannot create the client socket"); #ifdef MHD_socket_nosignal_ if (! MHD_socket_nosignal_ (sk)) hard_error ("Cannot suppress SIGPIPE on the client socket"); #endif /* MHD_socket_nosignal_ */ if (0 != setsockopt (sk, IPPROTO_TCP, TCP_NODELAY, (const void *) &on_val, sizeof (on_val))) hard_error ("Cannot set the TCP_NODELAY option"); memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (global_port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != connect (sk, (struct sockaddr *) &sa, sizeof (sa))) hard_error ("Cannot connect() to the test daemon"); if (! set_nonblocking (sk)) hard_error ("Cannot switch the client socket to the non-blocking mode"); return sk; } /** * Send @a data and read the answer, driving the daemon with MHD_run() when * the profile asks for external polling. * * @param sk the client socket * @param data the request bytes * @param size the number of bytes in @a data * @param[out] r the result * @param min_resp stop once that many complete responses have been read * @param want_close keep reading until the peer closes the connection * @param read_answer if zero, close right after sending */ static void client_exchange (MHD_socket sk, const char *data, size_t size, struct client_result *r, unsigned int min_resp, int want_close, int read_answer) { const uint64_t start = now_ms (); size_t sent = 0; uint64_t quiet_since = 0; memset (r, 0, sizeof (*r)); while (1) { fd_set rs; fd_set ws; fd_set es; struct timeval tv; MHD_socket maxfd_mhd = MHD_INVALID_SOCKET; int maxfd; int sel; if (now_ms () - start >= READ_DEADLINE_MS) { r->timed_out = 1; break; } if ((sent >= size) && (! read_answer)) break; r->n_resp = count_responses (r->rx, r->rx_len, &r->first_status); if ((sent >= size) && (! want_close) && (r->n_resp >= min_resp)) { /* Everything that was expected has arrived; accept a short silence as "the server is done and keeps the connection alive". */ if (0 == quiet_since) quiet_since = now_ms (); else if (now_ms () - quiet_since >= READ_GRACE_MS) break; } else quiet_since = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); #if defined(MHD_POSIX_SOCKETS) if (FD_SETSIZE <= (int) sk) hard_error ("The client socket does not fit into fd_set"); #endif /* MHD_POSIX_SOCKETS */ if (! r->peer_closed) FD_SET (sk, &rs); if (sent < size) FD_SET (sk, &ws); maxfd = (int) sk; if (NULL != extern_daemon) { if (MHD_YES != MHD_get_fdset (extern_daemon, &rs, &ws, &es, &maxfd_mhd)) hard_error ("MHD_get_fdset() failed"); #ifndef MHD_WINSOCK_SOCKETS if ((int) maxfd_mhd > maxfd) maxfd = (int) maxfd_mhd; #endif /* ! MHD_WINSOCK_SOCKETS */ } tv.tv_sec = 0; tv.tv_usec = 2000; sel = select (maxfd + 1, &rs, &ws, &es, &tv); if ((0 > sel) && (EINTR != errno)) hard_error ("select() failed"); if (NULL != extern_daemon) MHD_run (extern_daemon); if (sent < size) { ssize_t s = MHD_send_ (sk, data + sent, size - sent); if (0 > s) { const int err = MHD_socket_get_error_ (); if (! (MHD_SCKT_ERR_IS_EINTR_ (err) || MHD_SCKT_ERR_IS_EAGAIN_ (err))) { /* MHD closed the connection early; that is an observation, not an error of the test. */ sent = size; r->peer_closed = 1; } } else sent += (size_t) s; } if ((! r->peer_closed) && (r->rx_len < sizeof (r->rx))) { ssize_t got = MHD_recv_ (sk, r->rx + r->rx_len, sizeof (r->rx) - r->rx_len); if (0 > got) { const int err = MHD_socket_get_error_ (); if (! (MHD_SCKT_ERR_IS_EINTR_ (err) || MHD_SCKT_ERR_IS_EAGAIN_ (err))) r->peer_closed = 1; /* A connection reset counts as "closed" */ } else if (0 == got) r->peer_closed = 1; else { r->rx_len += (size_t) got; quiet_since = 0; } } if (r->peer_closed && (sent >= size)) break; } r->n_resp = count_responses (r->rx, r->rx_len, &r->first_status); } /** * Let the daemon run for @a ms milliseconds without any client activity. * * @param ms the number of milliseconds to spend */ static void settle (unsigned int ms) { const uint64_t start = now_ms (); do { if (NULL != extern_daemon) MHD_run (extern_daemon); sleep_ms (1); } while (now_ms () - start < (uint64_t) ms); } /** * Wait until the daemon has finished tearing down all connections, so that * the server side observations are stable. * * @return non-zero on success, zero on timeout */ static int wait_conns_closed (void) { const uint64_t start = now_ms (); while (conn_closed != conn_started) { if (NULL != extern_daemon) MHD_run (extern_daemon); else sleep_ms (1); if (now_ms () - start > CLOSE_WAIT_MS) return 0; } return ! 0; } /* ------------------------------------------------------------------ */ /* One scenario against one profile */ /* ------------------------------------------------------------------ */ static void report_failure (const char *what, const char *exp, const char *got) { failures++; fprintf (stderr, "\nFAILED: %s\n", what); print_context (stderr); if (NULL != exp) fprintf (stderr, " expected:\n%s", exp); if (NULL != got) fprintf (stderr, " observed:\n%s", got); fflush (stderr); } /** * Statuses with which MHD legitimately refuses a request that does not fit * into the connection memory pool. A 400 is never one of them. * * @param status the status code of the first response * @return non-zero if the status is a resource limitation */ static int is_resource_status (int status) { return ((413 == status) || (414 == status) || (431 == status) || (500 == status) || (503 == status)) ? ! 0 : 0; } /** * Run one scenario against the running daemon. */ static void run_scenario (const struct scenario *s) { struct client_result cr; struct obs_buf got; MHD_socket sk; const size_t len = strlen (s->raw); int degraded; cur_scen = s; obs_reset (&srv_obs); srv_n_req = 0; srv_error = 0; combos++; sk = client_connect (); client_exchange (sk, s->raw, len, &cr, s->n_resp, (0 == s->alive) && (! s->close_after_send), s->close_after_send ? 0 : 1); (void) MHD_socket_close_ (sk); /* The server side observation is complete as soon as MHD has closed the connection or has answered everything that was expected: the request handler always runs before the reply is sent. Waiting for the whole connection teardown is therefore only useful when neither happened. MHD keeps a connection around for a while after an error reply in the 'epoll' modes, so an unconditional wait would cost seconds per scenario for no gain at all. */ if (s->close_after_send) settle (SETTLE_MS); /* Give MHD a chance to mis-parse the truncated stream */ else if ((! s->loose) && (! cr.peer_closed) && (cr.n_resp < s->n_resp)) { if (! wait_conns_closed ()) { fprintf (stderr, "WARNING: timeout waiting for the connection teardown " "(started=%u closed=%u).\n", conn_started, conn_closed); print_context (stderr); } } obs_reset (&got); obs_addf (&got, "%s", srv_obs.d); if (0 != srv_error) { report_failure ("the request handler could not queue a response", NULL, NULL); return; } if (s->loose) { /* The daemon survived, which is all this probe asks for. */ if (1 < verbose) printf (" %-22s survived (loose probe)\n", s->name); return; } /* A connection memory pool that is too small for the request is a legitimate resource limitation: MHD then answers 413/414/431/500 without ever invoking the handler, or it cannot even build the reply header and closes the connection without answering a request it did parse. Everything MHD *did* parse must still match, and MHD may never parse more requests than the stream contains. A 400 Bad Request is never accepted as a resource limitation. */ degraded = 0; if (! s->close_after_send) { if ((0 != cr.n_resp) && (cr.n_resp < s->n_resp) && is_resource_status (cr.first_status)) degraded = 1; else if ((0 != cr.n_resp) && (0 != strcmp (s->exp, got.d)) && is_resource_status (cr.first_status)) degraded = 1; else if ((0 == cr.n_resp) && (0 != s->n_resp) && cr.peer_closed) degraded = 1; } if (degraded) { combos_degraded++; if (0 != memcmp (s->exp, got.d, strlen (got.d))) report_failure ("a request parsed with a small memory pool differs " "from the expectation", s->exp, got.d); else if (verbose) printf (" %-22s degraded by the memory pool, relaxed checking\n", s->name); return; } if (0 != strcmp (s->exp, got.d)) { report_failure ("the parsed requests do not match the expectation", s->exp, got.d); return; } if (srv_n_req != s->n_req) { char msg[128]; snprintf (msg, sizeof (msg), "MHD parsed %u request(s), %u expected", (unsigned int) srv_n_req, s->n_req); report_failure (msg, NULL, NULL); return; } if (s->close_after_send) { if (1 < verbose) printf (" %-22s ok (no answer expected)\n", s->name); return; } if (cr.n_resp != s->n_resp) { char msg[160]; snprintf (msg, sizeof (msg), "the client saw %u response(s), %u expected%s", cr.n_resp, s->n_resp, cr.timed_out ? " (timed out)" : ""); report_failure (msg, NULL, cr.rx_len ? cr.rx : "(nothing)"); return; } if ((0 != s->status) && (cr.first_status != s->status)) { char msg[128]; snprintf (msg, sizeof (msg), "the first response has status %d, %d expected", cr.first_status, s->status); report_failure (msg, NULL, cr.rx); return; } if (s->alive && cr.peer_closed) { report_failure ("MHD closed a connection that had to stay alive", NULL, NULL); return; } if ((! s->alive) && (! cr.peer_closed)) { report_failure ("MHD kept a connection that had to be closed", NULL, NULL); return; } if (1 < verbose) printf (" %-22s ok\n", s->name); } /* ------------------------------------------------------------------ */ /* Main test driver */ /* ------------------------------------------------------------------ */ /** * Start a daemon for @a prof. * * @param prof the profile to apply * @return the daemon, or NULL if it cannot be started */ static struct MHD_Daemon * start_daemon_for (const struct MHD_OptMatrixProfile *prof) { struct MHD_OptionItem ops[8]; struct MHD_Daemon *d; unsigned int n; unsigned int flags; n = mhd_opt_matrix_fill_options (prof, ops, (unsigned int) (sizeof(ops) / sizeof(ops[0]))); if (0 == n) hard_error ("The option array is too small"); if (mhd_opt_matrix_is_external (prof)) { /* Only meaningful without an internal polling thread; MHD complains about the option in every other mode. */ ops[n - 1].option = MHD_OPTION_APP_FD_SETSIZE; ops[n - 1].value = (intptr_t) (FD_SETSIZE); ops[n - 1].ptr_value = NULL; ops[n].option = MHD_OPTION_END; ops[n].value = 0; ops[n].ptr_value = NULL; } flags = mhd_opt_matrix_daemon_flags (prof, MHD_USE_ERROR_LOG, ! 0); /* MHD_OPTION_EXTERNAL_LOGGER has to be the first option, otherwise the complaints about the options that follow it go to the standard logger. */ d = MHD_start_daemon (flags, 0, NULL, NULL, &ahc_record, NULL, MHD_OPTION_EXTERNAL_LOGGER, &test_log, NULL, MHD_OPTION_ARRAY, ops, MHD_OPTION_NOTIFY_CONNECTION, &conn_notify, NULL, MHD_OPTION_NOTIFY_COMPLETED, &req_completed, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) DAEMON_TIMEOUT, MHD_OPTION_END); return d; } /** * Run the whole battery against one profile. * * @param prof the profile to test * @return zero on success, 99 if the daemon could not be started */ static int run_profile (const struct MHD_OptMatrixProfile *prof) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; size_t i; int discp; cur_prof = prof; (void) mhd_opt_matrix_describe (prof, cur_prof_desc, sizeof(cur_prof_desc)); if (! mhd_opt_matrix_profile_supported (prof)) { prof_skipped++; if (verbose) printf ("--- profile %s SKIPPED (not supported by this build) ---\n", cur_prof_desc); return 0; } if (verbose) { printf ("--- profile %s ---\n", cur_prof_desc); fflush (stdout); } conn_started = 0; conn_closed = 0; extern_daemon = NULL; d = start_daemon_for (prof); if (NULL == d) { fprintf (stderr, "Failed to start the daemon for profile %s.\n", cur_prof_desc); return 99; } if (mhd_opt_matrix_is_external (prof)) extern_daemon = d; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port)) { MHD_stop_daemon (d); fprintf (stderr, "Cannot get the port of the daemon for profile %s.\n", cur_prof_desc); return 99; } global_port = dinfo->port; /* Not prof->discipline_lvl: MHD_OPTION_STRICT_FOR_CLIENT maps its value, so the "legacy-lax" profile really runs at level -3 although it asks for -1. Deciding what a request must do from the configured value instead of from the effective one is a trap: MHD_OPTION_STRICT_FOR_CLIENT maps every value of -1 or below to level -3. */ discp = mhd_opt_matrix_effective_discipline (prof); for (i = 0; i < NUM_SCENARIOS; ++i) { const struct scenario *const s = scenarios + i; if ((NULL != only_scen) && (0 != strcmp (only_scen, s->name))) continue; if ((discp < s->min_discp) || (discp > s->max_discp)) { scen_skipped++; if (1 < verbose) printf (" %-22s skipped (needs discipline level %d..%d)\n", s->name, s->min_discp, s->max_discp); continue; } run_scenario (s); if (MAX_FAILURES < failures) break; } cur_scen = NULL; extern_daemon = NULL; MHD_stop_daemon (d); return 0; } int main (int argc, char *const *argv) { const uint64_t t_start = now_ms (); const struct MHD_OptMatrixProfile *env_prof; const char *only = NULL; unsigned int num_prof; unsigned int i; int ret; for (i = 1; i < (unsigned int) argc; ++i) { if ((0 == strcmp (argv[i], "-v")) || (0 == strcmp (argv[i], "--verbose"))) verbose++; else if (0 == strncmp (argv[i], "--profile=", 10)) only = argv[i] + 10; else if (0 == strncmp (argv[i], "--scenario=", 11)) only_scen = argv[i] + 11; else if (0 == strcmp (argv[i], "--list-profiles")) { unsigned int p; for (p = 0; p < mhd_opt_matrix_num_profiles (); ++p) printf ("%s\n", mhd_opt_matrix_profile (p)->name); return 0; } } strcpy (cur_prof_desc, "(not started)"); #if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE)) { if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) hard_error ("Cannot suppress the SIGPIPE signal"); } #endif /* HAVE_SIGNAL_H && SIGPIPE */ #if defined(HAVE_SIGNAL_H) && defined(SIGABRT) (void) signal (SIGABRT, &abort_handler); #endif /* HAVE_SIGNAL_H && SIGABRT */ /* Deliberately NOT mhd_panic_tripwire.h: this test installs its own panic and SIGABRT handlers, which print the failing input and the daemon options along with the diagnostic. That context is worth more here than the generic tripwire, and the two would collide (whichever runs last wins). See TESTING.md, P5. */ MHD_set_panic_func (&test_panic, NULL); mhd_opt_matrix_print_notice ("test_option_matrix"); env_prof = mhd_opt_matrix_from_env (); if (NULL != only) { /* The command line wins over the environment. */ env_prof = mhd_opt_matrix_lookup (only); if (NULL == env_prof) { fprintf (stderr, "Unknown profile '%s'.\n", only); return 99; } } if (NULL != env_prof) { if (! mhd_opt_matrix_profile_supported (env_prof)) { char desc[256]; printf ("test_option_matrix: the selected profile %s is not supported " "by this build, the test is skipped.\n", mhd_opt_matrix_describe (env_prof, desc, sizeof(desc))); return 77; } num_prof = 1; ret = run_profile (env_prof); if (0 != ret) return ret; } else { num_prof = mhd_opt_matrix_num_profiles (); for (i = 0; i < num_prof; ++i) { ret = run_profile (mhd_opt_matrix_profile (i)); if (0 != ret) return ret; if (MAX_FAILURES < failures) break; } if (num_prof == prof_skipped) { printf ("test_option_matrix: no profile of the matrix is supported by " "this build, the test is skipped.\n"); return 77; } } printf ("\ntest_option_matrix: %u profile(s) (%lu skipped), " "%u scenario(s), %lu combinations executed " "(%lu pool-limited, %lu out of the discipline range), %.1f s\n", num_prof, prof_skipped, (unsigned int) NUM_SCENARIOS, combos, combos_degraded, scen_skipped, (double) (now_ms () - t_start) / 1000.0); if (0 != failures) { printf ("test_option_matrix: FAILED (%lu failure(s))\n", failures); fflush (stdout); return 1; } printf ("test_option_matrix: PASSED\n"); fflush (stdout); return 0; } libmicrohttpd-1.0.10/src/microhttpd/mhd_byteorder.h0000644000175000017500000001357015035214301016062 /* This file is part of libmicrohttpd Copyright (C) 2015-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/mhd_byteorder.h * @brief macro definitions for host byte order * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_BYTEORDER_H #define MHD_BYTEORDER_H #include "mhd_options.h" #include #ifdef HAVE_ENDIAN_H #include #endif #ifdef HAVE_SYS_PARAM_H #include #endif #ifdef HAVE_MACHINE_ENDIAN_H #include #endif #ifdef HAVE_SYS_ENDIAN_H #include #endif #ifdef HAVE_SYS_TYPES_H #include #endif #ifdef HAVE_SYS_BYTEORDER_H #include #endif #ifdef HAVE_SYS_MACHINE_H #include #endif #ifdef HAVE_MACHINE_PARAM_H #include #endif #ifdef HAVE_SYS_ISA_DEFS_H #include #endif #define _MHD_BIG_ENDIAN 1234 #define _MHD_LITTLE_ENDIAN 4321 #define _MHD_PDP_ENDIAN 2143 #if defined(__BYTE_ORDER__) #if defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == \ __ORDER_LITTLE_ENDIAN__ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(__ORDER_PDP_ENDIAN__) && __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__ #define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN #endif /* __BYTE_ORDER__ == __ORDER_PDP_ENDIAN__ */ #elif defined(__BYTE_ORDER) #if defined(__BIG_ENDIAN) && __BYTE_ORDER == __BIG_ENDIAN #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(__PDP_ENDIAN) && __BYTE_ORDER == __PDP_ENDIAN #define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN #endif /* __BYTE_ORDER == __PDP_ENDIAN */ #elif defined(BYTE_ORDER) #if defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(LITTLE_ENDIAN) && BYTE_ORDER == LITTLE_ENDIAN #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(PDP_ENDIAN) && BYTE_ORDER == PDP_ENDIAN #define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN #endif /* __BYTE_ORDER == _PDP_ENDIAN */ #elif defined(_BYTE_ORDER) #if defined(_BIG_ENDIAN) && _BYTE_ORDER == _BIG_ENDIAN #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(_LITTLE_ENDIAN) && _BYTE_ORDER == _LITTLE_ENDIAN #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(_PDP_ENDIAN) && _BYTE_ORDER == _PDP_ENDIAN #define _MHD_BYTE_ORDER _MHD_PDP_ENDIAN #endif /* _BYTE_ORDER == _PDP_ENDIAN */ #endif /* _BYTE_ORDER */ #ifndef _MHD_BYTE_ORDER /* Byte order specification didn't detected in system headers */ /* Try some guessing */ #if (defined(__BIG_ENDIAN__) && ! defined(__LITTLE_ENDIAN__)) || \ (defined(_BIG_ENDIAN) && ! defined(_LITTLE_ENDIAN)) /* Seems that we are on big endian platform */ #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif (defined(__LITTLE_ENDIAN__) && ! defined(__BIG_ENDIAN__)) || \ (defined(_LITTLE_ENDIAN) && ! defined(_BIG_ENDIAN)) /* Seems that we are on little endian platform */ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || \ defined(__x86_64) || \ defined(_M_X64) || defined(_M_AMD64) || defined(i386) || defined(__i386) || \ defined(__i386__) || defined(__i486__) || defined(__i586__) || \ defined(__i686__) || \ defined(_M_IX86) || defined(_X86_) || defined(__THW_INTEL__) /* x86 family is little endian */ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(__ARMEB__) || defined(__THUMBEB__) || defined(__AARCH64EB__) || \ defined(_MIPSEB) || defined(__MIPSEB) || defined(__MIPSEB__) /* Looks like we are on ARM/MIPS in big endian mode */ #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(__ARMEL__) || defined(__THUMBEL__) || defined(__AARCH64EL__) || \ defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) /* Looks like we are on ARM/MIPS in little endian mode */ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(__m68k__) || defined(M68000) || defined(__hppa__) || \ defined(__hppa) || \ defined(__HPPA__) || defined(__370__) || defined(__THW_370__) || \ defined(__s390__) || defined(__s390x__) || defined(__SYSC_ZARCH__) /* Looks like we are on big endian platform */ #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #elif defined(__ia64__) || defined(_IA64) || defined(__IA64__) || \ defined(__ia64) || \ defined(_M_IA64) || defined(__itanium__) || defined(__bfin__) || \ defined(__BFIN__) || defined(bfin) || defined(BFIN) /* Looks like we are on little endian platform */ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(_WIN32) /* W32 is always little endian on all platforms */ #define _MHD_BYTE_ORDER _MHD_LITTLE_ENDIAN #elif defined(WORDS_BIGENDIAN) /* Use byte order detected by configure */ #define _MHD_BYTE_ORDER _MHD_BIG_ENDIAN #endif /* _WIN32 */ #endif /* !_MHD_BYTE_ORDER */ #ifdef _MHD_BYTE_ORDER /* Some safety checks */ #if defined(WORDS_BIGENDIAN) && _MHD_BYTE_ORDER != _MHD_BIG_ENDIAN #error \ Configure detected big endian byte order but headers specify different byte order #elif ! defined(WORDS_BIGENDIAN) && _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN #error \ Configure did not detect big endian byte order but headers specify big endian byte order #endif /* !WORDS_BIGENDIAN && _MHD_BYTE_ORDER == _MHD_BIG_ENDIAN */ #endif /* _MHD_BYTE_ORDER */ #endif /* !MHD_BYTEORDER_H */ libmicrohttpd-1.0.10/src/microhttpd/response.c0000664000175000017500000022751415223423441015101 /* This file is part of libmicrohttpd Copyright (C) 2007-2021 Daniel Pittman and Christian Grothoff Copyright (C) 2015-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file response.c * @brief Methods for managing response objects * @author Daniel Pittman * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #define MHD_NO_DEPRECATION 1 #include "mhd_options.h" #ifdef HAVE_SYS_IOCTL_H #include #endif /* HAVE_SYS_IOCTL_H */ #if defined(_WIN32) && ! defined(__CYGWIN__) #include #endif /* _WIN32 && !__CYGWIN__ */ #include "internal.h" #include "response.h" #include "mhd_limits.h" #include "mhd_sockets.h" #include "mhd_itc.h" #include "mhd_str.h" #include "connection.h" #include "memorypool.h" #include "mhd_send.h" #include "mhd_compat.h" #include "mhd_assert.h" #if defined(MHD_W32_MUTEX_) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif /* MHD_W32_MUTEX_ */ #if defined(_WIN32) #include /* for lseek(), read() */ #endif /* _WIN32 */ /** * Size of single file read operation for * file-backed responses. */ #ifndef MHD_FILE_READ_BLOCK_SIZE #ifdef _WIN32 #define MHD_FILE_READ_BLOCK_SIZE 16384 /* 16k */ #else /* _WIN32 */ #define MHD_FILE_READ_BLOCK_SIZE 4096 /* 4k */ #endif /* _WIN32 */ #endif /* !MHD_FD_BLOCK_SIZE */ /** * Insert a new header at the first position of the response */ #define _MHD_insert_header_first(presponse, phdr) do { \ mhd_assert (NULL == phdr->next); \ mhd_assert (NULL == phdr->prev); \ if (NULL == presponse->first_header) \ { \ mhd_assert (NULL == presponse->last_header); \ presponse->first_header = phdr; \ presponse->last_header = phdr; \ } \ else \ { \ mhd_assert (NULL != presponse->last_header); \ presponse->first_header->prev = phdr; \ phdr->next = presponse->first_header; \ presponse->first_header = phdr; \ } \ } while (0) /** * Insert a new header at the last position of the response */ #define _MHD_insert_header_last(presponse, phdr) do { \ mhd_assert (NULL == phdr->next); \ mhd_assert (NULL == phdr->prev); \ if (NULL == presponse->last_header) \ { \ mhd_assert (NULL == presponse->first_header); \ presponse->last_header = phdr; \ presponse->first_header = phdr; \ } \ else \ { \ mhd_assert (NULL != presponse->first_header); \ presponse->last_header->next = phdr; \ phdr->prev = presponse->last_header; \ presponse->last_header = phdr; \ } \ } while (0) /** * Remove a header from the response */ #define _MHD_remove_header(presponse, phdr) do { \ mhd_assert (NULL != presponse->first_header); \ mhd_assert (NULL != presponse->last_header); \ if (NULL == phdr->prev) \ { \ mhd_assert (phdr == presponse->first_header); \ presponse->first_header = phdr->next; \ } \ else \ { \ mhd_assert (phdr != presponse->first_header); \ mhd_assert (phdr == phdr->prev->next); \ phdr->prev->next = phdr->next; \ } \ if (NULL == phdr->next) \ { \ mhd_assert (phdr == presponse->last_header); \ presponse->last_header = phdr->prev; \ } \ else \ { \ mhd_assert (phdr != presponse->last_header); \ mhd_assert (phdr == phdr->next->prev); \ phdr->next->prev = phdr->prev; \ } \ } while (0) /** * Add preallocated strings a header or footer line to the response without * checking. * * Header/footer strings are not checked and assumed to be correct. * * The string must not be statically allocated! * The strings must be malloc()'ed and zero terminated. The strings will * be free()'ed when the response is destroyed. * * @param response response to add a header to * @param kind header or footer * @param header the header string to add, must be malloc()'ed and * zero-terminated * @param header_len the length of the @a header * @param content the value string to add, must be malloc()'ed and * zero-terminated * @param content_len the length of the @a content */ bool MHD_add_response_entry_no_alloc_ (struct MHD_Response *response, enum MHD_ValueKind kind, char *header, size_t header_len, char *content, size_t content_len) { struct MHD_HTTP_Res_Header *hdr; mhd_assert (0 != header_len); mhd_assert (0 != content_len); if (NULL == (hdr = MHD_calloc_ (1, sizeof (struct MHD_HTTP_Res_Header)))) return false; hdr->header = header; hdr->header_size = header_len; hdr->value = content; hdr->value_size = content_len; hdr->kind = kind; _MHD_insert_header_last (response, hdr); return true; /* Success exit point */ } /** * Add a header or footer line to the response without checking. * * It is assumed that parameters are correct. * * @param response response to add a header to * @param kind header or footer * @param header the header to add, does not need to be zero-terminated * @param header_len the length of the @a header * @param content value to add, does not need to be zero-terminated * @param content_len the length of the @a content * @return false on error (like out-of-memory), * true if succeed */ bool MHD_add_response_entry_no_check_ (struct MHD_Response *response, enum MHD_ValueKind kind, const char *header, size_t header_len, const char *content, size_t content_len) { char *header_malloced; char *value_malloced; mhd_assert (0 != header_len); mhd_assert (0 != content_len); header_malloced = malloc (header_len + 1); if (NULL == header_malloced) return false; memcpy (header_malloced, header, header_len); header_malloced[header_len] = 0; value_malloced = malloc (content_len + 1); if (NULL != value_malloced) { memcpy (value_malloced, content, content_len); value_malloced[content_len] = 0; if (MHD_add_response_entry_no_alloc_ (response, kind, header_malloced, header_len, value_malloced, content_len)) return true; /* Success exit point */ free (value_malloced); } free (header_malloced); return false; /* Failure exit point */ } /** * Add a header or footer line to the response. * * @param header the header to add, does not need to be zero-terminated * @param header_len the length of the @a header * @param content value to add, does not need to be zero-terminated * @param content_len the length of the @a content * @return false on error (out-of-memory, invalid header or content), * true if succeed */ static bool add_response_entry_n (struct MHD_Response *response, enum MHD_ValueKind kind, const char *header, size_t header_len, const char *content, size_t content_len) { if (NULL == response) return false; if (0 == header_len) return false; if (0 == content_len) return false; if (NULL != memchr (header, '\t', header_len)) return false; if (NULL != memchr (header, ' ', header_len)) return false; if (NULL != memchr (header, '\r', header_len)) return false; if (NULL != memchr (header, '\n', header_len)) return false; if (NULL != memchr (content, '\r', content_len)) return false; if (NULL != memchr (content, '\n', content_len)) return false; return MHD_add_response_entry_no_check_ (response, kind, header, header_len, content, content_len); } /** * Add a header or footer line to the response. * * @param response response to add a header to * @param kind header or footer * @param header the header to add * @param content value to add * @return #MHD_NO on error (i.e. invalid header or content format). */ static enum MHD_Result add_response_entry (struct MHD_Response *response, enum MHD_ValueKind kind, const char *header, const char *content) { size_t header_len; size_t content_len; if (NULL == content) return MHD_NO; if (NULL == header) return MHD_NO; header_len = strlen (header); content_len = strlen (content); return add_response_entry_n (response, kind, header, header_len, content, content_len) ? MHD_YES : MHD_NO; } /** * Add "Connection:" header to the response with special processing. * * "Connection:" header value will be combined with any existing "Connection:" * header, "close" token (if any) will be de-duplicated and moved to the first * position. * * @param response the response to add a header to * @param value the value to add * @return #MHD_NO on error (no memory). */ static enum MHD_Result add_response_header_connection (struct MHD_Response *response, const char *value) { static const char *key = MHD_HTTP_HEADER_CONNECTION; /** the length of the "Connection" key */ static const size_t key_len = MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONNECTION); size_t value_len; /**< the length of the @a value */ size_t old_value_len; /**< the length of the existing "Connection" value */ size_t buf_size; /**< the size of the buffer */ size_t norm_len; /**< the length of the normalised value */ char *buf; /**< the temporal buffer */ struct MHD_HTTP_Res_Header *hdr; /**< existing "Connection" header */ bool value_has_close; /**< the @a value has "close" token */ bool already_has_close; /**< existing "Connection" header has "close" token */ size_t pos = 0; /**< position of addition in the @a buf */ if ( (NULL != strchr (value, '\r')) || (NULL != strchr (value, '\n')) ) return MHD_NO; if (0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) { hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND, key, key_len); already_has_close = (0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)); mhd_assert (NULL != hdr); mhd_assert (already_has_close == (0 == memcmp (hdr->value, "close", 5))); } else { hdr = NULL; already_has_close = false; mhd_assert (NULL == MHD_get_response_element_n_ (response, MHD_HEADER_KIND, key, key_len)); mhd_assert (0 == (response->flags_auto & MHD_RAF_HAS_CONNECTION_CLOSE)); } if (NULL != hdr) old_value_len = hdr->value_size + 2; /* additional size for ", " */ else old_value_len = 0; value_len = strlen (value); if (value_len >= SSIZE_MAX) return MHD_NO; /* Additional space for normalisation and zero-termination */ norm_len = value_len + value_len / 2 + 1; if (norm_len >= SSIZE_MAX) return MHD_NO; buf_size = old_value_len + (size_t) norm_len; buf = malloc (buf_size); if (NULL == buf) return MHD_NO; if (1) { /* local scope */ ssize_t norm_len_s = (ssize_t) norm_len; /* Remove "close" token (if any), it will be moved to the front */ value_has_close = MHD_str_remove_token_caseless_ (value, value_len, "close", MHD_STATICSTR_LEN_ ( \ "close"), buf + old_value_len, &norm_len_s); mhd_assert (0 <= norm_len_s); if (0 > norm_len_s) { /* Must never happen with realistic sizes */ free (buf); return MHD_NO; } else norm_len = (size_t) norm_len_s; } #ifdef UPGRADE_SUPPORT if ( (NULL != response->upgrade_handler) && value_has_close) { /* The "close" token cannot be used with connection "upgrade" */ free (buf); return MHD_NO; } #endif /* UPGRADE_SUPPORT */ if (0 != norm_len) MHD_str_remove_tokens_caseless_ (buf + old_value_len, &norm_len, "keep-alive", MHD_STATICSTR_LEN_ ("keep-alive")); if (0 == norm_len) { /* New value is empty after normalisation */ if (! value_has_close) { /* The new value had no tokens */ free (buf); return MHD_NO; } if (already_has_close) { /* The "close" token is already present, nothing to modify */ free (buf); return MHD_YES; } } /* Add "close" token if required */ if (value_has_close && ! already_has_close) { /* Need to insert "close" token at the first position */ mhd_assert (buf_size >= old_value_len + norm_len \ + MHD_STATICSTR_LEN_ ("close, ") + 1); if (0 != norm_len) memmove (buf + MHD_STATICSTR_LEN_ ("close, ") + old_value_len, buf + old_value_len, norm_len + 1); memcpy (buf, "close", MHD_STATICSTR_LEN_ ("close")); pos += MHD_STATICSTR_LEN_ ("close"); } /* Add old value tokens (if any) */ if (0 != old_value_len) { if (0 != pos) { buf[pos++] = ','; buf[pos++] = ' '; } memcpy (buf + pos, hdr->value, hdr->value_size); pos += hdr->value_size; } /* Add new value token (if any) */ if (0 != norm_len) { if (0 != pos) { buf[pos++] = ','; buf[pos++] = ' '; } /* The new value tokens must be already at the correct position */ mhd_assert ((value_has_close && ! already_has_close) ? \ (MHD_STATICSTR_LEN_ ("close, ") + old_value_len == pos) : \ (old_value_len == pos)); pos += norm_len; } mhd_assert (buf_size > pos); buf[pos] = 0; /* Null terminate the result */ if (NULL == hdr) { struct MHD_HTTP_Res_Header *new_hdr; /**< new "Connection" header */ /* Create new response header entry */ new_hdr = MHD_calloc_ (1, sizeof (struct MHD_HTTP_Res_Header)); if (NULL != new_hdr) { new_hdr->header = malloc (key_len + 1); if (NULL != new_hdr->header) { memcpy (new_hdr->header, key, key_len + 1); new_hdr->header_size = key_len; new_hdr->value = buf; new_hdr->value_size = pos; new_hdr->kind = MHD_HEADER_KIND; if (value_has_close) response->flags_auto = (MHD_RAF_HAS_CONNECTION_HDR | MHD_RAF_HAS_CONNECTION_CLOSE); else response->flags_auto = MHD_RAF_HAS_CONNECTION_HDR; _MHD_insert_header_first (response, new_hdr); return MHD_YES; } free (new_hdr); } free (buf); return MHD_NO; } /* Update existing header entry */ free (hdr->value); hdr->value = buf; hdr->value_size = pos; if (value_has_close && ! already_has_close) response->flags_auto |= MHD_RAF_HAS_CONNECTION_CLOSE; return MHD_YES; } /** * Remove tokens from "Connection:" header of the response. * * Provided tokens will be removed from "Connection:" header value. * * @param response the response to manipulate "Connection:" header * @param value the tokens to remove * @return #MHD_NO on error (no headers or tokens found). */ static enum MHD_Result del_response_header_connection (struct MHD_Response *response, const char *value) { struct MHD_HTTP_Res_Header *hdr; /**< existing "Connection" header */ hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_CONNECTION)); if (NULL == hdr) return MHD_NO; if (! MHD_str_remove_tokens_caseless_ (hdr->value, &hdr->value_size, value, strlen (value))) return MHD_NO; if (0 == hdr->value_size) { _MHD_remove_header (response, hdr); free (hdr->value); free (hdr->header); free (hdr); response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_HDR | (enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); } else { hdr->value[hdr->value_size] = 0; /* Null-terminate the result */ if (0 != (response->flags_auto & ((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE))) { if (MHD_STATICSTR_LEN_ ("close") == hdr->value_size) { if (0 != memcmp (hdr->value, "close", MHD_STATICSTR_LEN_ ("close"))) response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); } else if (MHD_STATICSTR_LEN_ ("close, ") < hdr->value_size) { if (0 != memcmp (hdr->value, "close, ", MHD_STATICSTR_LEN_ ("close, "))) response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); } else response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONNECTION_CLOSE); } } return MHD_YES; } /** * Add a header line to the response. * * When reply is generated with queued response, some headers are generated * automatically. Automatically generated headers are only sent to the client, * but not added back to the response object. * * The list of automatic headers: * + "Date" header is added automatically unless already set by * this function * @see #MHD_USE_SUPPRESS_DATE_NO_CLOCK * + "Content-Length" is added automatically when required, attempt to set * it manually by this function is ignored. * @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH * + "Transfer-Encoding" with value "chunked" is added automatically, * when chunked transfer encoding is used automatically. Same header with * the same value can be set manually by this function to enforce chunked * encoding, however for HTTP/1.0 clients chunked encoding will not be used * and manually set "Transfer-Encoding" header is automatically removed * for HTTP/1.0 clients * + "Connection" may be added automatically with value "Keep-Alive" (only * for HTTP/1.0 clients) or "Close". The header "Connection" with value * "Close" could be set by this function to enforce closure of * the connection after sending this response. "Keep-Alive" cannot be * enforced and will be removed automatically. * @see #MHD_RF_SEND_KEEP_ALIVE_HEADER * * Some headers are pre-processed by this function: * * "Connection" headers are combined into single header entry, value is * normilised, "Keep-Alive" tokens are removed. * * "Transfer-Encoding" header: the only one header is allowed, the only * allowed value is "chunked". * * "Date" header: the only one header is allowed, the second added header * replaces the first one. * * "Content-Length" application-defined header is not allowed. * @see #MHD_RF_INSANITY_HEADER_CONTENT_LENGTH * * Headers are used in order as they were added. * * @param response the response to add a header to * @param header the header name to add, no need to be static, an internal copy * will be created automatically * @param content the header value to add, no need to be static, an internal * copy will be created automatically * @return #MHD_YES on success, * #MHD_NO on error (i.e. invalid header or content format), * or out of memory * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_add_response_header (struct MHD_Response *response, const char *header, const char *content) { if (MHD_str_equal_caseless_ (header, MHD_HTTP_HEADER_CONNECTION)) return add_response_header_connection (response, content); if (MHD_str_equal_caseless_ (header, MHD_HTTP_HEADER_TRANSFER_ENCODING)) { if (! MHD_str_equal_caseless_ (content, "chunked")) return MHD_NO; /* Only "chunked" encoding is allowed */ if (0 != (response->flags_auto & MHD_RAF_HAS_TRANS_ENC_CHUNKED)) return MHD_YES; /* Already has "chunked" encoding header */ if ( (0 != (response->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) && (0 == (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) ) return MHD_NO; /* Has "Content-Length" header and no "Insanity" flag */ if (MHD_NO != add_response_entry (response, MHD_HEADER_KIND, header, content)) { response->flags_auto |= MHD_RAF_HAS_TRANS_ENC_CHUNKED; return MHD_YES; } return MHD_NO; } if (MHD_str_equal_caseless_ (header, MHD_HTTP_HEADER_DATE)) { if (0 != (response->flags_auto & MHD_RAF_HAS_DATE_HDR)) { struct MHD_HTTP_Res_Header *hdr; hdr = MHD_get_response_element_n_ (response, MHD_HEADER_KIND, MHD_HTTP_HEADER_DATE, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_DATE)); mhd_assert (NULL != hdr); _MHD_remove_header (response, hdr); if (NULL != hdr->value) free (hdr->value); free (hdr->header); free (hdr); } if (MHD_NO != add_response_entry (response, MHD_HEADER_KIND, header, content)) { response->flags_auto |= MHD_RAF_HAS_DATE_HDR; return MHD_YES; } return MHD_NO; } if (MHD_str_equal_caseless_ (header, MHD_HTTP_HEADER_CONTENT_LENGTH)) { /* Generally MHD sets automatically correct "Content-Length" always when * needed. * Custom "Content-Length" header is allowed only in special cases. */ if ( (0 != (MHD_RF_INSANITY_HEADER_CONTENT_LENGTH & response->flags)) || ((0 != (MHD_RF_HEAD_ONLY_RESPONSE & response->flags)) && (0 == (response->flags_auto & (MHD_RAF_HAS_TRANS_ENC_CHUNKED | MHD_RAF_HAS_CONTENT_LENGTH)))) ) { if (MHD_NO != add_response_entry (response, MHD_HEADER_KIND, header, content)) { response->flags_auto |= MHD_RAF_HAS_CONTENT_LENGTH; return MHD_YES; } } return MHD_NO; } return add_response_entry (response, MHD_HEADER_KIND, header, content); } /** * Add a footer line to the response. * * @param response response to remove a header from * @param footer the footer to delete * @param content value to delete * @return #MHD_NO on error (i.e. invalid footer or content format). * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_add_response_footer (struct MHD_Response *response, const char *footer, const char *content) { return add_response_entry (response, MHD_FOOTER_KIND, footer, content); } /** * Delete a header (or footer) line from the response. * * For "Connection" headers this function remove all tokens from existing * value. Successful result means that at least one token has been removed. * If all tokens are removed from "Connection" header, the empty "Connection" * header removed. * * @param response response to remove a header from * @param header the header to delete * @param content value to delete * @return #MHD_NO on error (no such header known) * @ingroup response */ _MHD_EXTERN enum MHD_Result MHD_del_response_header (struct MHD_Response *response, const char *header, const char *content) { struct MHD_HTTP_Res_Header *pos; size_t header_len; size_t content_len; if ( (NULL == header) || (NULL == content) ) return MHD_NO; header_len = strlen (header); if ((0 != (response->flags_auto & MHD_RAF_HAS_CONNECTION_HDR)) && (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONNECTION) == header_len) && MHD_str_equal_caseless_bin_n_ (header, MHD_HTTP_HEADER_CONNECTION, header_len)) return del_response_header_connection (response, content); content_len = strlen (content); pos = response->first_header; while (NULL != pos) { if ((header_len == pos->header_size) && (content_len == pos->value_size) && (0 == memcmp (header, pos->header, header_len)) && (0 == memcmp (content, pos->value, content_len))) { _MHD_remove_header (response, pos); free (pos->header); free (pos->value); free (pos); if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING) == header_len) && MHD_str_equal_caseless_bin_n_ (header, MHD_HTTP_HEADER_TRANSFER_ENCODING, header_len) ) response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_TRANS_ENC_CHUNKED); else if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_DATE) == header_len) && MHD_str_equal_caseless_bin_n_ (header, MHD_HTTP_HEADER_DATE, header_len) ) response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_DATE_HDR); else if ( (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH) == header_len) && MHD_str_equal_caseless_bin_n_ (header, MHD_HTTP_HEADER_CONTENT_LENGTH, header_len) ) { if (NULL == MHD_get_response_element_n_ (response, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH, header_len)) response->flags_auto &= ~((enum MHD_ResponseAutoFlags) MHD_RAF_HAS_CONTENT_LENGTH); } return MHD_YES; } pos = pos->next; } return MHD_NO; } /** * Get all of the headers (and footers) added to a response. * * @param response response to query * @param iterator callback to call on each header; * maybe NULL (then just count headers) * @param iterator_cls extra argument to @a iterator * @return number of entries iterated over * @ingroup response */ _MHD_EXTERN int MHD_get_response_headers (struct MHD_Response *response, MHD_KeyValueIterator iterator, void *iterator_cls) { int numHeaders = 0; struct MHD_HTTP_Res_Header *pos; for (pos = response->first_header; NULL != pos; pos = pos->next) { numHeaders++; if ((NULL != iterator) && (MHD_NO == iterator (iterator_cls, pos->kind, pos->header, pos->value))) break; } return numHeaders; } /** * Get a particular header (or footer) from the response. * * @param response response to query * @param key which header to get * @return NULL if header does not exist * @ingroup response */ _MHD_EXTERN const char * MHD_get_response_header (struct MHD_Response *response, const char *key) { struct MHD_HTTP_Res_Header *pos; size_t key_size; if (NULL == key) return NULL; key_size = strlen (key); for (pos = response->first_header; NULL != pos; pos = pos->next) { if ((pos->header_size == key_size) && (MHD_str_equal_caseless_bin_n_ (pos->header, key, pos->header_size))) return pos->value; } return NULL; } /** * Get a particular header (or footer) element from the response. * * Function returns the first found element. * @param response response to query * @param kind the kind of element: header or footer * @param key the key which header to get * @param key_len the length of the @a key * @return NULL if header element does not exist * @ingroup response */ struct MHD_HTTP_Res_Header * MHD_get_response_element_n_ (struct MHD_Response *response, enum MHD_ValueKind kind, const char *key, size_t key_len) { struct MHD_HTTP_Res_Header *pos; mhd_assert (NULL != key); mhd_assert (0 != key[0]); mhd_assert (0 != key_len); for (pos = response->first_header; NULL != pos; pos = pos->next) { if ((pos->header_size == key_len) && (kind == pos->kind) && (MHD_str_equal_caseless_bin_n_ (pos->header, key, pos->header_size))) return pos; } return NULL; } /** * Check whether response header contains particular token. * * Token could be surrounded by spaces and tabs and delimited by comma. * Case-insensitive match used for header names and tokens. * * @param response the response to query * @param key header name * @param key_len the length of @a key, not including optional * terminating null-character. * @param token the token to find * @param token_len the length of @a token, not including optional * terminating null-character. * @return true if token is found in specified header, * false otherwise */ bool MHD_check_response_header_token_ci (const struct MHD_Response *response, const char *key, size_t key_len, const char *token, size_t token_len) { struct MHD_HTTP_Res_Header *pos; if ( (NULL == key) || ('\0' == key[0]) || (NULL == token) || ('\0' == token[0]) ) return false; /* Token must not contain binary zero! */ mhd_assert (strlen (token) == token_len); for (pos = response->first_header; NULL != pos; pos = pos->next) { if ( (pos->kind == MHD_HEADER_KIND) && (key_len == pos->header_size) && MHD_str_equal_caseless_bin_n_ (pos->header, key, key_len) && MHD_str_has_token_caseless_ (pos->value, token, token_len) ) return true; } return false; } /** * Create a response object. * The response object can be extended with header information and then be used * any number of times. * * If response object is used to answer HEAD request then the body of the * response is not used, while all headers (including automatic headers) are * used. * * @param size size of the data portion of the response, #MHD_SIZE_UNKNOWN for unknown * @param block_size preferred block size for querying crc (advisory only, * MHD may still call @a crc using smaller chunks); this * is essentially the buffer size used for IO, clients * should pick a value that is appropriate for IO and * memory performance requirements * @param crc callback to use to obtain response data * @param crc_cls extra argument to @a crc * @param crfc callback to call to free @a crc_cls resources * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_callback (uint64_t size, size_t block_size, MHD_ContentReaderCallback crc, void *crc_cls, MHD_ContentReaderFreeCallback crfc) { struct MHD_Response *response; if ((NULL == crc) || (0 == block_size)) return NULL; if (NULL == (response = MHD_calloc_ (1, sizeof (struct MHD_Response) + block_size))) return NULL; response->fd = -1; response->data = (void *) &response[1]; response->data_buffer_size = block_size; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (! MHD_mutex_init_ (&response->mutex)) { free (response); return NULL; } #endif response->crc = crc; response->crfc = crfc; response->crc_cls = crc_cls; response->reference_count = 1; response->total_size = size; return response; } /** * Set special flags and options for a response. * * @param response the response to modify * @param flags to set for the response * @param ... #MHD_RO_END terminated list of options * @return #MHD_YES on success, #MHD_NO on error */ _MHD_EXTERN enum MHD_Result MHD_set_response_options (struct MHD_Response *response, enum MHD_ResponseFlags flags, ...) { va_list ap; enum MHD_Result ret; enum MHD_ResponseOptions ro; if (0 != (response->flags_auto & MHD_RAF_HAS_CONTENT_LENGTH)) { /* Response has custom "Content-Lengh" header */ if ( (0 != (response->flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)) && (0 == (flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH))) { /* Request to remove MHD_RF_INSANITY_HEADER_CONTENT_LENGTH flag */ return MHD_NO; } if ( (0 != (response->flags & MHD_RF_HEAD_ONLY_RESPONSE)) && (0 == (flags & MHD_RF_HEAD_ONLY_RESPONSE))) { /* Request to remove MHD_RF_HEAD_ONLY_RESPONSE flag */ if (0 == (flags & MHD_RF_INSANITY_HEADER_CONTENT_LENGTH)) return MHD_NO; } } if ( (0 != (flags & MHD_RF_HEAD_ONLY_RESPONSE)) && (0 != response->total_size) ) return MHD_NO; ret = MHD_YES; response->flags = flags; va_start (ap, flags); while (MHD_RO_END != (ro = va_arg (ap, enum MHD_ResponseOptions))) { switch (ro) { case MHD_RO_END: /* Not possible */ break; default: ret = MHD_NO; break; } } va_end (ap); return ret; } /** * Given a file descriptor, read data from the file * to generate the response. * * @param cls pointer to the response * @param pos offset in the file to access * @param buf where to write the data * @param max number of bytes to write at most * @return number of bytes written */ static ssize_t file_reader (void *cls, uint64_t pos, char *buf, size_t max) { struct MHD_Response *response = cls; #if ! defined(_WIN32) || defined(__CYGWIN__) ssize_t n; #else /* _WIN32 && !__CYGWIN__ */ const HANDLE fh = (HANDLE) (uintptr_t) _get_osfhandle (response->fd); #endif /* _WIN32 && !__CYGWIN__ */ const int64_t offset64 = (int64_t) (pos + response->fd_off); if (offset64 < 0) return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */ #if ! defined(_WIN32) || defined(__CYGWIN__) if (max > SSIZE_MAX) max = SSIZE_MAX; /* Clamp to maximum return value. */ #if defined(HAVE_PREAD64) n = pread64 (response->fd, buf, max, offset64); #elif defined(HAVE_PREAD) if ( (sizeof(off_t) < sizeof (uint64_t)) && (offset64 > (uint64_t) INT32_MAX) ) return MHD_CONTENT_READER_END_WITH_ERROR; /* Read at required position is not possible. */ n = pread (response->fd, buf, max, (off_t) offset64); #else /* ! HAVE_PREAD */ #if defined(HAVE_LSEEK64) if (lseek64 (response->fd, offset64, SEEK_SET) != offset64) return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */ #else /* ! HAVE_LSEEK64 */ if ( (sizeof(off_t) < sizeof (uint64_t)) && (offset64 > (uint64_t) INT32_MAX) ) return MHD_CONTENT_READER_END_WITH_ERROR; /* seek to required position is not possible */ if (lseek (response->fd, (off_t) offset64, SEEK_SET) != (off_t) offset64) return MHD_CONTENT_READER_END_WITH_ERROR; /* can't seek to required position */ #endif /* ! HAVE_LSEEK64 */ n = read (response->fd, buf, max); #endif /* ! HAVE_PREAD */ if (0 == n) return MHD_CONTENT_READER_END_OF_STREAM; if (n < 0) return MHD_CONTENT_READER_END_WITH_ERROR; return n; #else /* _WIN32 && !__CYGWIN__ */ if (INVALID_HANDLE_VALUE == fh) return MHD_CONTENT_READER_END_WITH_ERROR; /* Value of 'response->fd' is not valid. */ else { OVERLAPPED f_ol = {0, 0, {{0, 0}}, 0}; /* Initialize to zero. */ ULARGE_INTEGER pos_uli; DWORD toRead = (max > INT32_MAX) ? INT32_MAX : (DWORD) max; DWORD resRead; pos_uli.QuadPart = (uint64_t) offset64; /* Simple transformation 64bit -> 2x32bit. */ f_ol.Offset = pos_uli.LowPart; f_ol.OffsetHigh = pos_uli.HighPart; if (! ReadFile (fh, (void *) buf, toRead, &resRead, &f_ol)) return MHD_CONTENT_READER_END_WITH_ERROR; /* Read error. */ if (0 == resRead) return MHD_CONTENT_READER_END_OF_STREAM; return (ssize_t) resRead; } #endif /* _WIN32 && !__CYGWIN__ */ } /** * Given a pipe descriptor, read data from the pipe * to generate the response. * * @param cls pointer to the response * @param pos offset in the pipe to access (ignored) * @param buf where to write the data * @param max number of bytes to write at most * @return number of bytes written */ static ssize_t pipe_reader (void *cls, uint64_t pos, char *buf, size_t max) { struct MHD_Response *response = cls; ssize_t n; (void) pos; #ifndef _WIN32 if (SSIZE_MAX < max) max = SSIZE_MAX; n = read (response->fd, buf, (MHD_SCKT_SEND_SIZE_) max); #else /* _WIN32 */ if (INT_MAX < max) max = INT_MAX; n = read (response->fd, buf, (unsigned int) max); #endif /* _WIN32 */ if (0 == n) return MHD_CONTENT_READER_END_OF_STREAM; if (n < 0) return MHD_CONTENT_READER_END_WITH_ERROR; return n; } /** * Destroy file reader context. Closes the file * descriptor. * * @param cls pointer to file descriptor */ static void free_callback (void *cls) { struct MHD_Response *response = cls; (void) close (response->fd); response->fd = -1; } #undef MHD_create_response_from_fd_at_offset /** * Create a response object with the content of provided file with * specified offset used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @param offset offset to start reading from in the file; * Be careful! `off_t` may have been compiled to be a * 64-bit variable for MHD, in which case your application * also has to be compiled using the same options! Read * the MHD manual for more details. * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd_at_offset (size_t size, int fd, off_t offset) { if (0 > offset) return NULL; return MHD_create_response_from_fd_at_offset64 (size, fd, (uint64_t) offset); } /** * Create a response object with the content of provided file with * specified offset used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response; * sizes larger than 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @param offset offset to start reading from in the file; * reading file beyond 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd_at_offset64 (uint64_t size, int fd, uint64_t offset) { struct MHD_Response *response; #if ! defined(HAVE___LSEEKI64) && ! defined(HAVE_LSEEK64) if ( (sizeof(uint64_t) > sizeof(off_t)) && ( (size > (uint64_t) INT32_MAX) || (offset > (uint64_t) INT32_MAX) || ((size + offset) >= (uint64_t) INT32_MAX) ) ) return NULL; #endif if ( ((int64_t) size < 0) || ((int64_t) offset < 0) || ((int64_t) (size + offset) < 0) ) return NULL; response = MHD_create_response_from_callback (size, MHD_FILE_READ_BLOCK_SIZE, &file_reader, NULL, &free_callback); if (NULL == response) return NULL; response->fd = fd; response->is_pipe = false; response->fd_off = offset; response->crc_cls = response; return response; } /** * Create a response object with the response body created by reading * the provided pipe. * * The response object can be extended with header information and * then be used ONLY ONCE. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param fd file descriptor referring to a read-end of a pipe with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_pipe (int fd) { struct MHD_Response *response; response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, MHD_FILE_READ_BLOCK_SIZE, &pipe_reader, NULL, &free_callback); if (NULL == response) return NULL; response->fd = fd; response->is_pipe = true; response->crc_cls = response; return response; } /** * Create a response object with the content of provided file used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param fd file descriptor referring to a file on disk with the data * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd (size_t size, int fd) { return MHD_create_response_from_fd_at_offset64 (size, fd, 0); } /** * Create a response object with the content of provided file used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response; * sizes larger than 2 GiB may be not supported by OS or * MHD build; see ::MHD_FEATURE_LARGE_FILE * @param fd file descriptor referring to a file on disk with the * data; will be closed when response is destroyed; * fd should be in 'blocking' mode * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_fd64 (uint64_t size, int fd) { return MHD_create_response_from_fd_at_offset64 (size, fd, 0); } /** * Create a response object. * The response object can be extended with header information and then be used * any number of times. * * If response object is used to answer HEAD request then the body of the * response is not used, while all headers (including automatic headers) are * used. * * @param size size of the @a data portion of the response * @param data the data itself * @param must_free libmicrohttpd should free data when done * @param must_copy libmicrohttpd must make a copy of @a data * right away, the data may be released anytime after * this call returns * @return NULL on error (i.e. invalid arguments, out of memory) * @deprecated use #MHD_create_response_from_buffer instead * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_data (size_t size, void *data, int must_free, int must_copy) { enum MHD_ResponseMemoryMode mode; if (0 != must_copy) mode = MHD_RESPMEM_MUST_COPY; else if (0 != must_free) mode = MHD_RESPMEM_MUST_FREE; else mode = MHD_RESPMEM_PERSISTENT; return MHD_create_response_from_buffer (size, data, mode); } /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param mode flags for buffer management * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer (size_t size, void *buffer, enum MHD_ResponseMemoryMode mode) { if (MHD_RESPMEM_MUST_FREE == mode) return MHD_create_response_from_buffer_with_free_callback_cls (size, buffer, &free, buffer); if (MHD_RESPMEM_MUST_COPY == mode) return MHD_create_response_from_buffer_copy (size, buffer); return MHD_create_response_from_buffer_with_free_callback_cls (size, buffer, NULL, NULL); } /** * Create a response object with the content of provided statically allocated * buffer used as the response body. * * The buffer must be valid for the lifetime of the response. The easiest way * to achieve this is to use a statically allocated buffer. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size the size of the data in @a buffer, can be zero * @param buffer the buffer with the data for the response body, can be NULL * if @a size is zero * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_static (size_t size, const void *buffer) { return MHD_create_response_from_buffer_with_free_callback_cls (size, buffer, NULL, NULL); } /** * Create a response object with the content of provided temporal buffer * used as the response body. * * An internal copy of the buffer will be made automatically, so buffer have * to be valid only during the call of this function (as a typical example: * buffer is a local (non-static) array). * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size the size of the data in @a buffer, can be zero * @param buffer the buffer with the data for the response body, can be NULL * if @a size is zero * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_copy (size_t size, const void *buffer) { struct MHD_Response *r; void *mhd_copy; if (0 == size) return MHD_create_response_from_buffer_with_free_callback_cls (0, NULL, NULL, NULL); if (NULL == buffer) return NULL; mhd_copy = malloc (size); if (NULL == mhd_copy) return NULL; memcpy (mhd_copy, buffer, size); r = MHD_create_response_from_buffer_with_free_callback_cls (size, mhd_copy, &free, mhd_copy); if (NULL == r) free (mhd_copy); else { /* TODO: remove the next assignment, the buffer should not be modifiable */ r->data_buffer_size = size; } return r; } /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param crfc function to call to free the @a buffer * @return NULL on error (i.e. invalid arguments, out of memory) * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_with_free_callback (size_t size, void *buffer, MHD_ContentReaderFreeCallback crfc) { return MHD_create_response_from_buffer_with_free_callback_cls (size, buffer, crfc, buffer); } /** * Create a response object with the content of provided buffer used as * the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param size size of the data portion of the response * @param buffer size bytes containing the response's data portion * @param crfc function to call to cleanup, if set to NULL then callback * is not called * @param crfc_cls an argument for @a crfc * @return NULL on error (i.e. invalid arguments, out of memory) * @note Available since #MHD_VERSION 0x00097302 * @note 'const' qualifier is used for @a buffer since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_buffer_with_free_callback_cls (size_t size, const void *buffer, MHD_ContentReaderFreeCallback crfc, void *crfc_cls) { struct MHD_Response *r; if ((NULL == buffer) && (size > 0)) return NULL; #if SIZEOF_SIZE_T >= SIZEOF_UINT64_T if (MHD_SIZE_UNKNOWN == size) return NULL; #endif /* SIZEOF_SIZE_T >= SIZEOF_UINT64_T */ r = MHD_calloc_ (1, sizeof (struct MHD_Response)); if (NULL == r) return NULL; #if defined(MHD_USE_THREADS) if (! MHD_mutex_init_ (&r->mutex)) { free (r); return NULL; } #endif r->fd = -1; r->reference_count = 1; r->total_size = size; r->data = buffer; r->data_size = size; r->crfc = crfc; r->crc_cls = crfc_cls; return r; } /** * Create a response object with an array of memory buffers * used as the response body. * * The response object can be extended with header information and then * be used any number of times. * * If response object is used to answer HEAD request then the body * of the response is not used, while all headers (including automatic * headers) are used. * * @param iov the array for response data buffers, an internal copy of this * will be made * @param iovcnt the number of elements in @a iov * @param free_cb the callback to clean up any data associated with @a iov when * the response is destroyed. * @param cls the argument passed to @a free_cb * @return NULL on error (i.e. invalid arguments, out of memory) */ _MHD_EXTERN struct MHD_Response * MHD_create_response_from_iovec (const struct MHD_IoVec *iov, unsigned int iovcnt, MHD_ContentReaderFreeCallback free_cb, void *cls) { struct MHD_Response *response; unsigned int i; int i_cp = 0; /**< Index in the copy of iov */ uint64_t total_size = 0; const void *last_valid_buffer = NULL; if ((NULL == iov) && (0 < iovcnt)) return NULL; response = MHD_calloc_ (1, sizeof (struct MHD_Response)); if (NULL == response) return NULL; if (! MHD_mutex_init_ (&response->mutex)) { free (response); return NULL; } /* Calculate final size, number of valid elements, and check 'iov' */ for (i = 0; i < iovcnt; ++i) { if (0 == iov[i].iov_len) continue; /* skip zero-sized elements */ if (NULL == iov[i].iov_base) { i_cp = -1; /* error */ break; } if ( (total_size > (total_size + iov[i].iov_len)) || (INT_MAX == i_cp) || (SSIZE_MAX < (total_size + iov[i].iov_len)) ) { i_cp = -1; /* overflow */ break; } last_valid_buffer = iov[i].iov_base; total_size += iov[i].iov_len; #if defined(MHD_POSIX_SOCKETS) || ! defined(_WIN64) i_cp++; #else /* ! MHD_POSIX_SOCKETS && _WIN64 */ { int64_t i_add; i_add = (int64_t) (iov[i].iov_len / ULONG_MAX); if (0 != iov[i].iov_len % ULONG_MAX) i_add++; if (INT_MAX < (i_add + i_cp)) { i_cp = -1; /* overflow */ break; } i_cp += (int) i_add; } #endif /* ! MHD_POSIX_SOCKETS && _WIN64 */ } if (-1 == i_cp) { /* Some error condition */ MHD_mutex_destroy_chk_ (&response->mutex); free (response); return NULL; } response->fd = -1; response->reference_count = 1; response->total_size = total_size; response->crc_cls = cls; response->crfc = free_cb; if (0 == i_cp) { mhd_assert (0 == total_size); return response; } if (1 == i_cp) { mhd_assert (NULL != last_valid_buffer); response->data = last_valid_buffer; response->data_size = (size_t) total_size; return response; } mhd_assert (1 < i_cp); if (1) { /* for local variables local scope only */ MHD_iovec_ *iov_copy; int num_copy_elements = i_cp; iov_copy = MHD_calloc_ ((size_t) num_copy_elements, \ sizeof(MHD_iovec_)); if (NULL == iov_copy) { MHD_mutex_destroy_chk_ (&response->mutex); free (response); return NULL; } i_cp = 0; for (i = 0; i < iovcnt; ++i) { size_t element_size = iov[i].iov_len; const uint8_t *buf = (const uint8_t *) iov[i].iov_base; if (0 == element_size) continue; /* skip zero-sized elements */ #if defined(MHD_WINSOCK_SOCKETS) && defined(_WIN64) while (MHD_IOV_ELMN_MAX_SIZE < element_size) { iov_copy[i_cp].iov_base = (char *) _MHD_DROP_CONST (buf); iov_copy[i_cp].iov_len = ULONG_MAX; buf += ULONG_MAX; element_size -= ULONG_MAX; i_cp++; } #endif /* MHD_WINSOCK_SOCKETS && _WIN64 */ iov_copy[i_cp].iov_base = _MHD_DROP_CONST (buf); iov_copy[i_cp].iov_len = (MHD_iov_size_) element_size; i_cp++; } mhd_assert (num_copy_elements == i_cp); mhd_assert (0 <= i_cp); response->data_iov = iov_copy; response->data_iovcnt = (unsigned int) i_cp; } return response; } /** * Create a response object with empty (zero size) body. * * The response object can be extended with header information and then be used * any number of times. * * This function is a faster equivalent of #MHD_create_response_from_buffer call * with zero size combined with call of #MHD_set_response_options. * * @param flags the flags for the new response object * @return NULL on error (i.e. invalid arguments, out of memory), * the pointer to the created response object otherwise * @note Available since #MHD_VERSION 0x00097701 * @ingroup response */ _MHD_EXTERN struct MHD_Response * MHD_create_response_empty (enum MHD_ResponseFlags flags) { struct MHD_Response *r; r = (struct MHD_Response *) MHD_calloc_ (1, sizeof (struct MHD_Response)); if (NULL != r) { if (MHD_mutex_init_ (&r->mutex)) { r->fd = -1; r->reference_count = 1; /* If any flags combination will be not allowed, replace the next * assignment with MHD_set_response_options() call. */ r->flags = flags; return r; /* Successful result */ } free (r); } return NULL; /* Something failed */ } #ifdef UPGRADE_SUPPORT /** * This connection-specific callback is provided by MHD to * applications (unusual) during the #MHD_UpgradeHandler. * It allows applications to perform 'special' actions on * the underlying socket from the upgrade. * * @param urh the handle identifying the connection to perform * the upgrade @a action on. * @param action which action should be performed * @param ... arguments to the action (depends on the action) * @return #MHD_NO on error, #MHD_YES on success */ _MHD_EXTERN enum MHD_Result MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh, enum MHD_UpgradeAction action, ...) { struct MHD_Connection *connection; struct MHD_Daemon *daemon; if (NULL == urh) return MHD_NO; connection = urh->connection; /* Precaution checks on external data. */ if (NULL == connection) return MHD_NO; daemon = connection->daemon; if (NULL == daemon) return MHD_NO; switch (action) { case MHD_UPGRADE_ACTION_CLOSE: if (urh->was_closed) return MHD_NO; /* Already closed. */ /* transition to special 'closed' state for start of cleanup */ #ifdef HTTPS_SUPPORT if (0 != (daemon->options & MHD_USE_TLS) ) { /* signal that app is done by shutdown() of 'app' socket */ /* Application will not use anyway this socket after this command. */ shutdown (urh->app.socket, SHUT_RDWR); } #endif /* HTTPS_SUPPORT */ mhd_assert (MHD_CONNECTION_UPGRADE == connection->state); /* The next function will mark the connection as closed by application * by setting 'urh->was_closed'. * As soon as connection will be marked with BOTH * 'urh->was_closed' AND 'urh->clean_ready', it will * be moved to cleanup list by MHD_resume_connection(). */ MHD_upgraded_connection_mark_app_closed_ (connection); return MHD_YES; case MHD_UPGRADE_ACTION_CORK_ON: /* Unportable API. TODO: replace with portable action. */ return MHD_connection_set_cork_state_ (connection, true) ? MHD_YES : MHD_NO; case MHD_UPGRADE_ACTION_CORK_OFF: /* Unportable API. TODO: replace with portable action. */ return MHD_connection_set_cork_state_ (connection, false) ? MHD_YES : MHD_NO; default: /* we don't understand this one */ return MHD_NO; } } /** * We are done sending the header of a given response to the client. * Now it is time to perform the upgrade and hand over the connection * to the application. * @remark To be called only from thread that process connection's * recv(), send() and response. Must be called right after sending * response headers. * * @param response the response that was created for an upgrade * @param connection the specific connection we are upgrading * @return #MHD_YES on success, #MHD_NO on failure (will cause * connection to be closed) */ enum MHD_Result MHD_response_execute_upgrade_ (struct MHD_Response *response, struct MHD_Connection *connection) { #if defined(HTTPS_SUPPORT) || defined(_DEBUG) || defined(HAVE_MESSAGES) struct MHD_Daemon *const daemon = connection->daemon; #endif /* HTTPS_SUPPORT || _DEBUG || HAVE_MESSAGES */ struct MHD_UpgradeResponseHandle *urh; size_t rbo; #ifdef MHD_USE_THREADS mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); #endif /* MHD_USE_THREADS */ /* "Upgrade" responses accepted only if MHD_ALLOW_UPGRADE is enabled */ mhd_assert (0 != (daemon->options & MHD_ALLOW_UPGRADE)); /* The header was checked when response queued */ mhd_assert (NULL != \ MHD_get_response_element_n_ (response, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_UPGRADE))); if (! connection->sk_nonblck) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Cannot execute \"upgrade\" as the socket is in " \ "the blocking mode.\n")); #endif return MHD_NO; } urh = MHD_calloc_ (1, sizeof (struct MHD_UpgradeResponseHandle)); if (NULL == urh) return MHD_NO; urh->connection = connection; rbo = connection->read_buffer_offset; connection->read_buffer_offset = 0; MHD_connection_set_nodelay_state_ (connection, false); MHD_connection_set_cork_state_ (connection, false); #ifdef HTTPS_SUPPORT if (0 != (daemon->options & MHD_USE_TLS) ) { MHD_socket sv[2]; #if defined(MHD_socket_nosignal_) || ! defined(MHD_socket_pair_nblk_) int res1; int res2; #endif /* MHD_socket_nosignal_ || !MHD_socket_pair_nblk_ */ #ifdef MHD_socket_pair_nblk_ if (! MHD_socket_pair_nblk_ (sv)) { free (urh); return MHD_NO; } #else /* !MHD_socket_pair_nblk_ */ if (! MHD_socket_pair_ (sv)) { free (urh); return MHD_NO; } res1 = MHD_socket_nonblocking_ (sv[0]); res2 = MHD_socket_nonblocking_ (sv[1]); if ( (! res1) || (! res2) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to make loopback sockets non-blocking.\n")); #endif if (! res2) { /* Socketpair cannot be used. */ MHD_socket_close_chk_ (sv[0]); MHD_socket_close_chk_ (sv[1]); free (urh); return MHD_NO; } } #endif /* !MHD_socket_pair_nblk_ */ #ifdef MHD_socket_nosignal_ res1 = MHD_socket_nosignal_ (sv[0]); res2 = MHD_socket_nosignal_ (sv[1]); if ( (! res1) || (! res2) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Failed to set SO_NOSIGPIPE on loopback sockets.\n")); #endif #ifndef MSG_NOSIGNAL if (! res2) { /* Socketpair cannot be used. */ MHD_socket_close_chk_ (sv[0]); MHD_socket_close_chk_ (sv[1]); free (urh); return MHD_NO; } #endif /* ! MSG_NOSIGNAL */ } #endif /* MHD_socket_nosignal_ */ if (MHD_D_IS_USING_SELECT_ (daemon) && (! MHD_D_DOES_SCKT_FIT_FDSET_ (sv[1], daemon)) ) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Socketpair descriptor is not less than FD_SETSIZE: " \ "%d >= %d\n"), (int) sv[1], (int) MHD_D_GET_FD_SETSIZE_ (daemon)); #endif MHD_socket_close_chk_ (sv[0]); MHD_socket_close_chk_ (sv[1]); free (urh); return MHD_NO; } urh->app.socket = sv[0]; urh->app.urh = urh; urh->app.celi = MHD_EPOLL_STATE_UNREADY; urh->mhd.socket = sv[1]; urh->mhd.urh = urh; urh->mhd.celi = MHD_EPOLL_STATE_UNREADY; #ifdef EPOLL_SUPPORT /* Launch IO processing by the event loop */ if (MHD_D_IS_USING_EPOLL_ (daemon)) { /* We're running with epoll(), need to add the sockets to the event set of the daemon's `epoll_upgrade_fd` */ struct epoll_event event; mhd_assert (-1 != daemon->epoll_upgrade_fd); /* First, add network socket */ event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET; event.data.ptr = &urh->app; if (0 != epoll_ctl (daemon->epoll_upgrade_fd, EPOLL_CTL_ADD, connection->socket_fd, &event)) { #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif MHD_socket_close_chk_ (sv[0]); MHD_socket_close_chk_ (sv[1]); free (urh); return MHD_NO; } /* Second, add our end of the UNIX socketpair() */ event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET; event.data.ptr = &urh->mhd; if (0 != epoll_ctl (daemon->epoll_upgrade_fd, EPOLL_CTL_ADD, urh->mhd.socket, &event)) { event.events = EPOLLIN | EPOLLOUT | EPOLLPRI; event.data.ptr = &urh->app; if (0 != epoll_ctl (daemon->epoll_upgrade_fd, EPOLL_CTL_DEL, connection->socket_fd, &event)) MHD_PANIC (_ ("Error cleaning up while handling epoll error.\n")); #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Call to epoll_ctl failed: %s\n"), MHD_socket_last_strerr_ ()); #endif MHD_socket_close_chk_ (sv[0]); MHD_socket_close_chk_ (sv[1]); free (urh); return MHD_NO; } EDLL_insert (daemon->eready_urh_head, daemon->eready_urh_tail, urh); urh->in_eready_list = true; } #endif /* EPOLL_SUPPORT */ if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) { /* This takes care of further processing for most event loops: simply add to DLL for bi-direcitonal processing */ DLL_insert (daemon->urh_head, daemon->urh_tail, urh); } /* In thread-per-connection mode, thread will switch to forwarding once * connection.urh is not NULL and connection.state == MHD_CONNECTION_UPGRADE. */ } else { urh->app.socket = MHD_INVALID_SOCKET; urh->mhd.socket = MHD_INVALID_SOCKET; /* Non-TLS connection do not hold any additional resources. */ urh->clean_ready = true; } #else /* ! HTTPS_SUPPORT */ urh->clean_ready = true; #endif /* ! HTTPS_SUPPORT */ connection->urh = urh; /* As far as MHD's event loops are concerned, this connection is suspended; it will be resumed once application is done by the #MHD_upgrade_action() function */ internal_suspend_connection_ (connection); /* hand over socket to application */ response->upgrade_handler (response->upgrade_handler_cls, connection, connection->rq.client_context, connection->read_buffer, rbo, #ifdef HTTPS_SUPPORT (0 == (daemon->options & MHD_USE_TLS) ) ? connection->socket_fd : urh->app.socket, #else /* ! HTTPS_SUPPORT */ connection->socket_fd, #endif /* ! HTTPS_SUPPORT */ urh); #ifdef HTTPS_SUPPORT if (0 != (daemon->options & MHD_USE_TLS)) { struct MemoryPool *const pool = connection->pool; size_t avail; char *buf; /* All data should be sent already */ mhd_assert (connection->write_buffer_send_offset == \ connection->write_buffer_append_offset); MHD_pool_deallocate (pool, connection->write_buffer, connection->write_buffer_size); connection->write_buffer_append_offset = 0; connection->write_buffer_send_offset = 0; connection->write_buffer_size = 0; connection->write_buffer = NULL; /* Extra read data should be processed already by the application */ MHD_pool_deallocate (pool, connection->read_buffer, connection->read_buffer_size); connection->read_buffer_offset = 0; connection->read_buffer_size = 0; connection->read_buffer = NULL; avail = MHD_pool_get_free (pool); if (avail < RESERVE_EBUF_SIZE) { /* connection's pool is totally at the limit, use our 'emergency' buffer of #RESERVE_EBUF_SIZE bytes. */ avail = RESERVE_EBUF_SIZE; buf = urh->e_buf; #ifdef HAVE_MESSAGES MHD_DLOG (daemon, _ ("Memory shortage in connection's memory pool. " \ "The \"upgraded\" communication will be inefficient.\n")); #endif } else { /* Normal case: grab all remaining memory from the connection's pool for the IO buffers; the connection certainly won't need it anymore as we've upgraded to another protocol. */ buf = MHD_pool_allocate (pool, avail, false); } /* use half the buffer for inbound, half for outbound */ urh->in_buffer_size = avail / 2; urh->out_buffer_size = avail - urh->in_buffer_size; urh->in_buffer = buf; urh->out_buffer = buf + urh->in_buffer_size; } #endif /* HTTPS_SUPPORT */ return MHD_YES; } /** * Create a response object that can be used for 101 UPGRADE * responses, for example to implement WebSockets. After sending the * response, control over the data stream is given to the callback (which * can then, for example, start some bi-directional communication). * If the response is queued for multiple connections, the callback * will be called for each connection. The callback * will ONLY be called after the response header was successfully passed * to the OS; if there are communication errors before, the usual MHD * connection error handling code will be performed. * * Setting the correct HTTP code (i.e. MHD_HTTP_SWITCHING_PROTOCOLS) * and setting correct HTTP headers for the upgrade must be done * manually (this way, it is possible to implement most existing * WebSocket versions using this API; in fact, this API might be useful * for any protocol switch, not just WebSockets). Note that * draft-ietf-hybi-thewebsocketprotocol-00 cannot be implemented this * way as the header "HTTP/1.1 101 WebSocket Protocol Handshake" * cannot be generated; instead, MHD will always produce "HTTP/1.1 101 * Switching Protocols" (if the response code 101 is used). * * As usual, the response object can be extended with header * information and then be used any number of times (as long as the * header information is not connection-specific). * * @param upgrade_handler function to call with the 'upgraded' socket * @param upgrade_handler_cls closure for @a upgrade_handler * @return NULL on error (i.e. invalid arguments, out of memory) */ _MHD_EXTERN struct MHD_Response * MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler, void *upgrade_handler_cls) { struct MHD_Response *response; if (NULL == upgrade_handler) return NULL; /* invalid request */ response = MHD_calloc_ (1, sizeof (struct MHD_Response)); if (NULL == response) return NULL; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) if (! MHD_mutex_init_ (&response->mutex)) { free (response); return NULL; } #endif response->upgrade_handler = upgrade_handler; response->upgrade_handler_cls = upgrade_handler_cls; response->total_size = 0; response->reference_count = 1; if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "Upgrade")) { MHD_destroy_response (response); return NULL; } return response; } #endif /* UPGRADE_SUPPORT */ /** * Destroy a response object and associated resources. Note that * libmicrohttpd may keep some of the resources around if the response * is still in the queue for some clients, so the memory may not * necessarily be freed immediately. * * @param response response to destroy * @ingroup response */ _MHD_EXTERN void MHD_destroy_response (struct MHD_Response *response) { struct MHD_HTTP_Res_Header *pos; if (NULL == response) return; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&response->mutex); #endif if (0 != --(response->reference_count)) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif return; } #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); MHD_mutex_destroy_chk_ (&response->mutex); #endif if (NULL != response->crfc) response->crfc (response->crc_cls); if (NULL != response->data_iov) { free (response->data_iov); } while (NULL != response->first_header) { pos = response->first_header; response->first_header = pos->next; free (pos->header); free (pos->value); free (pos); } free (response); } /** * Increments the reference counter for the @a response. * * @param response object to modify */ void MHD_increment_response_rc (struct MHD_Response *response) { #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_lock_chk_ (&response->mutex); #endif (response->reference_count)++; #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) MHD_mutex_unlock_chk_ (&response->mutex); #endif } /* end of response.c */ libmicrohttpd-1.0.10/src/microhttpd/mhd_align.h0000644000175000017500000000570515035214301015156 /* This file is part of libmicrohttpd Copyright (C) 2021-2022 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/mhd_align.h * @brief types alignment macros * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_ALIGN_H #define MHD_ALIGN_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include #endif #ifdef HAVE_C_ALIGNOF #ifdef HAVE_STDALIGN_H #include #endif /* HAVE_STDALIGN_H */ #define _MHD_ALIGNOF(type) alignof(type) #endif /* HAVE_C_ALIGNOF */ #ifndef _MHD_ALIGNOF #if defined(_MSC_VER) && ! defined(__clang__) && _MSC_VER >= 1700 #define _MHD_ALIGNOF(type) __alignof(type) #endif /* _MSC_VER >= 1700 */ #endif /* !_MHD_ALIGNOF */ #ifdef _MHD_ALIGNOF #if (defined(__GNUC__) && __GNUC__ < 4 && __GNUC_MINOR__ < 9 && \ ! defined(__clang__)) || \ (defined(__clang__) && __clang_major__ < 8) || \ (defined(__clang__) && __clang_major__ < 11 && \ defined(__apple_build_version__)) /* GCC before 4.9 and clang before 8.0 have incorrect implementation of 'alignof()' which returns preferred alignment instead of minimal required alignment */ #define _MHD_ALIGNOF_UNRELIABLE 1 #endif #if defined(_MSC_VER) && ! defined(__clang__) && _MSC_VER < 1900 /* MSVC has the same problem as old GCC versions: '__alignof()' may return "preferred" alignment instead of "required". */ #define _MHD_ALIGNOF_UNRELIABLE 1 #endif /* _MSC_VER < 1900 */ #endif /* _MHD_ALIGNOF */ #ifdef offsetof #define _MHD_OFFSETOF(strct, membr) offsetof(strct, membr) #else /* ! offsetof */ #define _MHD_OFFSETOF(strct, membr) (size_t)(((char*)&(((strct*)0)->membr)) - \ ((char*)((strct*)0))) #endif /* ! offsetof */ /* Provide a limited set of alignment macros */ /* The set could be extended as needed */ #if defined(_MHD_ALIGNOF) && ! defined(_MHD_ALIGNOF_UNRELIABLE) #define _MHD_UINT32_ALIGN _MHD_ALIGNOF(uint32_t) #define _MHD_UINT64_ALIGN _MHD_ALIGNOF(uint64_t) #else /* ! _MHD_ALIGNOF */ struct _mhd_dummy_uint32_offset_test { char dummy; uint32_t ui32; }; #define _MHD_UINT32_ALIGN \ _MHD_OFFSETOF(struct _mhd_dummy_uint32_offset_test, ui32) struct _mhd_dummy_uint64_offset_test { char dummy; uint64_t ui64; }; #define _MHD_UINT64_ALIGN \ _MHD_OFFSETOF(struct _mhd_dummy_uint64_offset_test, ui64) #endif /* ! _MHD_ALIGNOF */ #endif /* ! MHD_ALIGN_H */ libmicrohttpd-1.0.10/src/microhttpd/microhttpd_dll_res.rc.in0000644000175000017500000000331715035214301017674 /* W32 resources */ #include LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US VS_VERSION_INFO VERSIONINFO FILEVERSION @PACKAGE_VERSION_MAJOR@,@PACKAGE_VERSION_MINOR@,@PACKAGE_VERSION_SUBMINOR@,0 PRODUCTVERSION @PACKAGE_VERSION_MAJOR@,@PACKAGE_VERSION_MINOR@,@PACKAGE_VERSION_SUBMINOR@,0 FILEFLAGSMASK VS_FFI_FILEFLAGSMASK #if defined(_DEBUG) FILEFLAGS VS_FF_DEBUG #else FILEFLAGS 0 #endif FILEOS VOS_NT_WINDOWS32 #ifdef DLL_EXPORT FILETYPE VFT_DLL #else FILETYPE VFT_STATIC_LIB #endif FILESUBTYPE VFT2_UNKNOWN BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "04090000" /* Lang = US English, Charset = ASCII */ BEGIN VALUE "ProductName", "GNU libmicrohttpd\0" VALUE "ProductVersion", "@PACKAGE_VERSION@\0" VALUE "FileVersion", "@PACKAGE_VERSION@\0" #ifdef DLL_EXPORT VALUE "FileDescription", "GNU libmicrohttpd DLL for Windows (MinGW build, @W32CRT@ run-time lib)\0" #else VALUE "FileDescription", "GNU libmicrohttpd static library for Windows (MinGW build, @W32CRT@ run-time lib)\0" #endif VALUE "InternalName", "libmicrohttpd\0" #ifdef DLL_EXPORT VALUE "OriginalFilename", "libmicrohttpd-@MHD_W32_DLL_SUFF@.dll\0" #else VALUE "OriginalFilename", "libmicrohttpd.lib\0" #endif VALUE "CompanyName", "Free Software Foundation\0" VALUE "LegalCopyright", "Copyright (C) 2007-2024 Christian Grothoff, Evgeny Grin, and project contributors\0" VALUE "Comments", "http://www.gnu.org/software/libmicrohttpd/\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0409, 0 /* US English, ASCII */ END END libmicrohttpd-1.0.10/src/microhttpd/memorypool.h0000644000175000017500000001433115035214301015431 /* This file is part of libmicrohttpd Copyright (C) 2007--2024 Daniel Pittman and Christian Grothoff Copyright (C) 2016--2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file memorypool.h * @brief memory pool; mostly used for efficient (de)allocation * for each connection and bounding memory use for each * request * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef MEMORYPOOL_H #define MEMORYPOOL_H #include "mhd_options.h" #ifdef HAVE_STDDEF_H #include #endif /* HAVE_STDDEF_H */ #ifdef HAVE_STDBOOL_H #include #endif /** * Opaque handle for a memory pool. * Pools are not reentrant and must not be used * by multiple threads. */ struct MemoryPool; /** * Initialize values for memory pools */ void MHD_init_mem_pools_ (void); /** * Create a memory pool. * * @param max maximum size of the pool * @return NULL on error */ struct MemoryPool * MHD_pool_create (size_t max); /** * Destroy a memory pool. * * @param pool memory pool to destroy */ void MHD_pool_destroy (struct MemoryPool *pool); /** * Allocate size bytes from the pool. * * @param pool memory pool to use for the operation * @param size number of bytes to allocate * @param from_end allocate from end of pool (set to 'true'); * use this for small, persistent allocations that * will never be reallocated * @return NULL if the pool cannot support size more * bytes */ void * MHD_pool_allocate (struct MemoryPool *pool, size_t size, bool from_end); /** * Checks whether allocated block is re-sizable in-place. * If block is not re-sizable in-place, it still could be shrunk, but freed * memory will not be re-used until reset of the pool. * @param pool the memory pool to use * @param block the pointer to the allocated block to check * @param block_size the size of the allocated @a block * @return true if block can be resized in-place in the optimal way, * false otherwise */ bool MHD_pool_is_resizable_inplace (struct MemoryPool *pool, void *block, size_t block_size); /** * Try to allocate @a size bytes memory area from the @a pool. * * If allocation fails, @a required_bytes is updated with size required to be * freed in the @a pool from rellocatable area to allocate requested number * of bytes. * Allocated memory area is always not rellocatable ("from end"). * * @param pool memory pool to use for the operation * @param size the size of memory in bytes to allocate * @param[out] required_bytes the pointer to variable to be updated with * the size of the required additional free * memory area, set to 0 if function succeeds. * Cannot be NULL. * @return the pointer to allocated memory area if succeed, * NULL if the pool doesn't have enough space, required_bytes is updated * with amount of space needed to be freed in rellocatable area or * set to SIZE_MAX if requested size is too large for the pool. */ void * MHD_pool_try_alloc (struct MemoryPool *pool, size_t size, size_t *required_bytes); /** * Reallocate a block of memory obtained from the pool. * This is particularly efficient when growing or * shrinking the block that was last (re)allocated. * If the given block is not the most recently * (re)allocated block, the memory of the previous * allocation may be not released until the pool is * destroyed or reset. * * @param pool memory pool to use for the operation * @param old the existing block * @param old_size the size of the existing block * @param new_size the new size of the block * @return new address of the block, or * NULL if the pool cannot support @a new_size * bytes (old continues to be valid for @a old_size) */ void * MHD_pool_reallocate (struct MemoryPool *pool, void *old, size_t old_size, size_t new_size); /** * Check how much memory is left in the @a pool * * @param pool pool to check * @return number of bytes still available in @a pool */ size_t MHD_pool_get_free (struct MemoryPool *pool); /** * Deallocate a block of memory obtained from the pool. * * If the given block is not the most recently * (re)allocated block, the memory of the this block * allocation may be not released until the pool is * destroyed or reset. * * @param pool memory pool to use for the operation * @param block the allocated block, the NULL is tolerated * @param block_size the size of the allocated block */ void MHD_pool_deallocate (struct MemoryPool *pool, void *block, size_t block_size); /** * Clear all entries from the memory pool except * for @a keep of the given @a copy_bytes. The pointer * returned should be a buffer of @a new_size where * the first @a copy_bytes are from @a keep. * * @param pool memory pool to use for the operation * @param keep pointer to the entry to keep (maybe NULL) * @param copy_bytes how many bytes need to be kept at this address * @param new_size how many bytes should the allocation we return have? * (should be larger or equal to @a copy_bytes) * @return addr new address of @a keep (if it had to change) */ void * MHD_pool_reset (struct MemoryPool *pool, void *keep, size_t copy_bytes, size_t new_size); #endif libmicrohttpd-1.0.10/src/microhttpd/postprocessor.h0000644000175000017500000001205514760713577016204 /* This file is part of libmicrohttpd Copyright (C) 2007-2022 Daniel Pittman, Christian Grothoff, and Evgeny Grin This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file postprocessor.h * @brief Declarations for parsing POST data * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_POSTPROCESSOR_H #define MHD_POSTPROCESSOR_H 1 #include "internal.h" /** * States in the PP parser's state machine. */ enum PP_State { /* general states */ PP_Error, PP_Done, PP_Init, PP_NextBoundary, /* url encoding-states */ PP_ProcessKey, PP_ProcessValue, PP_Callback, /* post encoding-states */ PP_ProcessEntryHeaders, PP_PerformCheckMultipart, PP_ProcessValueToBoundary, PP_PerformCleanup, /* nested post-encoding states */ PP_Nested_Init, PP_Nested_PerformMarking, PP_Nested_ProcessEntryHeaders, PP_Nested_ProcessValueToBoundary, PP_Nested_PerformCleanup }; enum RN_State { /** * No RN-preprocessing in this state. */ RN_Inactive = 0, /** * If the next character is CR, skip it. Otherwise, * just go inactive. */ RN_OptN = 1, /** * Expect CRLF (and only CRLF). As always, we also * expect only LF or only CR. */ RN_Full = 2, /** * Expect either CRLF or '--'CRLF. If '--'CRLF, transition into dash-state * for the main state machine */ RN_Dash = 3, /** * Got a single dash, expect second dash. */ RN_Dash2 = 4 }; /** * Bits for the globally known fields that * should not be deleted when we exit the * nested state. */ enum NE_State { NE_none = 0, NE_content_name = 1, NE_content_type = 2, NE_content_filename = 4, NE_content_transfer_encoding = 8 }; /** * Internal state of the post-processor. Note that the fields * are sorted by type to enable optimal packing by the compiler. */ struct MHD_PostProcessor { /** * The connection for which we are doing * POST processing. */ struct MHD_Connection *connection; /** * Function to call with POST data. */ MHD_PostDataIterator ikvi; /** * Extra argument to ikvi. */ void *cls; /** * Encoding as given by the headers of the connection. */ const char *encoding; /** * Primary boundary (points into encoding string) */ const char *boundary; /** * Nested boundary (if we have multipart/mixed encoding). */ char *nested_boundary; /** * Pointer to the name given in disposition. */ char *content_name; /** * Pointer to the (current) content type. */ char *content_type; /** * Pointer to the (current) filename. */ char *content_filename; /** * Pointer to the (current) encoding. */ char *content_transfer_encoding; /** * Value data left over from previous iteration. */ char xbuf[2]; /** * Size of our buffer for the key. */ size_t buffer_size; /** * Current position in the key buffer. */ size_t buffer_pos; /** * Current position in @e xbuf. */ size_t xbuf_pos; /** * Current offset in the value being processed. */ uint64_t value_offset; /** * strlen(boundary) -- if boundary != NULL. */ size_t blen; /** * strlen(nested_boundary) -- if nested_boundary != NULL. */ size_t nlen; /** * Do we have to call the 'ikvi' callback when processing the * multipart post body even if the size of the payload is zero? * Set to #MHD_YES whenever we parse a new multiparty entry header, * and to #MHD_NO the first time we call the 'ikvi' callback. * Used to ensure that we do always call 'ikvi' even if the * payload is empty (but not more than once). */ bool must_ikvi; /** * Set if we still need to run the unescape logic * on the key allocated at the end of this struct. */ bool must_unescape_key; /** * State of the parser. */ enum PP_State state; /** * Side-state-machine: skip CRLF (or just LF). * Set to 0 if we are not in skip mode. Set to 2 * if a CRLF is expected, set to 1 if a CR should * be skipped if it is the next character. */ enum RN_State skip_rn; /** * If we are in skip_rn with "dash" mode and * do find 2 dashes, what state do we go into? */ enum PP_State dash_state; /** * Which headers are global? (used to tell which * headers were only valid for the nested multipart). */ enum NE_State have; }; #endif /* ! MHD_POSTPROCESSOR_H */ libmicrohttpd-1.0.10/src/microhttpd/test_set_panic.c0000644000175000017500000014113114760713574016251 /* This file is part of libmicrohttpd Copyright (C) 2021-2022 Evgeny Grin (Karlson2k) libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_set_panic.c * @brief Testcase for MHD_set_panic_func() * @author Karlson2k (Evgeny Grin) * @author Christian Grothoff */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif /* !WIN32_LEAN_AND_MEAN */ #include #endif #ifndef WINDOWS #include #include #endif #ifdef HAVE_LIMITS_H #include #endif /* HAVE_LIMITS_H */ #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #ifdef HAVE_SYSCTL #ifdef HAVE_SYS_TYPES_H #include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_SYS_SYSCTL_H #include #endif /* HAVE_SYS_SYSCTL_H */ #ifdef HAVE_SYS_SOCKET_H #include #endif /* HAVE_SYS_SOCKET_H */ #ifdef HAVE_NETINET_IN_H #include #endif /* HAVE_NETINET_IN_H */ #ifdef HAVE_NETINET_IP_H #include #endif /* HAVE_NETINET_IP_H */ #ifdef HAVE_NETINET_IP_ICMP_H #include #endif /* HAVE_NETINET_IP_ICMP_H */ #ifdef HAVE_NETINET_ICMP_VAR_H #include #endif /* HAVE_NETINET_ICMP_VAR_H */ #endif /* HAVE_SYSCTL */ #include #include "mhd_sockets.h" /* only macros used */ #include "test_helpers.h" #include "mhd_assert.h" #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 #undef MHD_CPU_COUNT #endif #if ! defined(MHD_CPU_COUNT) #define MHD_CPU_COUNT 2 #endif #if MHD_CPU_COUNT > 32 #undef MHD_CPU_COUNT /* Limit to reasonable value */ #define MHD_CPU_COUNT 32 #endif /* MHD_CPU_COUNT > 32 */ #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ #ifndef _MHD_INSTRMACRO /* Quoted macro parameter */ #define _MHD_INSTRMACRO(a) #a #endif /* ! _MHD_INSTRMACRO */ #ifndef _MHD_STRMACRO /* Quoted expanded macro parameter */ #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a) #endif /* ! _MHD_STRMACRO */ /* Could be increased to facilitate debugging */ #define TIMEOUTS_VAL 5 /* Time in ms to wait for final packets to be delivered */ #define FINAL_PACKETS_MS 20 #define EXPECTED_URI_BASE_PATH "/a" #define REQ_HOST "localhost" #define REQ_METHOD "PUT" #define REQ_BODY "Some content data." #define REQ_LINE_END "\r\n" /* Mandatory request headers */ #define REQ_HEADER_HOST_NAME "Host" #define REQ_HEADER_HOST_VALUE REQ_HOST #define REQ_HEADER_HOST \ REQ_HEADER_HOST_NAME ": " REQ_HEADER_HOST_VALUE REQ_LINE_END #define REQ_HEADER_UA_NAME "User-Agent" #define REQ_HEADER_UA_VALUE "dummyclient/0.9" #define REQ_HEADER_UA REQ_HEADER_UA_NAME ": " REQ_HEADER_UA_VALUE REQ_LINE_END /* Optional request headers */ #define REQ_HEADER_CT_NAME "Content-Type" #define REQ_HEADER_CT_VALUE "text/plain" #define REQ_HEADER_CT REQ_HEADER_CT_NAME ": " REQ_HEADER_CT_VALUE REQ_LINE_END #if defined(HAVE___FUNC__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __func__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __func__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __func__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __func__, __LINE__) #elif defined(HAVE___FUNCTION__) #define externalErrorExit(ignore) \ _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) #define mhdErrorExit(ignore) \ _mhdErrorExit_func (NULL, __FUNCTION__, __LINE__) #define mhdErrorExitDesc(errDesc) \ _mhdErrorExit_func (errDesc, __FUNCTION__, __LINE__) #else #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) #define externalErrorExitDesc(errDesc) \ _externalErrorExit_func (errDesc, NULL, __LINE__) #define mhdErrorExit(ignore) _mhdErrorExit_func (NULL, NULL, __LINE__) #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func (errDesc, NULL, __LINE__) #endif _MHD_NORETURN static void _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "System or external library call failed"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); #ifdef MHD_WINSOCK_SOCKETS fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); #endif /* MHD_WINSOCK_SOCKETS */ fflush (stderr); exit (99); } _MHD_NORETURN static void _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum) { if ((NULL != errDesc) && (0 != errDesc[0])) fprintf (stderr, "%s", errDesc); else fprintf (stderr, "MHD unexpected error"); if ((NULL != funcName) && (0 != funcName[0])) fprintf (stderr, " in %s", funcName); if (0 < lineNum) fprintf (stderr, " at line %d", lineNum); fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, strerror (errno)); fflush (stderr); exit (8); } #ifndef MHD_POSIX_SOCKETS /** * Pause execution for specified number of milliseconds. * @param ms the number of milliseconds to sleep */ static void _MHD_sleep (uint32_t ms) { #if defined(_WIN32) Sleep (ms); #elif defined(HAVE_NANOSLEEP) struct timespec slp = {ms / 1000, (ms % 1000) * 1000000}; struct timespec rmn; int num_retries = 0; while (0 != nanosleep (&slp, &rmn)) { if (EINTR != errno) externalErrorExit (); if (num_retries++ > 8) break; slp = rmn; } #elif defined(HAVE_USLEEP) uint64_t us = ms * 1000; do { uint64_t this_sleep; if (999999 < us) this_sleep = 999999; else this_sleep = us; /* Ignore return value as it could be void */ usleep (this_sleep); us -= this_sleep; } while (us > 0); #else externalErrorExitDesc ("No sleep function available on this system"); #endif } #endif /* ! MHD_POSIX_SOCKETS */ /* Global parameters */ static int verbose; /**< Be verbose */ static uint16_t global_port; /**< MHD daemons listen port number */ static void test_global_init (void) { if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE)) { #if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) externalErrorExitDesc ("Error suppressing SIGPIPE signal"); #else /* ! HAVE_SIGNAL_H || ! SIGPIPE */ fprintf (stderr, "Cannot suppress SIGPIPE signal.\n"); /* exit (77); */ #endif } } static void test_global_cleanup (void) { } /** * Change socket to blocking. * * @param fd the socket to manipulate */ static void make_blocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("Cannot make socket non-blocking"); if ((flags & ~O_NONBLOCK) != flags) { if (-1 == fcntl (fd, F_SETFL, flags & ~O_NONBLOCK)) externalErrorExitDesc ("Cannot make socket non-blocking"); } #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 0; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("Cannot make socket non-blocking"); #endif /* MHD_WINSOCK_SOCKETS */ } /** * Change socket to non-blocking. * * @param fd the socket to manipulate */ static void make_nonblocking (MHD_socket fd) { #if defined(MHD_POSIX_SOCKETS) int flags; flags = fcntl (fd, F_GETFL); if (-1 == flags) externalErrorExitDesc ("Cannot make socket non-blocking"); if ((flags | O_NONBLOCK) != flags) { if (-1 == fcntl (fd, F_SETFL, flags | O_NONBLOCK)) externalErrorExitDesc ("Cannot make socket non-blocking"); } #elif defined(MHD_WINSOCK_SOCKETS) unsigned long flags = 1; if (0 != ioctlsocket (fd, (int) FIONBIO, &flags)) externalErrorExitDesc ("Cannot make socket non-blocking"); #endif /* MHD_WINSOCK_SOCKETS */ } enum _MHD_clientStage { DUMB_CLIENT_INIT = 0, DUMB_CLIENT_CONNECTING, DUMB_CLIENT_CONNECTED, DUMB_CLIENT_REQ_SENDING, DUMB_CLIENT_REQ_SENT, DUMB_CLIENT_HEADER_RECVEIVING, DUMB_CLIENT_HEADER_RECVEIVED, DUMB_CLIENT_BODY_RECVEIVING, DUMB_CLIENT_BODY_RECVEIVED, DUMB_CLIENT_FINISHING, DUMB_CLIENT_FINISHED }; struct _MHD_dumbClient { MHD_socket sckt; /**< the socket to communicate */ int sckt_nonblock; /**< non-zero if socket is non-blocking */ uint16_t port; /**< the port to connect to */ char *send_buf; /**< the buffer for the request, malloced */ size_t req_size; /**< the size of the request, including header */ size_t send_off; /**< the number of bytes already sent */ enum _MHD_clientStage stage; /* the test-specific variables */ size_t single_send_size; /**< the maximum number of bytes to be sent by single send() */ size_t send_size_limit; /**< the total number of send bytes limit */ }; struct _MHD_dumbClient * _MHD_dumbClient_create (uint16_t port, const char *method, const char *url, const char *add_headers, const uint8_t *req_body, size_t req_body_size, int chunked); void _MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt, size_t step_size, size_t max_total_send); void _MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt); int _MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt); int _MHD_dumbClient_process (struct _MHD_dumbClient *clnt); void _MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt, MHD_socket *maxsckt, fd_set *rs, fd_set *ws, fd_set *es); /** * Process the client data with send()/recv() as needed based on * information in fd_sets. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt, fd_set *rs, fd_set *ws, fd_set *es); /** * Perform full request. * @param clnt the client to run * @return zero if client finished processing the request, * non-zero if timeout is reached. */ int _MHD_dumbClient_perform (struct _MHD_dumbClient *clnt); /** * Close the client and free internally allocated resources. * @param clnt the client to close */ void _MHD_dumbClient_close (struct _MHD_dumbClient *clnt); struct _MHD_dumbClient * _MHD_dumbClient_create (uint16_t port, const char *method, const char *url, const char *add_headers, const uint8_t *req_body, size_t req_body_size, int chunked) { struct _MHD_dumbClient *clnt; size_t method_size; size_t url_size; size_t add_hdrs_size; size_t buf_alloc_size; char *send_buf; mhd_assert (0 != port); mhd_assert (NULL != req_body || 0 == req_body_size); mhd_assert (0 == req_body_size || NULL != req_body); clnt = (struct _MHD_dumbClient *) malloc (sizeof(struct _MHD_dumbClient)); if (NULL == clnt) externalErrorExit (); memset (clnt, 0, sizeof(struct _MHD_dumbClient)); clnt->sckt = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (MHD_INVALID_SOCKET == clnt->sckt) externalErrorExitDesc ("Cannot create the client socket"); #ifdef MHD_socket_nosignal_ if (! MHD_socket_nosignal_ (clnt->sckt)) externalErrorExitDesc ("Cannot suppress SIGPIPE on the client socket"); #endif /* MHD_socket_nosignal_ */ clnt->sckt_nonblock = 0; if (clnt->sckt_nonblock) make_nonblocking (clnt->sckt); else make_blocking (clnt->sckt); if (1) { /* Always set TCP NODELAY */ const MHD_SCKT_OPT_BOOL_ on_val = 1; if (0 != setsockopt (clnt->sckt, IPPROTO_TCP, TCP_NODELAY, (const void *) &on_val, sizeof (on_val))) externalErrorExitDesc ("Cannot set TCP_NODELAY option"); } clnt->port = port; if (NULL != method) method_size = strlen (method); else { method = MHD_HTTP_METHOD_GET; method_size = MHD_STATICSTR_LEN_ (MHD_HTTP_METHOD_GET); } mhd_assert (0 != method_size); if (NULL != url) url_size = strlen (url); else { url = "/"; url_size = 1; } mhd_assert (0 != url_size); add_hdrs_size = (NULL == add_headers) ? 0 : strlen (add_headers); buf_alloc_size = 1024 + method_size + url_size + add_hdrs_size + req_body_size; send_buf = (char *) malloc (buf_alloc_size); if (NULL == send_buf) externalErrorExit (); clnt->req_size = 0; /* Form the request line */ memcpy (send_buf + clnt->req_size, method, method_size); clnt->req_size += method_size; send_buf[clnt->req_size++] = ' '; memcpy (send_buf + clnt->req_size, url, url_size); clnt->req_size += url_size; send_buf[clnt->req_size++] = ' '; memcpy (send_buf + clnt->req_size, MHD_HTTP_VERSION_1_1, MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1)); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_VERSION_1_1); send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; /* Form the header */ memcpy (send_buf + clnt->req_size, REQ_HEADER_HOST, MHD_STATICSTR_LEN_ (REQ_HEADER_HOST)); clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_HOST); memcpy (send_buf + clnt->req_size, REQ_HEADER_UA, MHD_STATICSTR_LEN_ (REQ_HEADER_UA)); clnt->req_size += MHD_STATICSTR_LEN_ (REQ_HEADER_UA); if ((NULL != req_body) || chunked) { if (! chunked) { int prn_size; memcpy (send_buf + clnt->req_size, MHD_HTTP_HEADER_CONTENT_LENGTH ": ", MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": ")); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_CONTENT_LENGTH ": "); prn_size = snprintf (send_buf + clnt->req_size, (buf_alloc_size - clnt->req_size), "%u", (unsigned int) req_body_size); if (0 >= prn_size) externalErrorExit (); if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size) externalErrorExit (); clnt->req_size += (unsigned int) prn_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } else { memcpy (send_buf + clnt->req_size, MHD_HTTP_HEADER_TRANSFER_ENCODING ": chunked\r\n", MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \ ": chunked\r\n")); clnt->req_size += MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_TRANSFER_ENCODING \ ": chunked\r\n"); } } if (0 != add_hdrs_size) { memcpy (send_buf + clnt->req_size, add_headers, add_hdrs_size); clnt->req_size += add_hdrs_size; } /* Terminate header */ send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; /* Add body (if any) */ if (! chunked) { if (0 != req_body_size) { memcpy (send_buf + clnt->req_size, req_body, req_body_size); clnt->req_size += req_body_size; } } else { if (0 != req_body_size) { int prn_size; prn_size = snprintf (send_buf + clnt->req_size, (buf_alloc_size - clnt->req_size), "%x", (unsigned int) req_body_size); if (0 >= prn_size) externalErrorExit (); if ((unsigned int) prn_size >= buf_alloc_size - clnt->req_size) externalErrorExit (); clnt->req_size += (unsigned int) prn_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; memcpy (send_buf + clnt->req_size, req_body, req_body_size); clnt->req_size += req_body_size; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } send_buf[clnt->req_size++] = '0'; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; send_buf[clnt->req_size++] = '\r'; send_buf[clnt->req_size++] = '\n'; } mhd_assert (clnt->req_size < buf_alloc_size); clnt->send_buf = send_buf; return clnt; } void _MHD_dumbClient_set_send_limits (struct _MHD_dumbClient *clnt, size_t step_size, size_t max_total_send) { clnt->single_send_size = step_size; clnt->send_size_limit = max_total_send; } /* internal */ static void _MHD_dumbClient_connect_init (struct _MHD_dumbClient *clnt) { struct sockaddr_in sa; mhd_assert (DUMB_CLIENT_INIT == clnt->stage); sa.sin_family = AF_INET; sa.sin_port = htons (clnt->port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != connect (clnt->sckt, (struct sockaddr *) &sa, sizeof(sa))) { const int err = MHD_socket_get_error_ (); if ( (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EINPROGRESS_)) || (MHD_SCKT_ERR_IS_EAGAIN_ (err))) clnt->stage = DUMB_CLIENT_CONNECTING; else externalErrorExitDesc ("Cannot 'connect()' the client socket"); } else clnt->stage = DUMB_CLIENT_CONNECTED; } void _MHD_dumbClient_start_connect (struct _MHD_dumbClient *clnt) { mhd_assert (DUMB_CLIENT_INIT == clnt->stage); _MHD_dumbClient_connect_init (clnt); } /* internal */ static void _MHD_dumbClient_connect_finish (struct _MHD_dumbClient *clnt) { int err = 0; socklen_t err_size = sizeof(err); mhd_assert (DUMB_CLIENT_CONNECTING == clnt->stage); if (0 != getsockopt (clnt->sckt, SOL_SOCKET, SO_ERROR, (void *) &err, &err_size)) externalErrorExitDesc ("'getsockopt()' call failed"); if (0 != err) externalErrorExitDesc ("Socket connect() failed"); clnt->stage = DUMB_CLIENT_CONNECTED; } /* internal */ static void _MHD_dumbClient_send_req (struct _MHD_dumbClient *clnt) { size_t send_size; ssize_t res; mhd_assert (DUMB_CLIENT_CONNECTED <= clnt->stage); mhd_assert (DUMB_CLIENT_REQ_SENT > clnt->stage); mhd_assert (clnt->req_size > clnt->send_off); send_size = (((0 != clnt->send_size_limit) && (clnt->req_size > clnt->send_size_limit)) ? clnt->send_size_limit : clnt->req_size) - clnt->send_off; mhd_assert (0 != send_size); if ((0 != clnt->single_send_size) && (clnt->single_send_size < send_size)) send_size = clnt->single_send_size; res = MHD_send_ (clnt->sckt, clnt->send_buf + clnt->send_off, send_size); if (res < 0) { const int err = MHD_socket_get_error_ (); if (MHD_SCKT_ERR_IS_EAGAIN_ (err)) return; if (MHD_SCKT_ERR_IS_EINTR_ (err)) return; if (MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) mhdErrorExitDesc ("The connection was aborted by MHD"); if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_EPIPE_)) mhdErrorExitDesc ("The connection was shut down on MHD side"); externalErrorExitDesc ("Unexpected network error"); } clnt->send_off += (size_t) res; mhd_assert (clnt->send_off <= clnt->req_size); mhd_assert (clnt->send_off <= clnt->send_size_limit || \ 0 == clnt->send_size_limit); if (clnt->req_size == clnt->send_off) clnt->stage = DUMB_CLIENT_REQ_SENT; if ((0 != clnt->send_size_limit) && (clnt->send_size_limit == clnt->send_off)) clnt->stage = DUMB_CLIENT_FINISHING; } /* internal */ _MHD_NORETURN /* not implemented */ static void _MHD_dumbClient_recv_reply (struct _MHD_dumbClient *clnt) { (void) clnt; externalErrorExitDesc ("Not implemented for this test"); } int _MHD_dumbClient_is_req_sent (struct _MHD_dumbClient *clnt) { return DUMB_CLIENT_REQ_SENT <= clnt->stage; } /* internal */ static void _MHD_dumbClient_socket_close (struct _MHD_dumbClient *clnt) { if (MHD_INVALID_SOCKET != clnt->sckt) { if (! MHD_socket_close_ (clnt->sckt)) externalErrorExitDesc ("Unexpected error while closing " \ "the client socket"); clnt->sckt = MHD_INVALID_SOCKET; } } /* internal */ static void _MHD_dumbClient_finalize (struct _MHD_dumbClient *clnt) { if (MHD_INVALID_SOCKET != clnt->sckt) { if (0 != shutdown (clnt->sckt, SHUT_WR)) { const int err = MHD_socket_get_error_ (); if (! MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ENOTCONN_) && ! MHD_SCKT_ERR_IS_REMOTE_DISCNN_ (err)) mhdErrorExitDesc ("Unexpected error when shutting down " \ "the client socket"); } } clnt->stage = DUMB_CLIENT_FINISHED; } /* internal */ static int _MHD_dumbClient_needs_send (const struct _MHD_dumbClient *clnt) { return ((DUMB_CLIENT_CONNECTING <= clnt->stage) && (DUMB_CLIENT_REQ_SENT > clnt->stage)) || (DUMB_CLIENT_FINISHING == clnt->stage); } /* internal */ static int _MHD_dumbClient_needs_recv (const struct _MHD_dumbClient *clnt) { return (DUMB_CLIENT_HEADER_RECVEIVING <= clnt->stage) && (DUMB_CLIENT_BODY_RECVEIVED > clnt->stage); } /* internal */ /** * Check whether the client needs unconditionally process the data. * @param clnt the client to check * @return non-zero if client needs unconditionally process the data, * zero otherwise. */ static int _MHD_dumbClient_needs_process (const struct _MHD_dumbClient *clnt) { switch (clnt->stage) { case DUMB_CLIENT_INIT: case DUMB_CLIENT_REQ_SENT: case DUMB_CLIENT_HEADER_RECVEIVED: case DUMB_CLIENT_BODY_RECVEIVED: case DUMB_CLIENT_FINISHED: return ! 0; case DUMB_CLIENT_CONNECTING: case DUMB_CLIENT_CONNECTED: case DUMB_CLIENT_REQ_SENDING: case DUMB_CLIENT_HEADER_RECVEIVING: case DUMB_CLIENT_BODY_RECVEIVING: case DUMB_CLIENT_FINISHING: default: return 0; } return 0; /* Should be unreachable */ } /** * Process the client data with send()/recv() as needed. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process (struct _MHD_dumbClient *clnt) { do { switch (clnt->stage) { case DUMB_CLIENT_INIT: _MHD_dumbClient_connect_init (clnt); break; case DUMB_CLIENT_CONNECTING: _MHD_dumbClient_connect_finish (clnt); break; case DUMB_CLIENT_CONNECTED: case DUMB_CLIENT_REQ_SENDING: _MHD_dumbClient_send_req (clnt); break; case DUMB_CLIENT_REQ_SENT: mhd_assert (0); clnt->stage = DUMB_CLIENT_HEADER_RECVEIVING; break; case DUMB_CLIENT_HEADER_RECVEIVING: _MHD_dumbClient_recv_reply (clnt); break; case DUMB_CLIENT_HEADER_RECVEIVED: clnt->stage = DUMB_CLIENT_BODY_RECVEIVING; break; case DUMB_CLIENT_BODY_RECVEIVING: _MHD_dumbClient_recv_reply (clnt); break; case DUMB_CLIENT_BODY_RECVEIVED: clnt->stage = DUMB_CLIENT_FINISHING; break; case DUMB_CLIENT_FINISHING: _MHD_dumbClient_finalize (clnt); break; case DUMB_CLIENT_FINISHED: return ! 0; default: mhd_assert (0); mhdErrorExit (); } } while (_MHD_dumbClient_needs_process (clnt)); return DUMB_CLIENT_FINISHED == clnt->stage; } void _MHD_dumbClient_get_fdsets (struct _MHD_dumbClient *clnt, MHD_socket *maxsckt, fd_set *rs, fd_set *ws, fd_set *es) { mhd_assert (NULL != rs); mhd_assert (NULL != ws); mhd_assert (NULL != es); if (DUMB_CLIENT_FINISHED > clnt->stage) { if (MHD_INVALID_SOCKET != clnt->sckt) { if ( (MHD_INVALID_SOCKET == *maxsckt) || (clnt->sckt > *maxsckt) ) *maxsckt = clnt->sckt; if (_MHD_dumbClient_needs_recv (clnt)) FD_SET (clnt->sckt, rs); if (_MHD_dumbClient_needs_send (clnt)) FD_SET (clnt->sckt, ws); FD_SET (clnt->sckt, es); } } } /** * Process the client data with send()/recv() as needed based on * information in fd_sets. * @param clnt the client to process * @return non-zero if client finished processing the request, * zero otherwise. */ int _MHD_dumbClient_process_from_fdsets (struct _MHD_dumbClient *clnt, fd_set *rs, fd_set *ws, fd_set *es) { if (_MHD_dumbClient_needs_process (clnt)) return _MHD_dumbClient_process (clnt); else if (MHD_INVALID_SOCKET != clnt->sckt) { if (_MHD_dumbClient_needs_recv (clnt) && FD_ISSET (clnt->sckt, rs)) return _MHD_dumbClient_process (clnt); else if (_MHD_dumbClient_needs_send (clnt) && FD_ISSET (clnt->sckt, ws)) return _MHD_dumbClient_process (clnt); else if (FD_ISSET (clnt->sckt, es)) return _MHD_dumbClient_process (clnt); } return DUMB_CLIENT_FINISHED == clnt->stage; } /** * Perform full request. * @param clnt the client to run * @return zero if client finished processing the request, * non-zero if timeout is reached. */ int _MHD_dumbClient_perform (struct _MHD_dumbClient *clnt) { time_t start; time_t now; start = time (NULL); now = start; do { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; struct timeval tv; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (! _MHD_dumbClient_needs_process (clnt)) { maxMhdSk = MHD_INVALID_SOCKET; _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es); mhd_assert (now >= start); #ifndef _WIN32 tv.tv_sec = (time_t) (TIMEOUTS_VAL * 2 - (now - start) + 1); #else tv.tv_sec = (long) (TIMEOUTS_VAL * 2 - (now - start) + 1); #endif tv.tv_usec = 250 * 1000; if (-1 == select ((int) (maxMhdSk + 1), &rs, &ws, &es, &tv)) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else /* ! MHD_POSIX_SOCKETS */ mhd_assert ((0 != rs.fd_count) || (0 != ws.fd_count) || \ (0 != es.fd_count)); externalErrorExitDesc ("Unexpected select() error"); _MHD_sleep ((uint32_t) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif /* ! MHD_POSIX_SOCKETS */ continue; } if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es)) return 0; } /* Use double timeout value here as MHD must catch timeout situations * in this test. Timeout in client as a last resort. */ } while ((now = time (NULL)) - start <= (TIMEOUTS_VAL * 2)); return 1; } /** * Close the client and free internally allocated resources. * @param clnt the client to close */ void _MHD_dumbClient_close (struct _MHD_dumbClient *clnt) { if (DUMB_CLIENT_FINISHED != clnt->stage) _MHD_dumbClient_finalize (clnt); _MHD_dumbClient_socket_close (clnt); if (NULL != clnt->send_buf) { free ((void *) clnt->send_buf); clnt->send_buf = NULL; } free (clnt); } _MHD_NORETURN static void socket_cb (void *cls, struct MHD_Connection *c, void **socket_context, enum MHD_ConnectionNotificationCode toe) { (void) cls; /* Unused */ (void) socket_context; /* Unused */ (void) toe; /* Unused */ MHD_suspend_connection (c); /* Should trigger panic */ mhdErrorExitDesc ("Function \"MHD_suspend_connection()\" succeed, while " \ "it must fail as daemon was started without MHD_ALLOW_SUSPEND_RESUME " \ "flag"); } struct ahc_cls_type { const char *volatile rp_data; volatile size_t rp_data_size; const char *volatile rq_method; const char *volatile rq_url; const char *volatile req_body; volatile unsigned int cb_called; /* Non-zero indicates that callback was called at least one time */ size_t req_body_size; /**< The number of bytes in @a req_body */ size_t req_body_uploaded; /* Updated by callback */ }; static enum MHD_Result ahcCheck (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; enum MHD_Result ret; struct ahc_cls_type *const param = (struct ahc_cls_type *) cls; (void) connection; /* Unused */ if (NULL == param) mhdErrorExitDesc ("cls parameter is NULL"); param->cb_called++; if (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) mhdErrorExitDesc ("Unexpected HTTP version"); if (0 != strcmp (url, param->rq_url)) mhdErrorExitDesc ("Unexpected URI"); if (0 != strcmp (param->rq_method, method)) mhdErrorExitDesc ("Unexpected request method"); if (NULL == upload_data_size) mhdErrorExitDesc ("'upload_data_size' pointer is NULL"); if (0 != *upload_data_size) { const char *const upload_body = param->req_body; if (NULL == upload_data) mhdErrorExitDesc ("'upload_data' is NULL while " \ "'*upload_data_size' value is not zero"); if (NULL == upload_body) mhdErrorExitDesc ("'*upload_data_size' value is not zero " \ "while no request body is expected"); if (param->req_body_uploaded + *upload_data_size > param->req_body_size) { fprintf (stderr, "Too large upload body received. Got %u, expected %u", (unsigned int) (param->req_body_uploaded + *upload_data_size), (unsigned int) param->req_body_size); mhdErrorExit (); } if (0 != memcmp (upload_data, upload_body + param->req_body_uploaded, *upload_data_size)) { fprintf (stderr, "Unexpected request body at offset %u: " \ "'%.*s', expected: '%.*s'\n", (unsigned int) param->req_body_uploaded, (int) *upload_data_size, upload_data, (int) *upload_data_size, upload_body + param->req_body_uploaded); mhdErrorExit (); } param->req_body_uploaded += *upload_data_size; *upload_data_size = 0; } if (&marker != *req_cls) { /* The first call of the callback for this connection */ mhd_assert (NULL == upload_data); param->req_body_uploaded = 0; *req_cls = ▮ return MHD_YES; } if (NULL != upload_data) return MHD_YES; /* Full request has not been received so far */ #if 0 /* Code unused in this test */ struct MHD_Response *response; response = MHD_create_response_from_buffer (param->rp_data_size, (void *) param->rp_data, MHD_RESPMEM_MUST_COPY); if (NULL == response) mhdErrorExitDesc ("Failed to create response"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); if (MHD_YES != ret) mhdErrorExitDesc ("Failed to queue response"); #else if (NULL == upload_data) mhdErrorExitDesc ("Full request received, " \ "while incomplete request expected"); ret = MHD_NO; #endif return ret; } struct simpleQueryParams { /* Destination path for HTTP query */ const char *queryPath; /* Custom query method, NULL for default */ const char *method; /* Destination port for HTTP query */ uint16_t queryPort; /* Additional request headers, static */ const char *headers; /* NULL for request without body */ const uint8_t *req_body; size_t req_body_size; /* Non-zero to use chunked encoding for request body */ int chunked; /* HTTP query result error flag */ volatile int queryError; /* Response HTTP code, zero if no response */ volatile int responseCode; }; /* returns non-zero if timed-out */ static int performQueryExternal (struct MHD_Daemon *d, struct _MHD_dumbClient *clnt) { time_t start; struct timeval tv; int ret; const union MHD_DaemonInfo *di; MHD_socket lstn_sk; int client_accepted; int full_req_recieved; int full_req_sent; int some_data_recieved; di = MHD_get_daemon_info (d, MHD_DAEMON_INFO_LISTEN_FD); if (NULL == di) mhdErrorExitDesc ("Cannot get listener socket"); lstn_sk = di->listen_fd; ret = 1; /* will be replaced with real result */ client_accepted = 0; _MHD_dumbClient_start_connect (clnt); full_req_recieved = 0; some_data_recieved = 0; start = time (NULL); do { fd_set rs; fd_set ws; fd_set es; MHD_socket maxMhdSk; int num_ready; int do_client; /**< Process data in client */ maxMhdSk = MHD_INVALID_SOCKET; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (NULL == clnt) { /* client has finished, check whether MHD is still * processing any connections */ full_req_sent = 1; do_client = 0; if (client_accepted && (0 > MHD_get_timeout64s (d))) { ret = 0; break; /* MHD finished as well */ } } else { full_req_sent = _MHD_dumbClient_is_req_sent (clnt); if (! full_req_sent) do_client = 1; /* Request hasn't been sent yet, send the data */ else { /* All request data has been sent. * Client will close the socket as the next step. */ if (full_req_recieved) do_client = 1; /* All data has been received by the MHD */ else if (some_data_recieved) { /* at least something was received by the MHD */ do_client = 1; } else { /* The MHD must receive at least something before closing * the connection. */ do_client = 0; } } if (do_client) _MHD_dumbClient_get_fdsets (clnt, &maxMhdSk, &rs, &ws, &es); } if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) mhdErrorExitDesc ("MHD_get_fdset() failed"); if (do_client) { tv.tv_sec = 1; tv.tv_usec = 250 * 1000; } else { /* Request completely sent but not yet fully received */ tv.tv_sec = 0; tv.tv_usec = FINAL_PACKETS_MS * 1000; } num_ready = select ((int) (maxMhdSk + 1), &rs, &ws, &es, &tv); if (-1 == num_ready) { #ifdef MHD_POSIX_SOCKETS if (EINTR != errno) externalErrorExitDesc ("Unexpected select() error"); #else if ((WSAEINVAL != WSAGetLastError ()) || (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) externalErrorExitDesc ("Unexpected select() error"); _MHD_sleep ((uint32_t) (tv.tv_sec * 1000 + tv.tv_usec / 1000)); #endif continue; } if (0 == num_ready) { /* select() finished by timeout, looks like no more packets are pending */ if (do_client) externalErrorExitDesc ("Timeout waiting for sockets"); if (full_req_sent && (! full_req_recieved)) full_req_recieved = 1; } if (full_req_recieved) mhdErrorExitDesc ("Full request has been received by MHD, while it " "must be aborted by the panic function"); if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) mhdErrorExitDesc ("MHD_run_from_select() failed"); if (! client_accepted) client_accepted = FD_ISSET (lstn_sk, &rs); else { /* Client connection was already accepted by MHD */ if (! some_data_recieved) { if (! do_client) { if (0 != num_ready) { /* Connection was accepted before, "ready" socket means data */ some_data_recieved = 1; } } else { if (2 == num_ready) some_data_recieved = 1; else if ((1 == num_ready) && ((MHD_INVALID_SOCKET == clnt->sckt) || ! FD_ISSET (clnt->sckt, &ws))) some_data_recieved = 1; } } } if (do_client) { if (_MHD_dumbClient_process_from_fdsets (clnt, &rs, &ws, &es)) clnt = NULL; } /* Use double timeout value here so MHD would be able to catch timeout * internally */ } while (time (NULL) - start <= (TIMEOUTS_VAL * 2)); return ret; } /* Returns zero for successful response and non-zero for failed response */ static int doClientQueryInThread (struct MHD_Daemon *d, struct simpleQueryParams *p) { const union MHD_DaemonInfo *dinfo; struct _MHD_dumbClient *c; int errornum; int use_external_poll; dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_FLAGS); if (NULL == dinfo) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); use_external_poll = (0 == (dinfo->flags & MHD_USE_INTERNAL_POLLING_THREAD)); if (0 == p->queryPort) externalErrorExit (); c = _MHD_dumbClient_create (p->queryPort, p->method, p->queryPath, p->headers, p->req_body, p->req_body_size, p->chunked); _MHD_dumbClient_set_send_limits (c, 1, 0); /* 'internal' polling should not be used in this test */ mhd_assert (use_external_poll); if (! use_external_poll) errornum = _MHD_dumbClient_perform (c); else errornum = performQueryExternal (d, c); if (errornum) fprintf (stderr, "Request timeout out.\n"); else mhdErrorExitDesc ("Request succeed, but it must fail"); _MHD_dumbClient_close (c); return errornum; } /* Perform test queries, shut down MHD daemon, and free parameters */ static unsigned int performTestQueries (struct MHD_Daemon *d, uint16_t d_port, struct ahc_cls_type *ahc_param) { struct simpleQueryParams qParam; /* Common parameters, to be individually overridden by specific test cases * if needed */ qParam.queryPort = d_port; qParam.method = MHD_HTTP_METHOD_PUT; qParam.queryPath = EXPECTED_URI_BASE_PATH; qParam.headers = REQ_HEADER_CT; qParam.req_body = (const uint8_t *) REQ_BODY; qParam.req_body_size = MHD_STATICSTR_LEN_ (REQ_BODY); qParam.chunked = 0; ahc_param->rq_url = EXPECTED_URI_BASE_PATH; ahc_param->rq_method = MHD_HTTP_METHOD_PUT; ahc_param->rp_data = "~"; ahc_param->rp_data_size = 1; ahc_param->req_body = (const char *) qParam.req_body; ahc_param->req_body_size = qParam.req_body_size; /* Make sure that maximum size is tested */ /* To be updated by callbacks */ ahc_param->cb_called = 0; if (0 != doClientQueryInThread (d, &qParam)) fprintf (stderr, "FAILED: client query failed."); MHD_stop_daemon (d); free (ahc_param); return 1; /* Always error if reached this point */ } enum testMhdThreadsType { testMhdThreadExternal = 0, testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD, testMhdThreadInternalPool }; enum testMhdPollType { testMhdPollBySelect = 0, testMhdPollByPoll = MHD_USE_POLL, testMhdPollByEpoll = MHD_USE_EPOLL, testMhdPollAuto = MHD_USE_AUTO }; /* Get number of threads for thread pool depending * on used poll function and test type. */ static unsigned int testNumThreadsForPool (enum testMhdPollType pollType) { unsigned int numThreads = MHD_CPU_COUNT; (void) pollType; /* Don't care about pollType for this test */ return numThreads; /* No practical limit for non-cleanup test */ } #define PANIC_MAGIC_CHECK 1133 _MHD_NORETURN static void myPanicCallback (void *cls, const char *file, unsigned int line, const char *reason) { int *const param = (int *) cls; if (NULL == cls) mhdErrorExitDesc ("The 'cls' parameter is NULL"); if (PANIC_MAGIC_CHECK != *param) mhdErrorExitDesc ("Wrong '*cls' value"); #ifdef HAVE_MESSAGES if (NULL == file) mhdErrorExitDesc ("The 'file' parameter is NULL"); if (NULL == reason) mhdErrorExitDesc ("The 'reason' parameter is NULL"); #else /* ! HAVE_MESSAGES */ if (NULL != file) mhdErrorExitDesc ("The 'file' parameter is not NULL"); if (NULL != reason) mhdErrorExitDesc ("The 'reason' parameter is not NULL"); #endif /* ! HAVE_MESSAGES */ fflush (stderr); fflush (stdout); printf ("User panic function has been called from file '%s' at line '%u' " "with the reason:\n%s", file, line, ((NULL != reason) ? reason : "(NULL)\n")); fflush (stdout); exit (0); } static struct MHD_Daemon * startTestMhdDaemon (enum testMhdThreadsType thrType, enum testMhdPollType pollType, uint16_t *pport, struct ahc_cls_type **ahc_param) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; static int magic_panic_param = PANIC_MAGIC_CHECK; if (NULL == ahc_param) externalErrorExit (); *ahc_param = (struct ahc_cls_type *) malloc (sizeof(struct ahc_cls_type)); if (NULL == *ahc_param) externalErrorExit (); if ( (0 == *pport) && (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) { *pport = 4190; } MHD_set_panic_func (&myPanicCallback, (void *) &magic_panic_param); if (testMhdThreadExternal == thrType) d = MHD_start_daemon (((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0) | MHD_USE_NO_THREAD_SAFETY, *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); else if (testMhdThreadInternalPool != thrType) d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_END); else d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | ((unsigned int) pollType) | (verbose ? MHD_USE_ERROR_LOG : 0), *pport, NULL, NULL, &ahcCheck, *ahc_param, MHD_OPTION_THREAD_POOL_SIZE, testNumThreadsForPool (pollType), MHD_OPTION_NOTIFY_CONNECTION, &socket_cb, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned) TIMEOUTS_VAL, MHD_OPTION_END); if (NULL == d) mhdErrorExitDesc ("Failed to start MHD daemon"); if (0 == *pport) { dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port)) mhdErrorExitDesc ("MHD_get_daemon_info() failed"); *pport = dinfo->port; if (0 == global_port) global_port = *pport; /* Reuse the same port for all tests */ } return d; } /* Test runners */ static unsigned int testExternalGet (void) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port, &ahc_param); return performTestQueries (d, d_port, ahc_param); } #if 0 /* disabled runners, not suitable for this test */ static unsigned int testInternalGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternal, pollType, &d_port, &ahc_param, &uri_cb_param, &term_result); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } static int testMultithreadedGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } static unsigned int testMultithreadedPoolGet (enum testMhdPollType pollType) { struct MHD_Daemon *d; uint16_t d_port = global_port; /* Daemon's port */ struct ahc_cls_type *ahc_param; struct check_uri_cls *uri_cb_param; struct term_notif_cb_param *term_result; d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, &d_port, &ahc_param, &uri_cb_param); return performTestQueries (d, d_port, ahc_param, uri_cb_param, term_result); } #endif /* disabled runners, not suitable for this test */ int main (int argc, char *const *argv) { unsigned int errorCount = 0; unsigned int test_result = 0; verbose = 0; (void) has_in_name; /* Unused, mute compiler warning */ if ((NULL == argv) || (0 == argv[0])) return 99; verbose = ! (has_param (argc, argv, "-q") || has_param (argc, argv, "--quiet") || has_param (argc, argv, "-s") || has_param (argc, argv, "--silent")); test_global_init (); /* Could be set to non-zero value to enforce using specific port * in the test */ global_port = 0; test_result = testExternalGet (); if (test_result) fprintf (stderr, "FAILED: testExternalGet (). Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testExternalGet ().\n"); errorCount += test_result; #if 0 /* disabled runners, not suitable for this test */ if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) { test_result = testInternalGet (testMhdPollAuto); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollAuto). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; #ifdef _MHD_HEAVY_TESTS /* Actually tests are not heavy, but took too long to complete while * not really provide any additional results. */ test_result = testInternalGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedPoolGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedPoolGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); errorCount += test_result; test_result = testMultithreadedGet (testMhdPollBySelect); if (test_result) fprintf (stderr, "FAILED: testMultithreadedGet (testMhdPollBySelect). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); errorCount += test_result; if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) { test_result = testInternalGet (testMhdPollByPoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); errorCount += test_result; } if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) { test_result = testInternalGet (testMhdPollByEpoll); if (test_result) fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll). " "Result: %u.\n", test_result); else if (verbose) printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); errorCount += test_result; } #else /* Mute compiler warnings */ (void) testMultithreadedGet; (void) testMultithreadedPoolGet; #endif /* _MHD_HEAVY_TESTS */ } #endif /* disabled runners, not suitable for this test */ if (0 != errorCount) fprintf (stderr, "Error (code: %u)\n", errorCount); else if (verbose) printf ("All tests passed.\n"); test_global_cleanup (); return (errorCount == 0) ? 0 : 1; /* 0 == pass */ } libmicrohttpd-1.0.10/src/microhttpd/test_helpers.h0000644000175000017500000000545414760713577015765 /* This file is part of libmicrohttpd Copyright (C) 2016 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_helpers.h * @brief Static functions and macros helpers for testsuite. * @author Karlson2k (Evgeny Grin) */ #include /** * Check whether program name contains specific @a marker string. * Only last component in pathname is checked for marker presence, * all leading directories names (if any) are ignored. Directories * separators are handled correctly on both non-W32 and W32 * platforms. * @param prog_name program name, may include path * @param marker marker to look for. * @return zero if any parameter is NULL or empty string or * @a prog_name ends with slash or @a marker is not found in * program name, non-zero if @a maker is found in program * name. */ static int has_in_name (const char *prog_name, const char *marker) { size_t name_pos; size_t pos; if (! prog_name || ! marker || ! prog_name[0] || ! marker[0]) return 0; pos = 0; name_pos = 0; while (prog_name[pos]) { if ('/' == prog_name[pos]) name_pos = pos + 1; #if defined(_WIN32) || defined(__CYGWIN__) else if ('\\' == prog_name[pos]) name_pos = pos + 1; #endif /* _WIN32 || __CYGWIN__ */ pos++; } if (name_pos == pos) return 0; return strstr (prog_name + name_pos, marker) != (char *) 0; } /** * Check whether one of strings in array is equal to @a param. * String @a argv[0] is ignored. * @param argc number of strings in @a argv, as passed to main function * @param argv array of strings, as passed to main function * @param param parameter to look for. * @return zero if @a argv is NULL, @a param is NULL or empty string, * @a argc is less then 2 or @a param is not found in @a argv, * non-zero if one of strings in @a argv is equal to @a param. */ static int has_param (int argc, char *const argv[], const char *param) { int i; if (! argv || ! param || ! param[0]) return 0; for (i = 1; i < argc; i++) { if (argv[i] && (strcmp (argv[i], param) == 0) ) return ! 0; } return 0; } libmicrohttpd-1.0.10/src/microhttpd/reason_phrase.c0000644000175000017500000002352614760713574016105 /* This file is part of libmicrohttpd Copyright (C) 2007, 2011, 2017, 2019 Christian Grothoff Copyright (C) 2017-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file reason_phrase.c * @brief Tables of the string response phrases * @author Elliot Glaysher * @author Christian Grothoff (minor code clean up) * @author Karlson2k (Evgeny Grin) */ #include "platform.h" #include "microhttpd.h" #include "mhd_str.h" #ifndef NULL #define NULL ((void*) 0) #endif static const struct _MHD_cstr_w_len invalid_hundred[] = { { NULL, 0 } }; static const struct _MHD_cstr_w_len one_hundred[] = { /* 100 */ _MHD_S_STR_W_LEN ("Continue"), /* RFC9110, Section 15.2.1 */ /* 101 */ _MHD_S_STR_W_LEN ("Switching Protocols"), /* RFC9110, Section 15.2.2 */ /* 102 */ _MHD_S_STR_W_LEN ("Processing"), /* RFC2518 */ /* 103 */ _MHD_S_STR_W_LEN ("Early Hints") /* RFC8297 */ }; static const struct _MHD_cstr_w_len two_hundred[] = { /* 200 */ _MHD_S_STR_W_LEN ("OK"), /* RFC9110, Section 15.3.1 */ /* 201 */ _MHD_S_STR_W_LEN ("Created"), /* RFC9110, Section 15.3.2 */ /* 202 */ _MHD_S_STR_W_LEN ("Accepted"), /* RFC9110, Section 15.3.3 */ /* 203 */ _MHD_S_STR_W_LEN ("Non-Authoritative Information"), /* RFC9110, Section 15.3.4 */ /* 204 */ _MHD_S_STR_W_LEN ("No Content"), /* RFC9110, Section 15.3.5 */ /* 205 */ _MHD_S_STR_W_LEN ("Reset Content"), /* RFC9110, Section 15.3.6 */ /* 206 */ _MHD_S_STR_W_LEN ("Partial Content"), /* RFC9110, Section 15.3.7 */ /* 207 */ _MHD_S_STR_W_LEN ("Multi-Status"), /* RFC4918 */ /* 208 */ _MHD_S_STR_W_LEN ("Already Reported"), /* RFC5842 */ /* 209 */ {"Unknown", 0}, /* Not used */ /* 210 */ {"Unknown", 0}, /* Not used */ /* 211 */ {"Unknown", 0}, /* Not used */ /* 212 */ {"Unknown", 0}, /* Not used */ /* 213 */ {"Unknown", 0}, /* Not used */ /* 214 */ {"Unknown", 0}, /* Not used */ /* 215 */ {"Unknown", 0}, /* Not used */ /* 216 */ {"Unknown", 0}, /* Not used */ /* 217 */ {"Unknown", 0}, /* Not used */ /* 218 */ {"Unknown", 0}, /* Not used */ /* 219 */ {"Unknown", 0}, /* Not used */ /* 220 */ {"Unknown", 0}, /* Not used */ /* 221 */ {"Unknown", 0}, /* Not used */ /* 222 */ {"Unknown", 0}, /* Not used */ /* 223 */ {"Unknown", 0}, /* Not used */ /* 224 */ {"Unknown", 0}, /* Not used */ /* 225 */ {"Unknown", 0}, /* Not used */ /* 226 */ _MHD_S_STR_W_LEN ("IM Used") /* RFC3229 */ }; static const struct _MHD_cstr_w_len three_hundred[] = { /* 300 */ _MHD_S_STR_W_LEN ("Multiple Choices"), /* RFC9110, Section 15.4.1 */ /* 301 */ _MHD_S_STR_W_LEN ("Moved Permanently"), /* RFC9110, Section 15.4.2 */ /* 302 */ _MHD_S_STR_W_LEN ("Found"), /* RFC9110, Section 15.4.3 */ /* 303 */ _MHD_S_STR_W_LEN ("See Other"), /* RFC9110, Section 15.4.4 */ /* 304 */ _MHD_S_STR_W_LEN ("Not Modified"), /* RFC9110, Section 15.4.5 */ /* 305 */ _MHD_S_STR_W_LEN ("Use Proxy"), /* RFC9110, Section 15.4.6 */ /* 306 */ _MHD_S_STR_W_LEN ("Switch Proxy"), /* Not used! RFC9110, Section 15.4.7 */ /* 307 */ _MHD_S_STR_W_LEN ("Temporary Redirect"), /* RFC9110, Section 15.4.8 */ /* 308 */ _MHD_S_STR_W_LEN ("Permanent Redirect") /* RFC9110, Section 15.4.9 */ }; static const struct _MHD_cstr_w_len four_hundred[] = { /* 400 */ _MHD_S_STR_W_LEN ("Bad Request"), /* RFC9110, Section 15.5.1 */ /* 401 */ _MHD_S_STR_W_LEN ("Unauthorized"), /* RFC9110, Section 15.5.2 */ /* 402 */ _MHD_S_STR_W_LEN ("Payment Required"), /* RFC9110, Section 15.5.3 */ /* 403 */ _MHD_S_STR_W_LEN ("Forbidden"), /* RFC9110, Section 15.5.4 */ /* 404 */ _MHD_S_STR_W_LEN ("Not Found"), /* RFC9110, Section 15.5.5 */ /* 405 */ _MHD_S_STR_W_LEN ("Method Not Allowed"), /* RFC9110, Section 15.5.6 */ /* 406 */ _MHD_S_STR_W_LEN ("Not Acceptable"), /* RFC9110, Section 15.5.7 */ /* 407 */ _MHD_S_STR_W_LEN ("Proxy Authentication Required"), /* RFC9110, Section 15.5.8 */ /* 408 */ _MHD_S_STR_W_LEN ("Request Timeout"), /* RFC9110, Section 15.5.9 */ /* 409 */ _MHD_S_STR_W_LEN ("Conflict"), /* RFC9110, Section 15.5.10 */ /* 410 */ _MHD_S_STR_W_LEN ("Gone"), /* RFC9110, Section 15.5.11 */ /* 411 */ _MHD_S_STR_W_LEN ("Length Required"), /* RFC9110, Section 15.5.12 */ /* 412 */ _MHD_S_STR_W_LEN ("Precondition Failed"), /* RFC9110, Section 15.5.13 */ /* 413 */ _MHD_S_STR_W_LEN ("Content Too Large"), /* RFC9110, Section 15.5.14 */ /* 414 */ _MHD_S_STR_W_LEN ("URI Too Long"), /* RFC9110, Section 15.5.15 */ /* 415 */ _MHD_S_STR_W_LEN ("Unsupported Media Type"), /* RFC9110, Section 15.5.16 */ /* 416 */ _MHD_S_STR_W_LEN ("Range Not Satisfiable"), /* RFC9110, Section 15.5.17 */ /* 417 */ _MHD_S_STR_W_LEN ("Expectation Failed"), /* RFC9110, Section 15.5.18 */ /* 418 */ {"Unknown", 0}, /* Not used */ /* 419 */ {"Unknown", 0}, /* Not used */ /* 420 */ {"Unknown", 0}, /* Not used */ /* 421 */ _MHD_S_STR_W_LEN ("Misdirected Request"), /* RFC9110, Section 15.5.20 */ /* 422 */ _MHD_S_STR_W_LEN ("Unprocessable Content"), /* RFC9110, Section 15.5.21 */ /* 423 */ _MHD_S_STR_W_LEN ("Locked"), /* RFC4918 */ /* 424 */ _MHD_S_STR_W_LEN ("Failed Dependency"), /* RFC4918 */ /* 425 */ _MHD_S_STR_W_LEN ("Too Early"), /* RFC8470 */ /* 426 */ _MHD_S_STR_W_LEN ("Upgrade Required"), /* RFC9110, Section 15.5.22 */ /* 427 */ {"Unknown", 0}, /* Not used */ /* 428 */ _MHD_S_STR_W_LEN ("Precondition Required"), /* RFC6585 */ /* 429 */ _MHD_S_STR_W_LEN ("Too Many Requests"), /* RFC6585 */ /* 430 */ {"Unknown", 0}, /* Not used */ /* 431 */ _MHD_S_STR_W_LEN ("Request Header Fields Too Large"), /* RFC6585 */ /* 432 */ {"Unknown", 0}, /* Not used */ /* 433 */ {"Unknown", 0}, /* Not used */ /* 434 */ {"Unknown", 0}, /* Not used */ /* 435 */ {"Unknown", 0}, /* Not used */ /* 436 */ {"Unknown", 0}, /* Not used */ /* 437 */ {"Unknown", 0}, /* Not used */ /* 438 */ {"Unknown", 0}, /* Not used */ /* 439 */ {"Unknown", 0}, /* Not used */ /* 440 */ {"Unknown", 0}, /* Not used */ /* 441 */ {"Unknown", 0}, /* Not used */ /* 442 */ {"Unknown", 0}, /* Not used */ /* 443 */ {"Unknown", 0}, /* Not used */ /* 444 */ {"Unknown", 0}, /* Not used */ /* 445 */ {"Unknown", 0}, /* Not used */ /* 446 */ {"Unknown", 0}, /* Not used */ /* 447 */ {"Unknown", 0}, /* Not used */ /* 448 */ {"Unknown", 0}, /* Not used */ /* 449 */ _MHD_S_STR_W_LEN ("Reply With"), /* MS IIS extension */ /* 450 */ _MHD_S_STR_W_LEN ("Blocked by Windows Parental Controls"), /* MS extension */ /* 451 */ _MHD_S_STR_W_LEN ("Unavailable For Legal Reasons") /* RFC7725 */ }; static const struct _MHD_cstr_w_len five_hundred[] = { /* 500 */ _MHD_S_STR_W_LEN ("Internal Server Error"), /* RFC9110, Section 15.6.1 */ /* 501 */ _MHD_S_STR_W_LEN ("Not Implemented"), /* RFC9110, Section 15.6.2 */ /* 502 */ _MHD_S_STR_W_LEN ("Bad Gateway"), /* RFC9110, Section 15.6.3 */ /* 503 */ _MHD_S_STR_W_LEN ("Service Unavailable"), /* RFC9110, Section 15.6.4 */ /* 504 */ _MHD_S_STR_W_LEN ("Gateway Timeout"), /* RFC9110, Section 15.6.5 */ /* 505 */ _MHD_S_STR_W_LEN ("HTTP Version Not Supported"), /* RFC9110, Section 15.6.6 */ /* 506 */ _MHD_S_STR_W_LEN ("Variant Also Negotiates"), /* RFC2295 */ /* 507 */ _MHD_S_STR_W_LEN ("Insufficient Storage"), /* RFC4918 */ /* 508 */ _MHD_S_STR_W_LEN ("Loop Detected"), /* RFC5842 */ /* 509 */ _MHD_S_STR_W_LEN ("Bandwidth Limit Exceeded"), /* Apache extension */ /* 510 */ _MHD_S_STR_W_LEN ("Not Extended"), /* (OBSOLETED) RFC2774; status-change-http-experiments-to-historic */ /* 511 */ _MHD_S_STR_W_LEN ("Network Authentication Required") /* RFC6585 */ }; struct MHD_Reason_Block { size_t max; const struct _MHD_cstr_w_len *const data; }; #define BLOCK(m) { (sizeof(m) / sizeof(m[0])), m } static const struct MHD_Reason_Block reasons[] = { BLOCK (invalid_hundred), BLOCK (one_hundred), BLOCK (two_hundred), BLOCK (three_hundred), BLOCK (four_hundred), BLOCK (five_hundred), }; _MHD_EXTERN const char * MHD_get_reason_phrase_for (unsigned int code) { if ( (code >= 100) && (code < 600) && (reasons[code / 100].max > (code % 100)) ) return reasons[code / 100].data[code % 100].str; return "Unknown"; } _MHD_EXTERN size_t MHD_get_reason_phrase_len_for (unsigned int code) { if ( (code >= 100) && (code < 600) && (reasons[code / 100].max > (code % 100)) ) return reasons[code / 100].data[code % 100].len; return 0; } libmicrohttpd-1.0.10/src/microhttpd/memorypool.c0000664000175000017500000007176715232360725015461 /* This file is part of libmicrohttpd Copyright (C) 2007--2024 Daniel Pittman and Christian Grothoff Copyright (C) 2014--2024 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file memorypool.c * @brief memory pool * @author Christian Grothoff * @author Karlson2k (Evgeny Grin) */ #include "memorypool.h" #ifdef HAVE_STDLIB_H #include #endif /* HAVE_STDLIB_H */ #include #include #include "mhd_assert.h" #include "mhd_check.h" #ifdef HAVE_SYS_MMAN_H #include #endif #ifdef _WIN32 #include #endif #ifdef HAVE_SYSCONF #include #if defined(_SC_PAGE_SIZE) #define MHD_SC_PAGESIZE _SC_PAGE_SIZE #elif defined(_SC_PAGESIZE) #define MHD_SC_PAGESIZE _SC_PAGESIZE #endif /* _SC_PAGESIZE */ #endif /* HAVE_SYSCONF */ #include "mhd_limits.h" /* for SIZE_MAX, PAGESIZE / PAGE_SIZE */ #if defined(MHD_USE_PAGESIZE_MACRO) || defined(MHD_USE_PAGE_SIZE_MACRO) #ifndef HAVE_SYSCONF /* Avoid duplicate include */ #include #endif /* HAVE_SYSCONF */ #ifdef HAVE_SYS_PARAM_H #include #endif /* HAVE_SYS_PARAM_H */ #endif /* MHD_USE_PAGESIZE_MACRO || MHD_USE_PAGE_SIZE_MACRO */ /** * Fallback value of page size */ #define _MHD_FALLBACK_PAGE_SIZE (4096) #if defined(MHD_USE_PAGESIZE_MACRO) #define MHD_DEF_PAGE_SIZE_ PAGESIZE #elif defined(MHD_USE_PAGE_SIZE_MACRO) #define MHD_DEF_PAGE_SIZE_ PAGE_SIZE #else /* ! PAGESIZE */ #define MHD_DEF_PAGE_SIZE_ _MHD_FALLBACK_PAGE_SIZE #endif /* ! PAGESIZE */ #ifdef MHD_ASAN_POISON_ACTIVE #include #endif /* MHD_ASAN_POISON_ACTIVE */ /* define MAP_ANONYMOUS for Mac OS X */ #if defined(MAP_ANON) && ! defined(MAP_ANONYMOUS) #define MAP_ANONYMOUS MAP_ANON #endif #if defined(_WIN32) #define MAP_FAILED NULL #elif ! defined(MAP_FAILED) #define MAP_FAILED ((void*) -1) #endif /** * Align to 2x word size (as GNU libc does). */ #define ALIGN_SIZE (2 * sizeof(void*)) /** * Round up 'n' to a multiple of ALIGN_SIZE. */ #define ROUND_TO_ALIGN(n) (((n) + (ALIGN_SIZE - 1)) \ / (ALIGN_SIZE) *(ALIGN_SIZE)) /* ROUND_TO_ALIGN_PLUS_RED_ZONE() rounds up and, when user poisoning is active, adds a red zone, so its result is always >= its argument -- unless it wrapped. Every caller that passes a caller-supplied size must therefore reject the result with if (asize < size) and not by testing for zero. Testing for zero is correct only in the build where the red zone is 0: ROUND_TO_ALIGN() lands exactly on 0 for the top ALIGN_SIZE-1 values of size_t, so a zero result is the only wrapped outcome there. Adding a red zone moves that outcome to _MHD_RED_ZONE_SIZE, which is non-zero and small enough to pass the remaining-space test below it, so a zero test silently stops firing in exactly the build that has the extra instrumentation. Sizes that are already bounded by pool->size (MHD_pool_reset(), the block_offset + block_size expressions) cannot wrap and need no such test -- but they do need the trailing red zone clamped to pool->size, see the two sites that do so. */ #ifndef MHD_ASAN_POISON_ACTIVE #define _MHD_NOSANITIZE_PTRS /**/ #define _MHD_RED_ZONE_SIZE (0) #define ROUND_TO_ALIGN_PLUS_RED_ZONE(n) ROUND_TO_ALIGN(n) #define _MHD_POISON_MEMORY(pointer, size) (void)0 #define _MHD_UNPOISON_MEMORY(pointer, size) (void)0 /** * Boolean 'true' if the first pointer is less or equal the second pointer */ #define mp_ptr_le_(p1,p2) \ (((const uint8_t*)(p1)) <= ((const uint8_t*)(p2))) /** * The difference in bytes between positions of the first and * the second pointers */ #define mp_ptr_diff_(p1,p2) \ ((size_t)(((const uint8_t*)(p1)) - ((const uint8_t*)(p2)))) #else /* MHD_ASAN_POISON_ACTIVE */ #define _MHD_RED_ZONE_SIZE (ALIGN_SIZE) #define ROUND_TO_ALIGN_PLUS_RED_ZONE(n) (ROUND_TO_ALIGN(n) + _MHD_RED_ZONE_SIZE) #define _MHD_POISON_MEMORY(pointer, size) \ ASAN_POISON_MEMORY_REGION ((pointer), (size)) #define _MHD_UNPOISON_MEMORY(pointer, size) \ ASAN_UNPOISON_MEMORY_REGION ((pointer), (size)) #if defined(FUNC_PTRCOMPARE_CAST_WORKAROUND_WORKS) /** * Boolean 'true' if the first pointer is less or equal the second pointer */ #define mp_ptr_le_(p1,p2) \ (((uintptr_t)((const void*)(p1))) <= ((uintptr_t)((const void*)(p2)))) /** * The difference in bytes between positions of the first and * the second pointers */ #define mp_ptr_diff_(p1,p2) \ ((size_t)(((uintptr_t)((const uint8_t*)(p1))) - \ ((uintptr_t)((const uint8_t*)(p2))))) #elif defined(FUNC_ATTR_PTRCOMPARE_WORKS) && \ defined(FUNC_ATTR_PTRSUBTRACT_WORKS) #ifdef _DEBUG /** * Boolean 'true' if the first pointer is less or equal the second pointer */ __attribute__((no_sanitize ("pointer-compare"))) static bool mp_ptr_le_ (const void *p1, const void *p2) { return (((const uint8_t *) p1) <= ((const uint8_t *) p2)); } #endif /* _DEBUG */ /** * The difference in bytes between positions of the first and * the second pointers */ __attribute__((no_sanitize ("pointer-subtract"))) static size_t mp_ptr_diff_ (const void *p1, const void *p2) { return (size_t) (((const uint8_t *) p1) - ((const uint8_t *) p2)); } #elif defined(FUNC_ATTR_NOSANITIZE_WORKS) #ifdef _DEBUG /** * Boolean 'true' if the first pointer is less or equal the second pointer */ __attribute__((no_sanitize ("address"))) static bool mp_ptr_le_ (const void *p1, const void *p2) { return (((const uint8_t *) p1) <= ((const uint8_t *) p2)); } #endif /* _DEBUG */ /** * The difference in bytes between positions of the first and * the second pointers */ __attribute__((no_sanitize ("address"))) static size_t mp_ptr_diff_ (const void *p1, const void *p2) { return (size_t) (((const uint8_t *) p1) - ((const uint8_t *) p2)); } #else /* ! FUNC_ATTR_NOSANITIZE_WORKS */ #error User-poisoning cannot be used #endif /* ! FUNC_ATTR_NOSANITIZE_WORKS */ #endif /* MHD_ASAN_POISON_ACTIVE */ /** * Size of memory page */ static size_t MHD_sys_page_size_ = (size_t) #if defined(MHD_USE_PAGESIZE_MACRO_STATIC) PAGESIZE; #elif defined(MHD_USE_PAGE_SIZE_MACRO_STATIC) PAGE_SIZE; #else /* ! MHD_USE_PAGE_SIZE_MACRO_STATIC */ _MHD_FALLBACK_PAGE_SIZE; /* Default fallback value */ #endif /* ! MHD_USE_PAGE_SIZE_MACRO_STATIC */ /** * Initialise values for memory pools */ void MHD_init_mem_pools_ (void) { #ifdef MHD_SC_PAGESIZE long result; result = sysconf (MHD_SC_PAGESIZE); if (-1 != result) MHD_sys_page_size_ = (size_t) result; else MHD_sys_page_size_ = (size_t) MHD_DEF_PAGE_SIZE_; #elif defined(_WIN32) SYSTEM_INFO si; GetSystemInfo (&si); MHD_sys_page_size_ = (size_t) si.dwPageSize; #else MHD_sys_page_size_ = (size_t) MHD_DEF_PAGE_SIZE_; #endif /* _WIN32 */ mhd_assert (0 == (MHD_sys_page_size_ % ALIGN_SIZE)); } /** * Handle for a memory pool. Pools are not reentrant and must not be * used by multiple threads. */ struct MemoryPool { /** * Pointer to the pool's memory */ uint8_t *memory; /** * Size of the pool. */ size_t size; /** * Offset of the first unallocated byte. */ size_t pos; /** * Offset of the byte after the last unallocated byte. */ size_t end; /** * 'false' if pool was malloc'ed, 'true' if mmapped (VirtualAlloc'ed for W32). */ bool is_mmap; }; /** * Create a memory pool. * * @param max maximum size of the pool * @return NULL on error */ struct MemoryPool * MHD_pool_create (size_t max) { struct MemoryPool *pool; size_t alloc_size; mhd_assert (max > 0); alloc_size = 0; pool = malloc (sizeof (struct MemoryPool)); if (NULL == pool) return NULL; #if defined(MAP_ANONYMOUS) || defined(_WIN32) if ( (max <= 32 * 1024) || (max < MHD_sys_page_size_ * 4 / 3) ) { pool->memory = MAP_FAILED; } else { /* Round up allocation to page granularity. */ alloc_size = max + MHD_sys_page_size_ - 1; alloc_size -= alloc_size % MHD_sys_page_size_; #if defined(MAP_ANONYMOUS) && ! defined(_WIN32) pool->memory = mmap (NULL, alloc_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); #elif defined(_WIN32) pool->memory = VirtualAlloc (NULL, alloc_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); #endif /* _WIN32 */ } #else /* ! _WIN32 && ! MAP_ANONYMOUS */ pool->memory = MAP_FAILED; #endif /* ! _WIN32 && ! MAP_ANONYMOUS */ if (MAP_FAILED == pool->memory) { alloc_size = ROUND_TO_ALIGN (max); pool->memory = malloc (alloc_size); if (NULL == pool->memory) { free (pool); return NULL; } pool->is_mmap = false; } #if defined(MAP_ANONYMOUS) || defined(_WIN32) else { pool->is_mmap = true; } #endif /* _WIN32 || MAP_ANONYMOUS */ mhd_assert (0 == (((uintptr_t) pool->memory) % ALIGN_SIZE)); pool->pos = 0; pool->end = alloc_size; pool->size = alloc_size; mhd_assert (0 < alloc_size); _MHD_POISON_MEMORY (pool->memory, pool->size); return pool; } /** * Destroy a memory pool. * * @param pool memory pool to destroy */ void MHD_pool_destroy (struct MemoryPool *pool) { if (NULL == pool) return; mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); _MHD_UNPOISON_MEMORY (pool->memory, pool->size); if (! pool->is_mmap) free (pool->memory); else #if defined(MAP_ANONYMOUS) && ! defined(_WIN32) munmap (pool->memory, pool->size); #elif defined(_WIN32) VirtualFree (pool->memory, 0, MEM_RELEASE); #else abort (); #endif free (pool); } /** * Check how much memory is left in the @a pool * * @param pool pool to check * @return number of bytes still available in @a pool */ size_t MHD_pool_get_free (struct MemoryPool *pool) { mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); #ifdef MHD_ASAN_POISON_ACTIVE if ((pool->end - pool->pos) <= _MHD_RED_ZONE_SIZE) return 0; #endif /* MHD_ASAN_POISON_ACTIVE */ return (pool->end - pool->pos) - _MHD_RED_ZONE_SIZE; } /** * Allocate size bytes from the pool. * * @param pool memory pool to use for the operation * @param size number of bytes to allocate * @param from_end allocate from end of pool (set to 'true'); * use this for small, persistent allocations that * will never be reallocated * @return NULL if the pool cannot support size more * bytes */ void * MHD_pool_allocate (struct MemoryPool *pool, size_t size, bool from_end) { void *ret; size_t asize; mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); asize = ROUND_TO_ALIGN_PLUS_RED_ZONE (size); if (asize < size) return NULL; /* Value wrap, @a size is too close to SIZE_MAX */ if (asize > pool->end - pool->pos) return NULL; if (from_end) { ret = &pool->memory[pool->end - asize]; pool->end -= asize; } else { ret = &pool->memory[pool->pos]; pool->pos += asize; } _MHD_UNPOISON_MEMORY (ret, size); return ret; } /** * Checks whether allocated block is re-sizable in-place. * If block is not re-sizable in-place, it still could be shrunk, but freed * memory will not be re-used until reset of the pool. * @param pool the memory pool to use * @param block the pointer to the allocated block to check * @param block_size the size of the allocated @a block * @return true if block can be resized in-place in the optimal way, * false otherwise */ bool MHD_pool_is_resizable_inplace (struct MemoryPool *pool, void *block, size_t block_size) { mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (block != NULL || block_size == 0); mhd_assert (pool->size >= block_size); if (NULL != block) { const size_t block_offset = mp_ptr_diff_ (block, pool->memory); mhd_assert (mp_ptr_le_ (pool->memory, block)); mhd_assert (pool->size >= block_offset); mhd_assert (pool->size >= block_offset + block_size); return (pool->pos == ROUND_TO_ALIGN_PLUS_RED_ZONE (block_offset + block_size)); } return false; /* Unallocated blocks cannot be resized in-place */ } /** * Try to allocate @a size bytes memory area from the @a pool. * * If allocation fails, @a required_bytes is updated with size required to be * freed in the @a pool from rellocatable area to allocate requested number * of bytes. * Allocated memory area is always not rellocatable ("from end"). * * @param pool memory pool to use for the operation * @param size the size of memory in bytes to allocate * @param[out] required_bytes the pointer to variable to be updated with * the size of the required additional free * memory area, set to 0 if function succeeds. * Cannot be NULL. * @return the pointer to allocated memory area if succeed, * NULL if the pool doesn't have enough space, required_bytes is updated * with amount of space needed to be freed in rellocatable area or * set to SIZE_MAX if requested size is too large for the pool. */ void * MHD_pool_try_alloc (struct MemoryPool *pool, size_t size, size_t *required_bytes) { void *ret; size_t asize; mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); asize = ROUND_TO_ALIGN_PLUS_RED_ZONE (size); if (asize < size) { /* Value wrap, @a size is too close to SIZE_MAX, very unlikely */ *required_bytes = SIZE_MAX; return NULL; } if (asize > pool->end - pool->pos) { mhd_assert ((pool->end - pool->pos) == \ ROUND_TO_ALIGN (pool->end - pool->pos)); if (asize <= pool->end) *required_bytes = asize - (pool->end - pool->pos); else *required_bytes = SIZE_MAX; return NULL; } *required_bytes = 0; ret = &pool->memory[pool->end - asize]; pool->end -= asize; _MHD_UNPOISON_MEMORY (ret, size); return ret; } /** * Reallocate a block of memory obtained from the pool. * This is particularly efficient when growing or * shrinking the block that was last (re)allocated. * If the given block is not the most recently * (re)allocated block, the memory of the previous * allocation may be not released until the pool is * destroyed or reset. * * @param pool memory pool to use for the operation * @param old the existing block * @param old_size the size of the existing block * @param new_size the new size of the block * @return new address of the block, or * NULL if the pool cannot support @a new_size * bytes (old continues to be valid for @a old_size) */ void * MHD_pool_reallocate (struct MemoryPool *pool, void *old, size_t old_size, size_t new_size) { size_t asize; uint8_t *new_blc; mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (old != NULL || old_size == 0); mhd_assert (pool->size >= old_size); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); #if defined(MHD_ASAN_POISON_ACTIVE) && defined(HAVE___ASAN_REGION_IS_POISONED) mhd_assert (NULL == __asan_region_is_poisoned (old, old_size)); #endif /* MHD_ASAN_POISON_ACTIVE && HAVE___ASAN_REGION_IS_POISONED */ /* No block can ever be larger than the pool, so reject that here once rather than in each of the paths below. This is what stops a wrapping @a new_size: both remaining size tests are made on values that ROUND_TO_ALIGN_PLUS_RED_ZONE() has already wrapped back to something small and plausible, so neither of them fires and the caller is handed a block it believes is nearly SIZE_MAX bytes long. The documented contract is to return NULL when the pool cannot support @a new_size bytes. */ if (new_size > pool->size) return NULL; if (NULL != old) { /* Have previously allocated data */ const size_t old_offset = mp_ptr_diff_ (old, pool->memory); const bool shrinking = (old_size > new_size); /* 'old' and 'old_size' come from the caller and bound both the memset() that shrinking performs a few lines below and the memcpy (new_blc, old, old_size) at the end of this function, so this is the precondition of two unbounded copies and must hold in release builds too. Failing it returns NULL, aka "the pool cannot satisfy this request" and which leaves 'old' valid, so the connection is failed by the caller instead of corrupting the pool. The lower bound stays an assertion because mp_ptr_le_() only exists in debug builds when user-poisoning is active; it is subsumed anyway, because mp_ptr_diff_() wraps for a pointer below pool->memory and the resulting huge 'old_offset' fails the bound below. */ mhd_assert (mp_ptr_le_ (pool->memory, old)); /* (pool->memory + pool->size >= (uint8_t*) old + old_size) */ MHD_CHECK_RET_ ((pool->size - _MHD_RED_ZONE_SIZE) >= (old_offset + old_size), NULL); /* Blocks "from the end" must not be reallocated */ /* (old_size == 0 || pool->memory + pool->pos > (uint8_t*) old) */ mhd_assert ((old_size == 0) || \ (pool->pos > old_offset)); mhd_assert ((old_size == 0) || \ ((pool->end - _MHD_RED_ZONE_SIZE) >= (old_offset + old_size))); /* Try resizing in-place */ if (shrinking) { /* Shrinking in-place, zero-out freed part */ memset ((uint8_t *) old + new_size, 0, old_size - new_size); _MHD_POISON_MEMORY ((uint8_t *) old + new_size, old_size - new_size); } if (pool->pos == ROUND_TO_ALIGN_PLUS_RED_ZONE (old_offset + old_size)) { /* "old" block is the last allocated block */ const size_t new_apos = ROUND_TO_ALIGN_PLUS_RED_ZONE (old_offset + new_size); if (! shrinking) { /* Grow in-place, check for enough space. */ /* Reject a wrapping @a new_size before looking at 'new_apos'. 'old_offset + new_size' can wrap all the way round and land back inside [pool->pos, pool->end], and the two tests below then both pass: the caller is handed a block it believes is nearly SIZE_MAX bytes long. The "allocate a new block" path further down already has an explicit wrap test; this is the same check for the in-place path. */ if (new_size > pool->size - old_offset) return NULL; /* Value wrap, or beyond the pool */ if ( (new_apos > pool->end) || (new_apos < pool->pos) ) /* Value wrap */ return NULL; /* No space */ } /* Resized in-place */ pool->pos = new_apos; _MHD_UNPOISON_MEMORY (old, new_size); return old; } if (shrinking) return old; /* Resized in-place, freed part remains allocated */ } /* Need to allocate new block */ asize = ROUND_TO_ALIGN_PLUS_RED_ZONE (new_size); if ( (asize < new_size) || /* Value wrap, too large new_size. */ (asize > pool->end - pool->pos) ) /* Not enough space */ return NULL; new_blc = pool->memory + pool->pos; pool->pos += asize; _MHD_UNPOISON_MEMORY (new_blc, new_size); if (0 != old_size) { /* Move data to new block, old block remains allocated */ memcpy (new_blc, old, old_size); /* Zero-out old block */ memset (old, 0, old_size); _MHD_POISON_MEMORY (old, old_size); } return new_blc; } /** * Deallocate a block of memory obtained from the pool. * * If the given block is not the most recently * (re)allocated block, the memory of the this block * allocation may be not released until the pool is * destroyed or reset. * * @param pool memory pool to use for the operation * @param block the allocated block, the NULL is tolerated * @param block_size the size of the allocated block */ void MHD_pool_deallocate (struct MemoryPool *pool, void *block, size_t block_size) { mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (block != NULL || block_size == 0); mhd_assert (pool->size >= block_size); mhd_assert (pool->pos == ROUND_TO_ALIGN (pool->pos)); if (NULL != block) { /* Have previously allocated data */ const size_t block_offset = mp_ptr_diff_ (block, pool->memory); mhd_assert (mp_ptr_le_ (pool->memory, block)); mhd_assert (block_offset <= pool->size); /* A block allocated "from the end" starts at or after pool->end, a "normal" block starts before it. Those two ranges meet when the pool is exactly full (pool->pos == pool->end), so an end block may legitimately start at pool->pos; only a normal block may not. */ mhd_assert ((block_offset >= pool->end) || \ (block_offset != pool->pos) || (block_size == 0)); /* Zero-out deallocated region */ if (0 != block_size) { memset (block, 0, block_size); _MHD_POISON_MEMORY (block, block_size); } #if ! defined(MHD_FAVOR_SMALL_CODE) && ! defined(MHD_ASAN_POISON_ACTIVE) else return; /* Zero size, no need to do anything */ #endif /* ! MHD_FAVOR_SMALL_CODE && ! MHD_ASAN_POISON_ACTIVE */ if (block_offset < pool->end) { /* "Normal" block, not allocated "from the end". The test is against pool->end, not pool->pos: when the pool is exactly full the two are equal, and a block allocated "from the end" then also satisfies 'block_offset <= pool->pos', so it would be mistaken for a normal block and never returned. */ size_t alg_end = ROUND_TO_ALIGN_PLUS_RED_ZONE (block_offset + block_size); /* Clamped exactly as MHD_pool_reset() clamps pool->pos, and for the same reason: a block that reaches the end of the pool has no room for a trailing red zone, so its recorded end is pool->size. The two have to agree or the "is this the last block" test below can never match such a block. */ if (alg_end > pool->size) alg_end = pool->size; mhd_assert (alg_end <= pool->pos); if (alg_end == pool->pos) { /* The last allocated block, return deallocated block to the pool */ size_t alg_start = ROUND_TO_ALIGN (block_offset); mhd_assert (alg_start >= block_offset); #if defined(MHD_ASAN_POISON_ACTIVE) if (alg_start != block_offset) { _MHD_POISON_MEMORY (pool->memory + block_offset, \ alg_start - block_offset); } else if (0 != alg_start) { bool need_red_zone_before; mhd_assert (_MHD_RED_ZONE_SIZE <= alg_start); #if defined(HAVE___ASAN_REGION_IS_POISONED) need_red_zone_before = (NULL == __asan_region_is_poisoned (pool->memory + alg_start - _MHD_RED_ZONE_SIZE, _MHD_RED_ZONE_SIZE)); #elif defined(HAVE___ASAN_ADDRESS_IS_POISONED) need_red_zone_before = (0 == __asan_address_is_poisoned (pool->memory + alg_start - 1)); #else /* ! HAVE___ASAN_ADDRESS_IS_POISONED */ need_red_zone_before = true; /* Unknown, assume new red zone needed */ #endif /* ! HAVE___ASAN_ADDRESS_IS_POISONED */ if (need_red_zone_before) { _MHD_POISON_MEMORY (pool->memory + alg_start, _MHD_RED_ZONE_SIZE); alg_start += _MHD_RED_ZONE_SIZE; } } #endif /* MHD_ASAN_POISON_ACTIVE */ mhd_assert (alg_start <= pool->pos); mhd_assert (alg_start == ROUND_TO_ALIGN (alg_start)); pool->pos = alg_start; } } else { /* Allocated "from the end" block. */ /* The size and the pointers of such block should not be manipulated by MHD code (block split is disallowed). */ mhd_assert (block_offset >= pool->end); mhd_assert (ROUND_TO_ALIGN (block_offset) == block_offset); if (block_offset == pool->end) { /* The last allocated block, return deallocated block to the pool */ const size_t alg_end = ROUND_TO_ALIGN_PLUS_RED_ZONE (block_offset + block_size); pool->end = alg_end; } } } } /** * Clear all entries from the memory pool except * for @a keep of the given @a copy_bytes. The pointer * returned should be a buffer of @a new_size where * the first @a copy_bytes are from @a keep. * * @param pool memory pool to use for the operation * @param keep pointer to the entry to keep (maybe NULL) * @param copy_bytes how many bytes need to be kept at this address * @param new_size how many bytes should the allocation we return have? * (should be larger or equal to @a copy_bytes) * @return addr new address of @a keep (if it had to change) */ void * MHD_pool_reset (struct MemoryPool *pool, void *keep, size_t copy_bytes, size_t new_size) { mhd_assert (pool->end >= pool->pos); mhd_assert (pool->size >= pool->end - pool->pos); mhd_assert (copy_bytes <= new_size); mhd_assert (new_size <= pool->size); mhd_assert (copy_bytes <= pool->size); mhd_assert (keep != NULL || copy_bytes == 0); mhd_assert (keep == NULL || mp_ptr_le_ (pool->memory, keep)); /* (keep == NULL || pool->memory + pool->size >= (uint8_t*) keep + copy_bytes) */ mhd_assert ((keep == NULL) || \ (pool->size >= mp_ptr_diff_ (keep, pool->memory) + copy_bytes)); #if defined(MHD_ASAN_POISON_ACTIVE) && defined(HAVE___ASAN_REGION_IS_POISONED) mhd_assert (NULL == __asan_region_is_poisoned (keep, copy_bytes)); #endif /* MHD_ASAN_POISON_ACTIVE && HAVE___ASAN_REGION_IS_POISONED */ _MHD_UNPOISON_MEMORY (pool->memory, new_size); if ( (NULL != keep) && (keep != pool->memory) ) { if (0 != copy_bytes) memmove (pool->memory, keep, copy_bytes); } /* technically not needed, but safer to zero out */ if (pool->size > copy_bytes) { size_t to_zero; /** Size of area to zero-out */ to_zero = pool->size - copy_bytes; _MHD_UNPOISON_MEMORY (pool->memory + copy_bytes, to_zero); #ifdef _WIN32 if (pool->is_mmap) { size_t to_recommit; /** Size of decommitted and re-committed area. */ uint8_t *recommit_addr; /* Round down to page size */ to_recommit = to_zero - to_zero % MHD_sys_page_size_; recommit_addr = pool->memory + pool->size - to_recommit; /* De-committing and re-committing again clear memory and make * pages free / available for other needs until accessed. */ if (VirtualFree (recommit_addr, to_recommit, MEM_DECOMMIT)) { to_zero -= to_recommit; if (recommit_addr != VirtualAlloc (recommit_addr, to_recommit, MEM_COMMIT, PAGE_READWRITE)) abort (); /* Serious error, must never happen */ } } #endif /* _WIN32 */ memset (&pool->memory[copy_bytes], 0, to_zero); } pool->pos = ROUND_TO_ALIGN_PLUS_RED_ZONE (new_size); /* The red zone is a gap kept *inside* the pool so that an overrun of the block lands in poisoned bytes. There is no room for it once the kept block reaches the end of the pool, and none is needed there either -- past pool->size the allocation's own ASAN red zone takes over. Without this clamp pool->pos would be set past pool->end for any @a new_size within a red zone of pool->size, breaking the pool->end >= pool->pos invariant that every other entry point asserts. In the build with no user poisoning _MHD_RED_ZONE_SIZE is 0 and this can never fire. */ if (pool->pos > pool->size) pool->pos = pool->size; pool->end = pool->size; _MHD_POISON_MEMORY (((uint8_t *) pool->memory) + new_size, \ pool->size - new_size); return pool->memory; } /* end of memorypool.c */ libmicrohttpd-1.0.10/src/microhttpd/gen_auth.c0000644000175000017500000005632215232067271015035 /* This file is part of libmicrohttpd Copyright (C) 2022-2023 Evgeny Grin (Karlson2k) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/gen_auth.c * @brief HTTP authorisation general functions * @author Karlson2k (Evgeny Grin) */ #include "gen_auth.h" #include "internal.h" #include "connection.h" #include "mhd_str.h" #include "mhd_assert.h" #ifdef BAUTH_SUPPORT #include "basicauth.h" #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT #include "digestauth.h" #endif /* DAUTH_SUPPORT */ #if ! defined(BAUTH_SUPPORT) && ! defined(DAUTH_SUPPORT) #error This file requires Basic or Digest authentication support #endif /** * Type of authorisation */ enum MHD_AuthType { MHD_AUTHTYPE_NONE = 0,/**< No authorisation, unused */ MHD_AUTHTYPE_BASIC, /**< Basic Authorisation, RFC 7617 */ MHD_AUTHTYPE_DIGEST, /**< Digest Authorisation, RFC 7616 */ MHD_AUTHTYPE_UNKNOWN, /**< Unknown/Unsupported authorisation type, unused */ MHD_AUTHTYPE_INVALID /**< Wrong/broken authorisation header, unused */ }; /** * Find required "Authorization" request header * @param c the connection with request * @param type the type of the authorisation: basic or digest * @param[out] auth_value will be set to the remaining of header value after * authorisation token (after "Basic " or "Digest ") * @return true if requested header is found, * false otherwise */ static bool find_auth_rq_header_ (const struct MHD_Connection *c, enum MHD_AuthType type, struct _MHD_str_w_len *auth_value) { const struct MHD_HTTP_Req_Header *h; const char *token; size_t token_len; mhd_assert (MHD_CONNECTION_HEADERS_PROCESSED <= c->state); if (MHD_CONNECTION_HEADERS_PROCESSED > c->state) return false; #ifdef DAUTH_SUPPORT if (MHD_AUTHTYPE_DIGEST == type) { token = _MHD_AUTH_DIGEST_BASE; token_len = MHD_STATICSTR_LEN_ (_MHD_AUTH_DIGEST_BASE); } else /* combined with the next line */ #endif /* DAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT if (MHD_AUTHTYPE_BASIC == type) { token = _MHD_AUTH_BASIC_BASE; token_len = MHD_STATICSTR_LEN_ (_MHD_AUTH_BASIC_BASE); } else /* combined with the next line */ #endif /* BAUTH_SUPPORT */ { mhd_assert (0); return false; } for (h = c->rq.headers_received; NULL != h; h = h->next) { if (MHD_HEADER_KIND != h->kind) continue; if (MHD_STATICSTR_LEN_ (MHD_HTTP_HEADER_AUTHORIZATION) != h->header_size) continue; if (token_len > h->value_size) continue; if (! MHD_str_equal_caseless_bin_n_ (MHD_HTTP_HEADER_AUTHORIZATION, h->header, MHD_STATICSTR_LEN_ ( \ MHD_HTTP_HEADER_AUTHORIZATION))) continue; if (! MHD_str_equal_caseless_bin_n_ (h->value, token, token_len)) continue; /* Match only if token string is full header value or token is * followed by space or tab * Note: RFC 9110 (and RFC 7234) allows only space character, but * tab is supported here as well for additional flexibility and uniformity * as tabs are supported as separators between parameters. */ if ((token_len == h->value_size) || (' ' == h->value[token_len]) || ('\t' == h->value[token_len])) { if (token_len != h->value_size) { /* Skip whitespace */ auth_value->str = h->value + token_len + 1; auth_value->len = h->value_size - (token_len + 1); } else { /* No whitespace to skip */ auth_value->str = h->value + token_len; auth_value->len = h->value_size - token_len; } return true; /* Found a match */ } } return false; /* No matching header has been found */ } #ifdef BAUTH_SUPPORT /** * Parse request Authorization header parameters for Basic Authentication * @param str the header string, everything after "Basic " substring * @param str_len the length of @a str in characters * @param[out] pbauth the pointer to the structure with Basic Authentication * parameters * @return true if parameters has been successfully parsed, * false if format of the @a str is invalid */ static bool parse_bauth_params (const char *str, size_t str_len, struct MHD_RqBAuth *pbauth) { size_t i; i = 0; /* Skip all whitespaces at start */ while (i < str_len && (' ' == str[i] || '\t' == str[i])) i++; if (str_len > i) { size_t token68_start; size_t token68_len; /* 'i' points to the first non-whitespace char after scheme token */ token68_start = i; /* Find end of the token. Token cannot contain whitespace. */ while (i < str_len && ' ' != str[i] && '\t' != str[i]) { if (0 == str[i]) return false; /* Binary zero is not allowed */ if ((',' == str[i]) || (';' == str[i])) return false; /* Only single token68 is allowed */ i++; } token68_len = i - token68_start; mhd_assert (0 != token68_len); /* Skip all whitespaces */ while (i < str_len && (' ' == str[i] || '\t' == str[i])) i++; /* Check whether any garbage is present at the end of the string */ if (str_len != i) return false; else { /* No more data in the string, only single token68. */ pbauth->token68.str = str + token68_start; pbauth->token68.len = token68_len; } } return true; } /** * Return request's Basic Authorisation parameters. * * Function return result of parsing of the request's "Authorization" header or * returns cached parsing result if the header was already parsed for * the current request. * @param connection the connection to process * @return the pointer to structure with Authentication parameters, * NULL if no memory in memory pool, if called too early (before * header has been received) or if no valid Basic Authorisation header * found. */ const struct MHD_RqBAuth * MHD_get_rq_bauth_params_ (struct MHD_Connection *connection) { struct _MHD_str_w_len h_auth_value; struct MHD_RqBAuth *bauth; mhd_assert (MHD_CONNECTION_HEADERS_PROCESSED <= connection->state); if (connection->rq.bauth_tried) return connection->rq.bauth; if (MHD_CONNECTION_HEADERS_PROCESSED > connection->state) return NULL; if (! find_auth_rq_header_ (connection, MHD_AUTHTYPE_BASIC, &h_auth_value)) { connection->rq.bauth_tried = true; connection->rq.bauth = NULL; return NULL; } bauth = (struct MHD_RqBAuth *) MHD_connection_alloc_memory_ (connection, sizeof (struct MHD_RqBAuth)); if (NULL == bauth) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Not enough memory in the connection's pool to allocate " \ "for Basic Authorization header parsing.\n")); #endif /* HAVE_MESSAGES */ return NULL; } memset (bauth, 0, sizeof(struct MHD_RqBAuth)); if (parse_bauth_params (h_auth_value.str, h_auth_value.len, bauth)) connection->rq.bauth = bauth; else { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The Basic Authorization client's header has " "incorrect format.\n")); #endif /* HAVE_MESSAGES */ connection->rq.bauth = NULL; /* Memory in the pool remains allocated until next request */ } connection->rq.bauth_tried = true; return connection->rq.bauth; } #endif /* BAUTH_SUPPORT */ #ifdef DAUTH_SUPPORT /** * Get client's Digest Authorization algorithm type. * If no algorithm is specified by client, MD5 is assumed. * @param params the Digest Authorization 'algorithm' parameter * @return the algorithm type */ static enum MHD_DigestAuthAlgo3 get_rq_dauth_algo (const struct MHD_RqDAuthParam *const algo_param) { if (NULL == algo_param->value.str) return MHD_DIGEST_AUTH_ALGO3_MD5; /* Assume MD5 by default */ if (algo_param->quoted) { if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_MD5_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_MD5; if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_SHA256_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_SHA256; if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_SHA512_256_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_SHA512_256; /* Algorithms below are not supported by MHD for authentication */ if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_MD5_TOKEN _MHD_SESS_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_MD5_SESSION; if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_SHA256_TOKEN \ _MHD_SESS_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION; if (MHD_str_equal_caseless_quoted_s_bin_n (algo_param->value.str, \ algo_param->value.len, \ _MHD_SHA512_256_TOKEN \ _MHD_SESS_TOKEN)) return MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION; /* No known algorithm has been detected */ return MHD_DIGEST_AUTH_ALGO3_INVALID; } /* The algorithm value is not quoted */ if (MHD_str_equal_caseless_s_bin_n_ (_MHD_MD5_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_MD5; if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA256_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_SHA256; if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA512_256_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_SHA512_256; /* Algorithms below are not supported by MHD for authentication */ if (MHD_str_equal_caseless_s_bin_n_ (_MHD_MD5_TOKEN _MHD_SESS_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_MD5_SESSION; if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA256_TOKEN _MHD_SESS_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_SHA256_SESSION; if (MHD_str_equal_caseless_s_bin_n_ (_MHD_SHA512_256_TOKEN _MHD_SESS_TOKEN, \ algo_param->value.str, \ algo_param->value.len)) return MHD_DIGEST_AUTH_ALGO3_SHA512_256_SESSION; /* No known algorithm has been detected */ return MHD_DIGEST_AUTH_ALGO3_INVALID; } /** * Get QOP ('quality of protection') type. * @param qop_param the Digest Authorization 'QOP' parameter * @return detected QOP ('quality of protection') type. */ static enum MHD_DigestAuthQOP get_rq_dauth_qop (const struct MHD_RqDAuthParam *const qop_param) { if (NULL == qop_param->value.str) return MHD_DIGEST_AUTH_QOP_NONE; if (qop_param->quoted) { if (MHD_str_equal_caseless_quoted_s_bin_n (qop_param->value.str, \ qop_param->value.len, \ MHD_TOKEN_AUTH_)) return MHD_DIGEST_AUTH_QOP_AUTH; if (MHD_str_equal_caseless_quoted_s_bin_n (qop_param->value.str, \ qop_param->value.len, \ MHD_TOKEN_AUTH_INT_)) return MHD_DIGEST_AUTH_QOP_AUTH_INT; } else { if (MHD_str_equal_caseless_s_bin_n_ (MHD_TOKEN_AUTH_, \ qop_param->value.str, \ qop_param->value.len)) return MHD_DIGEST_AUTH_QOP_AUTH; if (MHD_str_equal_caseless_s_bin_n_ (MHD_TOKEN_AUTH_INT_, \ qop_param->value.str, \ qop_param->value.len)) return MHD_DIGEST_AUTH_QOP_AUTH_INT; } /* No know QOP has been detected */ return MHD_DIGEST_AUTH_QOP_INVALID; } /** * Parse request Authorization header parameters for Digest Authentication * @param str the header string, everything after "Digest " substring * @param str_len the length of @a str in characters * @param[out] pdauth the pointer to the structure with Digest Authentication * parameters * @return true if parameters has been successfully parsed, * false if format of the @a str is invalid */ static bool parse_dauth_params (const char *str, const size_t str_len, struct MHD_RqDAuth *pdauth) { /* The tokens */ static const struct _MHD_cstr_w_len nonce_tk = _MHD_S_STR_W_LEN ("nonce"); static const struct _MHD_cstr_w_len opaque_tk = _MHD_S_STR_W_LEN ("opaque"); static const struct _MHD_cstr_w_len algorithm_tk = _MHD_S_STR_W_LEN ("algorithm"); static const struct _MHD_cstr_w_len response_tk = _MHD_S_STR_W_LEN ("response"); static const struct _MHD_cstr_w_len username_tk = _MHD_S_STR_W_LEN ("username"); static const struct _MHD_cstr_w_len username_ext_tk = _MHD_S_STR_W_LEN ("username*"); static const struct _MHD_cstr_w_len realm_tk = _MHD_S_STR_W_LEN ("realm"); static const struct _MHD_cstr_w_len uri_tk = _MHD_S_STR_W_LEN ("uri"); static const struct _MHD_cstr_w_len qop_tk = _MHD_S_STR_W_LEN ("qop"); static const struct _MHD_cstr_w_len cnonce_tk = _MHD_S_STR_W_LEN ("cnonce"); static const struct _MHD_cstr_w_len nc_tk = _MHD_S_STR_W_LEN ("nc"); static const struct _MHD_cstr_w_len userhash_tk = _MHD_S_STR_W_LEN ("userhash"); /* The locally processed parameters */ struct MHD_RqDAuthParam userhash; struct MHD_RqDAuthParam algorithm; /* Indexes */ size_t i; size_t p; /* The list of the tokens. The order of the elements matches the next array. */ static const struct _MHD_cstr_w_len *const tk_names[] = { &nonce_tk, /* 0 */ &opaque_tk, /* 1 */ &algorithm_tk, /* 2 */ &response_tk, /* 3 */ &username_tk, /* 4 */ &username_ext_tk, /* 5 */ &realm_tk, /* 6 */ &uri_tk, /* 7 */ &qop_tk, /* 8 */ &cnonce_tk, /* 9 */ &nc_tk, /* 10 */ &userhash_tk /* 11 */ }; /* The list of the parameters. The order of the elements matches the previous array. */ struct MHD_RqDAuthParam *params[sizeof(tk_names) / sizeof(tk_names[0])]; params[0 ] = &(pdauth->nonce); /* 0 */ params[1 ] = &(pdauth->opaque); /* 1 */ params[2 ] = &algorithm; /* 2 */ params[3 ] = &(pdauth->response); /* 3 */ params[4 ] = &(pdauth->username); /* 4 */ params[5 ] = &(pdauth->username_ext); /* 5 */ params[6 ] = &(pdauth->realm); /* 6 */ params[7 ] = &(pdauth->uri); /* 7 */ params[8 ] = &(pdauth->qop_raw); /* 8 */ params[9 ] = &(pdauth->cnonce); /* 9 */ params[10] = &(pdauth->nc); /* 10 */ params[11] = &userhash; /* 11 */ mhd_assert ((sizeof(tk_names) / sizeof(tk_names[0])) == \ (sizeof(params) / sizeof(params[0]))); memset (&userhash, 0, sizeof(userhash)); memset (&algorithm, 0, sizeof(algorithm)); i = 0; /* Skip all whitespaces at start */ while (i < str_len && (' ' == str[i] || '\t' == str[i])) i++; while (str_len > i) { size_t left; mhd_assert (' ' != str[i]); mhd_assert ('\t' != str[i]); left = str_len - i; if ('=' == str[i]) return false; /* The equal sign is not allowed as the first character */ for (p = 0; p < (sizeof(tk_names) / sizeof(tk_names[0])); ++p) { const struct _MHD_cstr_w_len *const tk_name = tk_names[p]; struct MHD_RqDAuthParam *const param = params[p]; if ( (tk_name->len <= left) && MHD_str_equal_caseless_bin_n_ (str + i, tk_name->str, tk_name->len) && ((tk_name->len == left) || ('=' == str[i + tk_name->len]) || (' ' == str[i + tk_name->len]) || ('\t' == str[i + tk_name->len]) || (',' == str[i + tk_name->len]) || (';' == str[i + tk_name->len])) ) { size_t value_start; size_t value_len; bool quoted; /* Only mark as "quoted" if backslash-escape used */ if (tk_name->len == left) return false; /* No equal sign after parameter name, broken data */ quoted = false; i += tk_name->len; /* Skip all whitespaces before '=' */ while (str_len > i && (' ' == str[i] || '\t' == str[i])) i++; if ((i == str_len) || ('=' != str[i])) return false; /* No equal sign, broken data */ i++; /* Skip all whitespaces after '=' */ while (str_len > i && (' ' == str[i] || '\t' == str[i])) i++; if ((str_len > i) && ('"' == str[i])) { /* Value is in quotation marks */ i++; /* Advance after the opening quote */ value_start = i; while (str_len > i && '"' != str[i]) { if ('\\' == str[i]) { i++; quoted = true; /* Have escaped chars */ } if (0 == str[i]) return false; /* Binary zero in parameter value */ i++; } if (str_len <= i) return false; /* No closing quote */ mhd_assert ('"' == str[i]); value_len = i - value_start; i++; /* Advance after the closing quote */ } else { value_start = i; while (str_len > i && ',' != str[i] && ' ' != str[i] && '\t' != str[i] && ';' != str[i]) { if (0 == str[i]) return false; /* Binary zero in parameter value */ i++; } if (';' == str[i]) return false; /* Semicolon in parameter value */ value_len = i - value_start; } /* Skip all whitespaces after parameter value */ while (str_len > i && (' ' == str[i] || '\t' == str[i])) i++; if ((str_len > i) && (',' != str[i])) return false; /* Garbage after parameter value */ /* Have valid parameter name and value */ mhd_assert (! quoted || 0 != value_len); param->value.str = str + value_start; param->value.len = value_len; param->quoted = quoted; break; /* Found matching parameter name */ } } if (p == (sizeof(tk_names) / sizeof(tk_names[0]))) { /* No matching parameter name */ while (str_len > i && ',' != str[i]) { if ((0 == str[i]) || (';' == str[i])) return false; /* Not allowed characters */ if ('"' == str[i]) { /* Skip quoted part */ i++; /* Advance after the opening quote */ while (str_len > i && '"' != str[i]) { if (0 == str[i]) return false; /* Binary zero is not allowed */ if ('\\' == str[i]) i++; /* Skip escaped char */ i++; } if (str_len <= i) return false; /* No closing quote */ mhd_assert ('"' == str[i]); } i++; } } mhd_assert (str_len == i || ',' == str[i]); if (str_len > i) i++; /* Advance after ',' */ /* Skip all whitespaces before next parameter name */ while (i < str_len && (' ' == str[i] || '\t' == str[i])) i++; } /* Postprocess values */ if (NULL != userhash.value.str) { if (userhash.quoted) pdauth->userhash = MHD_str_equal_caseless_quoted_s_bin_n (userhash.value.str, \ userhash.value.len, \ "true"); else pdauth->userhash = MHD_str_equal_caseless_s_bin_n_ ("true", userhash.value.str, \ userhash.value.len); } else pdauth->userhash = false; pdauth->algo3 = get_rq_dauth_algo (&algorithm); pdauth->qop = get_rq_dauth_qop (&pdauth->qop_raw); return true; } /** * Return request's Digest Authorisation parameters. * * Function return result of parsing of the request's "Authorization" header or * returns cached parsing result if the header was already parsed for * the current request. * @param connection the connection to process * @return the pointer to structure with Authentication parameters, * NULL if no memory in memory pool, if called too early (before * header has been received) or if no valid Basic Authorisation header * found. */ const struct MHD_RqDAuth * MHD_get_rq_dauth_params_ (struct MHD_Connection *connection) { struct _MHD_str_w_len h_auth_value; struct MHD_RqDAuth *dauth; mhd_assert (MHD_CONNECTION_HEADERS_PROCESSED <= connection->state); if (connection->rq.dauth_tried) return connection->rq.dauth; if (MHD_CONNECTION_HEADERS_PROCESSED > connection->state) return NULL; if (! find_auth_rq_header_ (connection, MHD_AUTHTYPE_DIGEST, &h_auth_value)) { connection->rq.dauth_tried = true; connection->rq.dauth = NULL; return NULL; } dauth = (struct MHD_RqDAuth *) MHD_connection_alloc_memory_ (connection, sizeof (struct MHD_RqDAuth)); if (NULL == dauth) { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("Not enough memory in the connection's pool to allocate " \ "for Digest Authorization header parsing.\n")); #endif /* HAVE_MESSAGES */ return NULL; } memset (dauth, 0, sizeof(struct MHD_RqDAuth)); if (parse_dauth_params (h_auth_value.str, h_auth_value.len, dauth)) connection->rq.dauth = dauth; else { #ifdef HAVE_MESSAGES MHD_DLOG (connection->daemon, _ ("The Digest Authorization client's header has " "incorrect format.\n")); #endif /* HAVE_MESSAGES */ connection->rq.dauth = NULL; /* Memory in the pool remains allocated until next request */ } connection->rq.dauth_tried = true; return connection->rq.dauth; } #endif /* DAUTH_SUPPORT */ libmicrohttpd-1.0.10/src/microhttpd/mhd_threads.h0000644000175000017500000004536515035214301015524 /* This file is part of libmicrohttpd Copyright (C) 2016-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_threads.h * @brief Header for platform-independent threads abstraction * @author Karlson2k (Evgeny Grin) * * Provides basic abstraction for threads. * Any functions can be implemented as macro on some platforms * unless explicitly marked otherwise. * Any function argument can be skipped in macro, so avoid * variable modification in function parameters. * * @warning Unlike pthread functions, most of functions return * nonzero on success. */ #ifndef MHD_THREADS_H #define MHD_THREADS_H 1 #include "mhd_options.h" #ifdef HAVE_STDDEF_H # include /* for size_t */ #elif defined(HAVE_STDLIB_H) # include /* for size_t */ #else /* ! HAVE_STDLIB_H */ # include /* for size_t */ #endif /* ! HAVE_STDLIB_H */ #if defined(MHD_USE_POSIX_THREADS) # undef HAVE_CONFIG_H # include # define HAVE_CONFIG_H 1 # ifndef MHD_USE_THREADS # define MHD_USE_THREADS 1 # endif #elif defined(MHD_USE_W32_THREADS) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN 1 # endif /* !WIN32_LEAN_AND_MEAN */ # include # ifndef MHD_USE_THREADS # define MHD_USE_THREADS 1 # endif #else # error No threading API is available. #endif #ifdef HAVE_STDBOOL_H # include #endif /* HAVE_STDBOOL_H */ #if defined(MHD_USE_POSIX_THREADS) && defined(MHD_USE_W32_THREADS) # error Both MHD_USE_POSIX_THREADS and MHD_USE_W32_THREADS are defined #endif /* MHD_USE_POSIX_THREADS && MHD_USE_W32_THREADS */ #ifndef MHD_NO_THREAD_NAMES # if defined(MHD_USE_POSIX_THREADS) # if defined(HAVE_PTHREAD_SETNAME_NP_GNU) || \ defined(HAVE_PTHREAD_SET_NAME_NP_FREEBSD) || \ defined(HAVE_PTHREAD_SETNAME_NP_DARWIN) || \ defined(HAVE_PTHREAD_SETNAME_NP_NETBSD) || \ defined(HAVE_PTHREAD_ATTR_SETNAME_NP_NETBSD) || \ defined(HAVE_PTHREAD_ATTR_SETNAME_NP_IBMI) # define MHD_USE_THREAD_NAME_ # endif /* HAVE_PTHREAD_SETNAME_NP */ # elif defined(MHD_USE_W32_THREADS) # ifdef _MSC_FULL_VER /* Thread names only available with VC compiler */ # define MHD_USE_THREAD_NAME_ # endif /* _MSC_FULL_VER */ # endif #endif /* ** Thread handle - used to control the thread ** */ #if defined(MHD_USE_POSIX_THREADS) /** * Wait until specified thread is ended and free thread handle on success. * @param thread handle to watch * @return nonzero on success, zero otherwise */ # define MHD_join_thread_(native_handle) \ (! pthread_join ((native_handle), NULL)) #elif defined(MHD_USE_W32_THREADS) /** * Wait until specified thread is ended and free thread handle on success. * @param thread handle to watch * @return nonzero on success, zero otherwise */ # define MHD_join_thread_(native_handle) \ ( (WAIT_OBJECT_0 == WaitForSingleObject ( (native_handle), INFINITE)) ? \ (CloseHandle ( (native_handle)), ! 0) : 0 ) #endif #if defined(MHD_USE_POSIX_THREADS) /** * The native type to control the thread from other threads */ typedef pthread_t MHD_thread_handle_native_; #elif defined(MHD_USE_W32_THREADS) /** * The native type to control the thread from other threads */ typedef HANDLE MHD_thread_handle_native_; #endif #if defined(MHD_USE_POSIX_THREADS) # if defined(__gnu_linux__) || \ (defined(__linux__) && defined(__GLIBC__)) /* The next part of code is disabled because it relies on undocumented behaviour. It could be enabled for neglectable performance and size improvements. */ # if 0 /* Disabled code */ /** * The native invalid value for native thread handle */ # define MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ \ ((MHD_thread_handle_native_) 0) # endif /* Disabled code */ # endif /* __gnu_linux__ || (__linux__ && __GLIBC__) */ #elif defined(MHD_USE_W32_THREADS) /** * The native invalid value for native thread handle */ # define MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ \ ((MHD_thread_handle_native_) NULL) #endif /* MHD_USE_W32_THREADS */ #if ! defined(MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) /** * Structure with thread handle and validity flag */ struct MHD_thread_handle_struct_ { bool valid; /**< true if native handle is set */ MHD_thread_handle_native_ native; /**< the native thread handle */ }; /** * Type with thread handle that can be set to invalid value */ typedef struct MHD_thread_handle_struct_ MHD_thread_handle_; /** * Set variable pointed by @a handle_ptr to invalid (unset) value */ # define MHD_thread_handle_set_invalid_(handle_ptr) \ ((handle_ptr)->valid = false) /** * Set native handle in variable pointed by @a handle_ptr * to @a native_val value */ # define MHD_thread_handle_set_native_(handle_ptr,native_val) \ ((handle_ptr)->valid = true, (handle_ptr)->native = native_val) /** * Check whether native handle value is set in @a handle_var variable */ # define MHD_thread_handle_is_valid_(handle_var) \ ((handle_var).valid) /** * Get native handle value from @a handle_var variable */ # define MHD_thread_handle_get_native_(handle_var) \ ((handle_var).native) #else /* MHD_THREAD_HANDLE_NATIVE_INVALID_ */ /** * Type with thread handle that can be set to invalid value */ typedef MHD_thread_handle_native_ MHD_thread_handle_; /** * Set variable pointed by @a handle_ptr to invalid (unset) value */ # define MHD_thread_handle_set_invalid_(handle_ptr) \ ((*(handle_ptr)) = MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) /** * Set native handle in the variable pointed by @a handle_ptr * to @a native_val value */ # define MHD_thread_handle_set_native_(handle_ptr,native_val) \ ((*(handle_ptr)) = native_val) /** * Check whether native handle value is set in @a handle_var variable */ # define MHD_thread_handle_is_valid_(handle_var) \ (MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ != handle_var) /** * Get native handle value from @a handle_var variable */ # define MHD_thread_handle_get_native_(handle_var) \ (handle_var) /** * Get pointer to native handle stored the variable pointed by @a handle_ptr * @note This macro could not available if direct manipulation of * the native handle is not possible */ # define MHD_thread_handle_get_native_ptr_(handle_ptr) \ (handle_ptr) #endif /* MHD_THREAD_HANDLE_NATIVE_INVALID_ */ /* ** Thread ID - used to check threads match ** */ #if defined(MHD_USE_POSIX_THREADS) /** * The native type used to check whether current thread matches expected thread */ typedef pthread_t MHD_thread_ID_native_; /** * Function to get the current thread native ID. */ # define MHD_thread_ID_native_current_ pthread_self /** * Check whether two native thread IDs are equal. * @return non-zero if equal, zero if not equal */ # define MHD_thread_ID_native_equal_(id1,id2) \ (pthread_equal(id1,id2)) #elif defined(MHD_USE_W32_THREADS) /** * The native type used to check whether current thread matches expected thread */ typedef DWORD MHD_thread_ID_native_; /** * Function to get the current thread native ID. */ # define MHD_thread_ID_native_current_ GetCurrentThreadId /** * Check whether two native thread IDs are equal. * @return non-zero if equal, zero if not equal */ # define MHD_thread_ID_native_equal_(id1,id2) \ ((id1) == (id2)) #endif /** * Check whether specified thread ID matches current thread. * @param id the thread ID to match * @return nonzero on match, zero otherwise */ #define MHD_thread_ID_native_is_current_thread_(id) \ MHD_thread_ID_native_equal_(id, MHD_thread_ID_native_current_()) #if defined(MHD_USE_POSIX_THREADS) # if defined(MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) /** * The native invalid value for native thread ID */ # define MHD_THREAD_ID_NATIVE_VALUE_INVALID_ \ MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ # endif /* MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ */ #elif defined(MHD_USE_W32_THREADS) /** * The native invalid value for native thread ID */ # define MHD_THREAD_ID_NATIVE_VALUE_INVALID_ \ ((MHD_thread_ID_native_) 0) #endif /* MHD_USE_W32_THREADS */ #if ! defined(MHD_THREAD_ID_NATIVE_VALUE_INVALID_) /** * Structure with thread id and validity flag */ struct MHD_thread_ID_struct_ { bool valid; /**< true if native ID is set */ MHD_thread_ID_native_ native; /**< the native thread ID */ }; /** * Type with thread ID that can be set to invalid value */ typedef struct MHD_thread_ID_struct_ MHD_thread_ID_; /** * Set variable pointed by @a ID_ptr to invalid (unset) value */ # define MHD_thread_ID_set_invalid_(ID_ptr) \ ((ID_ptr)->valid = false) /** * Set native ID in variable pointed by @a ID_ptr * to @a native_val value */ # define MHD_thread_ID_set_native_(ID_ptr,native_val) \ ((ID_ptr)->valid = true, (ID_ptr)->native = native_val) /** * Check whether native ID value is set in @a ID_var variable */ # define MHD_thread_ID_is_valid_(ID_var) \ ((ID_var).valid) /** * Get native ID value from @a ID_var variable */ # define MHD_thread_ID_get_native_(ID_var) \ ((ID_var).native) /** * Check whether @a ID_var variable is equal current thread */ # define MHD_thread_ID_is_current_thread_(ID_var) \ (MHD_thread_ID_is_valid_(ID_var) && \ MHD_thread_ID_native_is_current_thread_((ID_var).native)) #else /* MHD_THREAD_ID_NATIVE_INVALID_ */ /** * Type with thread ID that can be set to invalid value */ typedef MHD_thread_ID_native_ MHD_thread_ID_; /** * Set variable pointed by @a ID_ptr to invalid (unset) value */ # define MHD_thread_ID_set_invalid_(ID_ptr) \ ((*(ID_ptr)) = MHD_THREAD_ID_NATIVE_VALUE_INVALID_) /** * Set native ID in variable pointed by @a ID_ptr * to @a native_val value */ # define MHD_thread_ID_set_native_(ID_ptr,native_val) \ ((*(ID_ptr)) = native_val) /** * Check whether native ID value is set in @a ID_var variable */ # define MHD_thread_ID_is_valid_(ID_var) \ (MHD_THREAD_ID_NATIVE_VALUE_INVALID_ != ID_var) /** * Get native ID value from @a ID_var variable */ # define MHD_thread_ID_get_native_(ID_var) \ (ID_var) /** * Check whether @a ID_var variable is equal current thread */ # define MHD_thread_ID_is_current_thread_(ID_var) \ MHD_thread_ID_native_is_current_thread_(ID_var) #endif /* MHD_THREAD_ID_NATIVE_INVALID_ */ /** * Set current thread ID in variable pointed by @a ID_ptr */ # define MHD_thread_ID_set_current_thread_(ID_ptr) \ MHD_thread_ID_set_native_(ID_ptr,MHD_thread_ID_native_current_()) #if defined(MHD_USE_POSIX_THREADS) # if defined(MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) && \ ! defined(MHD_THREAD_ID_NATIVE_VALUE_INVALID_) # error \ MHD_THREAD_ID_NATIVE_VALUE_INVALID_ is defined, but MHD_THREAD_ID_NATIVE_VALUE_INVALID_ is not defined # elif ! defined(MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) && \ defined(MHD_THREAD_ID_NATIVE_VALUE_INVALID_) # error \ MHD_THREAD_ID_NATIVE_VALUE_INVALID_ is not defined, but MHD_THREAD_ID_NATIVE_VALUE_INVALID_ is defined # endif #endif /* MHD_USE_POSIX_THREADS */ /* When staring a new thread, the kernel (and thread implementation) may * pause the calling (initial) thread and start the new thread. * If thread identifier is assigned to variable in the initial thread then * the value of the identifier variable will be undefined in the new thread * until the initial thread continue processing. * However, it is also possible that the new thread created, but not executed * for some time while the initial thread continue execution. In this case any * variable assigned in the new thread will be undefined for some time until * they really processed by the new thread. * To avoid data races, a special structure MHD_thread_handle_ID_ is used. * The "handle" is assigned by calling (initial) thread and should be always * defined when checked in the initial thread. * The "ID" is assigned by the new thread and should be always defined when * checked inside the new thread. */ /* Depending on implementation, pthread_create() MAY set thread ID into * provided pointer and after it start thread OR start thread and after * it set thread ID. In the latter case, to avoid data races, additional * pthread_self() call is required in thread routine. If some platform * is known for setting thread ID BEFORE starting thread macro * MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD could be defined * to save some resources. */ /* #define MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD 1 */ /* * handle - must be valid when other thread knows that particular thread is started. * ID - must be valid when code is executed inside thread */ #if defined(MHD_USE_POSIX_THREADS) && \ defined(MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD) && \ defined(MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_) && \ defined(MHD_THREAD_ID_NATIVE_VALUE_INVALID_) && \ defined(MHD_thread_handle_get_native_ptr_) union _MHD_thread_handle_ID_ { MHD_thread_handle_ handle; /**< To be used in other threads */ MHD_thread_ID_ ID; /**< To be used in the thread itself */ }; typedef union _MHD_thread_handle_ID_ MHD_thread_handle_ID_; # define MHD_THREAD_HANDLE_ID_IS_UNION 1 #else /* !MHD_USE_POSIX_THREADS || !MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD || !MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ || !MHD_THREAD_ID_NATIVE_VALUE_INVALID_ || !MHD_thread_handle_get_native_ptr_ */ struct _MHD_thread_handle_ID_ { MHD_thread_handle_ handle; /**< To be used in other threads */ MHD_thread_ID_ ID; /**< To be used in the thread itself */ }; typedef struct _MHD_thread_handle_ID_ MHD_thread_handle_ID_; #endif /* !MHD_USE_POSIX_THREADS || !MHD_PTHREAD_CREATE__SET_ID_BEFORE_START_THREAD || !MHD_THREAD_HANDLE_NATIVE_VALUE_INVALID_ || !MHD_THREAD_ID_NATIVE_VALUE_INVALID_ || !MHD_thread_handle_get_native_ptr_ */ /** * Set MHD_thread_handle_ID_ to invalid value */ #define MHD_thread_handle_ID_set_invalid_(hndl_id_ptr) \ (MHD_thread_handle_set_invalid_(&((hndl_id_ptr)->handle)), \ MHD_thread_ID_set_invalid_(&((hndl_id_ptr)->ID))) /** * Check whether thread handle is valid. * To be used in threads other then the thread specified by @a hndl_id. */ #define MHD_thread_handle_ID_is_valid_handle_(hndl_id) \ MHD_thread_handle_is_valid_((hndl_id).handle) /** * Set native handle in variable pointed by @a hndl_id_ptr * to @a native_val value */ #define MHD_thread_handle_ID_set_native_handle_(hndl_id_ptr,native_val) \ MHD_thread_handle_set_native_(&((hndl_id_ptr)->handle),native_val) #if defined(MHD_thread_handle_get_native_ptr_) /** * Get pointer to native handle stored the variable pointed by @a hndl_id_ptr * @note This macro could not available if direct manipulation of * the native handle is not possible */ # define MHD_thread_handle_ID_get_native_handle_ptr_(hndl_id_ptr) \ MHD_thread_handle_get_native_ptr_(&((hndl_id_ptr)->handle)) #endif /* MHD_thread_handle_get_native_ptr_ */ /** * Get native thread handle from MHD_thread_handle_ID_ variable. */ #define MHD_thread_handle_ID_get_native_handle_(hndl_id) \ MHD_thread_handle_get_native_((hndl_id).handle) /** * Check whether thread ID is valid. * To be used in the thread itself. */ #define MHD_thread_handle_ID_is_valid_ID_(hndl_id) \ MHD_thread_ID_is_valid_((hndl_id).ID) #if defined(MHD_THREAD_HANDLE_ID_IS_UNION) # if defined(MHD_USE_W32_THREADS) # error MHD_thread_handle_ID_ cannot be a union with W32 threads # endif /* MHD_USE_W32_THREADS */ /** * Set current thread ID in the variable pointed by @a hndl_id_ptr */ # define MHD_thread_handle_ID_set_current_thread_ID_(hndl_id_ptr) (void) 0 #else /* ! MHD_THREAD_HANDLE_ID_IS_UNION */ /** * Set current thread ID in the variable pointed by @a hndl_id_ptr */ # define MHD_thread_handle_ID_set_current_thread_ID_(hndl_id_ptr) \ MHD_thread_ID_set_current_thread_(&((hndl_id_ptr)->ID)) #endif /* ! MHD_THREAD_HANDLE_ID_IS_UNION */ /** * Check whether provided thread ID matches current thread. * @param ID thread ID to match * @return nonzero on match, zero otherwise */ #define MHD_thread_handle_ID_is_current_thread_(hndl_id) \ MHD_thread_ID_is_current_thread_((hndl_id).ID) /** * Wait until specified thread is ended and free thread handle on success. * @param hndl_id_ handle with ID to watch * @return nonzero on success, zero otherwise */ #define MHD_thread_handle_ID_join_thread_(hndl_id) \ MHD_join_thread_(MHD_thread_handle_ID_get_native_handle_(hndl_id)) #if defined(MHD_USE_POSIX_THREADS) # define MHD_THRD_RTRN_TYPE_ void* # define MHD_THRD_CALL_SPEC_ #elif defined(MHD_USE_W32_THREADS) # define MHD_THRD_RTRN_TYPE_ unsigned # define MHD_THRD_CALL_SPEC_ __stdcall #endif /** * Signature of main function for a thread. * * @param cls closure argument for the function * @return termination code from the thread */ typedef MHD_THRD_RTRN_TYPE_ (MHD_THRD_CALL_SPEC_ *MHD_THREAD_START_ROUTINE_)(void *cls); /** * Create a thread and set the attributes according to our options. * * If thread is created, thread handle must be freed by MHD_join_thread_(). * * @param handle_id handle to initialise * @param stack_size size of stack for new thread, 0 for default * @param start_routine main function of thread * @param arg argument for start_routine * @return non-zero on success; zero otherwise (with errno set) */ int MHD_create_thread_ (MHD_thread_handle_ID_ *handle_id, size_t stack_size, MHD_THREAD_START_ROUTINE_ start_routine, void *arg); #ifndef MHD_USE_THREAD_NAME_ #define MHD_create_named_thread_(t,n,s,r,a) MHD_create_thread_ ((t),(s),(r),(a)) #else /* MHD_USE_THREAD_NAME_ */ /** * Create a named thread and set the attributes according to our options. * * @param handle_id handle to initialise * @param thread_name name for new thread * @param stack_size size of stack for new thread, 0 for default * @param start_routine main function of thread * @param arg argument for start_routine * @return non-zero on success; zero otherwise */ int MHD_create_named_thread_ (MHD_thread_handle_ID_ *handle_id, const char *thread_name, size_t stack_size, MHD_THREAD_START_ROUTINE_ start_routine, void *arg); #endif /* MHD_USE_THREAD_NAME_ */ #endif /* ! MHD_THREADS_H */ libmicrohttpd-1.0.10/src/microhttpd/mhd_str.h0000644000175000017500000007403415232074411014702 /* This file is part of libmicrohttpd Copyright (C) 2015-2023 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/mhd_str.h * @brief Header for string manipulating helpers * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_STR_H #define MHD_STR_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include #endif /* HAVE_STDDEF_H */ #ifdef HAVE_SYS_TYPES_H #include #endif /* HAVE_SYS_TYPES_H */ #ifdef HAVE_STDBOOL_H #include #endif /* HAVE_STDBOOL_H */ #include "mhd_str_types.h" #if defined(_MSC_FULL_VER) && ! defined(_SSIZE_T_DEFINED) #define _SSIZE_T_DEFINED typedef intptr_t ssize_t; #endif /* !_SSIZE_T_DEFINED */ #ifdef MHD_FAVOR_SMALL_CODE #include "mhd_limits.h" #endif /* MHD_FAVOR_SMALL_CODE */ /* * Block of functions/macros that use US-ASCII charset as required by HTTP * standards. Not affected by current locale settings. */ #ifndef MHD_FAVOR_SMALL_CODE /** * Check two strings for equality, ignoring case of US-ASCII letters. * * @param str1 first string to compare * @param str2 second string to compare * @return non-zero if two strings are equal, zero otherwise. */ int MHD_str_equal_caseless_ (const char *str1, const char *str2); #else /* MHD_FAVOR_SMALL_CODE */ /* Reuse MHD_str_equal_caseless_n_() to reduce size */ #define MHD_str_equal_caseless_(s1,s2) MHD_str_equal_caseless_n_ ((s1),(s2), \ SIZE_MAX) #endif /* MHD_FAVOR_SMALL_CODE */ /** * Check two string for equality, ignoring case of US-ASCII letters and * checking not more than @a maxlen characters. * Compares up to first terminating null character, but not more than * first @a maxlen characters. * @param str1 first string to compare * @param str2 second string to compare * @param maxlen maximum number of characters to compare * @return non-zero if two strings are equal, zero otherwise. */ int MHD_str_equal_caseless_n_ (const char *const str1, const char *const str2, size_t maxlen); /** * Check two string for equality, ignoring case of US-ASCII letters and * checking not more than @a len bytes. * Compares not more first than @a len bytes, including binary zero characters. * Comparison stops at first unmatched byte. * @param str1 first string to compare * @param str2 second string to compare * @param len number of characters to compare * @return non-zero if @a len bytes are equal, zero otherwise. */ bool MHD_str_equal_caseless_bin_n_ (const char *const str1, const char *const str2, size_t len); /** * Check whether string is equal statically allocated another string, * ignoring case of US-ASCII letters and checking not more than @a len bytes. * * If strings have different sizes (lengths) then macro returns boolean false * without checking the content. * * Compares not more first than @a len bytes, including binary zero characters. * Comparison stops at first unmatched byte. * @param a the statically allocated string to compare * @param s the string to compare * @param len number of characters to compare * @return non-zero if @a len bytes are equal, zero otherwise. */ #define MHD_str_equal_caseless_s_bin_n_(a,s,l) \ ((MHD_STATICSTR_LEN_(a) == (l)) \ && MHD_str_equal_caseless_bin_n_(a,s,l)) /** * Check whether @a str has case-insensitive @a token. * Token could be surrounded by spaces and tabs and delimited by comma. * Match succeed if substring between start, end (of string) or comma * contains only case-insensitive token and optional spaces and tabs. * @warning token must not contain null-characters except optional * terminating null-character. * @param str the string to check * @param token the token to find * @param token_len length of token, not including optional terminating * null-character. * @return non-zero if two strings are equal, zero otherwise. */ bool MHD_str_has_token_caseless_ (const char *str, const char *const token, size_t token_len); /** * Check whether @a str has case-insensitive static @a tkn. * Token could be surrounded by spaces and tabs and delimited by comma. * Match succeed if substring between start, end of string or comma * contains only case-insensitive token and optional spaces and tabs. * @warning tkn must be static string * @param str the string to check * @param tkn the static string of token to find * @return non-zero if two strings are equal, zero otherwise. */ #define MHD_str_has_s_token_caseless_(str,tkn) \ MHD_str_has_token_caseless_ ((str),(tkn),MHD_STATICSTR_LEN_ (tkn)) /** * Remove case-insensitive @a token from the @a str and put result * to the output @a buf. * * Tokens in @a str could be surrounded by spaces and tabs and delimited by * comma. The token match succeed if substring between start, end (of string) * or comma contains only case-insensitive token and optional spaces and tabs. * The quoted strings and comments are not supported by this function. * * The output string is normalised: empty tokens and repeated whitespaces * are removed, no whitespaces before commas, exactly one space is used after * each comma. * * @param str the string to process * @param str_len the length of the @a str, not including optional * terminating null-character. * @param token the token to find * @param token_len the length of @a token, not including optional * terminating null-character. * @param[out] buf the output buffer, not null-terminated. * @param[in,out] buf_size pointer to the size variable, at input it * is the size of allocated buffer, at output * it is the size of the resulting string (can * be up to 50% larger than input) or negative value * if there is not enough space for the result * @return 'true' if token has been removed, * 'false' otherwise. */ bool MHD_str_remove_token_caseless_ (const char *str, size_t str_len, const char *const token, const size_t token_len, char *buf, ssize_t *buf_size); /** * Perform in-place case-insensitive removal of @a tokens from the @a str. * * Token could be surrounded by spaces and tabs and delimited by comma. * The token match succeed if substring between start, end (of the string), or * comma contains only case-insensitive token and optional spaces and tabs. * The quoted strings and comments are not supported by this function. * * The input string must be normalised: empty tokens and repeated whitespaces * are removed, no whitespaces before commas, exactly one space is used after * each comma. The string is updated in-place. * * Behavior is undefined is the input string in not normalised. * * @param[in,out] str the string to update * @param[in,out] str_len the length of the @a str, not including optional * terminating null-character, not null-terminated * @param tokens the token to find * @param tokens_len the length of @a tokens, not including optional * terminating null-character. * @return 'true' if any token has been removed, * 'false' otherwise. */ bool MHD_str_remove_tokens_caseless_ (char *str, size_t *str_len, const char *const tokens, const size_t tokens_len); #ifndef MHD_FAVOR_SMALL_CODE /* Use individual function for each case to improve speed */ /** * Convert decimal US-ASCII digits in string to number in uint64_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_str_to_uint64_ (const char *str, uint64_t *out_val); /** * Convert not more then @a maxlen decimal US-ASCII digits in string to * number in uint64_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_str_to_uint64_n_ (const char *str, size_t maxlen, uint64_t *out_val); /** * Convert hexadecimal US-ASCII digits in string to number in uint32_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint32_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint32_t or @a out_val is NULL */ size_t MHD_strx_to_uint32_ (const char *str, uint32_t *out_val); /** * Convert not more then @a maxlen hexadecimal US-ASCII digits in string * to number in uint32_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint32_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint32_t or @a out_val is NULL */ size_t MHD_strx_to_uint32_n_ (const char *str, size_t maxlen, uint32_t *out_val); /** * Convert hexadecimal US-ASCII digits in string to number in uint64_t. * Conversion stopped at first non-digit character. * * @param str string to convert * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_strx_to_uint64_ (const char *str, uint64_t *out_val); /** * Convert not more then @a maxlen hexadecimal US-ASCII digits in string * to number in uint64_t. * Conversion stopped at first non-digit character or after @a maxlen * digits. * * @param str string to convert * @param maxlen maximum number of characters to process * @param[out] out_val pointer to uint64_t to store result of conversion * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then possible to store in uint64_t or @a out_val is NULL */ size_t MHD_strx_to_uint64_n_ (const char *str, size_t maxlen, uint64_t *out_val); #else /* MHD_FAVOR_SMALL_CODE */ /* Use one universal function and macros to reduce size */ /** * Generic function for converting not more then @a maxlen * hexadecimal or decimal US-ASCII digits in string to number. * Conversion stopped at first non-digit character or after @a maxlen * digits. * To be used only within macro. * * @param str the string to convert * @param maxlen the maximum number of characters to process * @param out_val the pointer to variable to store result of conversion * @param val_size the size of variable pointed by @a out_val, in bytes, 4 or 8 * @param max_val the maximum decoded number * @param base the numeric base, 10 or 16 * @return non-zero number of characters processed on succeed, * zero if no digit is found, resulting value is larger * then @a max_val, @a val_size is not 4/8 or @a out_val is NULL */ size_t MHD_str_to_uvalue_n_ (const char *str, size_t maxlen, void *out_val, size_t val_size, uint64_t max_val, unsigned int base); #define MHD_str_to_uint64_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \ sizeof(uint64_t), \ UINT64_MAX,10) #define MHD_str_to_uint64_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \ sizeof(uint64_t), \ UINT64_MAX,10) #define MHD_strx_to_sizet_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \ sizeof(size_t),SIZE_MAX, \ 16) #define MHD_strx_to_sizet_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \ sizeof(size_t), \ SIZE_MAX,16) #define MHD_strx_to_uint32_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \ sizeof(uint32_t), \ UINT32_MAX,16) #define MHD_strx_to_uint32_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \ sizeof(uint32_t), \ UINT32_MAX,16) #define MHD_strx_to_uint64_(s,ov) MHD_str_to_uvalue_n_ ((s),SIZE_MAX,(ov), \ sizeof(uint64_t), \ UINT64_MAX,16) #define MHD_strx_to_uint64_n_(s,ml,ov) MHD_str_to_uvalue_n_ ((s),(ml),(ov), \ sizeof(uint64_t), \ UINT64_MAX,16) #endif /* MHD_FAVOR_SMALL_CODE */ /** * Convert uint32_t value to hexadecimal US-ASCII string. * @note: result is NOT zero-terminated. * @param val the value to convert * @param buf the buffer to result to * @param buf_size size of the @a buffer * @return number of characters has been put to the @a buf, * zero if buffer is too small (buffer may be modified). */ size_t MHD_uint32_to_strx (uint32_t val, char *buf, size_t buf_size); #ifndef MHD_FAVOR_SMALL_CODE /** * Convert uint16_t value to decimal US-ASCII string. * @note: result is NOT zero-terminated. * @param val the value to convert * @param buf the buffer to result to * @param buf_size size of the @a buffer * @return number of characters has been put to the @a buf, * zero if buffer is too small (buffer may be modified). */ size_t MHD_uint16_to_str (uint16_t val, char *buf, size_t buf_size); #else /* MHD_FAVOR_SMALL_CODE */ #define MHD_uint16_to_str(v,b,s) MHD_uint64_to_str(v,b,s) #endif /* MHD_FAVOR_SMALL_CODE */ /** * Convert uint64_t value to decimal US-ASCII string. * @note: result is NOT zero-terminated. * @param val the value to convert * @param buf the buffer to result to * @param buf_size size of the @a buffer * @return number of characters has been put to the @a buf, * zero if buffer is too small (buffer may be modified). */ size_t MHD_uint64_to_str (uint64_t val, char *buf, size_t buf_size); /** * Convert uint16_t value to decimal US-ASCII string padded with * zeros on the left side. * * @note: result is NOT zero-terminated. * @param val the value to convert * @param min_digits the minimal number of digits to print, * output padded with zeros on the left side, * 'zero' value is interpreted as 'one', * valid values are 3, 2, 1, 0 * @param buf the buffer to result to * @param buf_size size of the @a buffer * @return number of characters has been put to the @a buf, * zero if buffer is too small (buffer may be modified). */ size_t MHD_uint8_to_str_pad (uint8_t val, uint8_t min_digits, char *buf, size_t buf_size); /** * Convert @a size bytes from input binary data to lower case * hexadecimal digits. * Result is NOT zero-terminated * @param bin the pointer to the binary data to convert * @param size the size in bytes of the binary data to convert * @param[out] hex the output buffer, should be at least 2 * @a size * @return The number of characters written to the output buffer. */ size_t MHD_bin_to_hex (const void *bin, size_t size, char *hex); /** * Convert @a size bytes from input binary data to lower case * hexadecimal digits, zero-terminate the result. * @param bin the pointer to the binary data to convert * @param size the size in bytes of the binary data to convert * @param[out] hex the output buffer, should be at least 2 * @a size + 1 * @return The number of characters written to the output buffer, * not including terminating zero. */ size_t MHD_bin_to_hex_z (const void *bin, size_t size, char *hex); /** * Convert hexadecimal digits to binary data. * * The input decoded byte-by-byte (each byte is two hexadecimal digits). * If length is an odd number, extra leading zero is assumed. * * @param hex the input string with hexadecimal digits * @param len the length of the input string * @param[out] bin the output buffer, must be at least len/2 bytes long (or * len/2 + 1 if @a len is not even number) * @return the number of bytes written to the output buffer, * zero if found any character which is not hexadecimal digits */ size_t MHD_hex_to_bin (const char *hex, size_t len, void *bin); /** * Decode string with percent-encoded characters as defined by * RFC 3986 #section-2.1. * * This function decode string by converting percent-encoded characters to * their decoded versions and copying all other characters without extra * processing. * * @param pct_encoded the input string to be decoded * @param pct_encoded_len the length of the @a pct_encoded * @param[out] decoded the output buffer, NOT zero-terminated, can point * to the same buffer as @a pct_encoded * @param buf_size the size of the output buffer * @return the number of characters written to the output buffer or * zero if any percent-encoded characters is broken ('%' followed * by less than two hexadecimal digits) or output buffer is too * small to hold the result */ size_t MHD_str_pct_decode_strict_n_ (const char *pct_encoded, size_t pct_encoded_len, char *decoded, size_t buf_size); /** * Decode string with percent-encoded characters as defined by * RFC 3986 #section-2.1. * * This function decode string by converting percent-encoded characters to * their decoded versions and copying all other characters without extra * processing. * * Any invalid percent-encoding sequences ('%' symbol not followed by two * valid hexadecimal digits) are copied to the output string without decoding. * * @param pct_encoded the input string to be decoded * @param pct_encoded_len the length of the @a pct_encoded * @param[out] decoded the output buffer, NOT zero-terminated, can point * to the same buffer as @a pct_encoded * @param buf_size the size of the output buffer * @param[out] broken_encoding will be set to true if any '%' symbol is not * followed by two valid hexadecimal digits, * optional, can be NULL * @return the number of characters written to the output buffer or * zero if output buffer is too small to hold the result */ size_t MHD_str_pct_decode_lenient_n_ (const char *pct_encoded, size_t pct_encoded_len, char *decoded, size_t buf_size, bool *broken_encoding); /** * Decode string in-place with percent-encoded characters as defined by * RFC 3986 #section-2.1. * * This function decode string by converting percent-encoded characters to * their decoded versions and copying back all other characters without extra * processing. * * @param[in,out] str the string to be updated in-place, must be zero-terminated * on input, the output is zero-terminated; the string is * truncated to zero length if broken encoding is found * @return the number of character in decoded string */ size_t MHD_str_pct_decode_in_place_strict_ (char *str); /** * Decode string in-place with percent-encoded characters as defined by * RFC 3986 #section-2.1. * * This function decode string by converting percent-encoded characters to * their decoded versions and copying back all other characters without extra * processing. * * Any invalid percent-encoding sequences ('%' symbol not followed by two * valid hexadecimal digits) are copied to the output string without decoding. * * @param[in,out] str the string to be updated in-place, must be zero-terminated * on input, the output is zero-terminated * @param[out] broken_encoding will be set to true if any '%' symbol is not * followed by two valid hexadecimal digits, * optional, can be NULL * @return the number of character in decoded string */ size_t MHD_str_pct_decode_in_place_lenient_ (char *str, bool *broken_encoding); #ifdef DAUTH_SUPPORT /** * Check two strings for equality, "unquoting" the first string from quoted * form as specified by RFC7230#section-3.2.6 and RFC7694#quoted.strings. * * Null-termination for input strings is not required, binary zeros compared * like other characters. * * @param quoted the quoted string to compare, must NOT include leading and * closing DQUOTE chars, does not need to be zero-terminated * @param quoted_len the length in chars of the @a quoted string * @param unquoted the unquoted string to compare, does not need to be * zero-terminated * @param unquoted_len the length in chars of the @a unquoted string * @return zero if quoted form is broken (no character after the last escaping * backslash), zero if strings are not equal after unquoting of the * first string, * non-zero if two strings are equal after unquoting of the * first string. */ bool MHD_str_equal_quoted_bin_n (const char *quoted, size_t quoted_len, const char *unquoted, size_t unquoted_len); /** * Check whether the string after "unquoting" equals static string. * * Null-termination for input string is not required, binary zeros compared * like other characters. * * @param q the quoted string to compare, must NOT include leading and * closing DQUOTE chars, does not need to be zero-terminated * @param l the length in chars of the @a q string * @param u the unquoted static string to compare * @return zero if quoted form is broken (no character after the last escaping * backslash), zero if strings are not equal after unquoting of the * first string, * non-zero if two strings are equal after unquoting of the * first string. */ #define MHD_str_equal_quoted_s_bin_n(q,l,u) \ MHD_str_equal_quoted_bin_n(q,l,u,MHD_STATICSTR_LEN_(u)) /** * Check two strings for equality, "unquoting" the first string from quoted * form as specified by RFC7230#section-3.2.6 and RFC7694#quoted.strings and * ignoring case of US-ASCII letters. * * Null-termination for input strings is not required, binary zeros compared * like other characters. * * @param quoted the quoted string to compare, must NOT include leading and * closing DQUOTE chars, does not need to be zero-terminated * @param quoted_len the length in chars of the @a quoted string * @param unquoted the unquoted string to compare, does not need to be * zero-terminated * @param unquoted_len the length in chars of the @a unquoted string * @return zero if quoted form is broken (no character after the last escaping * backslash), zero if strings are not equal after unquoting of the * first string, * non-zero if two strings are caseless equal after unquoting of the * first string. */ bool MHD_str_equal_caseless_quoted_bin_n (const char *quoted, size_t quoted_len, const char *unquoted, size_t unquoted_len); /** * Check whether the string after "unquoting" equals static string, ignoring * case of US-ASCII letters. * * Null-termination for input string is not required, binary zeros compared * like other characters. * * @param q the quoted string to compare, must NOT include leading and * closing DQUOTE chars, does not need to be zero-terminated * @param l the length in chars of the @a q string * @param u the unquoted static string to compare * @return zero if quoted form is broken (no character after the last escaping * backslash), zero if strings are not equal after unquoting of the * first string, * non-zero if two strings are caseless equal after unquoting of the * first string. */ #define MHD_str_equal_caseless_quoted_s_bin_n(q,l,u) \ MHD_str_equal_caseless_quoted_bin_n(q,l,u,MHD_STATICSTR_LEN_(u)) /** * Convert string from quoted to unquoted form as specified by * RFC7230#section-3.2.6 and RFC7694#quoted.strings. * * @param quoted the quoted string, must NOT include leading and closing * DQUOTE chars, does not need to be zero-terminated * @param quoted_len the length in chars of the @a quoted string * @param[out] result the pointer to the buffer to put the result, must * be at least @a size character long. May be modified even * if @a quoted is invalid sequence. The result is NOT * zero-terminated. * @return The number of characters written to the output buffer, * zero if last backslash is not followed by any character (or * @a quoted_len is zero). */ size_t MHD_str_unquote (const char *quoted, size_t quoted_len, char *result); #endif /* DAUTH_SUPPORT */ #if defined(DAUTH_SUPPORT) || defined(BAUTH_SUPPORT) /** * Convert string from unquoted to quoted form as specified by * RFC7230#section-3.2.6 and RFC7694#quoted.strings. * * @param unquoted the unquoted string, does not need to be zero-terminated * @param unquoted_len the length in chars of the @a unquoted string * @param[out] result the pointer to the buffer to put the result. May be * modified even if function failed due to insufficient * space. The result is NOT zero-terminated and does not * have opening and closing DQUOTE chars. * @param buf_size the size of the allocated memory for @a result * @return The number of copied characters, can be up to two times more than * @a unquoted_len, zero if @a unquoted_len is zero or if quoted * string is larger than @a buf_size. */ size_t MHD_str_quote (const char *unquoted, size_t unquoted_len, char *result, size_t buf_size); #endif /* DAUTH_SUPPORT || BAUTH_SUPPORT */ #ifdef BAUTH_SUPPORT /** * Returns the maximum possible size of the Base64 decoded data. * The real recoded size could be up to two bytes smaller. * @param enc_size the size of encoded data, in characters * @return the maximum possible size of the decoded data, in bytes, if * @a enc_size is valid (properly padded), * undefined value smaller then @a enc_size if @a enc_size is not valid */ #define MHD_base64_max_dec_size_(enc_size) (((enc_size) / 4) * 3) /** * Convert Base64 encoded string to binary data. * @param base64 the input string with Base64 encoded data, could be NOT zero * terminated * @param base64_len the number of characters to decode in @a base64 string, * valid number must be a multiple of four * @param[out] bin the pointer to the output buffer, the buffer may be altered * even if decoding failed * @param bin_size the size of the @a bin buffer in bytes, if the size is * at least @a base64_len / 4 * 3 then result will always * fit, regardless of the amount of the padding characters * @return 0 if @a base64_len is zero, or input string has wrong data (not * valid Base64 sequence), or @a bin_size is too small; * non-zero number of bytes written to the @a bin, the number must be * (base64_len / 4 * 3 - 2), (base64_len / 4 * 3 - 1) or * (base64_len / 4 * 3), depending on the number of padding characters. */ size_t MHD_base64_to_bin_n (const char *base64, size_t base64_len, void *bin, size_t bin_size); #endif /* BAUTH_SUPPORT */ #endif /* MHD_STR_H */ libmicrohttpd-1.0.10/src/microhttpd/test_str_tokens_remove.c0000664000175000017500000003335715232103064020046 /* This file is part of libmicrohttpd Copyright (C) 2017-2021 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_str_token.c * @brief Unit tests for MHD_str_remove_tokens_caseless_() function * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "mhd_str.h" #include "mhd_assert.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static int expect_result_n (const char *str, size_t str_len, const char *tokens, size_t tokens_len, const char *expected, size_t expected_len, const bool expected_removed) { char buf_in[1024]; char buf_tokens[256]; bool res; size_t result_len; mhd_assert (sizeof(buf_in) > str_len + 2); mhd_assert (sizeof(buf_tokens) > tokens_len + 2); memset (buf_tokens, '#', sizeof(buf_tokens)); memcpy (buf_tokens, tokens, tokens_len); /* Copy without zero-termination */ memset (buf_in, '$', sizeof(buf_in)); memcpy (buf_in, str, str_len); /* Copy without zero-termination */ result_len = str_len; res = MHD_str_remove_tokens_caseless_ (buf_in, &result_len, buf_tokens, tokens_len); if ( (expected_removed != res) || (expected_len != result_len) || ((0 != result_len) && (0 != memcmp (expected, buf_in, result_len))) || ('$' != buf_in[str_len])) { fprintf (stderr, "MHD_str_remove_tokens_caseless_() FAILED:\n" "\tRESULT: " "\tMHD_str_remove_token_caseless_(\"%s\"->\"%.*s\", &(%lu->%lu)," " \"%.*s\", %lu) returned %s\n", str, (int) result_len, buf_in, (unsigned long) str_len, (unsigned long) result_len, (int) tokens_len, buf_tokens, (unsigned long) tokens_len, res ? "true" : "false"); fprintf (stderr, "\tEXPECTED: " "\tMHD_str_remove_token_caseless_(\"%s\"->\"%s\", &(%lu->%lu)," " \"%.*s\", %lu) returned %s\n", str, expected, (unsigned long) str_len, (unsigned long) expected_len, (int) tokens_len, buf_tokens, (unsigned long) tokens_len, expected_removed ? "true" : "false"); return 1; } return 0; } #define expect_result(s,t,e,found) \ expect_result_n ((s),MHD_STATICSTR_LEN_ (s), \ (t),MHD_STATICSTR_LEN_ (t), \ (e),MHD_STATICSTR_LEN_ (e), found) static int check_result (void) { int errcount = 0; errcount += expect_result ("string", "string", "", true); errcount += expect_result ("String", "string", "", true); errcount += expect_result ("string", "String", "", true); errcount += expect_result ("strinG", "String", "", true); errcount += expect_result ("strinG", "String\t", "", true); errcount += expect_result ("strinG", "\tString", "", true); errcount += expect_result ("tOkEn", " \t toKEN ", "", true); errcount += expect_result ("not-token, tOkEn", "token", "not-token", true); errcount += expect_result ("not-token1, tOkEn1, token", "token1", "not-token1, token", true); errcount += expect_result ("token, tOkEn1", "token1", "token", true); errcount += expect_result ("not-token, tOkEn", " \t toKEN", "not-token", true); errcount += expect_result ("not-token, tOkEn, more-token", "toKEN\t", "not-token, more-token", true); errcount += expect_result ("not-token, tOkEn, more-token", "\t toKEN,,,,,", "not-token, more-token", true); errcount += expect_result ("a, b, c, d", ",,,,,a", "b, c, d", true); errcount += expect_result ("a, b, c, d", "a,,,,,,", "b, c, d", true); errcount += expect_result ("a, b, c, d", ",,,,a,,,,,,", "b, c, d", true); errcount += expect_result ("a, b, c, d", "\t \t,,,,a,, , ,,,\t", "b, c, d", true); errcount += expect_result ("a, b, c, d", "b, c, d", "a", true); errcount += expect_result ("a, b, c, d", "a, b, c, d", "", true); errcount += expect_result ("a, b, c, d", "d, c, b, a", "", true); errcount += expect_result ("a, b, c, d", "b, d, a, c", "", true); errcount += expect_result ("a, b, c, d, e", "b, d, a, c", "e", true); errcount += expect_result ("e, a, b, c, d", "b, d, a, c", "e", true); errcount += expect_result ("e, a, b, c, d, e", "b, d, a, c", "e, e", true); errcount += expect_result ("a, b, c, d", "b,c,d", "a", true); errcount += expect_result ("a, b, c, d", "a,b,c,d", "", true); errcount += expect_result ("a, b, c, d", "d,c,b,a", "", true); errcount += expect_result ("a, b, c, d", "b,d,a,c", "", true); errcount += expect_result ("a, b, c, d, e", "b,d,a,c", "e", true); errcount += expect_result ("e, a, b, c, d", "b,d,a,c", "e", true); errcount += expect_result ("e, a, b, c, d, e", "b,d,a,c", "e, e", true); errcount += expect_result ("a, b, c, d", "d,,,,,,,,,c,b,a", "", true); errcount += expect_result ("a, b, c, d", "b,d,a,c,,,,,,,,,,", "", true); errcount += expect_result ("a, b, c, d, e", ",,,,\t,,,,b,d,a,c,\t", "e", true); errcount += expect_result ("e, a, b, c, d", "b,d,a,c", "e", true); errcount += expect_result ("token, a, b, c, d", "token", "a, b, c, d", true); errcount += expect_result ("token1, a, b, c, d", "token1", "a, b, c, d", true); errcount += expect_result ("token12, a, b, c, d", "token12", "a, b, c, d", true); errcount += expect_result ("token123, a, b, c, d", "token123", "a, b, c, d", true); errcount += expect_result ("token1234, a, b, c, d", "token1234", "a, b, c, d", true); errcount += expect_result ("token12345, a, b, c, d", "token12345", "a, b, c, d", true); errcount += expect_result ("token123456, a, b, c, d", "token123456", "a, b, c, d", true); errcount += expect_result ("token1234567, a, b, c, d", "token1234567", "a, b, c, d", true); errcount += expect_result ("token12345678, a, b, c, d", "token12345678", "a, b, c, d", true); errcount += expect_result ("", "a", "", false); errcount += expect_result ("", "", "", false); errcount += expect_result ("a, b, c, d", "bb, dd, aa, cc", "a, b, c, d", false); errcount += expect_result ("a, b, c, d, e", "bb, dd, aa, cc", "a, b, c, d, e", false); errcount += expect_result ("e, a, b, c, d", "bb, dd, aa, cc", "e, a, b, c, d", false); errcount += expect_result ("e, a, b, c, d, e", "bb, dd, aa, cc", "e, a, b, c, d, e", false); errcount += expect_result ("aa, bb, cc, dd", "b, d, a, c", "aa, bb, cc, dd", false); errcount += expect_result ("aa, bb, cc, dd, ee", "b, d, a, c", "aa, bb, cc, dd, ee", false); errcount += expect_result ("ee, aa, bb, cc, dd", "b, d, a, c", "ee, aa, bb, cc, dd", false); errcount += expect_result ("ee, aa, bb, cc, dd, ee", "b, d, a, c", "ee, aa, bb, cc, dd, ee", false); errcount += expect_result ("TESt", ",,,,,,test,,,,", "", true); errcount += expect_result ("TESt", ",,,,,\t,test,,,,", "", true); errcount += expect_result ("TESt", ",,,,,,test, ,,,", "", true); errcount += expect_result ("TESt", ",,,,,, test,,,,", "", true); errcount += expect_result ("TESt", ",,,,,, test-not,test,,", "", true); errcount += expect_result ("TESt", ",,,,,, test-not,,test,,", "", true); errcount += expect_result ("TESt", ",,,,,, test-not ,test,,", "", true); errcount += expect_result ("TESt", ",,,,,, test", "", true); errcount += expect_result ("TESt", ",,,,,, test ", "", true); errcount += expect_result ("TESt", "no-test,,,,,, test ", "", true); errcount += expect_result ("the-token, a, the-token, b, the-token, " \ "the-token, c, the-token", "the-token", "a, b, c", true); errcount += expect_result ("aa, the-token, bb, the-token, cc, the-token, " \ "the-token, dd, the-token", "the-token", "aa, bb, cc, dd", true); errcount += expect_result ("the-token, a, the-token, b, the-token, " \ "the-token, c, the-token, e", "the-token", "a, b, c, e", true); errcount += expect_result ("aa, the-token, bb, the-token, cc, the-token, " \ "the-token, dd, the-token, ee", "the-token", "aa, bb, cc, dd, ee", true); errcount += expect_result ("the-token, the-token, the-token, " \ "the-token, the-token", "the-token", "", true); errcount += expect_result ("the-token, a, the-token, the-token, b, " \ "the-token, c, the-token, a", "c,a,b", "the-token, the-token, the-token, the-token, the-token", true); errcount += expect_result ("the-token, xx, the-token, the-token, zz, " \ "the-token, yy, the-token, ww", "ww,zz,yy", "the-token, xx, the-token, the-token, the-token, the-token", true); errcount += expect_result ("the-token, a, the-token, the-token, b, " \ "the-token, c, the-token, a", " c,\t a,b,,,", "the-token, the-token, the-token, the-token, the-token", true); errcount += expect_result ("the-token, xx, the-token, the-token, zz, " \ "the-token, yy, the-token, ww", ",,,,ww,\t zz, yy", "the-token, xx, the-token, the-token, the-token, the-token", true); errcount += expect_result ("the-token, a, the-token, the-token, b, " \ "the-token, c, the-token, a", ",,,,c,\t a,b", "the-token, the-token, the-token, the-token, the-token", true); errcount += expect_result ("the-token, xx, the-token, the-token, zz, " \ "the-token, yy, the-token, ww", " ww,\t zz,yy,,,,", "the-token, xx, the-token, the-token, the-token, the-token", true); errcount += expect_result ("close, 2", "close", "2", true); errcount += expect_result ("close, 22", "close", "22", true); errcount += expect_result ("close, nothing", "close", "nothing", true); errcount += expect_result ("close, 2", "2", "close", true); errcount += expect_result ("close", "close", "", true); errcount += expect_result ("close, nothing", "close, token", "nothing", true); errcount += expect_result ("close, nothing", "nothing, token", "close", true); errcount += expect_result ("close, 2", "close, 10, 12, 22, nothing", "2", true); errcount += expect_result ("strin", "string", "strin", false); errcount += expect_result ("Stringer", "string", "Stringer", false); errcount += expect_result ("sstring", "String", "sstring", false); errcount += expect_result ("string", "Strin", "string", false); errcount += expect_result ("String", "\t(-strinG", "String", false); errcount += expect_result ("String", ")strinG\t ", "String", false); errcount += expect_result ("not-token, tOkEner", "toKEN", "not-token, tOkEner", false); errcount += expect_result ("not-token, tOkEns, more-token", "toKEN", "not-token, tOkEns, more-token", false); errcount += expect_result ("tests, quest", "TESt", "tests, quest", false); errcount += expect_result ("testы", "TESt", "testы", false); errcount += expect_result ("test-not, хtest", "TESt", "test-not, хtest", false); errcount += expect_result ("testing, test not, test2", "TESt", "testing, test not, test2", false); errcount += expect_result ("", ",,,,,,,,,,,,,,,,,,,the-token", "", false); errcount += expect_result ("a1, b1, c1, d1, e1, f1, g1", "", "a1, b1, c1, d1, e1, f1, g1", false); return errcount; } int main (int argc, char *argv[]) { int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += check_result (); if (0 == errcount) printf ("All tests were passed without errors.\n"); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.10/src/microhttpd/test_postprocessor_amp.c0000664000175000017500000001222615232103064020050 #include "platform.h" #include "microhttpd.h" #include "internal.h" #include #include #include /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static uint64_t num_errors; static enum MHD_Result check_post (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *content_encoding, const char *data, uint64_t off, size_t size) { (void) cls; (void) kind; (void) filename; (void) content_type; /* Unused. Silent compiler warning. */ (void) content_encoding; (void) data; (void) off; (void) size; /* Unused. Silent compiler warning. */ if ((0 != strcmp (key, "a")) && (0 != strcmp (key, "b"))) { printf ("ERROR: got unexpected '%s'\n", key); num_errors++; } return MHD_YES; } int main (int argc, char *const *argv) { struct MHD_Connection connection; struct MHD_HTTP_Req_Header header; struct MHD_PostProcessor *pp; const char *post = "a=xx+xx+xxx+xxxxx+xxxx+xxxxxxxx+xxx+xxxxxx+xxx+xxx+xxxxxxx+xxxxx%0A+++" "++++xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxx%0A+++++++--%3E%0A++++++++++++++%3Cxxxxx+xxxxx%3D%22xxx%" "25%22%3E%0A+++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xxxxxxx%3D%22x%2" "2+xxxxx%3D%22xxxxx%22%3E%0A+++++++++++++++++++%3Cxxxxx+xxxxx%3D%22xxx%" "25%22%3E%0A+++++++++++++++++++++++%3Cxx%3E%0A+++++++++++++++++++++++++" "++%3Cxx+xxxxx%3D%22xxxx%22%3E%0A+++++++++++++++++++++++++++++++%3Cx+xx" "xxx%3D%22xxxx-xxxxx%3Axxxxx%22%3Exxxxx%3A%3C%2Fx%3E%0A%0A+++++++++++++" "++++++++++++++++++%3Cx+xxxxx%3D%22xxxx-xxxxx%3Axxxxx%22%3Exxx%3A%3C%2F" "x%3E%0A%0A+++++++++++++++++++++++++++++++%3Cx+xxxxx%3D%22xxxx-xxxxx%3A" "xxxxx%3B+xxxx-xxxxxx%3A+xxxx%3B%22%3Exxxxx+xxxxx%3A%3C%2Fx%3E%0A++++++" "+++++++++++++++++++++%3C%2Fxx%3E%0A+++++++++++++++++++++++%3C%2Fxx%3E%" "0A+++++++++++++++++++%3C%2Fxxxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++" "++++++++++++%3Cxx+xxxxx%3D%22xxxx-xxxxx%3A+xxxxx%3B+xxxxx%3A+xxxx%22%3" "E%26xxxxx%3B+%3Cxxxx%0A+++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxxxxx" "xx%22%3Exxxx.xx%3C%2Fxxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A++++++++++" "+%3C%2Fxx%3E%0A++++++++++++++++++++++++++%3Cxx%3E%0A++++++++++++++++++" "+%3Cxx+xxxxx%3D%22xxxx-xxxxx%3A+xxxxx%3B+xxxxx%3A+xxxx%22%3E%26xxxxx%3" "B+%3Cxxxx%0A+++++++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxxxxxxx%22%3" "Exxx.xx%3C%2Fxxxx%3E%0A+++++++++++++++++++%3C%2Fxx%3E%0A++++++++++++++" "+%3C%2Fxx%3E%0A++++++++++++++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+x" "xxxx%3D%22xxxx-xxxxx%3A+xxxxx%3Bxxxx-xxxxxx%3A+xxxx%3B+xxxxx%3A+xxxx%2" "2%3E%26xxxxx%3B+%3Cxxxx%0A+++++++++++++++++++++++xxxxx%3D%22xxxxxxxxxx" "xxxxx%22%3Exxxx.xx%3C%2Fxxxx%3E%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A" "+++++++%3C%2Fxxxxx%3E%0A+++++++%3C%21--%0A+++++++xxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%0A+++++++x" "xx+xx+xxxxx+xxxxxxx+xxxxxxx%0A+++++++xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%0A+++++++--%3E%0A+++%3" "C%2Fxxx%3E%0A%0A%0A%0A+++%3Cxxx+xxxxx%3D%22xxxxxxxxx%22+xx%3D%22xxxxxx" "xxx%22%3E%3C%2Fxxx%3E%0A%0A+++%3Cxxx+xx%3D%22xxxx%22+xxxxx%3D%22xxxx%2" "2%3E%0A+++++++%3Cxxxxx+xxxxx%3D%22xxxxxxxxx%22%3E%0A+++++++++++%3Cxx%3" "E%0A+++++++++++++++%3Cxx+xxxxxxx%3D%22x%22+xx%3D%22xxxxxxxxxxxxx%22+xx" "xxx%3D%22xxxxxxxxxxxxx%22%3E%0A+++++++++++++++++++%3Cxxx+xx%3D%22xxxxx" "x%22%3E%3C%2Fxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx" "%3E%0A+++++++++++%3Cxx%3E%0A+++++++++++++++%3Cxx+xx%3D%22xxxxxxxxxxxxx" "xxxx%22+xxxxx%3D%22xxxxxxxxxxxxxxxxx%22%3E%3C%2Fxx%3E%0A++++++++++++++" "+%3Cxx+xx%3D%22xxxxxxxxxxxxxx%22+xxxxx%3D%22xxxxxxxxxxxxxx%22%3E%0A+++" "++++++++++++++++%3Cxxx+xx%3D%22xxxxxxx%22%3E%3C%2Fxxx%3E%0A+++++++++++" "++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A+++++++++++%3Cxx%3E%0A+++++" "++++++++++%3Cxx+xxxxxxx%3D%22x%22+xx%3D%22xxxxxxxxxxxxx%22+xxxxx%3D%22" "xxxxxxxxxxxxx%22%3E%0A+++++++++++++++++++%3Cxxx+xx%3D%22xxxxxx%22%3E%3" "C%2Fxxx%3E%0A+++++++++++++++%3C%2Fxx%3E%0A+++++++++++%3C%2Fxx%3E%0A+++" "++++%3C%2Fxxxxx%3E%0A+++%3C%2Fxxx%3E%0A%3C%2Fxxx%3E%0A%0A%3Cxxx+xx%3D%" "22xxxxxx%22%3E%3C%2Fxxx%3E%0A%0A%3C%2Fxxxx%3E%0A%3C%2Fxxxx%3E+&b=value"; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ num_errors = 0; memset (&connection, 0, sizeof (struct MHD_Connection)); memset (&header, 0, sizeof (struct MHD_HTTP_Res_Header)); connection.rq.headers_received = &header; header.header = MHD_HTTP_HEADER_CONTENT_TYPE; header.value = MHD_HTTP_POST_ENCODING_FORM_URLENCODED; header.header_size = strlen (header.header); header.value_size = strlen (header.value); header.kind = MHD_HEADER_KIND; pp = MHD_create_post_processor (&connection, 4096, &check_post, NULL); if (NULL == pp) return 1; if (MHD_YES != MHD_post_process (pp, post, strlen (post))) num_errors++; MHD_destroy_post_processor (pp); return num_errors == 0 ? 0 : 2; } libmicrohttpd-1.0.10/src/microhttpd/Makefile.am0000664000175000017500000004740015232103064015121 # This Makefile.am is in the public domain AM_CPPFLAGS = \ -I$(top_srcdir)/src/include \ $(CPPFLAGS_ac) AM_CFLAGS = $(CFLAGS_ac) $(HIDDEN_VISIBILITY_CFLAGS) AM_LDFLAGS = $(LDFLAGS_ac) AM_TESTS_ENVIRONMENT = $(TESTS_ENVIRONMENT_ac) lib_LTLIBRARIES = \ libmicrohttpd.la noinst_DATA = MOSTLYCLEANFILES = # Test-only header, #included by every test program but not compiled on its # own and not part of the library; see mhd_panic_tripwire.h. EXTRA_DIST = \ mhd_panic_tripwire.h AM_V_LIB = $(am__v_LIB_@AM_V@) am__v_LIB_ = $(am__v_LIB_@AM_DEFAULT_V@) am__v_LIB_0 = @echo " LIB " $@; am__v_LIB_1 = if W32_SHARED_LIB_EXP AM_V_DLLTOOL = $(am__v_DLLTOOL_@AM_V@) am__v_DLLTOOL_ = $(am__v_DLLTOOL_@AM_DEFAULT_V@) am__v_DLLTOOL_0 = @echo " DLLTOOL " $@; am__v_DLLTOOL_1 = W32_MHD_LIB_LDFLAGS = -Wl,--output-def,$(lt_cv_objdir)/libmicrohttpd.def -XCClinker -static-libgcc noinst_DATA += $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def MOSTLYCLEANFILES += $(lt_cv_objdir)/libmicrohttpd.lib $(lt_cv_objdir)/libmicrohttpd.def $(lt_cv_objdir)/libmicrohttpd.exp $(lt_cv_objdir)/libmicrohttpd.def: libmicrohttpd.la $(AM_V_at)test -f $@ && touch $@ || \ ( rm -f libmicrohttpd.la ; $(MAKE) $(AM_MAKEFLAGS) libmicrohttpd.la && touch $@ ) if USE_EXPORT_FILE noinst_DATA += $(lt_cv_objdir)/libmicrohttpd.exp $(lt_cv_objdir)/libmicrohttpd.exp: $(lt_cv_objdir)/libmicrohttpd.lib $(AM_V_at)test -f $@ && touch $@ || \ ( rm -f $(lt_cv_objdir)/libmicrohttpd.lib ; $(MAKE) $(AM_MAKEFLAGS) $(lt_cv_objdir)/libmicrohttpd.lib && touch $@ ) endif if USE_MS_LIB_TOOL $(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) $(AM_V_LIB) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ $(MS_LIB_TOOL) -nologo -def:libmicrohttpd.def -name:$$dll_name -out:libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -ignore:4221 else if USE_EXPORT_FILE $(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) $(AM_V_DLLTOOL) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ $(DLLTOOL) -d libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib $(libmicrohttpd_la_OBJECTS:.lo=.o) -e ./libmicrohttpd.exp else $(lt_cv_objdir)/libmicrohttpd.lib: $(lt_cv_objdir)/libmicrohttpd.def libmicrohttpd.la $(AM_V_DLLTOOL) cd "$(lt_cv_objdir)" && dll_name=`$(SED) -n -e "s/^dlname='\(.*\)'/\1/p" libmicrohttpd.la` && test -n "$$dll_name" && \ $(DLLTOOL) -d libmicrohttpd.def -D $$dll_name -l libmicrohttpd.lib endif endif else W32_MHD_LIB_LDFLAGS = endif if W32_STATIC_LIB noinst_DATA += $(lt_cv_objdir)/libmicrohttpd-static.lib MOSTLYCLEANFILES += $(lt_cv_objdir)/libmicrohttpd-static.lib $(lt_cv_objdir)/libmicrohttpd-static.lib: libmicrohttpd.la $(libmicrohttpd_la_OBJECTS) if USE_MS_LIB_TOOL $(AM_V_LIB) $(MS_LIB_TOOL) -nologo -out:$@ $(libmicrohttpd_la_OBJECTS:.lo=.o) else $(AM_V_at)cp $(lt_cv_objdir)/libmicrohttpd.a $@ endif endif libmicrohttpd_la_SOURCES = \ connection.c connection.h \ reason_phrase.c \ daemon.c \ internal.c internal.h \ memorypool.c memorypool.h \ mhd_mono_clock.c mhd_mono_clock.h \ mhd_limits.h \ sysfdsetsize.h \ mhd_str.c mhd_str.h mhd_str_types.h\ mhd_send.h mhd_send.c \ mhd_assert.h \ mhd_check.h \ mhd_sockets.c mhd_sockets.h \ mhd_itc.c mhd_itc.h mhd_itc_types.h \ mhd_compat.c mhd_compat.h \ mhd_panic.c mhd_panic.h \ response.c response.h if USE_POSIX_THREADS libmicrohttpd_la_SOURCES += \ mhd_threads.c mhd_threads.h \ mhd_locks.h endif if USE_W32_THREADS libmicrohttpd_la_SOURCES += \ mhd_threads.c mhd_threads.h \ mhd_locks.h endif if NEED_SYS_FD_SET_SIZE_VALUE libmicrohttpd_la_SOURCES += \ sysfdsetsize.c endif libmicrohttpd_la_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_LIB_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) \ -DBUILDING_MHD_LIB=1 libmicrohttpd_la_CFLAGS = \ $(AM_CFLAGS) $(MHD_LIB_CFLAGS) $(MHD_TLS_LIB_CFLAGS) libmicrohttpd_la_LDFLAGS = \ $(AM_LDFLAGS) $(MHD_LIB_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) \ $(W32_MHD_LIB_LDFLAGS) \ -export-dynamic -no-undefined \ -version-info @LIB_VERSION_CURRENT@:@LIB_VERSION_REVISION@:@LIB_VERSION_AGE@ libmicrohttpd_la_LIBADD = \ $(MHD_LIBDEPS) $(MHD_TLS_LIBDEPS) AM_V_RC = $(am__v_RC_@AM_V@) am__v_RC_ = $(am__v_RC_@AM_DEFAULT_V@) am__v_RC_0 = @echo " RC " $@; am__v_RC_1 = # General rule is not required, but keep it just in case # Note: windres does not understand '-isystem' flag, so all # possible '-isystem' flags are replaced by simple '-I' flags. .rc.lo: $(AM_V_RC) RC_ALL_CPPFLAGS=`echo ' $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) ' | $(SED) -e 's/ -isystem / -I /g'`; \ $(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_ALL_CPPFLAGS} $< -o $@ # Note: windres does not understand '-isystem' flag, so all # possible '-isystem' flags are replaced by simple '-I' flags. libmicrohttpd_la-microhttpd_dll_res.lo: $(builddir)/microhttpd_dll_res.rc $(AM_V_RC) RC_ALL_CPPFLAGS=`echo ' $(DEFAULT_INCLUDES) $(INCLUDES) $(libmicrohttpd_la_CPPFLAGS) $(CPPFLAGS) ' | $(SED) -e 's/ -isystem / -I /g'`; \ $(LIBTOOL) $(AM_V_lt) --tag=RC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(RC) $(RCFLAGS) $(DEFS) $${RC_ALL_CPPFLAGS} $(builddir)/microhttpd_dll_res.rc -o $@ if HAVE_W32 MHD_DLL_RES_LO = libmicrohttpd_la-microhttpd_dll_res.lo else MHD_DLL_RES_LO = endif EXTRA_libmicrohttpd_la_DEPENDENCIES = $(MHD_DLL_RES_LO) libmicrohttpd_la_LIBADD += $(MHD_DLL_RES_LO) if USE_COVERAGE AM_CFLAGS += --coverage endif if !MHD_USE_SYS_TSEARCH libmicrohttpd_la_SOURCES += \ tsearch.c tsearch.h endif if HAVE_POSTPROCESSOR libmicrohttpd_la_SOURCES += \ postprocessor.c postprocessor.h endif if HAVE_ANYAUTH libmicrohttpd_la_SOURCES += \ gen_auth.c gen_auth.h endif if ENABLE_DAUTH libmicrohttpd_la_SOURCES += \ digestauth.c digestauth.h \ mhd_bithelpers.h mhd_byteorder.h mhd_align.h if ENABLE_MD5 libmicrohttpd_la_SOURCES += \ mhd_md5_wrap.h if ! ENABLE_MD5_EXT libmicrohttpd_la_SOURCES += \ md5.c md5.h else libmicrohttpd_la_SOURCES += \ md5_ext.c md5_ext.h endif endif if ENABLE_SHA256 libmicrohttpd_la_SOURCES += \ mhd_sha256_wrap.h if ! ENABLE_SHA256_EXT libmicrohttpd_la_SOURCES += \ sha256.c sha256.h else libmicrohttpd_la_SOURCES += \ sha256_ext.c sha256_ext.h endif endif if ENABLE_SHA512_256 libmicrohttpd_la_SOURCES += \ sha512_256.c sha512_256.h endif endif if ENABLE_BAUTH libmicrohttpd_la_SOURCES += \ basicauth.c basicauth.h endif if ENABLE_HTTPS libmicrohttpd_la_SOURCES += \ connection_https.c connection_https.h endif check_PROGRAMS = \ test_str_compare \ test_str_to_value \ test_str_from_value \ test_str_token \ test_str_token_remove \ test_str_tokens_remove \ test_str_pct \ test_str_bin_hex \ test_http_reasons \ test_sha1 \ test_start_stop \ test_daemon \ test_response_entries \ test_postprocessor_md \ test_client_put_shutdown \ test_client_put_close \ test_client_put_hard_close \ test_client_put_steps_shutdown \ test_client_put_steps_close \ test_client_put_steps_hard_close \ test_client_put_chunked_shutdown \ test_client_put_chunked_close \ test_client_put_chunked_hard_close \ test_client_put_chunked_steps_shutdown \ test_client_put_chunked_steps_close \ test_client_put_chunked_steps_hard_close \ test_options \ test_mhd_version \ test_set_panic \ test_rq_shift_back \ test_chunked_ext \ test_raw_requests \ test_option_matrix if ENABLE_MD5 check_PROGRAMS += \ test_md5 endif if ENABLE_SHA256 check_PROGRAMS += \ test_sha256 endif if ENABLE_SHA512_256 check_PROGRAMS += \ test_sha512_256 endif if HAVE_POSIX_THREADS if ENABLE_UPGRADE if USE_THREADS check_PROGRAMS += test_upgrade test_upgrade_large test_upgrade_vlarge if ENABLE_HTTPS if USE_UPGRADE_TLS_TESTS check_PROGRAMS += test_upgrade_tls test_upgrade_large_tls test_upgrade_vlarge_tls endif endif endif endif endif if HAVE_POSTPROCESSOR check_PROGRAMS += \ test_postprocessor \ test_postprocessor_large \ test_postprocessor_amp endif # Do not test trigger of select by shutdown of listen socket # on Cygwin as this ability is deliberately ignored on Cygwin # to improve compatibility with core OS. if !CYGWIN_TARGET if HAVE_POSIX_THREADS if HAVE_LISTEN_SHUTDOWN check_PROGRAMS += \ test_shutdown_select \ test_shutdown_poll else check_PROGRAMS += \ test_shutdown_select_ignore \ test_shutdown_poll_ignore endif endif endif if HAVE_ANYAUTH if HAVE_MESSAGES check_PROGRAMS += \ test_auth_parse endif endif if ENABLE_DAUTH check_PROGRAMS += \ test_str_quote \ test_dauth_userdigest \ test_dauth_userhash \ test_dauth_malformed endif if ENABLE_BAUTH check_PROGRAMS += \ test_str_base64 endif if HEAVY_TESTS if TESTS_STRESS_OS check_PROGRAMS += \ test_client_put_hard_close_stress_os \ test_client_put_steps_hard_close_stress_os \ test_client_put_chunked_steps_hard_close_stress_os endif endif TESTS = $(check_PROGRAMS) update-po-POTFILES.in: $(top_srcdir)/po/POTFILES.in $(top_srcdir)/po/POTFILES.in: $(srcdir)/Makefile.am @echo "Creating $@" @echo src/include/microhttpd.h > "$@" && \ for src in $(am__libmicrohttpd_la_SOURCES_DIST) ; do \ echo "$(subdir)/$$src" >> "$@" ; \ done test_start_stop_SOURCES = \ test_start_stop.c test_start_stop_LDADD = \ libmicrohttpd.la test_daemon_SOURCES = \ test_daemon.c test_daemon_LDADD = \ $(builddir)/libmicrohttpd.la test_response_entries_SOURCES = \ test_response_entries.c test_response_entries_LDADD = \ libmicrohttpd.la test_upgrade_SOURCES = \ test_upgrade.c test_helpers.h mhd_sockets.h test_upgrade_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_upgrade_CFLAGS = \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_upgrade_LDFLAGS = \ $(MHD_TLS_LIB_LDFLAGS) test_upgrade_LDADD = \ $(builddir)/libmicrohttpd.la \ $(MHD_TLS_LIBDEPS) \ $(PTHREAD_LIBS) test_upgrade_large_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_large_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_large_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_large_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_large_LDADD = \ $(test_upgrade_LDADD) test_upgrade_vlarge_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_vlarge_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_vlarge_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_vlarge_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_vlarge_LDADD = \ $(test_upgrade_LDADD) test_upgrade_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_tls_LDADD = \ $(test_upgrade_LDADD) test_upgrade_large_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_large_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_large_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_large_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_large_tls_LDADD = \ $(test_upgrade_LDADD) test_upgrade_vlarge_tls_SOURCES = \ $(test_upgrade_SOURCES) test_upgrade_vlarge_tls_CPPFLAGS = \ $(test_upgrade_CPPFLAGS) test_upgrade_vlarge_tls_CFLAGS = \ $(test_upgrade_CFLAGS) test_upgrade_vlarge_tls_LDFLAGS = \ $(test_upgrade_LDFLAGS) test_upgrade_vlarge_tls_LDADD = \ $(test_upgrade_LDADD) test_postprocessor_SOURCES = \ test_postprocessor.c test_postprocessor_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_amp_SOURCES = \ test_postprocessor_amp.c test_postprocessor_amp_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_amp_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_amp_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_large_SOURCES = \ test_postprocessor_large.c test_postprocessor_large_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_postprocessor_large_CFLAGS = \ $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_postprocessor_large_LDADD = \ $(builddir)/libmicrohttpd.la test_postprocessor_md_SOURCES = \ test_postprocessor_md.c postprocessor.h postprocessor.c \ internal.h internal.c mhd_str.h mhd_str.c \ mhd_panic.h mhd_panic.c test_postprocessor_md_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_shutdown_select_SOURCES = \ test_shutdown_select.c test_shutdown_select_CFLAGS = $(AM_CFLAGS) test_shutdown_select_LDADD = $(LDADD) if USE_POSIX_THREADS test_shutdown_select_CFLAGS += \ $(PTHREAD_CFLAGS) test_shutdown_select_LDADD += \ $(PTHREAD_LIBS) endif test_shutdown_poll_SOURCES = \ test_shutdown_select.c mhd_threads.h test_shutdown_poll_CFLAGS = $(AM_CFLAGS) test_shutdown_poll_LDADD = $(LDADD) if USE_POSIX_THREADS test_shutdown_poll_CFLAGS += \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_shutdown_poll_LDADD += \ $(PTHREAD_LIBS) endif test_shutdown_select_ignore_SOURCES = \ test_shutdown_select.c test_shutdown_select_ignore_CFLAGS = $(AM_CFLAGS) test_shutdown_select_ignore_LDADD = $(LDADD) if USE_POSIX_THREADS test_shutdown_select_ignore_CFLAGS += \ $(PTHREAD_CFLAGS) test_shutdown_select_ignore_LDADD += \ $(PTHREAD_LIBS) endif test_shutdown_poll_ignore_SOURCES = \ test_shutdown_select.c mhd_threads.h test_shutdown_poll_ignore_CFLAGS = $(AM_CFLAGS) test_shutdown_poll_ignore_LDADD = $(LDADD) if USE_POSIX_THREADS test_shutdown_poll_ignore_CFLAGS += \ $(AM_CFLAGS) $(PTHREAD_CFLAGS) test_shutdown_poll_ignore_LDADD += \ $(PTHREAD_LIBS) endif test_str_compare_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_to_value_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_from_value_SOURCES = \ test_str.c test_helpers.h mhd_str.c mhd_str.h test_str_token_SOURCES = \ test_str_token.c mhd_str.c mhd_str.h test_str_token_remove_SOURCES = \ test_str_token_remove.c mhd_str.c mhd_str.h mhd_assert.h ../include/mhd_options.h test_str_tokens_remove_SOURCES = \ test_str_tokens_remove.c mhd_str.c mhd_str.h mhd_assert.h ../include/mhd_options.h test_http_reasons_SOURCES = \ test_http_reasons.c \ reason_phrase.c mhd_str.c mhd_str.h test_md5_SOURCES = \ test_md5.c test_helpers.h mhd_md5_wrap.h ../include/mhd_options.h if ! ENABLE_MD5_EXT test_md5_SOURCES += \ md5.c md5.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_md5_CPPFLAGS = $(AM_CPPFLAGS) test_md5_CFLAGS = $(AM_CFLAGS) test_md5_LDFLAGS = $(AM_LDFLAGS) test_md5_LDADD = $(LDADD) else test_md5_SOURCES += \ md5_ext.c md5_ext.h test_md5_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_md5_CFLAGS = $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_md5_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) test_md5_LDADD = $(MHD_TLS_LIBDEPS) $(LDADD) endif test_sha256_SOURCES = \ test_sha256.c test_helpers.h mhd_sha256_wrap.h ../include/mhd_options.h if ! ENABLE_SHA256_EXT test_sha256_SOURCES += \ sha256.c sha256.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_sha256_CPPFLAGS = $(AM_CPPFLAGS) test_sha256_CFLAGS = $(AM_CFLAGS) test_sha256_LDFLAGS = $(AM_LDFLAGS) test_sha256_LDADD = $(LDADD) else test_sha256_SOURCES += \ sha256_ext.c sha256_ext.h test_sha256_CPPFLAGS = $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_sha256_CFLAGS = $(AM_CFLAGS) $(MHD_TLS_LIB_CFLAGS) test_sha256_LDFLAGS = $(AM_LDFLAGS) $(MHD_TLS_LIB_LDFLAGS) test_sha256_LDADD = $(MHD_TLS_LIBDEPS) $(LDADD) endif test_sha512_256_SOURCES = \ test_sha512_256.c test_helpers.h \ sha512_256.c sha512_256.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_sha1_SOURCES = \ test_sha1.c test_helpers.h \ sha1.c sha1.h mhd_bithelpers.h mhd_byteorder.h mhd_align.h test_auth_parse_SOURCES = \ test_auth_parse.c gen_auth.c gen_auth.h mhd_str.h mhd_str.c mhd_assert.h test_auth_parse_CPPFLAGS = \ $(AM_CPPFLAGS) $(MHD_TLS_LIB_CPPFLAGS) test_str_quote_SOURCES = \ test_str_quote.c mhd_str.h mhd_str.c mhd_assert.h test_str_base64_SOURCES = \ test_str_base64.c mhd_str.h mhd_str.c mhd_assert.h test_str_pct_SOURCES = \ test_str_pct.c mhd_str.h mhd_str.c mhd_assert.h test_str_bin_hex_SOURCES = \ test_str_bin_hex.c mhd_str.h mhd_str.c mhd_assert.h test_options_SOURCES = \ test_options.c test_options_LDADD = \ $(builddir)/libmicrohttpd.la # The environment-driven daemon option matrix (see mhd_opt_matrix.h and # contrib/run-option-matrix.sh). It uses the public API only, so it is # simply compiled into every test that honours the matrix. MHD_OPT_MATRIX_SOURCES = \ mhd_opt_matrix.c mhd_opt_matrix.h test_rq_shift_back_SOURCES = \ test_rq_shift_back.c mhd_sockets.h mhd_assert.h \ $(MHD_OPT_MATRIX_SOURCES) test_rq_shift_back_LDADD = \ $(builddir)/libmicrohttpd.la test_chunked_ext_SOURCES = \ test_chunked_ext.c mhd_sockets.h mhd_assert.h \ $(MHD_OPT_MATRIX_SOURCES) test_chunked_ext_LDADD = \ $(builddir)/libmicrohttpd.la test_raw_requests_SOURCES = \ test_raw_requests.c mhd_sockets.h mhd_assert.h \ $(MHD_OPT_MATRIX_SOURCES) test_raw_requests_LDADD = \ $(builddir)/libmicrohttpd.la test_option_matrix_SOURCES = \ test_option_matrix.c mhd_sockets.h mhd_assert.h \ $(MHD_OPT_MATRIX_SOURCES) test_option_matrix_LDADD = \ $(builddir)/libmicrohttpd.la test_dauth_malformed_SOURCES = \ test_dauth_malformed.c mhd_sockets.h mhd_assert.h \ $(MHD_OPT_MATRIX_SOURCES) test_dauth_malformed_LDADD = \ $(builddir)/libmicrohttpd.la test_client_put_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_shutdown_LDADD = \ libmicrohttpd.la test_client_put_close_SOURCES = \ test_client_put_stop.c test_client_put_close_LDADD = \ libmicrohttpd.la test_client_put_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_hard_close_LDADD = \ libmicrohttpd.la test_client_put_hard_close_stress_os_SOURCES = \ $(test_client_put_hard_close_SOURCES) test_client_put_hard_close_stress_os_LDADD = \ $(test_client_put_hard_close_LDADD) test_client_put_steps_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_steps_shutdown_LDADD = \ libmicrohttpd.la test_client_put_steps_close_SOURCES = \ test_client_put_stop.c test_client_put_steps_close_LDADD = \ libmicrohttpd.la test_client_put_steps_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_steps_hard_close_LDADD = \ libmicrohttpd.la test_client_put_steps_hard_close_stress_os_SOURCES = \ $(test_client_put_steps_hard_close_SOURCES) test_client_put_steps_hard_close_stress_os_LDADD = \ $(test_client_put_steps_hard_close_LDADD) test_client_put_chunked_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_chunked_shutdown_LDADD = \ libmicrohttpd.la test_client_put_chunked_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_hard_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_shutdown_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_shutdown_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_hard_close_SOURCES = \ test_client_put_stop.c test_client_put_chunked_steps_hard_close_LDADD = \ libmicrohttpd.la test_client_put_chunked_steps_hard_close_stress_os_SOURCES = \ $(test_client_put_chunked_steps_hard_close_SOURCES) test_client_put_chunked_steps_hard_close_stress_os_LDADD = \ $(test_client_put_chunked_steps_hard_close_LDADD) test_set_panic_SOURCES = \ test_set_panic.c test_set_panic_LDADD = \ libmicrohttpd.la test_dauth_userdigest_SOURCES = \ test_dauth_userdigest.c test_dauth_userdigest_LDADD = \ libmicrohttpd.la test_dauth_userhash_SOURCES = \ test_dauth_userhash.c test_dauth_userhash_LDADD = \ libmicrohttpd.la test_mhd_version_SOURCES = \ test_mhd_version.c test_mhd_version_LDADD = \ libmicrohttpd.la .PHONY: update-po-POTFILES.in libmicrohttpd-1.0.10/src/microhttpd/test_rq_shift_back.c0000664000175000017500000004637215232103064017076 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with libmicrohttpd; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file test_rq_shift_back.c * @brief Regression test for the read buffer "shift back" underflow that * happened when the last element of the request headers list was * a query argument without the '=' character. * * The "shift back" optimisation at the end of get_req_headers() re-uses the * tail of the parsed request header area for the read buffer. It computes * the end of the last element of the @a headers_received list as * "value + value_size". A query argument given without '=' is stored with * a NULL @a value, so the computed end was NULL, the resulting shift size * was huge and the read buffer became a wild pointer. * * The optimisation is performed only when the space in the connection * memory pool is small (MHD_BUF_INC_SIZE > read_buffer_size), therefore the * daemons are started with a small MHD_OPTION_CONNECTION_MEMORY_LIMIT. * The tail of the headers list is a query argument only when the request has * no header lines at all, as the query arguments are added while the request * line is parsed and the header fields are appended afterwards. * * The test honours the daemon option matrix of mhd_opt_matrix.h: when one of * the MHD_TEST_* environment variables selects a profile, the built-in sweep * of connection memory limits is replaced by the memory limit of the profile * and the threading/polling mode of the profile is used as well. Without * those variables nothing changes. As the sub-cases need a pool that can * still hold the request, a profile asking for less than * #MIN_POOL_FOR_TEST bytes is raised to that value and the adjustment is * reported. * * @author Christian Grothoff */ #include "MHD_config.h" #include "platform.h" #include #include #include #include #include #ifdef HAVE_STRINGS_H #include #endif /* HAVE_STRINGS_H */ #ifndef WINDOWS #include #endif /* ! WINDOWS */ #ifdef HAVE_SIGNAL_H #include #endif /* HAVE_SIGNAL_H */ #include "mhd_sockets.h" /* only macros used */ #include "mhd_opt_matrix.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" #ifndef MHD_STATICSTR_LEN_ /** * Determine length of static string / macro strings at compile time. */ #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1) #endif /* ! MHD_STATICSTR_LEN_ */ /** * The smallest connection memory pool this test can work with: below that * MHD cannot even build the reply header and the sub-cases would fail for a * reason that has nothing to do with the "shift back" code. */ #define MIN_POOL_FOR_TEST 512 #if MHD_VERSION >= 0x00097701 #define TEST_MK_RESPONSE(len,str) \ MHD_create_response_from_buffer_static ((len), (str)) #else /* MHD_VERSION < 0x00097701 */ #define TEST_MK_RESPONSE(len,str) \ MHD_create_response_from_buffer ((len), (void *) (str), \ MHD_RESPMEM_PERSISTENT) #endif /* MHD_VERSION < 0x00097701 */ /** * The exit code for a failed test. */ #define EXIT_FAILED_TEST 1 /** * The exit code for a failure of the test framework itself. */ #define EXIT_HARD_ERROR 99 /** * The maximum time (in seconds) to wait for any single socket operation. */ #define TEST_SOCKET_TIMEOUT_SEC 5 /** * The body of the response sent by the test daemon. */ #define RESP_BODY "OK" /** * The expected start of the response. */ #define EXPECTED_STATUS "HTTP/1.1 200" /** * Be verbose. */ static int verbose; _MHD_NORETURN static void hard_error (const char *desc, int line_num) { fprintf (stderr, "HARD ERROR: %s at line %d. Last errno: %d (%s).\n", desc, line_num, (int) errno, strerror (errno)); fflush (stderr); exit (EXIT_HARD_ERROR); } #define hardErrorExit(desc) hard_error ((desc), __LINE__) /** * The handler of the requests, always replies with a tiny static response. */ static enum MHD_Result ahc_reply (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int marker; struct MHD_Response *resp; enum MHD_Result ret; (void) cls; (void) url; (void) method; (void) version; (void) upload_data; if (NULL == *req_cls) { *req_cls = ▮ return MHD_YES; } if (0 != *upload_data_size) { *upload_data_size = 0; return MHD_YES; } resp = TEST_MK_RESPONSE (MHD_STATICSTR_LEN_ (RESP_BODY), RESP_BODY); if (NULL == resp) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_OK, resp); MHD_destroy_response (resp); return ret; } /** * Set send and receive timeouts on the socket so that the test cannot * block indefinitely. * * @param sk the socket to set the timeouts on * @return non-zero if succeed, zero if failed */ static int set_socket_timeouts (MHD_socket sk) { #if defined(MHD_WINSOCK_SOCKETS) DWORD tv = (DWORD) (TEST_SOCKET_TIMEOUT_SEC * 1000); #else /* ! MHD_WINSOCK_SOCKETS */ struct timeval tv; tv.tv_sec = (time_t) TEST_SOCKET_TIMEOUT_SEC; tv.tv_usec = 0; #endif /* ! MHD_WINSOCK_SOCKETS */ if (0 != setsockopt (sk, SOL_SOCKET, SO_RCVTIMEO, (const void *) &tv, (socklen_t) sizeof (tv))) return 0; if (0 != setsockopt (sk, SOL_SOCKET, SO_SNDTIMEO, (const void *) &tv, (socklen_t) sizeof (tv))) return 0; return ! 0; } /** * Open a TCP connection to the given port on the loopback interface. * * @param port the port to connect to * @return the connected socket, MHD_INVALID_SOCKET on failure */ static MHD_socket connect_to_port (uint16_t port) { MHD_socket sk; struct sockaddr_in sa; sk = socket (PF_INET, SOCK_STREAM, 0); if (MHD_INVALID_SOCKET == sk) return MHD_INVALID_SOCKET; if (! set_socket_timeouts (sk)) { (void) MHD_socket_close_ (sk); return MHD_INVALID_SOCKET; } memset (&sa, 0, sizeof (sa)); sa.sin_family = AF_INET; sa.sin_port = htons (port); sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); if (0 != connect (sk, (const struct sockaddr *) &sa, (socklen_t) sizeof (sa))) { (void) MHD_socket_close_ (sk); return MHD_INVALID_SOCKET; } return sk; } /** * Send all the given data over the socket. * * @param sk the socket to use * @param buf the data to send * @param size the size of @a buf * @return non-zero if succeed, zero if failed */ static int send_all (MHD_socket sk, const char *buf, size_t size) { size_t off = 0; while (off < size) { ssize_t res; res = MHD_send_ (sk, buf + off, size - off); if (0 > res) { if (MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) continue; return 0; } if (0 == res) return 0; off += (size_t) res; } return ! 0; } /** * Receive data from the socket until @a min_size bytes are received, the * remote side closes the connection or the receive timeout expires. * * @param sk the socket to use * @param[out] buf the buffer to fill * @param buf_size the size of @a buf, the result is always zero-terminated, * therefore at most @a buf_size minus one bytes are received * @param min_size stop receiving as soon as this number of bytes is collected * @return the number of the received bytes */ static size_t recv_reply (MHD_socket sk, char *buf, size_t buf_size, size_t min_size) { size_t off = 0; while ((off < min_size) && (off + 1 < buf_size)) { ssize_t res; res = MHD_recv_ (sk, buf + off, buf_size - 1 - off); if (0 > res) { if (MHD_SCKT_ERR_IS_EINTR_ (MHD_socket_get_error_ ())) continue; break; /* Timeout or error */ } if (0 == res) break; /* The remote side closed the connection */ off += (size_t) res; } buf[off] = 0; return off; } /** * The description of a single sub-case. */ struct SubCase { /** * The human readable name of the sub-case. */ const char *name; /** * The raw request (and any trailing data) to be sent in a single write. */ const char *request; }; /** * The sub-cases. * The sub-cases with a trailing query argument without '=' and without any * header line are the ones triggering the bug. The requests with some * trailing data force a non-zero read buffer offset, which turns the * underflow into a memmove() with a wild destination pointer (detected * even when the asserts are disabled), therefore these variants are run * first. The control sub-cases are run before them, so that a failure of * the test harness itself can be distinguished from the bug. */ static const struct SubCase subcases[] = { /* Controls, must always succeed. */ { "no query arguments at all (control)", "GET /a HTTP/1.0\r\n\r\n" }, { "no query arguments at all, with trailing data (control)", "GET /a HTTP/1.0\r\n\r\nZZZZZZZZ" }, { "empty argument value (control)", "GET /a?x= HTTP/1.0\r\n\r\n" }, { "empty argument value, with trailing data (control)", "GET /a?x= HTTP/1.0\r\n\r\nZZZZZZZZ" }, { "non-empty argument value (control)", "GET /a?x=1 HTTP/1.0\r\n\r\n" }, { "non-empty argument value, with trailing data (control)", "GET /a?x=1 HTTP/1.0\r\n\r\nZZZZZZZZ" }, { "argument without '=' plus a header line (control)", "GET /a?x HTTP/1.1\r\nHost: h\r\nConnection: close\r\n\r\n" }, { "arguments without '=' plus a header line (control)", "GET /a?x&y HTTP/1.1\r\nHost: h\r\nConnection: close\r\n\r\n" }, { "argument with trailing '&' plus a header line (control)", "GET /a?x& HTTP/1.1\r\nHost: h\r\nConnection: close\r\n\r\n" }, /* The sub-cases triggering the bug. */ { "single argument without '=', with trailing data", "GET /a?x HTTP/1.0\r\n\r\nZZZZZZZZ" }, { "single argument without '='", "GET /a?x HTTP/1.0\r\n\r\n" }, { "two arguments, both without '=', with trailing data", "GET /a?x&y HTTP/1.0\r\n\r\nZZZZZZZZ" }, { "two arguments, both without '='", "GET /a?x&y HTTP/1.0\r\n\r\n" }, { "argument with value followed by argument without '=', trailing data", "GET /a?x=1&y HTTP/1.0\r\n\r\nZZZZZZZZ" }, { "argument with value followed by argument without '='", "GET /a?x=1&y HTTP/1.0\r\n\r\n" }, { "single argument with trailing '&', with trailing data", "GET /a?x& HTTP/1.0\r\n\r\nZZZZZZZZ" }, { "single argument with trailing '&'", "GET /a?x& HTTP/1.0\r\n\r\n" }, { "percent-encoded argument name without '=', with trailing data", "GET /a?%78%79 HTTP/1.0\r\n\r\nZZZZZZZZ" }, { "percent-encoded argument name without '='", "GET /a?%78%79 HTTP/1.0\r\n\r\n" }, { "plus-encoded argument name without '=', with trailing data", "GET /a?x+y HTTP/1.0\r\n\r\nZZZZZZZZ" }, { "plus-encoded argument name without '='", "GET /a?x+y HTTP/1.0\r\n\r\n" } }; /** * The values for MHD_OPTION_CONNECTION_MEMORY_LIMIT to be tested. * All of them must be small enough to keep the read buffer size below * MHD_BUF_INC_SIZE (1500), otherwise the "shift back" code is not used * at all. */ static const size_t mem_limits[] = { 512, 1024 }; /** * The profile selected by the environment, NULL if the built-in sweep is * used (which is the case for a stock "make check"). */ static const struct MHD_OptMatrixProfile *test_prof; /** * The (possibly adjusted) copy of the profile @a test_prof points to. */ static struct MHD_OptMatrixProfile test_prof_copy; /** * Run a single sub-case against the given port. * * @param port the port of the test daemon * @param sc the sub-case to run * @return non-zero if the sub-case succeeded, zero if it failed */ static int run_subcase (uint16_t port, const struct SubCase *sc) { MHD_socket sk; char buf[1024]; size_t got; int ret = ! 0; sk = connect_to_port (port); if (MHD_INVALID_SOCKET == sk) hardErrorExit ("Cannot connect to the test daemon"); if (! send_all (sk, sc->request, strlen (sc->request))) { fprintf (stderr, "FAILED: cannot send the request of the sub-case '%s'.\n", sc->name); (void) MHD_socket_close_ (sk); return 0; } got = recv_reply (sk, buf, sizeof (buf), MHD_STATICSTR_LEN_ (EXPECTED_STATUS)); if (MHD_STATICSTR_LEN_ (EXPECTED_STATUS) > got) { fprintf (stderr, "FAILED: sub-case '%s': no reply received " "(got %u bytes, expected at least %u bytes). " "The daemon may have crashed.\n", sc->name, (unsigned) got, (unsigned) MHD_STATICSTR_LEN_ (EXPECTED_STATUS)); ret = 0; } else if (0 != memcmp (buf, EXPECTED_STATUS, MHD_STATICSTR_LEN_ (EXPECTED_STATUS))) { fprintf (stderr, "FAILED: sub-case '%s': unexpected reply status. " "Expected '%s', got '%.*s'.\n", sc->name, EXPECTED_STATUS, (int) MHD_STATICSTR_LEN_ (EXPECTED_STATUS), buf); ret = 0; } else if (verbose) printf ("PASSED: %s\n", sc->name); (void) MHD_socket_close_ (sk); return ret; } /** * Run all sub-cases with the given connection memory limit. * * @param mem_limit the value for MHD_OPTION_CONNECTION_MEMORY_LIMIT * @return the number of the failed sub-cases */ static unsigned int run_with_mem_limit (size_t mem_limit) { struct MHD_Daemon *d; const union MHD_DaemonInfo *dinfo; uint16_t port; unsigned int num_failed = 0; size_t i; struct MHD_OptMatrixProfile prof; struct MHD_OptionItem ops[8]; unsigned int flags; /* The profile (if any) supplies the discipline level, the threading mode and the polling backend; the memory limit is the one of the sweep, which the caller has already taken from the profile. */ if (NULL != test_prof) { prof = *test_prof; prof.mem_limit = mem_limit; } else { memset (&prof, 0, sizeof (prof)); prof.name = "built-in"; prof.mem_limit = mem_limit; prof.threading = MHD_OPT_MATRIX_THR_INTERNAL; prof.poll_backend = MHD_OPT_MATRIX_POLL_SELECT; } if (0 == mhd_opt_matrix_fill_options (&prof, ops, (unsigned int) (sizeof (ops) / sizeof (ops[0])))) hardErrorExit ("The daemon option array is too small"); /* The client of this test is a plain blocking socket client, so external polling is served with an internal polling thread instead. */ flags = mhd_opt_matrix_daemon_flags (&prof, MHD_USE_ERROR_LOG, 0); d = MHD_start_daemon (flags, 0, NULL, NULL, &ahc_reply, NULL, MHD_OPTION_ARRAY, ops, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) TEST_SOCKET_TIMEOUT_SEC, MHD_OPTION_END); if (NULL == d) hardErrorExit ("Cannot start the test daemon"); dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); if ((NULL == dinfo) || (0 == dinfo->port)) { MHD_stop_daemon (d); hardErrorExit ("Cannot detect the port used by the test daemon"); } port = (uint16_t) dinfo->port; for (i = 0; i < sizeof (subcases) / sizeof (subcases[0]); ++i) { /* Report the sub-case before running it: if the daemon aborts (which is the expected failure mode of the un-fixed code) the whole test process is terminated and the last reported sub-case is the failing one. */ fprintf (stderr, "Running sub-case with memory limit %u: %s\n", (unsigned) mem_limit, subcases[i].name); fflush (stderr); if (! run_subcase (port, subcases + i)) ++num_failed; } MHD_stop_daemon (d); return num_failed; } int main (int argc, char *const *argv) { unsigned int num_failed = 0; size_t i; verbose = 0; for (i = 1; i < (size_t) argc; ++i) { if ((0 == strcmp (argv[i], "-v")) || (0 == strcmp (argv[i], "--verbose"))) verbose = 1; } if (MHD_YES != MHD_is_feature_supported (MHD_FEATURE_AUTOSUPPRESS_SIGPIPE)) { #if defined(HAVE_SIGNAL_H) && defined(SIGPIPE) if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) hardErrorExit ("Cannot suppress the SIGPIPE signal"); #else /* ! HAVE_SIGNAL_H || ! SIGPIPE */ fprintf (stderr, "Cannot suppress the SIGPIPE signal.\n"); #endif /* ! HAVE_SIGNAL_H || ! SIGPIPE */ } mhd_opt_matrix_print_notice ("test_rq_shift_back"); test_prof = mhd_opt_matrix_from_env (); if (NULL != test_prof) { /* A profile pins one configuration: its memory limit replaces the built-in sweep so that the driver script can walk the matrix. */ char desc[256]; test_prof_copy = *test_prof; test_prof = &test_prof_copy; if (! mhd_opt_matrix_profile_supported (test_prof)) { printf ("test_rq_shift_back: the selected profile %s is not supported " "by this build, the test is skipped.\n", mhd_opt_matrix_describe (test_prof, desc, sizeof (desc))); return 77; } if (mhd_opt_matrix_raise_mem_limit (&test_prof_copy, MIN_POOL_FOR_TEST)) printf ("test_rq_shift_back: the connection memory limit of the " "profile was raised to %u, the smallest pool this test can " "work with.\n", (unsigned) MIN_POOL_FOR_TEST); if (0 == test_prof_copy.mem_limit) printf ("test_rq_shift_back: NOTE: the profile uses the default " "connection memory pool, so the \"shift back\" code path is " "not reached at all by this run.\n"); num_failed = run_with_mem_limit (test_prof_copy.mem_limit); } else { for (i = 0; i < sizeof (mem_limits) / sizeof (mem_limits[0]); ++i) num_failed += run_with_mem_limit (mem_limits[i]); } if (0 != num_failed) { fprintf (stderr, "FAILED: %u sub-case(s) failed.\n", num_failed); return EXIT_FAILED_TEST; } if (verbose) printf ("All sub-cases passed.\n"); return 0; } libmicrohttpd-1.0.10/src/microhttpd/mhd_check.h0000664000175000017500000001771415232103064015150 /* This file is part of libmicrohttpd Copyright (C) 2026 Christian Grothoff This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/mhd_check.h * @brief macros for MHD_CHECK_(), always-compiled memory-safety invariants * @author Christian Grothoff * * mhd_assert() is compiled out in release builds (NDEBUG), which is the right * thing for the several hundred internal state assertions of this library but * the wrong thing for the handful of them that stand between attacker-supplied * data and a memmove()/memcpy()/array index. For those, an assertion that is * absent in the shipped build is not a safety net at all. * * MHD_CHECK_() is the always-compiled companion for exactly that subset. It * does NOT depend on NDEBUG, _DEBUG or --enable-asserts: the test is one * predictable, well-predicted branch that is present in every build. * * RULES FOR USING IT * ------------------ * 1. Only invariants whose violation would mean memory-unsafe behaviour - * pointer/offset arithmetic, buffer bounds, length subtractions that could * underflow, indices into fixed-size arrays. Ordinary state assertions * stay mhd_assert(). * 2. Check the *precondition*, not the symptom. An assertion that compares * two pointers after the bad one has already been derived is decoration: * it happily passes on a NULL-derived pointer. Assert what has to be true * for the following arithmetic to be defined. See commit 29eaa56b. * 3. A failing check must FAIL THE CONNECTION - close it, or reply 4xx/5xx - * and must not continue and must not panic. MHD_PANIC() aborts the whole * daemon, which turns a bounded per-connection problem into a global * denial of service; that is the opposite of what this is for. * 4. Deliberately no mhd_assert() inside: a check must behave identically in * debug and in release builds, otherwise the debug build stops exercising * the recovery path that the release build relies on. * * WHERE THE MACROS COME FROM * -------------------------- * The connection-level macros below expand to the failure exits that * connection.c already uses - connection_close_error() / * CONNECTION_CLOSE_ERROR() and transmit_error_response_static() - rather than * introducing a parallel mechanism. They are therefore usable only from * connection.c and only after those helpers have been defined; this header * intentionally does not include connection.c's internals, the macros are * expanded at the point of use. * * Translation units that have a `struct MHD_Daemon *` at hand (connection.c, * digestauth.c, postprocessor.c, ...) get a log line through the usual * MHD_DLOG()/HAVE_MESSAGES machinery; they must include "internal.h" before * this header. Translation units without a daemon (memorypool.c, mhd_str.c) * use the MHD_CHECK_RET_() form, which is silent. */ #ifndef MHD_CHECK_H #define MHD_CHECK_H 1 #include "mhd_options.h" /** * Branch hint: an invariant violation is by construction the unlikely case. */ #if defined(__GNUC__) || defined(__clang__) # define MHD_CHECK_FAILED_(expr) (__builtin_expect (! (expr), 0)) #else /* ! __GNUC__ */ # define MHD_CHECK_FAILED_(expr) (! (expr)) #endif /* ! __GNUC__ */ /** * Report a violated invariant through the daemon's log. * * @param daemon the daemon to log to * @param expr_str the stringified invariant that was violated */ #ifdef HAVE_MESSAGES # define MHD_CHECK_LOG_(daemon,expr_str) \ MHD_DLOG (daemon, \ _ ("Internal invariant violated at %s:%u: (%s). " \ "Failing the connection.\n"), \ __FILE__, \ (unsigned int) __LINE__, \ expr_str) #else /* ! HAVE_MESSAGES */ # define MHD_CHECK_LOG_(daemon,expr_str) ((void) 0) #endif /* ! HAVE_MESSAGES */ /** * The generic always-compiled invariant check. * * @param daemon the daemon to log to * @param expr the invariant, must evaluate to true * @param fail_stmt a single statement to execute when @a expr is false; it * must transfer control out of the current function * (return, goto or break), because execution must not * continue past a violated memory-safety invariant. * When the failure action needs several statements, spell * the check out instead - "if (MHD_CHECK_FAILED_ (expr)) { * MHD_CHECK_LOG_ (daemon, "expr"); ... }" - because a * braced block passed as a macro argument is re-indented * by contrib/uncrustify.cfg */ #define MHD_CHECK_(daemon,expr,fail_stmt) \ do { \ if (MHD_CHECK_FAILED_ (expr)) \ { \ MHD_CHECK_LOG_ (daemon, #expr); \ fail_stmt; \ } \ } while (0) /** * Always-compiled invariant check for translation units that have no daemon * pointer available for logging (memorypool.c, mhd_str.c). Silent; the * caller is expected to turn the returned failure value into a log message * and a failed connection. * * @param expr the invariant, must evaluate to true * @param retval the value to return when @a expr is false */ #define MHD_CHECK_RET_(expr,retval) \ do { \ if (MHD_CHECK_FAILED_ (expr)) \ return retval; \ } while (0) /** * Always-compiled invariant check that closes the connection with an error * and returns @a retval. For use in connection.c only, and only after * connection_close_error() has been defined. * * @param c the connection to fail * @param expr the invariant, must evaluate to true * @param retval the value to return when @a expr is false */ #define MHD_CHECK_CONN_CLOSE_RET_(c,expr,retval) \ MHD_CHECK_ ((c)->daemon, \ expr, \ { \ connection_close_error ((c), \ NULL); \ return retval; \ }) /** * Always-compiled invariant check that closes the connection with an error * and returns from a void function. For use in connection.c only, and only * after connection_close_error() has been defined. * * @param c the connection to fail * @param expr the invariant, must evaluate to true */ #define MHD_CHECK_CONN_CLOSE_RET_VOID_(c,expr) \ MHD_CHECK_ ((c)->daemon, \ expr, \ { \ connection_close_error ((c), \ NULL); \ return; \ }) /** * Always-compiled invariant check that queues a static error reply for the * connection and returns @a retval. For use in connection.c only, and only * after transmit_error_response_static() has been defined. * * @param c the connection to fail * @param expr the invariant, must evaluate to true * @param code the HTTP status code to reply with * @param msg the static message to reply with * @param retval the value to return when @a expr is false */ #define MHD_CHECK_CONN_REPLY_RET_(c,expr,code,msg,retval) \ MHD_CHECK_ ((c)->daemon, \ expr, \ { \ transmit_error_response_static ((c), \ (code), \ msg); \ return retval; \ }) #endif /* ! MHD_CHECK_H */ libmicrohttpd-1.0.10/src/microhttpd/test_http_reasons.c0000664000175000017500000001206015232103064016773 /* This file is part of libmicrohttpd Copyright (C) 2017-2021 Karlson2k (Evgeny Grin) This test tool is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This test tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file microhttpd/test_http_reasons.c * @brief Unit tests for MHD_get_reason_phrase_for() function * @author Karlson2k (Evgeny Grin) */ #include "mhd_options.h" #include #include #include "microhttpd.h" #include "mhd_str.h" /* Turn any MHD_PANIC() or failing mhd_assert() reached from this test into a marked, classifiable test error (TESTING.md, P5). */ #include "mhd_panic_tripwire.h" static const char *const r_unknown = "unknown"; /* Return zero when no error is detected */ static int expect_result (unsigned int code, const char *expected) { const char *const reason = MHD_get_reason_phrase_for (code); const size_t len = MHD_get_reason_phrase_len_for (code); size_t exp_len; if (! MHD_str_equal_caseless_ (reason, expected)) { fprintf (stderr, "Incorrect reason returned for code %u:\n Returned: \"%s\" \tExpected: \"%s\"\n", code, reason, expected); return 1; } if (r_unknown == expected) exp_len = 0; else exp_len = strlen (expected); if (exp_len != len) { fprintf (stderr, "Incorrect reason length returned for code %u:\n Returned: \"%u\" \tExpected: \"%u\"\n", code, (unsigned) len, (unsigned) exp_len); return 1; } return 0; } static int expect_absent (unsigned int code) { return expect_result (code, r_unknown); } static int test_absent_codes (void) { int errcount = 0; errcount += expect_absent (0); errcount += expect_absent (1); errcount += expect_absent (50); errcount += expect_absent (99); errcount += expect_absent (600); errcount += expect_absent (601); errcount += expect_absent (900); errcount += expect_absent (10000); return errcount; } static int test_1xx (void) { int errcount = 0; errcount += expect_result (MHD_HTTP_CONTINUE, "continue"); errcount += expect_result (MHD_HTTP_PROCESSING, "processing"); errcount += expect_absent (110); errcount += expect_absent (190); return errcount; } static int test_2xx (void) { int errcount = 0; errcount += expect_result (MHD_HTTP_OK, "ok"); errcount += expect_result (MHD_HTTP_ALREADY_REPORTED, "already reported"); errcount += expect_absent (217); errcount += expect_result (MHD_HTTP_IM_USED, "im used"); errcount += expect_absent (230); errcount += expect_absent (295); return errcount; } static int test_3xx (void) { int errcount = 0; errcount += expect_result (MHD_HTTP_MULTIPLE_CHOICES, "multiple choices"); errcount += expect_result (MHD_HTTP_SEE_OTHER, "see other"); errcount += expect_result (MHD_HTTP_PERMANENT_REDIRECT, "permanent redirect"); errcount += expect_absent (311); errcount += expect_absent (399); return errcount; } static int test_4xx (void) { int errcount = 0; errcount += expect_result (MHD_HTTP_BAD_REQUEST, "bad request"); errcount += expect_result (MHD_HTTP_NOT_FOUND, "not found"); errcount += expect_result (MHD_HTTP_URI_TOO_LONG, "uri too long"); errcount += expect_result (MHD_HTTP_EXPECTATION_FAILED, "expectation failed"); errcount += expect_result (MHD_HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, "request header fields too large"); errcount += expect_absent (441); errcount += expect_result (MHD_HTTP_UNAVAILABLE_FOR_LEGAL_REASONS, "unavailable for legal reasons"); errcount += expect_absent (470); errcount += expect_absent (493); return errcount; } static int test_5xx (void) { int errcount = 0; errcount += expect_result (MHD_HTTP_INTERNAL_SERVER_ERROR, "internal server error"); errcount += expect_result (MHD_HTTP_BAD_GATEWAY, "bad gateway"); errcount += expect_result (MHD_HTTP_HTTP_VERSION_NOT_SUPPORTED, "http version not supported"); errcount += expect_result (MHD_HTTP_NETWORK_AUTHENTICATION_REQUIRED, "network authentication required"); errcount += expect_absent (520); errcount += expect_absent (597); return errcount; } int main (int argc, char *argv[]) { int errcount = 0; (void) argc; (void) argv; /* Unused. Silent compiler warning. */ errcount += test_absent_codes (); errcount += test_1xx (); errcount += test_2xx (); errcount += test_3xx (); errcount += test_4xx (); errcount += test_5xx (); return errcount == 0 ? 0 : 1; } libmicrohttpd-1.0.10/src/microhttpd/sha1.h0000664000175000017500000000526615223423441014102 /* This file is part of libmicrohttpd Copyright (C) 2019-2021 Karlson2k (Evgeny Grin) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ /** * @file microhttpd/sha1.h * @brief Calculation of SHA-1 digest * @author Karlson2k (Evgeny Grin) */ #ifndef MHD_SHA1_H #define MHD_SHA1_H 1 #include "mhd_options.h" #include #ifdef HAVE_STDDEF_H #include /* for size_t */ #endif /* HAVE_STDDEF_H */ /** * SHA-1 digest is kept internally as 5 32-bit words. */ #define _SHA1_DIGEST_LENGTH 5 /** * Number of bits in single SHA-1 word */ #define SHA1_WORD_SIZE_BITS 32 /** * Number of bytes in single SHA-1 word */ #define SHA1_BYTES_IN_WORD (SHA1_WORD_SIZE_BITS / 8) /** * Size of SHA-1 digest in bytes */ #define SHA1_DIGEST_SIZE (_SHA1_DIGEST_LENGTH * SHA1_BYTES_IN_WORD) /** * Size of SHA-1 digest string in chars including termination NUL */ #define SHA1_DIGEST_STRING_SIZE ((SHA1_DIGEST_SIZE) * 2 + 1) /** * Size of single processing block in bits */ #define SHA1_BLOCK_SIZE_BITS 512 /** * Size of single processing block in bytes */ #define SHA1_BLOCK_SIZE (SHA1_BLOCK_SIZE_BITS / 8) struct sha1_ctx { uint32_t H[_SHA1_DIGEST_LENGTH]; /**< Intermediate hash value / digest at end of calculation */ uint8_t buffer[SHA1_BLOCK_SIZE]; /**< SHA1 input data buffer */ uint64_t count; /**< number of bytes, mod 2^64 */ }; /** * Initialise structure for SHA-1 calculation. * * @param ctx_ must be a `struct sha1_ctx *` */ void MHD_SHA1_init (void *ctx_); /** * Process portion of bytes. * * @param ctx_ must be a `struct sha1_ctx *` * @param data bytes to add to hash * @param length number of bytes in @a data */ void MHD_SHA1_update (void *ctx_, const uint8_t *data, size_t length); /** * Finalise SHA-1 calculation, return digest. * * @param ctx_ must be a `struct sha1_ctx *` * @param[out] digest set to the hash, must be #SHA1_DIGEST_SIZE bytes */ void MHD_SHA1_finish (void *ctx_, uint8_t digest[SHA1_DIGEST_SIZE]); #endif /* MHD_SHA1_H */ libmicrohttpd-1.0.10/src/Makefile.am0000664000175000017500000000060715232103064012742 # This Makefile.am is in the public domain SUBDIRS = include microhttpd . if RUN_LIBCURL_TESTS SUBDIRS += testcurl if RUN_ZZUF_TESTS SUBDIRS += testzzuf endif endif if ENABLE_FUZZING SUBDIRS += fuzz endif if BUILD_EXAMPLES SUBDIRS += examples endif if BUILD_TOOLS SUBDIRS += tools endif EXTRA_DIST = \ datadir/cert-and-key.pem \ datadir/cert-and-key-for-wireshark.pem .NOTPARALLEL: libmicrohttpd-1.0.10/doc/0000775000175000017500000000000015235437006010752 5libmicrohttpd-1.0.10/doc/libmicrohttpd.30000644000175000017500000000312014674632555013630 .Dd June 21, 2013 .Dt LIBMICROHTTPD 3 .Os .Sh NAME .Nm libmicrohttpd .Nd library for embedding HTTP servers .Sh LIBRARY .ds doc-str-Lb-libmicrohttpd library for embedding HTTP servers (libmicrohttpd) .Lb libmicrohttpd .Sh SYNOPSIS .In microhttpd.h .Sh DESCRIPTION GNU libmicrohttpd (short MHD) allows applications to easily integrate the functionality of a simple HTTP server. MHD is a GNU package. .sp The details of the API are described in comments in the header file, a detailed reference documentation in Texinfo, a tutorial, and in brief on the MHD webpage. .Sh LEGAL NOTICE libmicrohttpd is released under both the LGPL Version 2.1 or higher and the GNU GPL with eCos extension. For details on both licenses please read the respective appendix in the Texinfo manual. .Sh FILES .Bl -tag -width /etc/ttys -compact .It Pa microhttpd.h libmicrohttpd include file .It Pa libmicrohttpd.so libmicrohttpd library .El .Sh SEE ALSO .Xr curl 1 , .Xr libcurl 3 , info libmicrohttpd .Sh AUTHORS GNU .Nm was originally designed by .An -nosplit .An Christian Grothoff Aq Mt christian@grothoff.org and .An Chris GauthierDickey Aq Mt chrisg@cs.du.edu Ns . The original implementation was done by .An Daniel Pittman Aq Mt depittman@gmail.com and Christian Grothoff. SSL/TLS support was added by Sagie Amir using code from GnuTLS. See the AUTHORS file in the distribution for a more detailed list of contributors. .Sh AVAILABILITY You can obtain the latest version from .Lk https://www.gnu.org/software/libmicrohttpd/ Ns . .Sh BUGS Report bugs by using .Lk https://bugs.gnunet.org/set_project.php?project_id=10 "Mantis" Ns . libmicrohttpd-1.0.10/doc/libmicrohttpd-tutorial.info0000664000175000017500000107056115232223263016261 This is libmicrohttpd-tutorial.info, produced by makeinfo version 7.1.1 from libmicrohttpd-tutorial.texi. This tutorial documents GNU libmicrohttpd version 1.0.8, last updated 28 July 2026. Copyright (c) 2008 Sebastian Gerhardt. Copyright (c) 2010, 2011, 2012, 2013, 2016, 2021, 2026 Christian Grothoff. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". INFO-DIR-SECTION Software libraries START-INFO-DIR-ENTRY * libmicrohttpdtutorial: (libmicrohttpd-tutorial). A tutorial for GNU libmicrohttpd. END-INFO-DIR-ENTRY  File: libmicrohttpd-tutorial.info, Node: Top, Next: Introduction, Up: (dir) A Tutorial for GNU libmicrohttpd ******************************** This tutorial documents GNU libmicrohttpd version 1.0.8, last updated 28 July 2026. Copyright (c) 2008 Sebastian Gerhardt. Copyright (c) 2010, 2011, 2012, 2013, 2016, 2021, 2026 Christian Grothoff. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". * Menu: * Introduction:: * Hello browser example:: * Exploring requests:: * Response headers:: * Supporting basic authentication:: * Processing POST data:: * Improved processing of POST data:: * Session management:: * Generating responses on the fly:: * Answering from another thread:: * Adding a layer of security:: * Upgrading connections:: * Bibliography:: * License text:: * Example programs::  File: libmicrohttpd-tutorial.info, Node: Introduction, Next: Hello browser example, Prev: Top, Up: Top 1 Introduction ************** This tutorial is for developers who want to learn how they can add HTTP serving capabilities to their applications with the _GNU libmicrohttpd_ library, abbreviated _MHD_. The reader will learn how to implement basic HTTP functions from simple executable sample programs that implement various features. The text is supposed to be a supplement to the API reference manual of _GNU libmicrohttpd_ and for that reason does not explain many of the parameters. Therefore, the reader should always consult the manual to find the exact meaning of the functions used in the tutorial. Furthermore, the reader is encouraged to study the relevant _RFCs_, which document the HTTP standard. _GNU libmicrohttpd_ is assumed to be already installed. This tutorial is written for version 1.0.8. At the time being, this tutorial has only been tested on _GNU/Linux_ machines even though efforts were made not to rely on anything that would prevent the samples from being built on similar systems. 1.1 History =========== This tutorial was originally written by Sebastian Gerhardt for MHD 0.4.0. It was slightly polished and updated to MHD 0.9.0 by Christian Grothoff.  File: libmicrohttpd-tutorial.info, Node: Hello browser example, Next: Exploring requests, Prev: Introduction, Up: Top 2 Hello browser example *********************** The most basic task for a HTTP server is to deliver a static text message to any client connecting to it. Given that this is also easy to implement, it is an excellent problem to start with. For now, the particular URI the client asks for shall have no effect on the message that will be returned. In addition, the server shall end the connection after the message has been sent so that the client will know there is nothing more to expect. The C program ‘hellobrowser.c’, which is to be found in the examples section, does just that. If you are very eager, you can compile and start it right away but it is advisable to type the lines in by yourself as they will be discussed and explained in detail. After the necessary includes and the definition of the port which our server should listen on #include #include #include #include #include #include #define PORT 8888 the desired behaviour of our server when HTTP request arrive has to be implemented. We already have agreed that it should not care about the particular details of the request, such as who is requesting what. The server will respond merely with the same small HTML page to every request. The function we are going to write now will be called by _GNU libmicrohttpd_ every time an appropriate request comes in. While the name of this callback function is arbitrary, its parameter list has to follow a certain layout. So please, ignore the lot of parameters for now, they will be explained at the point they are needed. We have to use only one of them, ‘struct MHD_Connection *connection’, for the minimalistic functionality we want to achieve at the moment. This parameter is set by the _libmicrohttpd_ daemon and holds the necessary information to relate the call with a certain connection. Keep in mind that a server might have to satisfy hundreds of concurrent connections and we have to make sure that the correct data is sent to the destined client. Therefore, this variable is a means to refer to a particular connection if we ask the daemon to sent the reply. Talking about the reply, it is defined as a string right after the function header static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { const char *page = "Hello, browser!"; HTTP is a rather strict protocol and the client would certainly consider it "inappropriate" if we just sent the answer string "as is". Instead, it has to be wrapped with additional information stored in so-called headers and footers. Most of the work in this area is done by the library for us--we just have to ask. Our reply string packed in the necessary layers will be called a "response". To obtain such a response we hand our data (the reply-string) and its size over to the ‘MHD_create_response_from_buffer_static’ function. By using the ‘_static’ variant we tell _MHD_ that the buffer will stay valid and unchanged for at least as long as the response lives, so that _MHD_ neither has to free the message data for us when it has been sent nor has to make an internal copy of it--which is exactly the case for our _constant_ string. struct MHD_Response *response; enum MHD_Result ret; response = MHD_create_response_from_buffer_static (strlen (page), page); Now that the response has been laced up, it is ready for delivery and can be queued for sending. This is done by passing it to another _GNU libmicrohttpd_ function. As all our work was done in the scope of one function, the recipient is without doubt the one associated with the local variable ‘connection’ and consequently this variable is given to the queue function. Every HTTP response is accompanied by a status code, here "OK", so that the client knows this response is the intended result of his request and not due to some error or malfunction. Finally, the packet is destroyed and the return value from the queue returned, already being set at this point to either MHD_YES or MHD_NO in case of success or failure. ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } With the primary task of our server implemented, we can start the actual server daemon which will listen on ‘PORT’ for connections. This is done in the main function. int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; The first parameter is a bit-wise OR of flags selecting, among other things, the mode of operation. With ‘MHD_USE_INTERNAL_POLLING_THREAD’ we want the daemon to run in a separate thread and to manage all incoming connections in the same thread. This means that while producing the response for one connection, the other connections will be put on hold. In this example, where the reply is already known and therefore the request is served quickly, this poses no problem. The additional ‘MHD_USE_AUTO’ flag simply lets _MHD_ pick the best polling function (‘epoll’, ‘poll’ or ‘select’) available on the platform. We will allow all clients to connect regardless of their name or location, therefore we do not check them on connection and set the third and fourth parameter to NULL. Parameter five is the address of the function we want to be called whenever a new request has been received. Our ‘answer_to_connection’ knows best what the client wants and needs no additional information (which could be passed via the next parameter) so the next (sixth) parameter is NULL. Likewise, we do not need to pass extra options to the daemon so we just write the MHD_OPTION_END as the last parameter. As the server daemon runs in the background in its own thread, the execution flow in our main function will continue right after the call. Because of this, we must delay the execution flow in the main thread or else the program will terminate prematurely. We let it pause in a processing-time friendly manner by waiting for the enter key to be pressed. In the end, we stop the daemon so it can do its cleanup tasks. getchar (); MHD_stop_daemon (daemon); return 0; } The first example is now complete. Compile it with cc hellobrowser.c -o hellobrowser -I$PATH_TO_LIBMHD_INCLUDES -L$PATH_TO_LIBMHD_LIBS -lmicrohttpd with the two paths set accordingly and run it. Now open your favorite Internet browser and go to the address ‘http://localhost:8888/’, provided that 8888 is the port you chose. If everything works as expected, the browser will present the message of the static HTML page it got from our minimal server. Remarks ======= To keep this first example as small as possible, some drastic shortcuts were taken and are to be discussed now. Firstly, there is no distinction made between the kinds of requests a client could send. We implied that the client sends a GET request, that means, that he actually asked for some data. Even when it is not intended to accept POST requests, a good server should at least recognize that this request does not constitute a legal request and answer with an error code. This can be easily implemented by checking if the parameter ‘method’ equals the string "GET" and returning a ‘MHD_NO’ if not so. Secondly, the above practice of queuing a response upon the first call of the callback function brings with it some limitations. This is because the content of the message body will not be received if a response is queued in the first iteration. Furthermore, the connection will be closed right after the response has been transferred then. This is typically not what you want as it disables HTTP pipelining. The correct approach is to simply not queue a message on the first callback unless there is an error. The ‘void**’ argument to the callback provides a location for storing information about the history of the connection; for the first call, the pointer will point to NULL. A simplistic way to differentiate the first call from others is to check if the pointer is NULL and set it to a non-NULL value during the first call. Both of these issues you will find addressed in the official ‘minimal_example.c’ residing in the ‘src/examples’ directory of the _MHD_ package. The source code of this program should look very familiar to you by now and easy to understand. For our example, we create the response from a static (persistent) buffer in memory and thus use ‘MHD_create_response_from_buffer_static’. In the usual case, responses are not transmitted immediately after being queued. For example, there might be other data on the system that needs to be sent with a higher priority. Nevertheless, the queue function will return successfully--raising the problem that the data we have pointed to may be invalid by the time it is about being sent. This is not an issue here because we can expect the ‘page’ string, which is a constant _string literal_ here, to be static. That means it will be present and unchanged for as long as the program runs. For dynamic data, one could choose to either have _MHD_ free the memory ‘page’ points to itself when it is no longer needed (by using ‘MHD_create_response_from_buffer_with_free_callback’ with ‘&free’) or, alternatively, have the library make and manage its own copy of it (by using ‘MHD_create_response_from_buffer_copy’). Naturally, this last option is the most expensive. Exercises ========= • While the server is running, use a program like ‘telnet’ or ‘netcat’ to connect to it. Try to form a valid HTTP 1.1 request yourself like GET /dontcare HTTP/1.1 Host: itsme and see what the server returns to you. • Also, try other requests, like POST, and see how our server does not mind and why. How far in malforming a request can you go before the builtin functionality of _MHD_ intervenes and an altered response is sent? Make sure you read about the status codes in the _RFC_. • Add the option ‘MHD_OPTION_CLIENT_DISCIPLINE_LVL’ with a value of ‘1’ to the start function of the daemon in ‘main’ (this option supersedes the deprecated ‘MHD_USE_PEDANTIC_CHECKS’ flag). Mind the special format of the parameter list here which is described in the manual: the option is followed by its ‘int’ value, and ‘MHD_OPTION_END’ still terminates the list. How indulgent is the server now to your input? • Let the main function take a string as the first command line argument and pass ‘argv[1]’ to the ‘MHD_start_daemon’ function as the sixth parameter. The address of this string will be passed to the callback function via the ‘cls’ variable. Decorate the text given at the command line when the server is started with proper HTML tags and send it as the response instead of the former static string. • _Demanding:_ Write a separate function returning a string containing some useful information, for example, the time. Pass the function's address as the sixth parameter and evaluate this function on every request anew in ‘answer_to_connection’. Remember to free the memory of the string every time after satisfying the request.  File: libmicrohttpd-tutorial.info, Node: Exploring requests, Next: Response headers, Prev: Hello browser example, Up: Top 3 Exploring requests ******************** This chapter will deal with the information which the client sends to the server at every request. We are going to examine the most useful fields of such a request and print them out in a readable manner. This could be useful for logging facilities. The starting point is the _hellobrowser_ program with the former response removed. This time, we just want to collect information in the callback function, thus we will just return MHD_NO after we have probed the request. This way, the connection is closed without much ado by the server. static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { ... return MHD_NO; } The ellipsis marks the position where the following instructions shall be inserted. We begin with the most obvious information available to the server, the request line. You should already have noted that a request consists of a command (or "HTTP method") and a URI (e.g. a filename). It also contains a string for the version of the protocol which can be found in ‘version’. To call it a "new request" is justified because we return only ‘MHD_NO’, thus ensuring the function will not be called again for this connection. printf ("New %s request for %s using version %s\n", method, url, version); The rest of the information is a bit more hidden. Nevertheless, there is a lot of it sent from common Internet browsers. It is stored in "key-value" pairs and we want to list what we find in the header. As there is no mandatory set of keys a client has to send, each key-value pair is printed out one by one until there are no more left. We do this by writing a separate function which will be called for each pair just like the above function is called for each HTTP request. It can then print out the content of this pair. static enum MHD_Result print_out_key (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { printf ("%s: %s\n", key, value); return MHD_YES; } To start the iteration process that calls our new function for every key, the line MHD_get_connection_values (connection, MHD_HEADER_KIND, &print_out_key, NULL); needs to be inserted in the connection callback function too. The second parameter tells the function that we are only interested in keys from the general HTTP header of the request. Our iterating function ‘print_out_key’ does not rely on any additional information to fulfill its duties so the last parameter can be NULL. All in all, this constitutes the complete ‘logging.c’ program for this chapter which can be found in the ‘examples’ section. Connecting with any modern Internet browser should yield a handful of keys. You should try to interpret them with the aid of _RFC 9110_. Especially worth mentioning is the "Host" key which is often used to serve several different websites hosted under one single IP address but reachable by different domain names (this is called virtual hosting). Conclusion ========== The introduced capabilities to itemize the content of a simple GET request--especially the URI--should already allow the server to satisfy clients' requests for small specific resources (e.g. files) or even induce alteration of server state. However, the latter is not recommended as the GET method (including its header data) is by convention considered a "safe" operation, which should not change the server's state in a significant way. By convention, GET operations can thus be performed by crawlers and other automatic software. Naturally actions like searching for a passed string are fine. Of course, no transmission can occur while the return value is still set to ‘MHD_NO’ in the callback function. Exercises ========= • By parsing the ‘url’ string and delivering responses accordingly, implement a small server for "virtual" files. When asked for ‘/index.htm{l}’, let the response consist of a HTML page containing a link to ‘/another.html’ page which is also to be created "on the fly" in case of being requested. If neither of these two pages are requested, ‘MHD_HTTP_NOT_FOUND’ shall be returned accompanied by an informative message. • A very interesting information has still been ignored by our logger--the client's IP address. Implement a callback function static enum MHD_Result on_client_connect (void *cls, const struct sockaddr *addr, socklen_t addrlen) that prints out the IP address in an appropriate format. You might want to use the POSIX function ‘inet_ntoa’ but bear in mind that ‘addr’ is actually just a structure containing other substructures and is _not_ the variable this function expects. Make sure to return ‘MHD_YES’ so that the library knows the client is allowed to connect (and to then process the request). If one wanted to limit access basing on IP addresses, this would be the place to do it. The address of your ‘on_client_connect’ function must be passed as the third parameter to the ‘MHD_start_daemon’ call.  File: libmicrohttpd-tutorial.info, Node: Response headers, Next: Supporting basic authentication, Prev: Exploring requests, Up: Top 4 Response headers ****************** Now that we are able to inspect the incoming request in great detail, this chapter discusses the means to enrich the outgoing responses likewise. As you have learned in the _Hello, Browser_ chapter, some obligatory header fields are added and set automatically for simple responses by the library itself but if more advanced features are desired, additional fields have to be created. One of the possible fields is the content type field and an example will be developed around it. This will lead to an application capable of correctly serving different types of files. When we responded with HTML page packed in the static string previously, the client had no choice but guessing about how to handle the response, because the server had not told him. What if we had sent a picture or a sound file? Would the message have been understood or merely been displayed as an endless stream of random characters in the browser? This is what the mime content types are for. The header of the response is extended by certain information about how the data is to be interpreted. To introduce the concept, a picture of the format _PNG_ will be sent to the client and labeled accordingly with ‘image/png’. Once again, we can base the new example on the ‘hellobrowser’ program. #define FILENAME "picture.png" #define MIMETYPE "image/png" static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; We want the program to open the file for reading and determine its size: int fd; enum MHD_Result ret; struct stat sbuf; if (0 != strcmp (method, "GET")) return MHD_NO; if ( (-1 == (fd = open (FILENAME, O_RDONLY))) || (0 != fstat (fd, &sbuf)) ) { /* error accessing file */ /* ... (see below) */ } /* ... (see below) */ When dealing with files, there is a lot that could go wrong on the server side and if so, the client should be informed with ‘MHD_HTTP_INTERNAL_SERVER_ERROR’. /* error accessing file */ if (fd != -1) close (fd); const char *errorstr = "An internal server error has occurred!\ "; response = MHD_create_response_from_buffer_static (strlen (errorstr), errorstr); if (NULL != response) { ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response); MHD_destroy_response (response); return ret; } else return MHD_NO; Note that we nevertheless have to create a response object even for sending a simple error code. Otherwise, the connection would just be closed without comment, leaving the client curious about what has happened. But in the case of success a response will be constructed directly from the file descriptor: /* error accessing file */ /* ... (see above) */ } response = MHD_create_response_from_fd_at_offset64 ((uint64_t) sbuf.st_size, fd, 0); MHD_add_response_header (response, "Content-Type", MIMETYPE); Note that the response object will take care of closing the file descriptor for us. Up to this point, there was little new. The actual novelty is that we enhance the header with the meta data about the content. Aware of the field's name we want to add, it is as easy as that: MHD_add_response_header(response, "Content-Type", MIMETYPE); We do not have to append a colon expected by the protocol behind the first field--_GNU libmicrohttpd_ will take care of this. The function finishes with the well-known lines ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } The complete program ‘responseheaders.c’ is in the ‘examples’ section as usual. Find a _PNG_ file you like and save it to the directory the example is run from under the name ‘picture.png’. You should find the image displayed on your browser if everything worked well. Remarks ======= The include file of the _MHD_ library comes with the header types mentioned in _RFC 9110_ already defined as macros. Thus, we could have written ‘MHD_HTTP_HEADER_CONTENT_TYPE’ instead of ‘"Content-Type"’ as well. However, one is not limited to these standard headers and could add custom response headers without violating the protocol. Whether, and how, the client would react to these custom header is up to the receiver. Likewise, the client is allowed to send custom request headers to the server as well, opening up yet more possibilities how client and server could communicate with each other. The method of creating the response from a file on disk only works for static content. Serving dynamically created responses will be a topic of a future chapter. Exercises ========= • Remember that the original program was written under a few assumptions--a static response using a local file being one of them. In order to simulate a very large or hard to reach file that cannot be provided instantly, postpone the queuing in the callback with the ‘sleep’ function for 30 seconds _if_ the file ‘/big.png’ is requested (but deliver the same as above). A request for ‘/picture.png’ should provide just the same but without any artificial delays. Now start two instances of your browser (or even use two machines) and see how the second client is put on hold while the first waits for his request on the slow file to be fulfilled. Finally, change the sourcecode to add ‘MHD_USE_THREAD_PER_CONNECTION’ to the daemon's flags (this flag must be combined with ‘MHD_USE_INTERNAL_POLLING_THREAD’) and try again. • Did you succeed in implementing the clock exercise yet? This time, let the server save the program's start time ‘t’ and implement a response simulating a countdown that reaches 0 at ‘t+60’. Returning a message saying on which point the countdown is, the response should ultimately be to reply "Done" if the program has been running long enough, An unofficial, but widely understood, response header line is ‘Refresh: DELAY; url=URL’ with the uppercase words substituted to tell the client it should request the given resource after the given delay again. Improve your program in that the browser (any modern browser should work) automatically reconnects and asks for the status again every 5 seconds or so. The URL would have to be composed so that it begins with "http://", followed by the _URI_ the server is reachable from the client's point of view. Maybe you want also to visualize the countdown as a status bar by creating a ‘’ consisting of one row and ‘n’ columns whose fields contain small images of either a red or a green light.  File: libmicrohttpd-tutorial.info, Node: Supporting basic authentication, Next: Processing POST data, Prev: Response headers, Up: Top 5 Supporting basic authentication ********************************* With the small exception of IP address based access control, requests from all connecting clients where served equally until now. This chapter discusses a first method of client's authentication and its limits. A very simple approach feasible with the means already discussed would be to expect the password in the _URI_ string before granting access to the secured areas. The password could be separated from the actual resource identifier by a certain character, thus the request line might look like GET /picture.png?mypassword In the rare situation where the client is customized enough and the connection occurs through secured lines (e.g., a embedded device directly attached to another via wire) and where the ability to embed a password in the URI or to pass on a URI with a password are desired, this can be a reasonable choice. But when it is assumed that the user connecting does so with an ordinary Internet browser, this implementation brings some problems about. For example, the URI including the password stays in the address field or at least in the history of the browser for anybody near enough to see. It will also be inconvenient to add the password manually to any new URI when the browser does not know how to compose this automatically. At least the convenience issue can be addressed by employing the simplest built-in password facilities of HTTP compliant browsers, hence we want to start there. It will, however, turn out to have still severe weaknesses in terms of security which need consideration. Before we will start implementing _Basic Authentication_ as described in _RFC 7617_, we will also abandon the simplistic and generally problematic practice of responding every request the first time our callback is called for a given connection. Queuing a response upon the first request is akin to generating an error response (even if it is a "200 OK" reply!). The reason is that MHD usually calls the callback in three phases: 1. First, to initially tell the application about the connection and inquire whether it is OK to proceed. This call typically happens before the client could upload the request body, and can be used to tell the client to not proceed with the upload (if the client requested "Expect: 100 Continue"). Applications may queue a reply at this point, but it will force the connection to be closed and thus prevent keep-alive / pipelining, which is generally a bad idea. Applications wanting to proceed with the request throughout the other phases should just return "MHD_YES" and not queue any response. Note that when an application suspends a connection in this callback, the phase does not advance and the application will be called again in this first phase. 2. Next, to tell the application about upload data provided by the client. In this phase, the application may not queue replies, and trying to do so will result in MHD returning an error code from ‘MHD_queue_response’. If there is no upload data, this phase is skipped. 3. Finally, to obtain a regular response from the application. This can be almost any type of response, including ones indicating failures. The one exception is a "100 Continue" response, which applications must never generate: MHD generates that response automatically when necessary in the first phase. If the application does not queue a response, MHD may call the callback repeatedly (depending a bit on the threading model, the application should suspend the connection). But how can we tell whether the callback has been called before for the particular request? This is what the ‘req_cls’ parameter of the callback is for: initially, the pointer it references is set to NULL by _MHD_. But whatever we store there will be "remembered" on the next call (for the same request). Thus, we can use the ‘req_cls’ location to keep track of the request state. For now, we will simply generate no response until the parameter is non-null--implying the callback was called before at least once. We do not need to share information between different calls of the callback, so we can set the parameter to any address that is assured to be not null. The pointer to the ‘connection’ structure will be pointing to a legal address, so we take this. The first time ‘answer_to_connection’ is called, we will not even look at the headers. static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if (0 != strcmp(method, "GET")) return MHD_NO; if (NULL == *req_cls) {*req_cls = connection; return MHD_YES;} ... /* else respond accordingly */ ... } Note how we lop off the connection on the first condition (no "GET" request), but return asking for more on the other one with ‘MHD_YES’. With this minor change, we can proceed to implement the actual authentication process. Request for authentication ========================== Let us assume we had only files not intended to be handed out without the correct username/password, so every "GET" request will be challenged. _RFC 7617_ describes how the server shall ask for authentication by adding a _WWW-Authenticate_ response header with the name of the _realm_ protected. MHD can generate and queue such a failure response for you using the ‘MHD_queue_basic_auth_required_response3’ API. The only thing you need to do is construct a response with the error page to be shown to the user if he aborts basic authentication. But first, you should check if the proper credentials were already supplied using the ‘MHD_basic_auth_get_username_password3’ call. (The older ‘MHD_queue_basic_auth_fail_response’ and ‘MHD_basic_auth_get_username_password’ calls are deprecated.) Your code would then look like this: static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_BasicAuthInfo *auth_info; enum MHD_Result ret; struct MHD_Response *response; if (0 != strcmp (method, "GET")) return MHD_NO; if (NULL == *req_cls) { *req_cls = connection; return MHD_YES; } auth_info = MHD_basic_auth_get_username_password3 (connection); if (NULL == auth_info) { static const char *page = "Authorization required"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_required_response3 (connection, "admins", MHD_YES, response); } else if ((strlen ("root") != auth_info->username_len) || (0 != memcmp (auth_info->username, "root", auth_info->username_len)) || /* The next check against NULL is optional, * if 'password' is NULL then 'password_len' is always zero. */ (NULL == auth_info->password) || (strlen ("pa$$w0rd") != auth_info->password_len) || (0 != memcmp (auth_info->password, "pa$$w0rd", auth_info->password_len))) { static const char *page = "Wrong username or password"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_required_response3 (connection, "admins", MHD_YES, response); } else { static const char *page = "A secret."; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); } if (NULL != auth_info) MHD_free (auth_info); MHD_destroy_response (response); return ret; } See the ‘examples’ directory for the complete example file. Remarks ======= For a proper server, the conditional statements leading to a return of ‘MHD_NO’ should yield a response with a more precise status code instead of silently closing the connection. For example, failures of memory allocation are best reported as _internal server error_ and unexpected authentication methods as _400 bad request_. Exercises ========= • Make the server respond to wrong credentials (but otherwise well-formed requests) with the recommended _401 unauthorized_ status code. If the client still does not authenticate correctly within the same connection, close it and store the client's IP address for a certain time. (It is OK to check for expiration not until the main thread wakes up again on the next connection.) If the client fails authenticating three times during this period, add it to another list for which the ‘AcceptPolicyCallback’ function denies connection (temporally). • With the network utility ‘netcat’ connect and log the response of a "GET" request as you did in the exercise of the first example, this time to a file. Now stop the server and let _netcat_ listen on the same port the server used to listen on and have it fake being the proper server by giving the file's content as the response (e.g. ‘cat log | nc -l -p 8888’). Pretending to think your were connecting to the actual server, browse to the eavesdropper and give the correct credentials. Copy and paste the encoded string you see in ‘netcat’'s output to some of the Base64 decode tools available online and see how both the user's name and password could be completely restored.  File: libmicrohttpd-tutorial.info, Node: Processing POST data, Next: Improved processing of POST data, Prev: Supporting basic authentication, Up: Top 6 Processing POST data ********************** The previous chapters already have demonstrated a variety of possibilities to send information to the HTTP server, but it is not recommended that the _GET_ method is used to alter the way the server operates. To induce changes on the server, the _POST_ method is preferred over and is much more powerful than _GET_ and will be introduced in this chapter. We are going to write an application that asks for the visitor's name and, after the user has posted it, composes an individual response text. Even though it was not mandatory to use the _POST_ method here, as there is no permanent change caused by the POST, it is an illustrative example on how to share data between different functions for the same connection. Furthermore, the reader should be able to extend it easily. GET request =========== When the first _GET_ request arrives, the server shall respond with a HTML page containing an edit field for the name. const char* askpage = "\ What's your name, Sir?
    \ \ \ \ "; The ‘action’ entry is the _URI_ to be called by the browser when posting, and the ‘name’ will be used later to be sure it is the editbox's content that has been posted. We also prepare the answer page, where the name is to be filled in later, and an error page as the response for anything but proper _GET_ and _POST_ requests: const char* greetingpage="

    Welcome, %s!

    "; const char* errorpage="This doesn't seem to be right."; Whenever we need to send a page, we use an extra function ‘int send_page(struct MHD_Connection *connection, const char* page)’ for this, which does not contain anything new and whose implementation is therefore not discussed further in the tutorial. POST request ============ Posted data can be of arbitrary and considerable size; for example, if a user uploads a big image to the server. Similar to the case of the header fields, there may also be different streams of posted data, such as one containing the text of an editbox and another the state of a button. Likewise, we will have to register an iterator function that is going to be called maybe several times not only if there are different POSTs but also if one POST has only been received partly yet and needs processing before another chunk can be received. Such an iterator function is called by a _postprocessor_, which must be created upon arriving of the post request. We want the iterator function to read the first post data which is tagged ‘name’ and to create an individual greeting string based on the template and the name. But in order to pass this string to other functions and still be able to differentiate different connections, we must first define a structure to share the information, holding the most import entries. struct connection_info_struct { int connectiontype; char *answerstring; struct MHD_PostProcessor *postprocessor; }; With these information available to the iterator function, it is able to fulfill its task. Once it has composed the greeting string, it returns ‘MHD_YES’ so that the post processor keeps parsing the remainder of the upload. Returning ‘MHD_NO’ would instead abort the parsing and make the next call to ‘MHD_post_process’ fail. Note that this function does not handle processing of data for the same ‘key’. If we were to expect that the name will be posted in several chunks, we had to expand the namestring dynamically as additional parts of it with the same ‘key’ came in. But in this example, the name is assumed to fit entirely inside one single packet. static enum MHD_Result iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; if (0 == strcmp (key, "name")) { if ((size > 0) && (size <= MAXNAMESIZE)) { char *answerstring; answerstring = malloc (MAXANSWERSIZE); if (!answerstring) return MHD_NO; snprintf (answerstring, MAXANSWERSIZE, greetingpage, data); con_info->answerstring = answerstring; } else con_info->answerstring = NULL; } return MHD_YES; } Once a connection has been established, it can be terminated for many reasons. As these reasons include unexpected events, we have to register another function that cleans up any resources that might have been allocated for that connection by us, namely the post processor and the greetings string. This cleanup function must take into account that it will also be called for finished requests other than _POST_ requests. static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; if (NULL == con_info) return; if (con_info->connectiontype == POST) { MHD_destroy_post_processor (con_info->postprocessor); if (con_info->answerstring) free (con_info->answerstring); } free (con_info); *req_cls = NULL; } _GNU libmicrohttpd_ is informed that it shall call the above function when the daemon is started in the main function. ... daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL, MHD_OPTION_END); ... Request handling ================ With all other functions prepared, we can now discuss the actual request handling. On the first iteration for a new request, we start by allocating a new instance of a ‘struct connection_info_struct’ structure, which will store all necessary information for later iterations and other functions. static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if(NULL == *req_cls) { struct connection_info_struct *con_info; con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->answerstring = NULL; If the new request is a _POST_, the postprocessor must be created now. In addition, the type of the request is stored for convenience. if (0 == strcmp (method, "POST")) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, iterate_post, (void*) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } con_info->connectiontype = POST; } else con_info->connectiontype = GET; The address of our structure will both serve as the indicator for successive iterations and to remember the particular details about the connection. *req_cls = (void*) con_info; return MHD_YES; } The rest of the function will not be executed on the first iteration. A _GET_ request is easily satisfied by sending the question form. if (0 == strcmp (method, "GET")) { return send_page (connection, askpage); } In case of _POST_, we invoke the post processor for as long as data keeps incoming, setting ‘*upload_data_size’ to zero in order to indicate that we have processed--or at least have considered--all of it. if (0 == strcmp (method, "POST")) { struct connection_info_struct *con_info = *req_cls; if (*upload_data_size != 0) { if (MHD_YES != MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size)) return MHD_NO; *upload_data_size = 0; return MHD_YES; } else if (NULL != con_info->answerstring) return send_page (connection, con_info->answerstring); } Finally, if they are neither _GET_ nor _POST_ requests, the error page is returned. return send_page(connection, errorpage); } These were the important parts of the program ‘simplepost.c’.  File: libmicrohttpd-tutorial.info, Node: Improved processing of POST data, Next: Session management, Prev: Processing POST data, Up: Top 7 Improved processing of POST data ********************************** The previous chapter introduced a way to upload data to the server, but the developed example program has some shortcomings, such as not being able to handle larger chunks of data. In this chapter, we are going to discuss a more advanced server program that allows clients to upload a file in order to have it stored on the server's filesystem. The server shall also watch and limit the number of clients concurrently uploading, responding with a proper busy message if necessary. Prepared answers ================ We choose to operate the server with the ‘MHD_USE_INTERNAL_POLLING_THREAD’ method. This makes it easier to synchronize the global states at the cost of possible delays for other connections if the processing of a request is too slow. One of these variables that needs to be shared for all connections is the total number of clients that are uploading. #define MAXCLIENTS 2 static unsigned int nr_of_uploading_clients = 0; If there are too many clients uploading, we want the server to respond to all requests with a busy message. const char* busypage = "This server is busy, please try again later."; Otherwise, the server will send a _form_ that informs the user of the current number of uploading clients, and ask her to pick a file on her local filesystem which is to be uploaded. const char* askpage = "\n\ Upload a file, please!
    \n\ There are %u clients uploading at the moment.
    \n\ \n\ \n\ \n\ "; If the upload has succeeded, the server will respond with a message saying so. const char* completepage = "The upload has been completed."; We want the server to report malformed requests and internal errors, such as file access problems, adequately. const char* servererrorpage = "Invalid request."; const char* fileexistspage = "This file already exists."; const char* fileioerror = "IO error writing to disk."; const char* postprocerror = "Error processing POST data."; It would be tolerable to send all these responses undifferentiated with a ‘200 HTTP_OK’ status code but in order to improve the ‘HTTP’ conformance of our server a bit, we extend the ‘send_page’ function so that it accepts individual status codes. static enum MHD_Result send_page (struct MHD_Connection *connection, const char* page, unsigned int status_code) { enum MHD_Result ret; struct MHD_Response *response; response = MHD_create_response_from_buffer_copy (strlen (page), page); if (!response) return MHD_NO; ret = MHD_queue_response (connection, status_code, response); MHD_destroy_response (response); return ret; } Note how we ask _MHD_ to make its own copy of the message data--that is what the ‘_copy’ suffix stands for. The reason behind this will become clear later. Connection cycle ================ The decision whether the server is busy or not is made right at the beginning of the connection. To do that at this stage is especially important for _POST_ requests because if no response is queued at this point, and ‘MHD_YES’ returned, _MHD_ will not send any queued messages until a postprocessor has been created and the post iterator is called at least once. static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if (NULL == *req_cls) { struct connection_info_struct *con_info; if (nr_of_uploading_clients >= MAXCLIENTS) return send_page(connection, busypage, MHD_HTTP_SERVICE_UNAVAILABLE); If the server is not busy, the ‘connection_info’ structure is initialized as usual, with the addition of a filepointer for each connection. The status code is set to zero, which we use as the marker for "no answer decided yet". con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->answercode = 0; con_info->fp = NULL; if (0 == strcmp (method, "POST")) { ... } else con_info->connectiontype = GET; *req_cls = (void*) con_info; return MHD_YES; } For _POST_ requests, the postprocessor is created and we register a new uploading client. From this point on, there are many possible places for errors to occur that make it necessary to interrupt the uploading process. We need a means of having the proper response message ready at all times. Therefore, the ‘connection_info’ structure is extended to hold the most current response message so that whenever a response is sent, the client will get the most informative message. if (0 == strcmp (method, "POST")) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, iterate_post, (void*) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } nr_of_uploading_clients++; con_info->connectiontype = POST; } else con_info->connectiontype = GET; If the connection handler is called for the second time, _GET_ requests will be answered with the _form_. We can keep the buffer under function scope, because we asked _MHD_ to make its own copy of it for as long as it is needed. if (0 == strcmp (method, "GET")) { char buffer[1024]; snprintf (buffer, sizeof (buffer), askpage, nr_of_uploading_clients); return send_page (connection, buffer, MHD_HTTP_OK); } The rest of the ‘answer_to_connection’ function is very similar to the ‘simplepost.c’ example, except the more flexible content of the responses. The _POST_ data is processed until there is none left and the execution falls through to return an error page if the connection constituted no expected request method. Note that once we know the answer--because something went wrong--we no longer feed the data to the post processor, but we still have to consume it, or the client would never get to read our response. if (0 == strcmp (method, "POST")) { struct connection_info_struct *con_info = *req_cls; if (0 != *upload_data_size) { if (0 == con_info->answercode) { if (MHD_YES != MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size)) { con_info->answerstring = postprocerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; } } *upload_data_size = 0; return MHD_YES; } if (NULL != con_info->fp) { fclose (con_info->fp); con_info->fp = NULL; } if (0 == con_info->answercode) { con_info->answerstring = completepage; con_info->answercode = MHD_HTTP_OK; } return send_page (connection, con_info->answerstring, con_info->answercode); } return send_page(connection, errorpage, MHD_HTTP_BAD_REQUEST); } Storing the data ================ Unlike the ‘simplepost.c’ example, here it is to be expected that post iterator will be called several times now. This means that for any given connection (there might be several concurrent of them) the posted data has to be written to the correct file. That is why we store a file handle in every ‘connection_info’, so that it is preserved between successive iterations. static enum MHD_Result iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; FILE *fp; Because the following actions depend heavily on correct file processing, which might be error prone, we record the page to answer with as soon as anything goes wrong. Note that the iterator always returns ‘MHD_YES’: returning ‘MHD_NO’ would abort the post processor and thus make it impossible to send our carefully chosen error page to the client. In the "askpage" _form_, we told the client to label its post data with the "file" key. Anything else would be an error. if (0 != strcmp (key, "file")) { con_info->answerstring = servererrorpage; con_info->answercode = MHD_HTTP_BAD_REQUEST; return MHD_YES; } If the iterator is called for the first time, no file will have been opened yet. The ‘filename’ string contains the name of the file (without any paths) the user selected on his system. We want to take this as the name the file will be stored on the server and make sure no file of that name exists (or is being uploaded) before we create one (note that the code below technically contains a race between the two "fopen" calls, but we will overlook this for portability sake). if (!con_info->fp) { if (0 != con_info->answercode) /* something went wrong before */ return MHD_YES; if (NULL != (fp = fopen (filename, "rb")) ) { fclose (fp); con_info->answerstring = fileexistspage; con_info->answercode = MHD_HTTP_FORBIDDEN; return MHD_YES; } con_info->fp = fopen (filename, "ab"); if (!con_info->fp) { con_info->answerstring = fileioerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; return MHD_YES; } } Occasionally, the iterator function will be called even when there are 0 new bytes to process. The server only needs to write data to the file if there is some. if (size > 0) { if (!fwrite (data, sizeof (char), size, con_info->fp)) { con_info->answerstring = fileioerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; } } If this point has been reached without setting an answer code, everything worked well for this iteration. If the upload has finished, this iterator function will not be called again and ‘answer_to_connection’ will declare success. return MHD_YES; } The new client was registered when the postprocessor was created. Likewise, we unregister the client on destroying the postprocessor when the request is completed. static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; if (NULL == con_info) return; if (con_info->connectiontype == POST) { if (NULL != con_info->postprocessor) { MHD_destroy_post_processor (con_info->postprocessor); nr_of_uploading_clients--; } if (con_info->fp) fclose (con_info->fp); } free (con_info); *req_cls = NULL; } This is essentially the whole example ‘largepost.c’. Remarks ======= Now that the clients are able to create files on the server, security aspects are becoming even more important than before. Aside from proper client authentication, the server should always make sure explicitly that no files will be created outside of a dedicated upload directory. In particular, filenames must be checked to not contain strings like "../".  File: libmicrohttpd-tutorial.info, Node: Session management, Next: Generating responses on the fly, Prev: Improved processing of POST data, Up: Top 8 Session management ******************** This chapter discusses how one should manage sessions, that is, share state between multiple HTTP requests from the same user. We use a simple example where the user submits multiple forms and the server is supposed to accumulate state from all of these forms. Naturally, as this is a network protocol, our session mechanism must support having many users with many concurrent sessions at the same time. In order to track users, we use a simple session cookie. A session cookie expires when the user closes the browser. Changing from session cookies to persistent cookies only requires adding an expiration time to the cookie. The server creates a fresh session cookie whenever a request without a cookie is received, or if the supplied session cookie is not known to the server. Looking up the cookie ===================== Since MHD parses the HTTP cookie header for us, looking up an existing cookie is straightforward: const char *value; value = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, "KEY"); Here, "KEY" is the name we chose for our session cookie. Setting the cookie header ========================= MHD requires the user to provide the full cookie format string in order to set cookies. In order to generate a unique cookie, our example creates a random 32-character text string to be used as the value of the cookie: char value[128]; char raw_value[33]; for (unsigned int i=0;ioff == ctx->fill) { /* Everything we had was passed on, produce the next block. */ if (BLOCK_COUNT == ctx->block) return MHD_CONTENT_READER_END_OF_STREAM; generate_block (ctx); } ready = ctx->fill - ctx->off; if (ready > max) ready = max; memcpy (buf, &ctx->buf[ctx->off], ready); ctx->off += ready; return (ssize_t) ready; } ‘generate_block()’ is the place where a real application would run its expensive computation, query, or network fetch. The important property is that the same buffer is reused every time, so the memory the server needs does not grow with the size of the document. The handler assembles all of this and, from that moment on, hands ownership of the context to the response object: ctx = malloc (sizeof (struct ResponseContext)); if (NULL == ctx) return MHD_NO; ctx->buf = malloc (BUFFER_SIZE); if (NULL == ctx->buf) { free (ctx); return MHD_NO; } ctx->fill = 0; ctx->off = 0; ctx->block = 0; response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, IO_BLOCK_SIZE, &content_reader, ctx, &free_context); if (NULL == response) { /* No response object exists, so nobody will call the free callback for us. */ free_context (ctx); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); Note the error path: as long as ‘MHD_create_response_from_callback()’ has not returned a response, the free callback will never run and the application must clean up itself. Releasing the state =================== The free callback is trivial: static void free_context (void *cls) { struct ResponseContext *ctx = cls; free (ctx->buf); free (ctx); } _MHD_ invokes it when the last reference to the response object goes away. The call to ‘MHD_destroy_response()’ in the handler does not trigger it, because queuing the response took a reference; the callback runs when the connection is finished with the response. That happens after a completed body, but equally after a client that closed the socket in the middle of the download, after a timeout, and when the daemon is stopped. This is precisely what makes the free callback the right place for the cleanup: there is no other hook that covers all of these cases. Unknown size and chunked encoding ================================= Passing ‘MHD_SIZE_UNKNOWN’ as the size leaves _MHD_ with the problem of telling the client where the body ends. For an HTTP/1.1 client it solves it by switching to chunked transfer encoding: it adds a ‘Transfer-Encoding: chunked’ header and frames every piece the callback returns as one chunk, terminating the body with a zero-length chunk when the callback reports the end of the stream. Nothing has to be done for this; it is a consequence of the unknown size. < HTTP/1.1 200 OK < Content-Type: text/plain < Transfer-Encoding: chunked An HTTP/1.0 client cannot be sent chunks. In that case _MHD_ falls back to the only other framing the protocol offers and marks the connection as one that must be closed: the body is sent raw, without ‘Content-Length’, and its end is the end of the connection. The data arrives intact, but the client has no way to distinguish a complete answer from one that was cut short. If the size _is_ known--and in the example program the URL ‘/sized’ shows this variant--it should be announced, simply by passing the number instead of ‘MHD_SIZE_UNKNOWN’. _MHD_ then emits a normal ‘Content-Length’ header, no chunk framing is added, and the callback is queried with ‘max’ limited by both ‘block_size’ and the number of bytes still outstanding. The callback must produce exactly the announced number of bytes. Aborting a response =================== Generating data can fail halfway through--the database connection drops, a file disappears, an allocation fails. Since the response headers, and probably a good part of the body, have already been sent, there is no way to turn the answer into an error page any more. Returning ‘MHD_CONTENT_READER_END_WITH_ERROR’ is the way to give up: _MHD_ logs the condition and closes the connection immediately, without writing the terminating chunk. What the client sees depends on the framing. With chunked encoding it is an abnormally terminated chunk stream, and a well-behaved client reports it as such--‘curl’ for instance fails with "transfer closed with outstanding read data remaining" and a non-zero exit status. With an announced ‘Content-Length’ the client notices that the body is shorter than promised. Only in the HTTP/1.0 case discussed above, where the end of the body is the end of the connection, is the failure indistinguishable from a normal ending; that is a property of the protocol and not something _MHD_ can repair. The URL ‘/error’ of the example program aborts the stream after a few blocks so that this can be observed. When the data is not ready yet ============================== So far the generator could always produce the next block on the spot. If it cannot--because the data is coming from another thread, another process, or the network--then, as explained above, returning ‘0’ in an internal polling mode turns the daemon into a busy loop. The supported answer is to take the connection out of the event loop until the data has arrived, with the pair void MHD_suspend_connection (struct MHD_Connection *connection); void MHD_resume_connection (struct MHD_Connection *connection); The daemon has to be started with the ‘MHD_ALLOW_SUSPEND_RESUME’ flag; both functions call ‘MHD_PANIC()’ and abort the process otherwise. The flag implies ‘MHD_USE_ITC’, so that a resumed connection wakes the polling thread up instead of waiting for the next timeout. Suspending is not available for daemons running with ‘MHD_USE_THREAD_PER_CONNECTION’, and the daemon must not be stopped while connections are still suspended. ‘MHD_suspend_connection()’ may only be called from the access handler or from the content reader callback, which means the connection handle has to be stored in the context struct so that the callback can reach it. The pattern is then: if (! ctx->data_available) { MHD_suspend_connection (ctx->connection); return 0; } ‘MHD_resume_connection()’, in contrast, may be called from any thread and at any time. In particular it is explicitly allowed to call it before the suspension has taken effect: the producer may already be done by the time the callback gets around to suspending. _MHD_ handles this by remembering the resume request and, when the suspension is finally processed, cancelling it instead of parking the connection, so the wakeup can never be lost. This is what makes the "check, suspend, return 0" sequence above safe without a lock of its own. The difference is dramatic in practice. A callback that stalls for three hundred milliseconds and returns ‘0’ is entered several million times and burns a full core; the same callback suspending the connection is entered exactly once more and the daemon uses no measurable CPU time at all. Suspending brings requirements of its own--on who may call what from which thread, on how a worker thread wakes up a blocked event loop, and on who releases the shared state when a client disappears halfway through. *note Answering from another thread:: works all of that out on a complete program. Trailers ======== Chunked responses may carry trailers, that is header fields that are transmitted after the body. They are added with MHD_add_response_footer (response, "X-Checksum", "deadbeef"); _MHD_ writes them out after the terminating zero-length chunk: 0 X-Checksum: deadbeef Footers may still be added while the body is being generated--even from inside the content reader callback, immediately before returning ‘MHD_CONTENT_READER_END_OF_STREAM’--which is what makes them useful in the first place: a checksum or a row count over data that has only just been produced cannot be put into the headers, because those are long gone. This is safe as long as the response object belongs to a single request, as it does in the pattern used here. _MHD_ does not generate a ‘Trailer’ response header by itself; if the client should be told in advance which fields to expect, add it with ‘MHD_add_response_header()’. Be aware that many clients discard trailers silently. Example code ============ The complete program is available as ‘callbackresponse.c’. It serves a document of sixty-four blocks that are produced one at a time into a single heap buffer. ‘GET /’ streams it with ‘MHD_SIZE_UNKNOWN’ and thus with chunked encoding, ‘GET /sized’ streams the same bytes with a ‘Content-Length’ announced up front, and ‘GET /error’ aborts in the middle. Remarks ======= Calls into the content reader of one response object are serialized by _MHD_, so a per-request context needs no locking of its own as long as no other thread touches it. As soon as a producer thread is involved--the suspend/resume case--the shared fields do need protection. The chunk boundaries are not under the application's control and carry no meaning: a client may receive the bytes of one callback invocation spread over several chunks or, in other configurations, several invocations combined. Chunked encoding is a transport detail, and any record structure the application needs must be part of the body itself. Finally, returning very small amounts of data per invocation is correct but wasteful, since every invocation may become its own chunk with its own framing overhead. If the producer has more data ready, it should fill as much of ‘buf’ as ‘max’ permits. Exercises ========= • Add a URL that reports how far the transfer has progressed by writing the value of ‘pos’ into every line, and confirm with a slow client (‘curl --limit-rate’) that it really is the number of bytes already sent, and not a block counter. • Register a request completion callback with ‘MHD_OPTION_NOTIFY_COMPLETED’ and print the termination code. Then download the document, interrupt the client in the middle, and watch in which order the completion callback and the content reader's free callback are invoked, and that the free callback runs in both cases. • Turn the generator into an asynchronous one. Start a thread that appends a line to a shared buffer once per second, keep the connection handle in the context struct, and suspend the connection whenever the buffer is empty. Do not forget ‘MHD_ALLOW_SUSPEND_RESUME’ when starting the daemon. Then remove the call to ‘MHD_suspend_connection()’, leaving only the ‘return 0’, and compare the CPU usage of the server process. A complete solution, together with the ownership rules that a shared buffer between a worker and the event loop needs, is the subject of *note Answering from another thread::. • Compute a checksum over the generated document while it is being sent and append it as a trailer. Watch it on the wire--most command line clients will not show it to you, so a raw ‘nc’ or a small script speaking HTTP by hand is the easier tool here.  File: libmicrohttpd-tutorial.info, Node: Answering from another thread, Next: Adding a layer of security, Prev: Generating responses on the fly, Up: Top 10 Answering from another thread ******************************** The previous chapter left one question open. A content reader that has no data ready may return ‘0’, but doing so turns the daemon into a busy loop, and the honest answer--suspend the connection--was only sketched there. This chapter builds the thing itself: a server whose slow work happens in threads of its own, whose connections are parked while that work is under way, and which is driven by an external ‘select()’ loop so that the application stays in charge of its own event handling. The combination is a common one. Most requests are cheap and can be answered on the spot; a few of them start a report, a backup or a query that runs for seconds. Handling the slow ones inline would block every other client for as long as they take. Giving every connection its own thread--‘MHD_USE_THREAD_PER_CONNECTION’--is no answer either, both because it scales badly and because suspending is not available in that mode at all. What is wanted is a single event loop that never blocks, plus a worker per slow job. Who may call what ================= Almost every difficulty in this design comes from one rule, so it is worth stating before any code: ‘MHD_queue_response()’ Must be called from the thread that runs the daemon, from inside the access handler. A worker thread must never queue a response. ‘MHD_suspend_connection()’ May only be called from the access handler or from a content reader callback--that is, from _MHD_'s own thread, while _MHD_ is calling into the application. ‘MHD_resume_connection()’ May be called from any thread at any time, and this is the exception that makes the whole design work. It is the only _MHD_ function a worker thread ever needs. So the split is: the worker computes and, when it has something, resumes. Everything that touches the connection or the response happens on the daemon's thread, where _MHD_ calls the application back. The worker and the daemon share exactly one object, a per-request context, and the only thing the worker does with the connection handle it holds is pass it to ‘MHD_resume_connection()’. The daemon has to be started with ‘MHD_ALLOW_SUSPEND_RESUME’; both suspend and resume call ‘MHD_PANIC()’ and abort the process otherwise. Note also that suspending does not work with a thread pool: ‘MHD_resume_connection()’ asserts that the daemon has none. The event loop ============== Leaving out ‘MHD_USE_INTERNAL_POLLING_THREAD’ puts _MHD_ into external polling mode: it starts no thread of its own and does nothing until the application asks it to. The loop is the usual one, and the example adds its own descriptor to the very same sets--there is nothing special about _MHD_'s: FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); max = 0; if (MHD_YES != MHD_get_fdset (daemon, &rs, &ws, &es, &max)) break; /* fatal internal error */ FD_SET (wake_pipe[0], &rs); /* our own wakeup pipe */ if (max < wake_pipe[0]) max = wake_pipe[0]; if (MHD_YES == MHD_get_timeout64 (daemon, &mhd_timeout)) { ...fill tv...; tvp = &tv; } else tvp = NULL; /* nothing to wait for */ select ((int) max + 1, &rs, &ws, &es, tvp); MHD_run_from_select (daemon, &rs, &ws, &es); The interesting branch is the one that sets ‘tvp’ to ‘NULL’. ‘MHD_get_timeout64()’ returns ‘MHD_NO’ when _MHD_ has nothing whatsoever to wait for, and with every connection suspended that is precisely the situation: suspended connections do not time out, so there is no deadline to wake up for. The loop then blocks in ‘select()’ indefinitely. Whether the server works at all depends on something waking it up. Waking the loop up ================== That something is _MHD_'s inter-thread communication channel. ‘MHD_ALLOW_SUSPEND_RESUME’ is defined as ‘8192 | MHD_USE_ITC’, so requesting suspend support requests the ITC as well; ‘MHD_get_fdset()’ puts the reading end of that channel into the read set, ahead of everything else; and ‘MHD_resume_connection()’ writes a byte to it. A worker thread that resumes a connection therefore breaks the main thread out of ‘select()’, even though the two share nothing but the daemon handle. This deserves emphasis because the header file is misleading about it: the comment on ‘MHD_USE_ITC’ says the flag is ignored with external polling. That is true for the flag in isolation, but not for the channel: ‘MHD_ALLOW_SUSPEND_RESUME’ creates it regardless of the polling mode, and in external mode it is the application's own ‘select()’ that watches it. Without that, a resumed connection would sit untouched until some unrelated event happened to wake the loop. There is no race to guard against here. If the worker resumes in the window between ‘MHD_get_fdset()’ and ‘select()’, the byte is already in the channel when ‘select()’ is entered, and ‘select()’ returns immediately--the channel is level triggered, so a wakeup cannot be missed. The same property makes it safe for a worker to resume a connection that has not finished suspending yet: _MHD_ remembers the request and cancels the pending suspension instead of parking the connection. Neither side needs to know what the other is doing. Answering in one piece ====================== The simplest of the two patterns is for an answer that is only useful as a whole--a generated report, the result of a query. Nothing can be sent before it is finished, so the connection is suspended in the access handler and the response is queued when _MHD_ comes back: static enum MHD_Result handle_slow (struct MHD_Connection *connection, void **req_cls) { struct Job *job = *req_cls; if (NULL == job) { /* First call for this request: start the work and ask MHD to come back to us. */ job = job_create (connection, 0); if (NULL == job) return MHD_NO; if (MHD_NO == job_start (job)) { job_unref (job); job_unref (job); return MHD_NO; } *req_cls = job; return MHD_YES; } pthread_mutex_lock (&job->lock); if (0 == job->finished) { job->suspended = 1; MHD_suspend_connection (connection); pthread_mutex_unlock (&job->lock); return MHD_YES; } ...copy the result out from under the lock... pthread_mutex_unlock (&job->lock); ...MHD_create_response_from_buffer_copy() and MHD_queue_response()... } The control flow is worth following, because it is not obvious that it terminates. _MHD_ calls the access handler for a request more than once; the first call is the one where ‘*req_cls’ is still ‘NULL’, and returning ‘MHD_YES’ without queueing anything tells _MHD_ to carry on. On the second call the worker is running but not finished, so the connection is suspended and the handler returns again. When the worker resumes the connection, _MHD_ calls the handler a third time--on its own thread, with the same ‘*req_cls’--and this time ‘finished’ is set and the response is queued. That third call is the answer to the question this pattern exists for. The worker never queues anything; it merely makes the daemon call the application back at a moment when the answer is ready. Answering as it is produced =========================== The second pattern is the more useful one when the answer is long, and it is what makes a browser show results as they appear rather than after a long blank pause. Here the response is queued _immediately_, with a content reader and an unknown size, so the headers go out at once and the body follows as the worker fills it in: job = job_create (connection, 1); response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, IO_BLOCK_SIZE, &stream_reader, job, &stream_done); ... MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/event-stream"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); Because the size is unknown, _MHD_ uses chunked transfer encoding, and every piece the content reader hands back is framed as its own chunk and goes out on the wire straight away. The content reader is where suspending happens: static ssize_t stream_reader (void *cls, uint64_t pos, char *buf, size_t max) { struct Job *job = cls; size_t ready; pthread_mutex_lock (&job->lock); if (job->off == job->fill) { job->off = 0; job->fill = 0; if (0 != job->finished) { pthread_mutex_unlock (&job->lock); return MHD_CONTENT_READER_END_OF_STREAM; } /* Nothing to send yet. Take the connection out of the event loop; the worker will put it back in. */ job->suspended = 1; MHD_suspend_connection (job->connection); pthread_mutex_unlock (&job->lock); return 0; } ready = job->fill - job->off; if (ready > max) ready = max; memcpy (buf, &job->payload[job->off], ready); job->off += ready; pthread_mutex_unlock (&job->lock); return (ssize_t) ready; } The return value is still ‘0’, exactly as in the busy-waiting version the previous chapter warned about. The difference is the line above it. Suspending removes the connection from the event loop, so _MHD_ has no reason to come back until the worker says so, and the process goes to sleep. The example ships with a test that measures this: streaming a document that takes one second to produce costs the server no measurable CPU time at all while the connection is suspended, and very nearly a full second--one core, saturated--when the ‘MHD_suspend_connection()’ call is removed and only the ‘return 0’ is left. The bytes that arrive are identical in both cases, which is what makes this such an easy mistake to keep. The shared state ================ Everything the two threads share sits in one structure per request: struct Job { pthread_mutex_t lock; pthread_cond_t cond; struct MHD_Connection *connection; char payload[MAX_PAYLOAD]; size_t fill; size_t off; unsigned int rc; int finished; int suspended; int abandoned; ... }; There is no registry of pending requests involved in answering them, and no lookup: the pointer travels in ‘*req_cls’ for the first pattern and in the content reader's ‘crc_cls’ for the second, and both the daemon and the worker are handed it directly. A shared list of all jobs is still useful, but only for shutting down in an orderly fashion, and it is protected by a lock of its own that is always taken before any job's lock, never after. The structure is reference counted, with one reference held by _MHD_ and one by the worker. The _MHD_ side lets go in the free callback of the response for a streamed answer, and in the ‘MHD_OPTION_NOTIFY_COMPLETED’ callback for the other pattern; the worker lets go when it returns. Dropping the last reference does not free the job, though, because the worker still has to be joined and only the main thread may do that. The main loop therefore ends with a sweep that joins and frees whatever has no references left. When the client goes away ========================= This is the part that is easy to get wrong, because it does not happen during development and does happen constantly in production. A client that closes the connection halfway through a download leaves a worker running with a pointer to a connection _MHD_ is about to free. The two callbacks that tell the application a request is over--the response's free callback and ‘MHD_OPTION_NOTIFY_COMPLETED’--are therefore where the worker is cut loose: static void job_detach (struct Job *job) { pthread_mutex_lock (&job->lock); job->abandoned = 1; job->connection = NULL; pthread_cond_signal (&job->cond); pthread_mutex_unlock (&job->lock); job_unref (job); } and the worker checks that flag before every resume: static void job_resume_locked (struct Job *job) { if ( (0 == job->suspended) || (0 != job->abandoned) ) return; job->suspended = 0; MHD_resume_connection (job->connection); } Note that this function is called with the job's lock _held_, and calls into _MHD_ without releasing it. That is deliberate and it is what makes the pattern safe. _MHD_ destroys the connection only after the completion callback has returned, and that callback cannot run while the worker holds the lock; so for as long as the worker is inside ‘MHD_resume_connection()’, the connection it passes is guaranteed to still exist. Dropping the lock first and resuming afterwards would open exactly the window this is meant to close. The reverse order never occurs: _MHD_ invokes the free and completion callbacks without holding the internal locks that ‘MHD_resume_connection()’ acquires, so there is no way for the two to deadlock. The condition variable in the same function is a convenience rather than a necessity. Signalling it wakes a worker that is asleep between steps, so that the work stops within microseconds of the client disappearing instead of running to completion for nobody. Shutting down ============= Stopping a daemon that still has suspended connections is an API violation, and a suspended connection is one that only a worker can release. The order is therefore fixed: 1. Stop handing out new jobs. 2. Tell every worker to give up, and _join_ them. After this point no connection can be suspended any more: the workers resume before they exit, and the content reader only ever suspends while a worker is running. 3. Keep running the event loop until the connections have drained, so that the last bytes actually reach the clients. 4. ‘MHD_stop_daemon()’. Skipping the join in step two is the tempting shortcut, and it is the one that leaves a connection parked forever with nothing left alive to wake it. Example code ============ The complete program is available as ‘asyncresponse.c’. It runs one external ‘select()’ loop and serves four URLs: ‘/’ A small page whose JavaScript opens the stream below and appends a row for every event as it arrives. The rows visibly trickle in, one per step, which is the most direct demonstration of what the chapter is about. ‘/events’ The stream: a response is queued at once, and the content reader suspends between steps. The body is a sequence of server-sent events, which needs no library on the browser side. ‘/slow’ The other pattern: the connection is suspended in the access handler and a complete answer is queued once the worker is done. ‘/fast’ Answered on the spot. The page has a button that requests it and reports the round trip time; it stays in the low milliseconds while jobs are running, which is the point of suspending rather than blocking. The program takes the port, the duration of a step in milliseconds and the number of steps on the command line. Passing ‘0’ as the port makes the operating system choose a free one, which the program then reports via ‘MHD_DAEMON_INFO_BIND_PORT’: $ ./asyncresponse 0 250 20 Listening on port 44321 The accompanying ‘test_asyncresponse.c’ starts exactly that binary and checks over HTTP that ‘/slow’ waits for its worker, that the body of ‘/events’ really arrives in pieces spread over the lifetime of the request rather than in one burst at the end, that ‘/fast’ is still served promptly while jobs are parked, that a client which hangs up in the middle takes neither the server nor the worker with it, and that the process exits cleanly when it is signalled while a connection is suspended. It also compares the server's CPU time against the wall clock time of a transfer, which is the only one of those checks that notices the difference between a suspended connection and a busy-waiting one. Remarks ======= _MHD_ does not detect that a client has disconnected while a connection is suspended, and the connection timeout does not run either. A suspended connection stays suspended until somebody resumes it, without exception. Any timeout on the work itself is therefore the application's responsibility. Suspended connections still count against the connection limits, both the global one and the per-IP one. A server that parks connections for minutes needs its limits sized for the number of jobs it expects to have in flight, not for the number it expects to be transmitting. If the client vanishes in the middle of a chunked response, the next write fails and _MHD_ logs it--with ‘MHD_USE_ERROR_LOG’ enabled the example prints ‘Failed to send the chunked response body ... The socket is no longer available for sending’. That is the normal course of events for an aborted download and not a sign of a problem. Finally, none of this is specific to ‘select()’. The same argument holds for ‘poll()’ and for ‘epoll’, where the daemon's descriptor can be obtained with ‘MHD_DAEMON_INFO_EPOLL_FD’ and added to an epoll set of the application's own; ‘suspend_resume_epoll.c’ among the distribution's examples shows that variant. Exercises ========= • Give the jobs a deadline. Since a suspended connection never times out on its own, add a check to the main loop that resumes--and answers with ‘503’--any job that has been running for too long, and confirm with a step duration long enough to trigger it. • Remove the ‘MHD_suspend_connection()’ call from the content reader, leaving only the ‘return 0’, and watch the server process with ‘top’ while a single client downloads the stream. Then put it back and watch again. Both servers send the same bytes. • Take the resume out of the worker's final block, so that a finished job leaves its connection parked, and then stop the server while a job is in flight. Watch what the shutdown does--and what ‘valgrind’ has to say about it--and work out which of the four steps above was violated. • Replace the per-request thread with a fixed pool of worker threads and a queue of pending jobs. The reference counting and the ‘abandoned’ flag should not need to change at all; if they do, the ownership rules were not as clean as they looked. • Serve the stream to two browser windows at once and confirm from the timestamps that the two jobs run concurrently and are interleaved by a single-threaded event loop.  File: libmicrohttpd-tutorial.info, Node: Adding a layer of security, Next: Upgrading connections, Prev: Answering from another thread, Up: Top 11 Adding a layer of security ***************************** We left the basic authentication chapter with the unsatisfactory conclusion that any traffic, including the credentials, could be intercepted by anyone between the browser client and the server. Protecting the data while it is sent over unsecured lines will be the goal of this chapter. The _MHD_ library includes support for encrypting the traffic by employing TLS (the protocol formerly known as SSL). If _GNU libmicrohttpd_ has been configured to support this, encryption and decryption can be applied transparently on the data being sent, with only minimal changes to the actual source code of the example. Preparation =========== First, a private key for the server will be generated. With this key, the server will later be able to authenticate itself to the client--preventing anyone else from stealing the password by faking its identity. The _OpenSSL_ suite, which is available on many operating systems, can generate such a key. 1024 bit keys are no longer considered secure, so we use a 2048 bit key: > openssl genrsa -out server.key 2048 In addition to the key, a certificate describing the server in human readable tokens is also needed. This certificate will be attested with our aforementioned key. In this way, we obtain a self-signed certificate, valid for one year. To avoid unnecessary error messages in the browser, the certificate needs to carry a _subjectAltName_ that matches the _URI_, for example, "localhost" or the domain (current browsers ignore the common name and look at the _subjectAltName_ only). > openssl req -days 365 -out server.pem -new -x509 -key server.key \ -addext "subjectAltName=DNS:localhost" If you plan to have a publicly reachable server, you will need to ask a trusted third party, called _Certificate Authority_, or _CA_, to attest the certificate for you. This way, any visitor can make sure the server's identity is real. Whether the server's certificate is signed by us or a third party, once it has been accepted by the client, both sides will be communicating over encrypted channels. From this point on, it is the client's turn to authenticate itself. But this has already been implemented in the basic authentication scheme. Changing the source code ======================== We merely have to extend the server program so that it loads the two files into memory, int main (void) { struct MHD_Daemon *daemon; char *key_pem; char *cert_pem; key_pem = load_file (SERVERKEYFILE); cert_pem = load_file (SERVERCERTFILE); if ((key_pem == NULL) || (cert_pem == NULL)) { printf ("The key/certificate files could not be read.\n"); return 1; } and then we point the _MHD_ daemon to it upon initialization. daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END); if (NULL == daemon) { printf ("%s\n", cert_pem); free (key_pem); free (cert_pem); return 1; } The rest consists of little new besides some additional memory cleanups. getchar (); MHD_stop_daemon (daemon); free (key_pem); free (cert_pem); return 0; } The rather unexciting file loader can be found in the complete example ‘tlsauthentication.c’. Remarks ======= • While the standard _HTTP_ port is 80, it is 443 for _HTTPS_. The common internet browsers assume standard _HTTP_ if they are asked to access other ports than these. Therefore, you will have to type ‘https://localhost:8888’ explicitly when you test the example, or the browser will not know how to handle the answer properly. • The remaining weak point is the question how the server will be trusted initially. Either a _CA_ signs the certificate or the client obtains the key over secure means. Anyway, the clients have to be aware (or configured) that they should not accept certificates of unknown origin. • The introduced method of certificates makes it mandatory to set an expiration date--making it less feasible to hardcode certificates in embedded devices. • The cryptographic facilities consume memory space and computing time. For this reason, websites usually consists both of uncritically _HTTP_ parts and secured _HTTPS_. Client authentication ===================== You can also use MHD to authenticate the client via SSL/TLS certificates (as an alternative to using the password-based Basic or Digest authentication). To do this, you will need to link your application against _gnutls_. Next, when you start the MHD daemon, you must specify the root CA that you're willing to trust: daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_HTTPS_MEM_TRUST, root_ca_pem, MHD_OPTION_END); With this, you can then obtain client certificates for each session. In order to obtain the identity of the client, you first need to obtain the raw GnuTLS session handle from _MHD_ using ‘MHD_get_connection_info’. #include #include gnutls_session_t tls_session; const union MHD_ConnectionInfo *ci; ci = MHD_get_connection_info (connection, MHD_CONNECTION_INFO_GNUTLS_SESSION); tls_session = (gnutls_session_t) ci->tls_session; You can then extract the client certificate: /** * Get the client's certificate * * @param tls_session the TLS session * @return NULL if no valid client certificate could be found, a pointer * to the certificate if found */ static gnutls_x509_crt_t get_client_certificate (gnutls_session_t tls_session) { unsigned int listsize; const gnutls_datum_t * pcert; gnutls_certificate_status_t client_cert_status; gnutls_x509_crt_t client_cert; if (tls_session == NULL) return NULL; if (gnutls_certificate_verify_peers2(tls_session, &client_cert_status)) return NULL; if (0 != client_cert_status) { fprintf (stderr, "Failed client certificate invalid: %d\n", client_cert_status); return NULL; } pcert = gnutls_certificate_get_peers(tls_session, &listsize); if ( (pcert == NULL) || (listsize == 0)) { fprintf (stderr, "Failed to retrieve client certificate chain\n"); return NULL; } if (gnutls_x509_crt_init(&client_cert)) { fprintf (stderr, "Failed to initialize client certificate\n"); return NULL; } /* Note that by passing values between 0 and listsize here, you can get access to the CA's certs */ if (gnutls_x509_crt_import(client_cert, &pcert[0], GNUTLS_X509_FMT_DER)) { fprintf (stderr, "Failed to import client certificate\n"); gnutls_x509_crt_deinit(client_cert); return NULL; } return client_cert; } Using the client certificate, you can then get the client's distinguished name and alternative names: /** * Get the distinguished name from the client's certificate * * @param client_cert the client certificate * @return NULL if no dn or certificate could be found, a pointer * to the dn if found */ char * cert_auth_get_dn(gnutls_x509_crt_t client_cert) { char* buf; size_t lbuf; lbuf = 0; gnutls_x509_crt_get_dn(client_cert, NULL, &lbuf); buf = malloc(lbuf); if (buf == NULL) { fprintf (stderr, "Failed to allocate memory for certificate dn\n"); return NULL; } gnutls_x509_crt_get_dn(client_cert, buf, &lbuf); return buf; } /** * Get the alternative name of specified type from the client's certificate * * @param client_cert the client certificate * @param nametype The requested name type * @param index The position of the alternative name if multiple names are * matching the requested type, 0 for the first matching name * @return NULL if no matching alternative name could be found, a pointer * to the alternative name if found */ char * MHD_cert_auth_get_alt_name(gnutls_x509_crt_t client_cert, int nametype, unsigned int index) { char* buf; size_t lbuf; unsigned int seq; unsigned int subseq; unsigned int type; int result; subseq = 0; for (seq=0;;seq++) { lbuf = 0; result = gnutls_x509_crt_get_subject_alt_name2(client_cert, seq, NULL, &lbuf, &type, NULL); if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) return NULL; if (nametype != (int) type) continue; if (subseq == index) break; subseq++; } buf = malloc(lbuf); if (buf == NULL) { fprintf (stderr, "Failed to allocate memory for certificate alt name\n"); return NULL; } result = gnutls_x509_crt_get_subject_alt_name2(client_cert, seq, buf, &lbuf, NULL, NULL); if (result != nametype) { fprintf (stderr, "Unexpected return value from gnutls: %d\n", result); free (buf); return NULL; } return buf; } Finally, you should release the memory associated with the client certificate: gnutls_x509_crt_deinit (client_cert); Using TLS Server Name Indication (SNI) ====================================== SNI enables hosting multiple domains under one IP address with TLS. So SNI is the TLS-equivalent of virtual hosting. To use SNI with MHD, you need at least GnuTLS 3.0. The main change compared to the simple hosting of one domain is that you need to provide a callback instead of the key and certificate. For example, when you start the MHD daemon, you could do this: daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback, MHD_OPTION_END); Here, ‘sni_callback’ is the name of a function that you will have to implement to retrieve the X.509 certificate for an incoming connection. The callback has type ‘gnutls_certificate_retrieve_function2’ and is documented in the GnuTLS API for the ‘gnutls_certificate_set_retrieve_function2’ as follows: -- Function Pointer: int *gnutls_certificate_retrieve_function2 (gnutls_session_t, const gnutls_datum_t* req_ca_dn, int nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert, unsigned int *pcert_length, gnutls_privkey_t * pkey) REQ_CA_DN is only used in X.509 certificates. Contains a list with the CA names that the server considers trusted. Normally we should send a certificate that is signed by one of these CAs. These names are DER encoded. To get a more meaningful value use the function ‘gnutls_x509_rdn_get()’. PK_ALGOS contains a list with server's acceptable signature algorithms. The certificate returned should support the server's given algorithms. PCERT should contain a single certificate and public or a list of them. PCERT_LENGTH is the size of the previous list. PKEY is the private key. A possible implementation of this callback would look like this: struct Hosts { struct Hosts *next; const char *hostname; gnutls_pcert_st pcrt; gnutls_privkey_t key; }; static struct Hosts *hosts; int sni_callback (gnutls_session_t session, const gnutls_datum_t* req_ca_dn, int nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert, unsigned int *pcert_length, gnutls_privkey_t * pkey) { char name[256]; size_t name_len; struct Hosts *host; unsigned int type; name_len = sizeof (name); if (GNUTLS_E_SUCCESS != gnutls_server_name_get (session, name, &name_len, &type, 0 /* index */)) return -1; for (host = hosts; NULL != host; host = host->next) if (0 == strncmp (name, host->hostname, name_len)) break; if (NULL == host) { fprintf (stderr, "Need certificate for %.*s\n", (int) name_len, name); return -1; } fprintf (stderr, "Returning certificate for %.*s\n", (int) name_len, name); *pkey = host->key; *pcert_length = 1; *pcert = &host->pcrt; return 0; } Note that MHD cannot offer passing a closure or any other additional information to this callback, as the GnuTLS API unfortunately does not permit this at this point. The ‘hosts’ list can be initialized by loading the private keys and X.509 certificates from disk as follows: static void load_keys(const char *hostname, const char *CERT_FILE, const char *KEY_FILE) { int ret; gnutls_datum_t data; struct Hosts *host; host = malloc (sizeof (struct Hosts)); host->hostname = hostname; host->next = hosts; hosts = host; ret = gnutls_load_file (CERT_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading certificate file %s.\n", CERT_FILE); exit(1); } ret = gnutls_pcert_import_x509_raw (&host->pcrt, &data, GNUTLS_X509_FMT_PEM, 0); if (ret < 0) { fprintf(stderr, "*** Error loading certificate file: %s\n", gnutls_strerror (ret)); exit(1); } gnutls_free (data.data); ret = gnutls_load_file (KEY_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading key file %s.\n", KEY_FILE); exit(1); } gnutls_privkey_init (&host->key); ret = gnutls_privkey_import_x509_raw (host->key, &data, GNUTLS_X509_FMT_PEM, NULL, 0); if (ret < 0) { fprintf (stderr, "*** Error loading key file: %s\n", gnutls_strerror (ret)); exit(1); } gnutls_free (data.data); } The code above was largely lifted from GnuTLS. You can find other methods for initializing certificates and keys in the GnuTLS manual and source code.  File: libmicrohttpd-tutorial.info, Node: Upgrading connections, Next: Bibliography, Prev: Adding a layer of security, Up: Top 12 Upgrading connections ************************ HTTP is a request/response protocol: the client asks, the server answers, and the connection is either closed or reused for the next request. Some applications need something else entirely -- a bidirectional byte stream that neither side has to poll for. Rather than opening a second connection on another port, _RFC 9110_ lets a client ask the server to switch the already established connection over to a different protocol. The client sends an ordinary request carrying an ‘Upgrade:’ header field, and if the server agrees it answers with the status code ‘101 Switching Protocols’. Once that response has gone out, HTTP is over: the two sides simply talk whatever protocol they agreed on over the same TCP connection. Since version 0.9.52 _libmicrohttpd_ supports this protocol switch. The API is deliberately protocol-agnostic -- _MHD_ performs the HTTP part of the handshake and then hands you the socket. What you send over that socket afterwards is entirely your business; _MHD_ neither parses nor generates a single byte of it any more. The best known user of this mechanism is the Websocket protocol (_RFC 6455_), which uses the upgrade API as a means to an end and then needs a good deal of machinery of its own for framing, masking and the closing handshake. This chapter takes the opposite approach: it shows the upgrade API on its own, with a protocol so simple that no helper library is needed. Our server switches to a line-based echo protocol: every line the client sends is sent straight back, until the client sends the line ‘QUIT’. Enabling upgrades ================= Upgrading is not allowed by default, because handing raw sockets to application code has consequences the library cannot control. You opt in with the ‘MHD_ALLOW_UPGRADE’ flag: daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_ALLOW_UPGRADE | MHD_USE_ERROR_LOG, PORT, NULL, NULL, &access_handler, NULL, MHD_OPTION_END); The choice of threading mode matters more here than anywhere else in this tutorial, because it decides whether your code is allowed to block. With ‘MHD_USE_THREAD_PER_CONNECTION’ every connection already has a thread of its own, and that thread is the one that will run your upgrade callback. Blocking in it stalls exactly one client, so you may write the straightforward loop of ‘recv()’ and ‘send()’ calls that everybody has in their head. This is what makes the example in this chapter short enough to read in one go. Without it -- that is, with a single internal polling thread, a thread pool, epoll, or an external event loop -- your callback runs _inside_ _MHD_'s event loop. Blocking there freezes every other connection the same loop is serving. In that case the callback must return immediately, and you have to register the socket in your own event loop (or hand it to a thread you started yourself) and drive the conversation from there. Deciding whether to upgrade =========================== A client that wants to switch protocols says so twice: it names the protocol in the ‘Upgrade:’ header field, and it lists the token ‘Upgrade’ in the ‘Connection:’ header field. Both fields are comma-separated lists, so a browser may well send ‘Connection: keep-alive, Upgrade’. Comparing the whole field value against the string ‘"Upgrade"’ would reject such a request; the example therefore contains a small helper ‘has_token()’ that walks the list. Note also that a protocol switch is a HTTP/1.1 feature; ‘MHD_queue_response()’ will refuse an upgrade response on a HTTP/1.0 connection. if ( (0 != strcmp (method, MHD_HTTP_METHOD_GET)) || (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) || (! has_token (MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION), "Upgrade")) || (! has_token (MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE), PROTOCOL)) ) return answer_plain (connection, MHD_HTTP_UPGRADE_REQUIRED, PAGE_UPGRADE_REQUIRED, 1); Refusing is not an error condition: the client asked a question and gets an ordinary HTTP answer. Which answer depends on who is at fault. If the request is malformed -- for instance an ‘Upgrade:’ field without the matching ‘Connection:’ token -- ‘MHD_HTTP_BAD_REQUEST’ is appropriate. If the request is perfectly well-formed but simply does not speak the protocol this resource requires, ‘MHD_HTTP_UPGRADE_REQUIRED’ (426) is the better answer, and it should carry an ‘Upgrade:’ header field naming the protocol the server would have accepted. Our example folds both cases into a 426 for brevity. Either way you queue a perfectly normal response and the connection stays a HTTP connection. Creating the upgrade response ============================= If we do want to switch, we create a special response object with ‘MHD_create_response_for_upgrade()’. It takes the callback that will receive the socket and a closure pointer for it, and returns ‘NULL’ on error. The response has no body -- it is a header and nothing else. response = MHD_create_response_for_upgrade (&upgrade_handler, NULL); if (NULL == response) return MHD_NO; MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, PROTOCOL); ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, response); MHD_destroy_response (response); return ret; Two details are easy to get wrong here. The first is the ‘Connection: Upgrade’ response header field, and the surprise is that you must _not_ add it. ‘MHD_create_response_for_upgrade()’ puts it into the response itself, and ‘MHD_queue_response()’ then verifies that it is still there and still contains the ‘upgrade’ token before it accepts the response. _MHD_ does merge repeated ‘Connection:’ header fields into a single field rather than emitting two of them, but it only de-duplicates the ‘close’ token, so adding ‘Upgrade’ a second time puts ‘Connection: Upgrade, Upgrade’ on the wire. Clients tolerate that, but there is no reason to send it. What _MHD_ does _not_ invent for you is the ‘Upgrade:’ field naming the new protocol -- that one is yours to add, since only you know what you are switching to. Do not forget it: ‘MHD_queue_response()’ does not check for it, so in a normal build the client simply receives a 101 that fails to say what it switched to, while a library built with assertions enabled aborts when it performs the switch. The second is the status code. ‘MHD_queue_response()’ rejects an upgrade response with any status other than ‘MHD_HTTP_SWITCHING_PROTOCOLS’, and conversely it rejects status 101 combined with a response that is not an upgrade response. On any of these mistakes it returns ‘MHD_NO’ and, with ‘MHD_USE_ERROR_LOG’ enabled, explains itself on ‘stderr’; this is by far the quickest way to debug a handshake that does not happen. The response object itself follows the usual rules. ‘MHD_queue_response()’ takes its own reference, so calling ‘MHD_destroy_response()’ immediately afterwards is correct and is what all the other examples in this tutorial do. The object is only really freed once the last connection using it is done with it, which for an upgrade means after the callback has returned. As with any other response you may build one upgrade response and queue it for many connections; the callback is then simply invoked once per connection. The upgrade callback ==================== After the 101 response has been written to the socket, _MHD_ calls the ‘MHD_UpgradeHandler’ you registered: static void upgrade_handler (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) ‘cls’ The closure that was passed to ‘MHD_create_response_for_upgrade()’. Since the same response object may serve many connections, this is per-_response_ state, not per-connection state. ‘connection’ The original HTTP connection. It is handed over so that you can have a last look at the request -- ‘MHD_lookup_connection_value()’ still works here, which is how a real protocol picks up, say, a subprotocol name or an authentication token. Do not queue anything on it any more. ‘req_cls’ Whatever your access handler left in ‘*req_cls’. This is the natural place to put per-connection state that the access handler already computed. ‘extra_in / extra_in_size’ Bytes of your new protocol that the client sent immediately behind the request header, and that _MHD_ therefore already read off the socket while parsing the request. They are _gone_ from the socket: if you go straight to ‘recv()’ you silently lose them. Process this buffer first, exactly as if you had read it yourself. The buffer belongs to _MHD_ and is only valid for the duration of the call, so copy anything you want to keep. A client that waits for the 101 before it starts talking will produce ‘extra_in_size == 0’, which is why this argument is so easy to overlook and so annoying when it finally bites. ‘sock’ The socket. For a plain HTTP connection this is the connection to the client; for HTTPS it is one end of a socketpair with _MHD_ relaying the TLS traffic, so socket options and ‘getpeername()’ will not give you what you expect. Read and write it as you please, and you may call ‘shutdown()’ on it, but you must never call ‘close()’. ‘urh’ The handle for ‘MHD_upgrade_action()’, described below. The loop itself is then unremarkable, apart from consuming ‘extra_in’ before the first ‘recv()’: make_blocking (sock); es.line_len = 0; done = echo_feed (sock, &es, extra_in, extra_in_size); while (0 == done) { got = recv (sock, buf, sizeof (buf), 0); if (0 > got) { if (EINTR == errno) continue; break; /* read error */ } if (0 == got) break; /* client closed the connection */ done = echo_feed (sock, &es, buf, (size_t) got); } MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); Blocking or not blocking ======================== The call to ‘make_blocking()’ deserves a warning, because the current behaviour is the opposite of what the threading modes suggest. _MHD_ puts every accepted client socket into non-blocking mode, and it does so regardless of the threading mode -- in fact the library refuses to perform the switch at all, logging ‘Cannot execute "upgrade" as the socket is in the blocking mode’, if it finds the socket blocking. So even under ‘MHD_USE_THREAD_PER_CONNECTION’, where you are perfectly entitled to block, the socket you are handed is non-blocking and a ‘recv()’ on an idle connection returns ‘-1’ with ‘EAGAIN’ instead of waiting. If you want the simple blocking loop shown above, you therefore have to ask for it. The example does so with a small ‘make_blocking()’ helper -- ‘fcntl()’ clearing ‘O_NONBLOCK’ on POSIX systems, ‘ioctlsocket()’ on W32 -- which is the only operating-system-dependent code in the whole program. Under any other threading mode you leave the socket alone, keep it non-blocking, and add it to your own event loop instead. Closing the connection ====================== The last obligation of the callback is to hand the socket back: MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); This is not a formality. An upgraded connection is put into an internal "suspended" state, and it stays there -- socket open, connection structure allocated, slot counted against the connection limit -- until the application says it is done. Only ‘MHD_UPGRADE_ACTION_CLOSE’ says that. Calling ‘close()’ on the socket yourself does not, and additionally leaves _MHD_ holding a file descriptor number that the operating system may already have handed to somebody else. Call the action exactly once, on every path out of the callback, including the error paths. ‘MHD_upgrade_action()’ takes two further actions in the current release, ‘MHD_UPGRADE_ACTION_CORK_ON’ and ‘MHD_UPGRADE_ACTION_CORK_OFF’. They switch ‘TCP_CORK’ (or ‘TCP_NOPUSH’) on the underlying socket so that several small writes can be coalesced into a single segment. They are a hint, not a guarantee: the call returns ‘MHD_NO’ if the platform has no such option or if the socket is not a TCP socket, which is the normal case for HTTPS connections. The header file marks this part of the API as not yet finalised, so do not build anything load-bearing on it. Remarks ======= ‘MHD_stop_daemon()’ does _not_ interrupt an upgraded connection. It marks the connection as closed internally and logs ‘Initiated daemon shutdown while "upgraded" connection was not closed’, but it neither shuts down nor closes the socket -- and then it waits for the connection's thread, which means it blocks until your callback has returned. A callback parked in a blocking ‘recv()’ therefore hangs the shutdown for as long as the client keeps the connection open. Any server that wants to terminate on demand needs its own way out of that loop: a global shutdown flag combined with a ‘shutdown()’ on the sockets you are holding, a self-pipe added to a ‘select()’ in the loop, or a receive timeout on the socket. Our example sidesteps the problem by only stopping the daemon when the user presses return at a moment when nothing is connected. Error handling in the callback is entirely yours. _MHD_ will not tell you that a client vanished and will not time an upgraded connection out -- ‘MHD_OPTION_CONNECTION_TIMEOUT’ stops applying the moment the connection is upgraded. Treat ‘0’ from ‘recv()’ as a clean disconnect and a negative return as a broken one, and remember that a peer which disappears without a FIN produces neither until the TCP stack gives up, which can take a very long time. Whatever happens, end by calling ‘MHD_upgrade_action()’ with ‘MHD_UPGRADE_ACTION_CLOSE’. Finally, keep in mind that an upgraded connection is a connection that _MHD_ can no longer recycle, and that intermediaries are entitled to be unhelpful: ‘Upgrade:’ is listed in ‘Connection:’ and is therefore a hop-by-hop header field. A proxy that does not understand your protocol is allowed to drop it, in which case your server never sees an upgrade request at all and the client gets an ordinary HTTP response where it expected a 101. This is the main reason why deployed protocols on top of this mechanism -- Websockets above all -- make the handshake verifiable by both ends instead of trusting that the request arrived intact. The complete program is available as ‘upgrade.c’ in the ‘examples’ section. Start it and talk to it with any tool that lets you type raw bytes at a socket -- ‘telnet localhost 8888’ will do -- by sending GET / HTTP/1.1 Host: localhost Connection: Upgrade Upgrade: echo followed by an empty line. The server answers with HTTP/1.1 101 Switching Protocols Date: ... Connection: Upgrade Upgrade: echo and from then on echoes every line back until you type ‘QUIT’. Note the absence of a ‘Content-Length:’ field: a 101 response has no body, and everything after the empty line already belongs to the new protocol. For a real-world protocol built on exactly this API, read _RFC 6455_ and note how much of it exists only to make the handshake and the framing verifiable -- none of which the upgrade API itself has an opinion about. Exercises ========= • Point a browser at the server. The browser sends a plain ‘GET /’ and receives the ‘426’ page. Now add a second resource that serves a small HTML page and switch the upgrade to a different URL, so that the same server can be both browsed and upgraded. • Make the echo server useful: keep a list of the sockets of all upgraded connections and forward every line one client sends to all the others, turning the example into a minimal chat server. You will need a mutex around the list, and you will discover why the closing rules matter -- a socket must leave the list before its callback returns. • Fix the shutdown behaviour discussed in the remarks. Add a global "quitting" flag and a list of active sockets, have ‘main()’ set the flag and call ‘shutdown (sock, SHUT_RDWR)’ on every entry before it calls ‘MHD_stop_daemon()’, and verify that the daemon now stops even while a client is connected and silent. • Change the daemon flags to plain ‘MHD_USE_INTERNAL_POLLING_THREAD’ without ‘MHD_USE_THREAD_PER_CONNECTION’ and observe that the server now serves exactly one upgraded client and stops answering everybody else. Then repair it: leave the socket non-blocking, start a thread from within the callback, and return immediately. • Have the client send a line longer than ‘LINE_SIZE’. The example silently drops the excess. What should a real protocol do instead, and which status code would you have used if the problem had been detectable during the handshake?  File: libmicrohttpd-tutorial.info, Node: Bibliography, Next: License text, Prev: Upgrading connections, Up: Top Appendix A Bibliography *********************** API reference ============= • The _GNU libmicrohttpd_ manual by Marco Maggi and Christian Grothoff • All referenced RFCs can be found on the website of _The Internet Engineering Task Force_ • _RFC 2616_: Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext Transfer Protocol - HTTP/1.1", RFC 2616, June 1999. • _RFC 2617_: Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, "HTTP Authentication: Basic and Digest Access Authentication", RFC 2617, June 1999. • _RFC 6455_: Fette, I., Melnikov, A., "The WebSocket Protocol", RFC 6455, December 2011. • A well-structured _HTML_ reference can be found on For those readers understanding German, there is an excellent document both for learning _HTML_ and for reference, whose English and French versions unfortunately have been discontinued.  File: libmicrohttpd-tutorial.info, Node: License text, Next: Example programs, Prev: Bibliography, Up: Top Appendix B GNU Free Documentation License ***************************************** Version 1.3, 3 November 2008 Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 0. PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document “free” in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 1. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque". Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text. The "publisher" means any person or entity that distributes copies of the Document to the public. A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. 2. VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. 3. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 4. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modified Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. H. Include an unaltered copy of this License. I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified Version. N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 5. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements." 6. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. 7. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. 8. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. 9. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it. 10. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See . Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document. 11. RELICENSING "Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site. "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. "Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. ADDENDUM: How to use this License for your documents ==================================================== To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: Copyright (C) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this: with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.  File: libmicrohttpd-tutorial.info, Node: Example programs, Prev: License text, Up: Top Appendix C Example programs *************************** * Menu: * hellobrowser.c:: * logging.c:: * responseheaders.c:: * basicauthentication.c:: * simplepost.c:: * largepost.c:: * sessions.c:: * callbackresponse.c:: * asyncresponse.c:: * tlsauthentication.c:: * upgrade.c::  File: libmicrohttpd-tutorial.info, Node: hellobrowser.c, Next: logging.c, Up: Example programs C.1 hellobrowser.c ================== /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #define PORT 8888 static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { const char *page = "Hello, browser!"; struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) method; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: logging.c, Next: responseheaders.c, Prev: hellobrowser.c, Up: Example programs C.2 logging.c ============= /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #define PORT 8888 static enum MHD_Result print_out_key (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { (void) cls; /* Unused. Silent compiler warning. */ (void) kind; /* Unused. Silent compiler warning. */ printf ("%s: %s\n", key, value); return MHD_YES; } static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ printf ("New %s request for %s using version %s\n", method, url, version); MHD_get_connection_values (connection, MHD_HEADER_KIND, print_out_key, NULL); return MHD_NO; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: responseheaders.c, Next: basicauthentication.c, Prev: logging.c, Up: Example programs C.3 responseheaders.c ===================== /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #include #include #define PORT 8888 #define FILENAME "picture.png" #define MIMETYPE "image/png" static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; int fd; enum MHD_Result ret; struct stat sbuf; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; if ( (-1 == (fd = open (FILENAME, O_RDONLY))) || (0 != fstat (fd, &sbuf)) ) { const char *errorstr = "An internal server error has occurred!\ "; /* error accessing file */ if (fd != -1) (void) close (fd); response = MHD_create_response_from_buffer_static (strlen (errorstr), errorstr); if (NULL != response) { ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response); MHD_destroy_response (response); return ret; } else return MHD_NO; } response = MHD_create_response_from_fd_at_offset64 ((uint64_t) sbuf.st_size, fd, 0); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, MIMETYPE)) { fprintf (stderr, "Failed to set content type header!\n"); /* return response without content encoding anyway ... */ } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: basicauthentication.c, Next: simplepost.c, Prev: responseheaders.c, Up: Example programs C.4 basicauthentication.c ========================= /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #include #define PORT 8888 static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_BasicAuthInfo *auth_info; enum MHD_Result ret; struct MHD_Response *response; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; if (NULL == *req_cls) { *req_cls = connection; return MHD_YES; } auth_info = MHD_basic_auth_get_username_password3 (connection); if (NULL == auth_info) { static const char *page = "Authorization required"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_required_response3 (connection, "admins", MHD_YES, response); } else if ((strlen ("root") != auth_info->username_len) || (0 != memcmp (auth_info->username, "root", auth_info->username_len)) || /* The next check against NULL is optional, * if 'password' is NULL then 'password_len' is always zero. */ (NULL == auth_info->password) || (strlen ("pa$$w0rd") != auth_info->password_len) || (0 != memcmp (auth_info->password, "pa$$w0rd", auth_info->password_len))) { static const char *page = "Wrong username or password"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_required_response3 (connection, "admins", MHD_YES, response); } else { static const char *page = "A secret."; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); } if (NULL != auth_info) MHD_free (auth_info); MHD_destroy_response (response); return ret; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: simplepost.c, Next: largepost.c, Prev: basicauthentication.c, Up: Example programs C.5 simplepost.c ================ /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #if defined(_MSC_VER) && _MSC_VER + 0 <= 1800 /* Substitution is OK while return value is not used */ #define snprintf _snprintf #endif #define PORT 8888 #define POSTBUFFERSIZE 512 #define MAXNAMESIZE 20 #define MAXANSWERSIZE 512 struct connection_info_struct { enum { GET, POST } connectiontype; char *answerstring; struct MHD_PostProcessor *postprocessor; }; static const char *askpage = "\n" "What's your name, Sir?
    \n" "
    \n" "\n" "\n" ""; #define GREETINGPAGE \ "

    Welcome, %s!

    " static const char *errorpage = "This doesn't seem to be right."; static enum MHD_Result send_page (struct MHD_Connection *connection, const char *page) { enum MHD_Result ret; struct MHD_Response *response; response = MHD_create_response_from_buffer_static (strlen (page), page); if (! response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static enum MHD_Result iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; (void) kind; /* Unused. Silent compiler warning. */ (void) filename; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ (void) off; /* Unused. Silent compiler warning. */ if (0 != strcmp (key, "name")) return MHD_YES; if ( (size > 0) && (size <= MAXNAMESIZE) ) { char *answerstring; answerstring = malloc (MAXANSWERSIZE); if (! answerstring) return MHD_NO; snprintf (answerstring, MAXANSWERSIZE, GREETINGPAGE, data); con_info->answerstring = answerstring; } else { con_info->answerstring = NULL; } return MHD_YES; } static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == con_info) return; if (POST == con_info->connectiontype) { MHD_destroy_post_processor (con_info->postprocessor); if (con_info->answerstring) free (con_info->answerstring); } free (con_info); *req_cls = NULL; } static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct connection_info_struct *con_info = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ if (NULL == con_info) { con_info = malloc (sizeof (struct connection_info_struct)); *req_cls = (void *) con_info; if (NULL == con_info) return MHD_NO; con_info->answerstring = NULL; if (0 == strcmp (method, "POST")) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, iterate_post, (void *) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } con_info->connectiontype = POST; } else { con_info->connectiontype = GET; } return MHD_YES; } if (0 == strcmp (method, "GET")) { return send_page (connection, askpage); } if (0 == strcmp (method, "POST")) { if (0 != *upload_data_size) { if (MHD_YES != MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size)) return MHD_NO; *upload_data_size = 0; return MHD_YES; } else if (NULL != con_info->answerstring) return send_page (connection, con_info->answerstring); } return send_page (connection, errorpage); } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: largepost.c, Next: sessions.c, Prev: simplepost.c, Up: Example programs C.6 largepost.c =============== /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #if defined(_MSC_VER) && _MSC_VER + 0 <= 1800 /* Substitution is OK while return value is not used */ #define snprintf _snprintf #endif #define PORT 8888 #define POSTBUFFERSIZE 512 #define MAXCLIENTS 2 enum ConnectionType { GET = 0, POST = 1 }; static unsigned int nr_of_uploading_clients = 0; /** * Information we keep per connection. */ struct connection_info_struct { enum ConnectionType connectiontype; /** * Handle to the POST processing state. */ struct MHD_PostProcessor *postprocessor; /** * File handle where we write uploaded data. */ FILE *fp; /** * HTTP response body we will return, NULL if not yet known. */ const char *answerstring; /** * HTTP status code we will return, 0 for undecided. */ unsigned int answercode; }; #define ASKPAGE \ "\n" \ "Upload a file, please!
    \n" \ "There are %u clients uploading at the moment.
    \n" \ "
    \n" \ "\n" \ "\n" \ "" static const char *busypage = "This server is busy, please try again later."; static const char *completepage = "The upload has been completed."; static const char *errorpage = "This doesn't seem to be right."; static const char *servererrorpage = "Invalid request."; static const char *fileexistspage = "This file already exists."; static const char *fileioerror = "IO error writing to disk."; static const char *const postprocerror = "ErrorError processing POST data"; static enum MHD_Result send_page (struct MHD_Connection *connection, const char *page, unsigned int status_code) { enum MHD_Result ret; struct MHD_Response *response; /* NOTE: we let MHD make its own copy of the page, as some of the pages we serve live in a buffer on the stack of the caller. */ response = MHD_create_response_from_buffer_copy (strlen (page), page); if (! response) return MHD_NO; if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/html")) { fprintf (stderr, "Failed to set content type header!\n"); } ret = MHD_queue_response (connection, status_code, response); MHD_destroy_response (response); return ret; } static enum MHD_Result iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; FILE *fp; (void) kind; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ (void) off; /* Unused. Silent compiler warning. */ if (0 != strcmp (key, "file")) { con_info->answerstring = servererrorpage; con_info->answercode = MHD_HTTP_BAD_REQUEST; return MHD_YES; } if (! con_info->fp) { if (0 != con_info->answercode) /* something went wrong */ return MHD_YES; if (NULL != (fp = fopen (filename, "rb"))) { fclose (fp); con_info->answerstring = fileexistspage; con_info->answercode = MHD_HTTP_FORBIDDEN; return MHD_YES; } /* NOTE: This is technically a race with the 'fopen()' above, but there is no easy fix, short of moving to open(O_EXCL) instead of using fopen(). For the example, we do not care. */ con_info->fp = fopen (filename, "ab"); if (! con_info->fp) { con_info->answerstring = fileioerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; return MHD_YES; } } if (size > 0) { if (! fwrite (data, sizeof (char), size, con_info->fp)) { con_info->answerstring = fileioerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; return MHD_YES; } } return MHD_YES; } static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == con_info) return; if (con_info->connectiontype == POST) { if (NULL != con_info->postprocessor) { MHD_destroy_post_processor (con_info->postprocessor); nr_of_uploading_clients--; } if (con_info->fp) fclose (con_info->fp); } free (con_info); *req_cls = NULL; } static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ if (NULL == *req_cls) { /* First call, setup data structures */ struct connection_info_struct *con_info; if (nr_of_uploading_clients >= MAXCLIENTS) return send_page (connection, busypage, MHD_HTTP_SERVICE_UNAVAILABLE); con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->answercode = 0; /* none yet */ con_info->fp = NULL; if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, &iterate_post, (void *) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } nr_of_uploading_clients++; con_info->connectiontype = POST; } else { con_info->connectiontype = GET; } *req_cls = (void *) con_info; return MHD_YES; } if (0 == strcmp (method, MHD_HTTP_METHOD_GET)) { /* We just return the standard form for uploads on all GET requests */ char buffer[1024]; snprintf (buffer, sizeof (buffer), ASKPAGE, nr_of_uploading_clients); return send_page (connection, buffer, MHD_HTTP_OK); } if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { struct connection_info_struct *con_info = *req_cls; if (0 != *upload_data_size) { /* Upload not yet done */ if (0 != con_info->answercode) { /* we already know the answer, skip rest of upload */ *upload_data_size = 0; return MHD_YES; } if (MHD_YES != MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size)) { con_info->answerstring = postprocerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; } *upload_data_size = 0; return MHD_YES; } /* Upload finished */ if (NULL != con_info->fp) { fclose (con_info->fp); con_info->fp = NULL; } if (0 == con_info->answercode) { /* No errors encountered, declare success */ con_info->answerstring = completepage; con_info->answercode = MHD_HTTP_OK; } return send_page (connection, con_info->answerstring, con_info->answercode); } /* Not a GET or a POST, generate error */ return send_page (connection, errorpage, MHD_HTTP_BAD_REQUEST); } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL, MHD_OPTION_END); if (NULL == daemon) { fprintf (stderr, "Failed to start daemon.\n"); return 1; } (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: sessions.c, Next: callbackresponse.c, Prev: largepost.c, Up: Example programs C.7 sessions.c ============== /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #include #include #include #include #include /** * Invalid method page. */ #define METHOD_ERROR \ "Illegal requestGo away." /** * Invalid URL page. */ #define NOT_FOUND_ERROR \ "Not foundGo away." /** * Front page. (/) */ #define MAIN_PAGE \ "Welcome
    What is your name? " #define FORM_V1 MAIN_PAGE /** * Second page. (/2) */ #define SECOND_PAGE \ "Tell me moreprevious %s, what is your job? " #define FORM_V1_V2 SECOND_PAGE /** * Second page (/S) */ #define SUBMIT_PAGE \ "Ready to submit?previous " /** * Last page. */ #define LAST_PAGE \ "Thank youThank you." /** * Name of our cookie. */ #define COOKIE_NAME "session" /** * State we keep for each user/session/browser. */ struct Session { /** * We keep all sessions in a linked list. */ struct Session *next; /** * Unique ID for this session. */ char sid[33]; /** * Reference counter giving the number of connections * currently using this session. */ unsigned int rc; /** * Time when this session was last active. */ time_t start; /** * String submitted via form. */ char value_1[64]; /** * Another value submitted via form. */ char value_2[64]; }; /** * Data kept per request. */ struct Request { /** * Associated session. */ struct Session *session; /** * Post processor handling form data (IF this is * a POST request). */ struct MHD_PostProcessor *pp; /** * URL to serve in response to this POST (if this request * was a 'POST') */ const char *post_url; }; /** * Linked list of all active sessions. Yes, O(n) but a * hash table would be overkill for a simple example... */ static struct Session *sessions; /** * Return the session handle for this connection, or * create one if this is a new user. */ static struct Session * get_session (struct MHD_Connection *connection) { struct Session *ret; const char *cookie; cookie = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, COOKIE_NAME); if (cookie != NULL) { /* find existing session */ ret = sessions; while (NULL != ret) { if (0 == strcmp (cookie, ret->sid)) break; ret = ret->next; } if (NULL != ret) { ret->rc++; return ret; } } /* create fresh session */ ret = calloc (1, sizeof (struct Session)); if (NULL == ret) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return NULL; } /* not a super-secure way to generate a random session ID, but should do for a simple example... */ snprintf (ret->sid, sizeof (ret->sid), "%X%X%X%X", (unsigned int) rand (), (unsigned int) rand (), (unsigned int) rand (), (unsigned int) rand ()); ret->rc++; ret->start = time (NULL); ret->next = sessions; sessions = ret; return ret; } /** * Type of handler that generates a reply. * * @param cls content for the page (handler-specific) * @param mime mime type to use * @param session session information * @param connection connection to process * @param #MHD_YES on success, #MHD_NO on failure */ typedef enum MHD_Result (*PageHandler)(const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection); /** * Entry we generate for each page served. */ struct Page { /** * Acceptable URL for this page. */ const char *url; /** * Mime type to set for the page. */ const char *mime; /** * Handler to call to generate response. */ PageHandler handler; /** * Extra argument to handler. */ const void *handler_cls; }; /** * Add header to response to set a session cookie. * * @param session session to use * @param response response to modify */ static void add_session_cookie (struct Session *session, struct MHD_Response *response) { char cstr[256]; snprintf (cstr, sizeof (cstr), "%s=%s", COOKIE_NAME, session->sid); if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_SET_COOKIE, cstr)) { fprintf (stderr, "Failed to set session cookie header!\n"); } } /** * Handler that returns a simple static HTTP page that * is passed in via 'cls'. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result serve_simple_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; const char *form = cls; struct MHD_Response *response; /* return static form */ response = MHD_create_response_from_buffer_static (strlen (form), form); add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime)) { fprintf (stderr, "Failed to set content type header!\n"); /* return response without content type anyway ... */ } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Handler that adds the 'v1' value to the given HTML code. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result fill_v1_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; char *reply; struct MHD_Response *response; int reply_len; (void) cls; /* Unused */ /* Emulate 'asprintf' */ reply_len = snprintf (NULL, 0, FORM_V1, session->value_1); if (0 > reply_len) return MHD_NO; /* Internal error */ reply = (char *) malloc ((size_t) ((size_t) reply_len + 1)); if (NULL == reply) return MHD_NO; /* Out-of-memory error */ if (reply_len != snprintf (reply, (size_t) (((size_t) reply_len) + 1), FORM_V1, session->value_1)) { free (reply); return MHD_NO; /* printf error */ } /* return static form */ response = MHD_create_response_from_buffer_with_free_callback ((size_t) reply_len, (void *) reply, &free); if (NULL != response) { add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime)) { fprintf (stderr, "Failed to set content type header!\n"); /* return response without content type anyway ... */ } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } else { free (reply); ret = MHD_NO; } return ret; } /** * Handler that adds the 'v1' and 'v2' values to the given HTML code. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result fill_v1_v2_form (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; char *reply; struct MHD_Response *response; int reply_len; (void) cls; /* Unused */ /* Emulate 'asprintf' */ reply_len = snprintf (NULL, 0, FORM_V1_V2, session->value_1, session->value_2); if (0 > reply_len) return MHD_NO; /* Internal error */ reply = (char *) malloc ((size_t) ((size_t) reply_len + 1)); if (NULL == reply) return MHD_NO; /* Out-of-memory error */ if (reply_len != snprintf (reply, (size_t) ((size_t) reply_len + 1), FORM_V1_V2, session->value_1, session->value_2)) { free (reply); return MHD_NO; /* printf error */ } /* return static form */ response = MHD_create_response_from_buffer_with_free_callback ((size_t) reply_len, (void *) reply, &free); if (NULL != response) { add_session_cookie (session, response); if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime)) { fprintf (stderr, "Failed to set content type header!\n"); /* return response without content type anyway ... */ } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } else { free (reply); ret = MHD_NO; } return ret; } /** * Handler used to generate a 404 reply. * * @param cls a 'const char *' with the HTML webpage to return * @param mime mime type to use * @param session session handle * @param connection connection to use */ static enum MHD_Result not_found_page (const void *cls, const char *mime, struct Session *session, struct MHD_Connection *connection) { enum MHD_Result ret; struct MHD_Response *response; (void) cls; /* Unused. Silent compiler warning. */ (void) session; /* Unused. Silent compiler warning. */ /* unsupported HTTP method */ response = MHD_create_response_from_buffer_static (strlen (NOT_FOUND_ERROR), NOT_FOUND_ERROR); /* NOTE: headers must be added _before_ the response is queued, MHD refuses to modify a response that was already queued. */ if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime)) { fprintf (stderr, "Failed to set content type header!\n"); /* return response without content type anyway ... */ } ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response (response); return ret; } /** * List of all pages served by this HTTP server. */ static const struct Page pages[] = { { "/", "text/html", &fill_v1_form, NULL }, { "/2", "text/html", &fill_v1_v2_form, NULL }, { "/S", "text/html", &serve_simple_form, SUBMIT_PAGE }, { "/F", "text/html", &serve_simple_form, LAST_PAGE }, { NULL, "text/html", ¬_found_page, NULL } /* 404 */ }; /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return #MHD_YES to continue iterating, * #MHD_NO to abort the iteration */ static enum MHD_Result post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct Request *request = cls; struct Session *session = request->session; (void) kind; /* Unused. Silent compiler warning. */ (void) filename; /* Unused. Silent compiler warning. */ (void) content_type; /* Unused. Silent compiler warning. */ (void) transfer_encoding; /* Unused. Silent compiler warning. */ if (0 == strcmp ("DONE", key)) { fprintf (stdout, "Session `%s' submitted `%s', `%s'\n", session->sid, session->value_1, session->value_2); return MHD_YES; } if (0 == strcmp ("v1", key)) { if (off >= sizeof(session->value_1) - 1) return MHD_YES; /* Discard extra data */ if (size + off >= sizeof(session->value_1)) size = (size_t) (sizeof (session->value_1) - off - 1); /* crop extra data */ memcpy (&session->value_1[off], data, size); if (size + off < sizeof (session->value_1)) session->value_1[size + off] = '\0'; return MHD_YES; } if (0 == strcmp ("v2", key)) { if (off >= sizeof(session->value_2) - 1) return MHD_YES; /* Discard extra data */ if (size + off >= sizeof(session->value_2)) size = (size_t) (sizeof (session->value_2) - off - 1); /* crop extra data */ memcpy (&session->value_2[off], data, size); if (size + off < sizeof (session->value_2)) session->value_2[size + off] = '\0'; return MHD_YES; } fprintf (stderr, "Unsupported form value `%s'\n", key); return MHD_YES; } /** * Main MHD callback for handling requests. * * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param connection handle to connection which is being processed * @param url the requested url * @param method the HTTP method used ("GET", "PUT", etc.) * @param version the HTTP version string (i.e. "HTTP/1.1") * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of MHD_get_connection_values; very large POST * data *will* be made available incrementally in * upload_data) * @param upload_data_size set initially to the size of the * upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param req_cls pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global "MHD_RequestCompleted" callback (which * can be set with the MHD_OPTION_NOTIFY_COMPLETED). * Initially, *req_cls will be NULL. * @return MHS_YES if the connection was handled successfully, * MHS_NO if the socket must be closed due to a serious * error while handling the request */ static enum MHD_Result create_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; struct Request *request; struct Session *session; enum MHD_Result ret; unsigned int i; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ request = *req_cls; if (NULL == request) { request = calloc (1, sizeof (struct Request)); if (NULL == request) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return MHD_NO; } *req_cls = request; if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { request->pp = MHD_create_post_processor (connection, 1024, &post_iterator, request); if (NULL == request->pp) { fprintf (stderr, "Failed to setup post processor for `%s'\n", url); return MHD_NO; /* internal error */ } } return MHD_YES; } if (NULL == request->session) { request->session = get_session (connection); if (NULL == request->session) { fprintf (stderr, "Failed to setup session for `%s'\n", url); return MHD_NO; /* internal error */ } } session = request->session; session->start = time (NULL); if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { /* evaluate POST data */ if (MHD_YES != MHD_post_process (request->pp, upload_data, *upload_data_size)) return MHD_NO; /* internal error */ if (0 != *upload_data_size) { *upload_data_size = 0; return MHD_YES; } /* done with POST data, serve response */ MHD_destroy_post_processor (request->pp); request->pp = NULL; method = MHD_HTTP_METHOD_GET; /* fake 'GET' */ if (NULL != request->post_url) url = request->post_url; } if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) || (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) ) { /* find out which page to serve */ i = 0; while ( (pages[i].url != NULL) && (0 != strcmp (pages[i].url, url)) ) i++; ret = pages[i].handler (pages[i].handler_cls, pages[i].mime, session, connection); if (ret != MHD_YES) fprintf (stderr, "Failed to create page for `%s'\n", url); return ret; } /* unsupported HTTP method */ response = MHD_create_response_from_buffer_static (strlen (METHOD_ERROR), METHOD_ERROR); ret = MHD_queue_response (connection, MHD_HTTP_NOT_ACCEPTABLE, response); MHD_destroy_response (response); return ret; } /** * Callback called upon completion of a request. * Decrements session reference counter. * * @param cls not used * @param connection connection that completed * @param req_cls session handle * @param toe status code */ static void request_completed_callback (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct Request *request = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == request) return; if (NULL != request->session) request->session->rc--; if (NULL != request->pp) MHD_destroy_post_processor (request->pp); free (request); } /** * Clean up handles of sessions that have been idle for * too long. */ static void expire_sessions (void) { struct Session *pos; struct Session *prev; struct Session *next; time_t now; now = time (NULL); prev = NULL; pos = sessions; while (NULL != pos) { next = pos->next; if (now - pos->start > 60 * 60) { /* expire sessions after 1h */ if (NULL == prev) sessions = pos->next; else prev->next = next; free (pos); } else prev = pos; pos = next; } } /** * Call with the port number as the only argument. * Never terminates (other than by signals, such as CTRL-C). */ int main (int argc, char *const *argv) { struct MHD_Daemon *d; struct timeval tv; struct timeval *tvp; fd_set rs; fd_set ws; fd_set es; MHD_socket max; uint64_t mhd_timeout; unsigned int port; if (argc != 2) { printf ("%s PORT\n", argv[0]); return 1; } if ( (1 != sscanf (argv[1], "%u", &port)) || (0 == port) || (65535 < port) ) { fprintf (stderr, "Port must be a number between 1 and 65535.\n"); return 1; } /* initialize PRNG */ srand ((unsigned int) time (NULL)); d = MHD_start_daemon (MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &create_response, NULL, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15, MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL, MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, MHD_OPTION_END); if (NULL == d) return 1; while (1) { expire_sessions (); max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) break; /* fatal internal error */ if (MHD_get_timeout64 (d, &mhd_timeout) == MHD_YES) { #if ! defined(_WIN32) || defined(__CYGWIN__) tv.tv_sec = (time_t) (mhd_timeout / 1000); #else /* Native W32 */ tv.tv_sec = (long) (mhd_timeout / 1000); #endif /* Native W32 */ tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000; tvp = &tv; } else tvp = NULL; if (-1 == select ((int) max + 1, &rs, &ws, &es, tvp)) { if (EINTR != errno) fprintf (stderr, "Aborting due to error during select: %s\n", strerror (errno)); break; } MHD_run (d); } MHD_stop_daemon (d); return 0; }  File: libmicrohttpd-tutorial.info, Node: callbackresponse.c, Next: asyncresponse.c, Prev: sessions.c, Up: Example programs C.8 callbackresponse.c ====================== /* Feel free to use this example code in any way you see fit (Public Domain) */ /** * @file callbackresponse.c * @brief Example for generating a response on the fly with * MHD_create_response_from_callback(). The body is not a * file and is never assembled in memory as a whole; it is * produced block by block into a single heap buffer that is * refilled every time libmicrohttpd asks for more data. * "GET /" streams the document with an unknown size (and thus * with chunked transfer encoding), "GET /sized" streams the * very same document with a "Content-Length" announced up * front, and "GET /error" aborts the stream in the middle to * show MHD_CONTENT_READER_END_WITH_ERROR. * @author Christian Grothoff */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #define PORT 8888 /** * Length of one generated line, including the newline character. */ #define LINE_SIZE 64 /** * Size of the heap buffer that is refilled over and over again. This * is the amount of data we produce in one go; it has nothing to do * with the block size we pass to MHD. */ #define BUFFER_SIZE (64 * LINE_SIZE) /** * Number of times the buffer is refilled before the stream ends. The * complete document is BLOCK_COUNT * BUFFER_SIZE bytes long. */ #define BLOCK_COUNT 64 /** * Block size we ask MHD to use when it queries our callback. MHD * allocates a buffer of this size together with the response; it is an * advisory value and MHD may ask for less. */ #define IO_BLOCK_SIZE 1024 /** * For the "/error" URL: number of blocks to deliver before the stream * is aborted with MHD_CONTENT_READER_END_WITH_ERROR. */ #define ABORT_AFTER 3 /** * State we keep for one response that is being streamed. One such * structure is allocated per request and released by the free callback * that we hand to MHD_create_response_from_callback(). */ struct ResponseContext { /** * Heap buffer holding the block that is currently being delivered. * Refilled by generate_block() whenever it has been drained. */ char *buf; /** * Number of valid bytes in @e buf. */ size_t fill; /** * Number of bytes of @e buf that were already handed to MHD. */ size_t off; /** * Number of blocks generated so far, and thus the number of the * block that generate_block() will produce next. */ unsigned int block; /** * Non-zero if this stream is supposed to fail in the middle. */ int fail; }; /** * Produce the next block of the document into @a ctx->buf. This * stands in for whatever expensive computation, database query or * network fetch a real application would perform here. Note that the * same buffer is reused for every block, so the memory needed by the * server does not grow with the size of the document. * * Every line is exactly LINE_SIZE bytes long, which is what allows us * to announce an exact "Content-Length" for the "/sized" URL. * * @param ctx the per-response state to refill */ static void generate_block (struct ResponseContext *ctx) { unsigned int i; char *line; char label[32]; int len; for (i = 0; i < BUFFER_SIZE / LINE_SIZE; i++) { line = &ctx->buf[i * LINE_SIZE]; memset (line, '.', LINE_SIZE); len = snprintf (label, sizeof (label), "block %3u line %3u ", ctx->block, i); if ((0 < len) && (LINE_SIZE > (size_t) len)) memcpy (line, label, (size_t) len); line[LINE_SIZE - 1] = '\n'; } ctx->fill = BUFFER_SIZE; ctx->off = 0; ctx->block++; } /** * Callback used by MHD to obtain the next piece of the response body. * * @param cls our `struct ResponseContext` * @param pos number of bytes already returned for this response * @param buf where to copy the data * @param max maximum number of bytes to copy to @a buf * @return number of bytes written to @a buf, * MHD_CONTENT_READER_END_OF_STREAM for the regular end, * MHD_CONTENT_READER_END_WITH_ERROR to abort the transfer */ static ssize_t content_reader (void *cls, uint64_t pos, char *buf, size_t max) { struct ResponseContext *ctx = cls; size_t ready; /* We generate a pure stream and never look back, so the position is of no interest to us. MHD guarantees that it is the sum of all non-negative values we returned so far. */ (void) pos; /* Unused. Silent compiler warning. */ if (ctx->off == ctx->fill) { /* Everything we had was passed on, produce the next block. */ if (BLOCK_COUNT == ctx->block) return MHD_CONTENT_READER_END_OF_STREAM; if ((0 != ctx->fail) && (ABORT_AFTER == ctx->block)) return MHD_CONTENT_READER_END_WITH_ERROR; generate_block (ctx); } /* Hand over as much of the current block as MHD is willing to take; the rest follows on the next invocation. */ ready = ctx->fill - ctx->off; if (ready > max) ready = max; memcpy (buf, &ctx->buf[ctx->off], ready); ctx->off += ready; return (ssize_t) ready; } /** * Release the resources of a `struct ResponseContext`. MHD calls this * once the response is destroyed, which happens no matter whether the * body was transmitted completely or the client went away early. * * @param cls our `struct ResponseContext` */ static void free_context (void *cls) { struct ResponseContext *ctx = cls; free (ctx->buf); free (ctx); } static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct ResponseContext *ctx; struct MHD_Response *response; enum MHD_Result ret; uint64_t size; (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* Allocate the state of this particular response before the response object exists; from now on the free callback owns it. */ ctx = malloc (sizeof (struct ResponseContext)); if (NULL == ctx) return MHD_NO; ctx->buf = malloc (BUFFER_SIZE); if (NULL == ctx->buf) { free (ctx); return MHD_NO; } ctx->fill = 0; ctx->off = 0; ctx->block = 0; ctx->fail = (0 == strcmp (url, "/error")); /* "/sized" announces the length in advance, everything else is sent with an unknown size and thus with chunked transfer encoding. */ if (0 == strcmp (url, "/sized")) size = (uint64_t) BLOCK_COUNT * BUFFER_SIZE; else size = MHD_SIZE_UNKNOWN; response = MHD_create_response_from_callback (size, IO_BLOCK_SIZE, &content_reader, ctx, &free_context); if (NULL == response) { /* The response was never created, so nobody will call the free callback for us. */ free_context (ctx); return MHD_NO; } (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/plain"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  File: libmicrohttpd-tutorial.info, Node: asyncresponse.c, Next: tlsauthentication.c, Prev: callbackresponse.c, Up: Example programs C.9 asyncresponse.c =================== /* Feel free to use this example code in any way you see fit (Public Domain) */ /** * @file asyncresponse.c * @brief Example for answering a request from another thread while * the daemon is driven by an external select() loop. The * main thread owns libmicrohttpd and does nothing but poll; * every slow request gets a worker thread of its own and the * connection is suspended for as long as that worker has * nothing to say. * * "GET /" serves a small page whose JavaScript renders the * data as it trickles in, "GET /events" is the stream behind * it (a response is queued immediately and the content reader * suspends between chunks), "GET /slow" suspends in the access * handler until a complete answer is ready, and "GET /fast" is * answered on the spot so that it can be used to show that the * event loop never blocks. * * This example needs POSIX threads. * @author Christian Grothoff */ #include #include #include #include #include #include #include #include #include #include #include #include /** * Port to listen on if none was given on the command line. Pass 0 to * let the operating system pick a free port; the port that was * actually bound is then printed on standard output. */ #define DEFAULT_PORT 8888 /** * Time the worker thread pretends to need for one step, in * milliseconds. */ #define DEFAULT_STEP_MS 250 /** * Number of steps that make up one job. */ #define DEFAULT_STEPS 20 /** * Size of the buffer in which a job collects the bytes that the * content reader has not picked up yet. */ #define MAX_PAYLOAD 4096 /** * Block size we ask MHD to use when it queries our content reader. */ #define IO_BLOCK_SIZE 1024 /** * How long we are willing to wait for the last connections to go away * when the server is shutting down, in milliseconds. */ #define DRAIN_TIMEOUT_MS 2000 /** * The front page. Its JavaScript opens the "/events" stream and adds * a row for every server-sent event as it arrives, so that the delay * between the steps is plainly visible. The "ping" button fires a * request against "/fast" and reports the round trip time; it stays in * the low milliseconds even while several jobs are running, which is * the whole point of suspending instead of blocking. */ static const char *PAGE = "\n" "\n" "\n" "\n" "libmicrohttpd: answering from another thread\n" "\n" "\n" "\n" "

    Answering from another thread

    \n" "

    The server runs a single external select() loop. The job\n" "below is computed by a thread of its own, and the connection carrying it is\n" "suspended whenever that thread has nothing to say. Nothing is buffered: each\n" "row appears the moment the worker produced it.

    \n" "\n" "\n" "
    \n" "

    idle

    \n" "
      \n" "\n" "\n" "\n"; /** * State shared between the thread that runs libmicrohttpd and the * worker thread that produces the answer. Everything below @e lock is * protected by it. * * The structure is reference counted, with one reference held by MHD * (dropped in #stream_done() or #request_completed()) and one held by * the worker (dropped when the worker function returns). Reaching zero * does not free the job: only the main thread does that, in * #reap_jobs(), because it is also the thread that has to join the * worker. */ struct Job { /** * Kept in a doubly linked list of all jobs, so that the shutdown * code can reach every worker. The list is protected by * #jobs_lock, never by @e lock. */ struct Job *next; /** * See @e next. */ struct Job *prev; /** * Protects every field below, and---just as importantly---keeps the * connection alive across #MHD_resume_connection(). */ pthread_mutex_t lock; /** * Used to wake the worker out of its sleep when the client goes away * or the server is shutting down. */ pthread_cond_t cond; /** * The worker thread. Only touched by the main thread, under * #jobs_lock. */ pthread_t tid; /** * The connection this job answers. Set to NULL by the MHD side as * soon as MHD is done with the connection; the worker must not touch * it after that, which is why @e abandoned is checked under @e lock * before every #MHD_resume_connection(). */ struct MHD_Connection *connection; /** * Bytes produced by the worker that the content reader has not * picked up yet. */ char payload[MAX_PAYLOAD]; /** * Number of valid bytes in @e payload. */ size_t fill; /** * Number of bytes of @e payload already handed to MHD. */ size_t off; /** * Number of references, see the comment on the structure. */ unsigned int rc; /** * Non-zero if the answer is streamed as it is produced ("/events"), * zero if the client only ever sees the finished result ("/slow"). * A streaming job resumes the connection after every step, the other * kind only once, at the very end. */ int stream; /** * Non-zero once the worker has produced everything it is going to * produce. */ int finished; /** * Non-zero while the connection is suspended (or is just about to * be, which under @e lock is the same thing). */ int suspended; /** * Non-zero once MHD is done with the connection. The worker must * not call any MHD function on @e connection any more. */ int abandoned; /** * Non-zero if the worker should give up early. */ int stop; /** * Non-zero once the worker thread was started. Main thread only. */ int started; /** * Non-zero once the worker thread was joined. Main thread only. */ int joined; }; /** * Head of the list of all jobs. */ static struct Job *jobs_head; /** * Protects #jobs_head and the list links of every job. Lock order is * #jobs_lock before any `struct Job`'s @e lock, never the other way * round. */ static pthread_mutex_t jobs_lock = PTHREAD_MUTEX_INITIALIZER; /** * Set by the signal handler, read by the main loop. */ static volatile sig_atomic_t shutdown_requested; /** * Written to by the signal handler so that a blocking select() returns * at once. MHD's own wakeup goes through its inter-thread * communication channel, but our signal is our own business. */ static int wake_pipe[2] = { -1, -1 }; /** * Milliseconds the worker sleeps per step. */ static unsigned int step_ms = DEFAULT_STEP_MS; /** * Number of steps that make up one job. */ static unsigned int total_steps = DEFAULT_STEPS; /** * Signal handler for SIGINT and SIGTERM. Does the two things that are * safe to do here: set a flag and poke a pipe. * * @param sig the signal that was received */ static void signal_handler (int sig) { static const char c = 'x'; (void) sig; /* Unused. Silent compiler warning. */ shutdown_requested = 1; if (0 > write (wake_pipe[1], &c, 1)) { /* Nothing useful can be done about this here. */ } } /** * Allocate a job and put it on the global list. * * @param connection the connection the job answers * @param stream non-zero to deliver the steps as they are produced * @return the new job with a reference count of two (one for MHD, one * for the worker that the caller is about to start), NULL on * error */ static struct Job * job_create (struct MHD_Connection *connection, int stream) { struct Job *job; job = malloc (sizeof (struct Job)); if (NULL == job) return NULL; memset (job, 0, sizeof (struct Job)); if (0 != pthread_mutex_init (&job->lock, NULL)) { free (job); return NULL; } if (0 != pthread_cond_init (&job->cond, NULL)) { pthread_mutex_destroy (&job->lock); free (job); return NULL; } job->connection = connection; job->stream = stream; job->rc = 2; pthread_mutex_lock (&jobs_lock); job->next = jobs_head; if (NULL != jobs_head) jobs_head->prev = job; jobs_head = job; pthread_mutex_unlock (&jobs_lock); return job; } /** * Drop a reference. Note that this never frees the job: the main * thread has to join the worker first, and only it may do that. See * #reap_jobs(). * * @param job the job to release */ static void job_unref (struct Job *job) { pthread_mutex_lock (&job->lock); job->rc--; pthread_mutex_unlock (&job->lock); } /** * Called by the MHD side once MHD is done with the connection. After * this returns, the worker will not touch the connection again. * * @param job the job to detach from its connection */ static void job_detach (struct Job *job) { pthread_mutex_lock (&job->lock); job->abandoned = 1; job->connection = NULL; /* Wake the worker out of its sleep: if the client hung up in the middle of the transfer there is no point in producing the rest. */ pthread_cond_signal (&job->cond); pthread_mutex_unlock (&job->lock); job_unref (job); } /** * Resume the connection of @a job if it is suspended. * * Must be called with @a job's lock held, and it deliberately calls * into MHD while holding it: the MHD thread has to take the very same * lock in #job_detach() before it can finish the connection, so as * long as we hold the lock the connection cannot go away underneath * us. The reverse order never occurs---MHD invokes our callbacks * without holding any of its own locks that #MHD_resume_connection() * would need---so this cannot deadlock. * * @param job the job whose connection to resume */ static void job_resume_locked (struct Job *job) { if ( (0 == job->suspended) || (0 != job->abandoned) ) return; job->suspended = 0; MHD_resume_connection (job->connection); } /** * Sleep for one step, or until the job is woken up. * * @param job the job to sleep on * @return non-zero if the worker should stop early */ static int job_sleep (struct Job *job) { struct timespec ts; int stop; if (0 != clock_gettime (CLOCK_REALTIME, &ts)) return 1; ts.tv_sec += (time_t) (step_ms / 1000); ts.tv_nsec += (long) (step_ms % 1000) * 1000000L; if (1000000000L <= ts.tv_nsec) { ts.tv_nsec -= 1000000000L; ts.tv_sec++; } pthread_mutex_lock (&job->lock); while ( (0 == job->stop) && (0 == job->abandoned) ) { if (ETIMEDOUT == pthread_cond_timedwait (&job->cond, &job->lock, &ts)) break; } stop = (0 != job->stop) || (0 != job->abandoned); pthread_mutex_unlock (&job->lock); return stop; } /** * Append @a len bytes from @a data to the job's payload buffer, * compacting the buffer first. Must be called with @a job's lock * held. A real application would need a policy for the case that the * client cannot keep up; here we simply drop the step, which cannot * happen with the sizes used in this example. * * @param job the job to append to * @param data the bytes to append * @param len the number of bytes to append */ static void job_append_locked (struct Job *job, const char *data, size_t len) { if (0 != job->off) { memmove (job->payload, &job->payload[job->off], job->fill - job->off); job->fill -= job->off; job->off = 0; } if (len > MAX_PAYLOAD - job->fill) return; memcpy (&job->payload[job->fill], data, len); job->fill += len; } /** * The worker. This stands in for whatever expensive computation, * database cursor or remote query a real application would run: it * produces one server-sent event per step and resumes the connection * whenever it has something new to offer. * * Note that the only MHD function this thread ever calls is * #MHD_resume_connection(). Building and queueing the response is the * business of the thread that runs the daemon. * * @param cls the `struct Job` to work on * @return always NULL */ static void * worker (void *cls) { struct Job *job = cls; char event[256]; unsigned int i; int len; for (i = 1; i <= total_steps; i++) { if (0 != job_sleep (job)) break; if (0 != job->stream) len = snprintf (event, sizeof (event), "event: step\ndata: {\"n\":%u,\"total\":%u," "\"label\":\"step %u of %u done\"}\n\n", i, total_steps, i, total_steps); else len = snprintf (event, sizeof (event), "step %u of %u done\n", i, total_steps); if ( (0 >= len) || (sizeof (event) <= (size_t) len) ) break; pthread_mutex_lock (&job->lock); job_append_locked (job, event, (size_t) len); /* Only a streaming job has anything to show yet. The other kind stays suspended until the very last step. */ if (0 != job->stream) job_resume_locked (job); pthread_mutex_unlock (&job->lock); } if (0 != job->stream) len = snprintf (event, sizeof (event), "event: done\ndata: {\"n\":%u,\"total\":%u}\n\n", total_steps, total_steps); else len = snprintf (event, sizeof (event), "all %u steps done\n", total_steps); pthread_mutex_lock (&job->lock); if ( (0 < len) && (sizeof (event) > (size_t) len) ) job_append_locked (job, event, (size_t) len); job->finished = 1; /* The last resume is not optional: if the connection were left suspended, nothing would ever wake it up again, and the daemon could not be stopped. */ job_resume_locked (job); pthread_mutex_unlock (&job->lock); job_unref (job); return NULL; } /** * Start the worker thread of @a job. * * @param job the job whose worker to start * @return #MHD_YES on success */ static enum MHD_Result job_start (struct Job *job) { pthread_mutex_lock (&jobs_lock); if (0 != pthread_create (&job->tid, NULL, &worker, job)) { pthread_mutex_unlock (&jobs_lock); return MHD_NO; } job->started = 1; pthread_mutex_unlock (&jobs_lock); return MHD_YES; } /** * Content reader for the "/events" stream. This is the interesting * one: when the worker has produced nothing since the last call we * suspend the connection and return zero, instead of returning zero on * its own---which would make MHD ask again immediately and burn a CPU * core for the whole duration of the transfer. * * @param cls our `struct Job` * @param pos number of bytes already returned for this response * @param buf where to copy the data * @param max maximum number of bytes to copy to @a buf * @return number of bytes written to @a buf, 0 if the connection was * suspended, MHD_CONTENT_READER_END_OF_STREAM at the end */ static ssize_t stream_reader (void *cls, uint64_t pos, char *buf, size_t max) { struct Job *job = cls; size_t ready; (void) pos; /* Unused. Silent compiler warning. */ pthread_mutex_lock (&job->lock); if (job->off == job->fill) { job->off = 0; job->fill = 0; if (0 != job->finished) { pthread_mutex_unlock (&job->lock); return MHD_CONTENT_READER_END_OF_STREAM; } /* Nothing to send yet. Take the connection out of the event loop; the worker will put it back in. */ job->suspended = 1; MHD_suspend_connection (job->connection); pthread_mutex_unlock (&job->lock); return 0; } ready = job->fill - job->off; if (ready > max) ready = max; memcpy (buf, &job->payload[job->off], ready); job->off += ready; pthread_mutex_unlock (&job->lock); return (ssize_t) ready; } /** * Called by MHD when the response object of an "/events" request is * destroyed, which happens for a completed transfer just as well as * for a client that went away in the middle of one. This is the MHD * side of the job's reference count. * * @param cls our `struct Job` */ static void stream_done (void *cls) { job_detach (cls); } /** * Handle "GET /events": queue a streaming response right away and let * the content reader deal with the fact that the data does not exist * yet. * * @param connection the connection to answer * @return #MHD_YES on success */ static enum MHD_Result handle_events (struct MHD_Connection *connection) { struct MHD_Response *response; struct Job *job; enum MHD_Result ret; job = job_create (connection, 1); if (NULL == job) return MHD_NO; response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, IO_BLOCK_SIZE, &stream_reader, job, &stream_done); if (NULL == response) { /* No response object exists, so nobody will call stream_done() for us; drop both references by hand. The worker was never started. */ job_unref (job); job_unref (job); return MHD_NO; } if (MHD_NO == job_start (job)) { MHD_destroy_response (response); job_unref (job); return MHD_NO; } (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/event-stream"); (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CACHE_CONTROL, "no-cache"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Handle "GET /slow": the answer is only useful as a whole, so instead * of streaming we suspend the connection until the worker is done. * MHD then calls this function again---on its own thread---and that is * where the response is queued. #MHD_queue_response() is never called * from the worker. * * @param connection the connection to answer * @param req_cls the per-request pointer, holding our `struct Job` * @return #MHD_YES on success */ static enum MHD_Result handle_slow (struct MHD_Connection *connection, void **req_cls) { struct MHD_Response *response; struct Job *job = *req_cls; char answer[MAX_PAYLOAD]; size_t len; enum MHD_Result ret; if (NULL == job) { /* First call for this request: start the work and ask MHD to come back to us. */ job = job_create (connection, 0); if (NULL == job) return MHD_NO; if (MHD_NO == job_start (job)) { job_unref (job); job_unref (job); return MHD_NO; } *req_cls = job; return MHD_YES; } pthread_mutex_lock (&job->lock); if (0 == job->finished) { /* Still working. Park the connection; the worker resumes it when it is done, and MHD will then enter this function once more. */ job->suspended = 1; MHD_suspend_connection (connection); pthread_mutex_unlock (&job->lock); return MHD_YES; } len = job->fill - job->off; if (len > sizeof (answer)) len = sizeof (answer); memcpy (answer, &job->payload[job->off], len); pthread_mutex_unlock (&job->lock); response = MHD_create_response_from_buffer_copy (len, answer); if (NULL == response) return MHD_NO; (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/plain"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } /** * Queue a complete response that is already sitting in memory. * * @param connection the connection to answer * @param status the HTTP status code to use * @param mime the value for the "Content-Type" header * @param body the body to send * @return #MHD_YES on success */ static enum MHD_Result queue_static (struct MHD_Connection *connection, unsigned int status, const char *mime, const char *body) { struct MHD_Response *response; enum MHD_Result ret; response = MHD_create_response_from_buffer_copy (strlen (body), body); if (NULL == response) return MHD_NO; (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mime); (void) MHD_add_response_header (response, MHD_HTTP_HEADER_CACHE_CONTROL, "no-store"); ret = MHD_queue_response (connection, status, response); MHD_destroy_response (response); return ret; } static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) return MHD_NO; if (0 == strcmp (url, "/")) return queue_static (connection, MHD_HTTP_OK, "text/html", PAGE); if (0 == strcmp (url, "/fast")) return queue_static (connection, MHD_HTTP_OK, "text/plain", "pong\n"); if ( (0 == strcmp (url, "/events")) || (0 == strcmp (url, "/slow")) ) { if (0 != shutdown_requested) return queue_static (connection, MHD_HTTP_SERVICE_UNAVAILABLE, "text/plain", "shutting down\n"); if (0 == strcmp (url, "/events")) return handle_events (connection); return handle_slow (connection, req_cls); } return queue_static (connection, MHD_HTTP_NOT_FOUND, "text/plain", "not found\n"); } /** * Called by MHD when a request is done. For "/slow" this is where the * MHD side of the reference count is dropped; the other handlers leave * @a req_cls alone, so there is nothing to do for them. * * @param cls closure, unused * @param connection the connection that finished * @param req_cls the per-request pointer * @param toe why the request ended */ static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct Job *job = *req_cls; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) toe; /* Unused. Silent compiler warning. */ if (NULL == job) return; *req_cls = NULL; job_detach (job); } /** * Free every job that nobody references any more, joining its worker * on the way. Called from the main loop, and thus always from the * thread that also runs the daemon. */ static void reap_jobs (void) { struct Job *job; struct Job *next; unsigned int rc; pthread_mutex_lock (&jobs_lock); for (job = jobs_head; NULL != job; job = next) { next = job->next; pthread_mutex_lock (&job->lock); rc = job->rc; pthread_mutex_unlock (&job->lock); if (0 != rc) continue; if ( (0 != job->started) && (0 == job->joined) ) { pthread_join (job->tid, NULL); job->joined = 1; } if (NULL != job->prev) job->prev->next = job->next; else jobs_head = job->next; if (NULL != job->next) job->next->prev = job->prev; pthread_cond_destroy (&job->cond); pthread_mutex_destroy (&job->lock); free (job); } pthread_mutex_unlock (&jobs_lock); } /** * Ask every worker to stop and wait until they all did. * * This has to happen before the daemon is stopped: a worker that is * still asleep may be holding the only promise to resume a suspended * connection, and stopping a daemon that has suspended connections is * an API violation. Once every worker has returned, no connection can * be suspended any more, because the workers resume before they exit * and the content reader only ever suspends while a worker is running. */ static void stop_all_jobs (void) { struct Job *job; pthread_mutex_lock (&jobs_lock); for (job = jobs_head; NULL != job; job = job->next) { pthread_mutex_lock (&job->lock); job->stop = 1; pthread_cond_signal (&job->cond); pthread_mutex_unlock (&job->lock); } for (job = jobs_head; NULL != job; job = job->next) { if ( (0 != job->started) && (0 == job->joined) ) { pthread_join (job->tid, NULL); job->joined = 1; } } pthread_mutex_unlock (&jobs_lock); } /** * Number of connections the daemon is currently handling. * * @param daemon the daemon to query * @return the number of connections, 0 if it cannot be determined */ static unsigned int connection_count (struct MHD_Daemon *daemon) { const union MHD_DaemonInfo *info; info = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_CURRENT_CONNECTIONS); if (NULL == info) return 0; return info->num_connections; } int main (int argc, char *const *argv) { struct MHD_Daemon *daemon; const union MHD_DaemonInfo *info; struct sigaction sa; fd_set rs; fd_set ws; fd_set es; struct timeval tv; struct timeval *tvp; MHD_socket max; uint64_t mhd_timeout; unsigned long port = DEFAULT_PORT; unsigned int drained_ms = 0; char drain_buf[64]; int draining = 0; int ret = 0; if (1 < argc) port = strtoul (argv[1], NULL, 10); if (2 < argc) step_ms = (unsigned int) strtoul (argv[2], NULL, 10); if (3 < argc) total_steps = (unsigned int) strtoul (argv[3], NULL, 10); if ( (65535 < port) || (0 == total_steps) ) { fprintf (stderr, "Usage: %s [PORT [STEP_MS [STEPS]]]\n" "Pass 0 as PORT to let the system pick a free one.\n", argv[0]); return 1; } if (0 > pipe (wake_pipe)) { fprintf (stderr, "Failed to create wakeup pipe: %s\n", strerror (errno)); return 1; } memset (&sa, 0, sizeof (sa)); sa.sa_handler = &signal_handler; sigaction (SIGINT, &sa, NULL); sigaction (SIGTERM, &sa, NULL); sa.sa_handler = SIG_IGN; sigaction (SIGPIPE, &sa, NULL); /* No MHD_USE_INTERNAL_POLLING_THREAD: the loop below is ours. MHD_ALLOW_SUSPEND_RESUME implies MHD_USE_ITC, and that channel is what lets a worker thread break us out of the select() call. */ daemon = MHD_start_daemon (MHD_ALLOW_SUSPEND_RESUME | MHD_USE_ERROR_LOG, (uint16_t) port, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL, MHD_OPTION_END); if (NULL == daemon) { fprintf (stderr, "Failed to start daemon.\n"); return 1; } info = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_BIND_PORT); if ( (NULL == info) || (0 == info->port) ) { fprintf (stderr, "Failed to determine bound port.\n"); MHD_stop_daemon (daemon); return 1; } printf ("Listening on port %u\n", (unsigned int) info->port); fflush (stdout); while (1) { if ( (0 != shutdown_requested) && (0 == draining) ) { /* Every worker has to be gone before the daemon may be stopped. */ stop_all_jobs (); draining = 1; } if ( (0 != draining) && ( (0 == connection_count (daemon)) || (DRAIN_TIMEOUT_MS <= drained_ms) ) ) break; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); max = 0; if (MHD_YES != MHD_get_fdset (daemon, &rs, &ws, &es, &max)) { fprintf (stderr, "Failed to obtain the file descriptor set.\n"); ret = 1; break; } /* Our own descriptors go into the very same sets. */ FD_SET (wake_pipe[0], &rs); if (max < wake_pipe[0]) max = wake_pipe[0]; if (0 != draining) { /* Look at the drain deadline regularly. */ tv.tv_sec = 0; tv.tv_usec = 50 * 1000; tvp = &tv; drained_ms += 50; } else if (MHD_YES == MHD_get_timeout64 (daemon, &mhd_timeout)) { tv.tv_sec = (time_t) (mhd_timeout / 1000); tv.tv_usec = ((long) (mhd_timeout % 1000)) * 1000; tvp = &tv; } else { /* MHD has nothing to wait for. With every connection suspended this is the normal case, and the loop simply sleeps until a worker resumes one---which reaches us through MHD's ITC, as it is part of the read set above. */ tvp = NULL; } if (-1 == select ((int) max + 1, &rs, &ws, &es, tvp)) { if (EINTR == errno) continue; fprintf (stderr, "Aborting due to error during select: %s\n", strerror (errno)); ret = 1; break; } if (FD_ISSET (wake_pipe[0], &rs)) (void) read (wake_pipe[0], drain_buf, sizeof (drain_buf)); MHD_run_from_select (daemon, &rs, &ws, &es); reap_jobs (); } stop_all_jobs (); reap_jobs (); MHD_stop_daemon (daemon); close (wake_pipe[0]); close (wake_pipe[1]); return ret; }  File: libmicrohttpd-tutorial.info, Node: tlsauthentication.c, Next: upgrade.c, Prev: asyncresponse.c, Up: Example programs C.10 tlsauthentication.c ======================== /* Feel free to use this example code in any way you see fit (Public Domain) */ #include #ifndef _WIN32 #include #include #else #include #endif #include #include #include #include #define PORT 8888 #define REALM "Maintenance" #define USER "a legitimate user" #define PASSWORD "and his password" #define SERVERKEYFILE "server.key" #define SERVERCERTFILE "server.pem" static size_t get_file_size (const char *filename) { FILE *fp; fp = fopen (filename, "rb"); if (fp) { long size; if ((0 != fseek (fp, 0, SEEK_END)) || (-1 == (size = ftell (fp)))) size = 0; fclose (fp); return (size_t) size; } else return 0; } static char * load_file (const char *filename) { FILE *fp; char *buffer; size_t size; size = get_file_size (filename); if (0 == size) return NULL; fp = fopen (filename, "rb"); if (! fp) return NULL; buffer = malloc (size + 1); if (! buffer) { fclose (fp); return NULL; } buffer[size] = '\0'; if (size != fread (buffer, 1, size, fp)) { free (buffer); buffer = NULL; } fclose (fp); return buffer; } static enum MHD_Result ask_for_authentication (struct MHD_Connection *connection, const char *realm) { enum MHD_Result ret; struct MHD_Response *response; response = MHD_create_response_empty (MHD_RF_NONE); if (! response) return MHD_NO; ret = MHD_queue_basic_auth_required_response3 (connection, realm, MHD_YES, response); MHD_destroy_response (response); return ret; } static int is_authenticated (struct MHD_Connection *connection, const char *username, const char *password) { struct MHD_BasicAuthInfo *auth_info; int authenticated; auth_info = MHD_basic_auth_get_username_password3 (connection); if (NULL == auth_info) return 0; authenticated = ( (strlen (username) == auth_info->username_len) && (0 == memcmp (auth_info->username, username, auth_info->username_len)) && /* The next check against NULL is optional, * if 'password' is NULL then 'password_len' is always zero. */ (NULL != auth_info->password) && (strlen (password) == auth_info->password_len) && (0 == memcmp (auth_info->password, password, auth_info->password_len)) ); MHD_free (auth_info); return authenticated; } static enum MHD_Result secret_page (struct MHD_Connection *connection) { enum MHD_Result ret; struct MHD_Response *response; const char *page = "A secret."; response = MHD_create_response_from_buffer_static (strlen (page), page); if (! response) return MHD_NO; ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { (void) cls; /* Unused. Silent compiler warning. */ (void) url; /* Unused. Silent compiler warning. */ (void) version; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ if (0 != strcmp (method, "GET")) return MHD_NO; if (NULL == *req_cls) { *req_cls = connection; return MHD_YES; } if (! is_authenticated (connection, USER, PASSWORD)) return ask_for_authentication (connection, REALM); return secret_page (connection); } int main (void) { struct MHD_Daemon *daemon; char *key_pem; char *cert_pem; key_pem = load_file (SERVERKEYFILE); cert_pem = load_file (SERVERCERTFILE); if ((key_pem == NULL) || (cert_pem == NULL)) { printf ("The key/certificate files could not be read.\n"); if (NULL != key_pem) free (key_pem); if (NULL != cert_pem) free (cert_pem); return 1; } daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END); if (NULL == daemon) { printf ("%s\n", cert_pem); free (key_pem); free (cert_pem); return 1; } (void) getchar (); MHD_stop_daemon (daemon); free (key_pem); free (cert_pem); return 0; }  File: libmicrohttpd-tutorial.info, Node: upgrade.c, Prev: tlsauthentication.c, Up: Example programs C.11 upgrade.c ============== /* Feel free to use this example code in any way you see fit (Public Domain) */ /** * @file upgrade.c * @brief Minimal example for the HTTP "Upgrade" API of libmicrohttpd. * A "GET /" carrying "Connection: Upgrade" and "Upgrade: echo" * is answered with "101 Switching Protocols"; afterwards the * raw socket speaks a trivial line-based echo protocol until * the client sends the line "QUIT" or closes the connection. * @author Christian Grothoff */ #include #ifndef _WIN32 #include #include #include #else #include #endif #include #include #include #include #include #define PORT 8888 /** * Name of the protocol we are willing to switch to. Any name would * do; "echo" is not registered with IANA and is only used here to keep * the example self-contained. */ #define PROTOCOL "echo" /** * Maximum length of a line of the echo protocol. Longer lines are * truncated. */ #define LINE_SIZE 1024 #define PAGE_UPGRADE_REQUIRED \ "This resource speaks the \"" PROTOCOL "\" protocol only.\n" #define PAGE_NOT_FOUND \ "Not found.\n" /** * State of the line-based echo protocol for one connection. */ struct EchoState { /** * Bytes of the line received so far (without the line terminator). */ char line[LINE_SIZE]; /** * Number of valid bytes in @e line. */ size_t line_len; }; /** * Compare the first @a len bytes of @a a and @a b, ignoring case. * Only ASCII letters are folded, which is all HTTP tokens may contain. * * @param a first string * @param b second string * @param len number of bytes to compare * @return 1 if the strings match, 0 if they do not */ static int equal_caseless (const char *a, const char *b, size_t len) { size_t i; for (i = 0; i < len; i++) { char ca = a[i]; char cb = b[i]; if (('A' <= ca) && ('Z' >= ca)) ca = (char) (ca - 'A' + 'a'); if (('A' <= cb) && ('Z' >= cb)) cb = (char) (cb - 'A' + 'a'); if (ca != cb) return 0; } return 1; } /** * Check whether the comma-separated list @a value contains the token * @a token. Both the "Connection:" and the "Upgrade:" request header * fields are lists, so a client may legitimately send * "Connection: keep-alive, Upgrade"; a plain string comparison against * the whole field value would reject such a request. * * @param value the header field value, may be NULL * @param token the token to look for, compared case-insensitively * @return 1 if @a token is one of the tokens in @a value, 0 if not */ static int has_token (const char *value, const char *token) { const size_t token_len = strlen (token); const char *pos = value; if (NULL == value) return 0; while ('\0' != *pos) { const char *end; size_t len; /* skip separators and optional whitespace before the token */ while ((',' == *pos) || (' ' == *pos) || ('\t' == *pos)) pos++; end = pos; while (('\0' != *end) && (',' != *end)) end++; len = (size_t) (end - pos); /* strip optional whitespace after the token */ while ((0 != len) && ((' ' == pos[len - 1]) || ('\t' == pos[len - 1]))) len--; if ((len == token_len) && (equal_caseless (pos, token, token_len))) return 1; pos = end; if ('\0' != *pos) pos++; /* skip the comma */ } return 0; } /** * Send @a len bytes from @a buf over @a sock, retrying until either * everything was sent or the connection broke. * * @param sock the socket to write to * @param buf the data to send * @param len number of bytes in @a buf * @return 1 on success, 0 if the connection broke */ static int send_all (MHD_socket sock, const char *buf, size_t len) { ssize_t ret; size_t off; for (off = 0; off < len; off += (size_t) ret) { ret = send (sock, buf + off, (int) (len - off), 0); if (0 > ret) { if (EINTR == errno) { ret = 0; continue; } return 0; } if (0 == ret) return 0; } return 1; } /** * Make @a sock blocking. MHD hands out the socket in non-blocking * mode, see the tutorial chapter for the reason why. This function * contains the only operating-system-dependent code of this example. * * @param sock the socket to modify */ static void make_blocking (MHD_socket sock) { #ifndef _WIN32 int flags; flags = fcntl (sock, F_GETFL); if (-1 == flags) abort (); if ((flags & ~O_NONBLOCK) != flags) if (-1 == fcntl (sock, F_SETFL, flags & ~O_NONBLOCK)) abort (); #else /* _WIN32 */ unsigned long flags = 0; if (0 != ioctlsocket (sock, (int) FIONBIO, &flags)) abort (); #endif /* _WIN32 */ } /** * Feed @a size bytes of received data into the echo protocol state * machine, echoing back every complete line. * * @param sock the socket to echo to * @param es the protocol state of this connection * @param data the received bytes * @param size number of bytes in @a data * @return 1 if the client asked us to stop or the connection broke, * 0 if we should keep going */ static int echo_feed (MHD_socket sock, struct EchoState *es, const char *data, size_t size) { size_t i; for (i = 0; i < size; i++) { if ('\n' != data[i]) { if (es->line_len < sizeof (es->line)) es->line[es->line_len++] = data[i]; /* else: line too long, drop the excess bytes */ continue; } /* A complete line was received; drop the CR of a CRLF terminator */ if ((0 != es->line_len) && ('\r' == es->line[es->line_len - 1])) es->line_len--; if ((4 == es->line_len) && (equal_caseless (es->line, "QUIT", 4))) { (void) send_all (sock, "BYE\r\n", 5); es->line_len = 0; return 1; } if ((! send_all (sock, es->line, es->line_len)) || (! send_all (sock, "\r\n", 2))) return 1; es->line_len = 0; } return 0; } /** * Called by MHD once the "101 Switching Protocols" response was sent. * From here on MHD is out of the picture: @a sock is an ordinary * socket and we are free to speak whatever protocol we like on it. * * As the daemon runs with #MHD_USE_THREAD_PER_CONNECTION, this * function has a thread of its own and may block for as long as it * wants. * * @param cls closure given to #MHD_create_response_for_upgrade() * @param connection the original HTTP connection * @param req_cls last value of @a req_cls of the access handler * @param extra_in bytes the client sent after the request header and * which MHD read together with the header * @param extra_in_size number of bytes in @a extra_in * @param sock the socket to talk to the client on * @param urh handle to pass to #MHD_upgrade_action() */ static void upgrade_handler (void *cls, struct MHD_Connection *connection, void *req_cls, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) { struct EchoState es; char buf[256]; ssize_t got; int done; (void) cls; /* Unused. Silent compiler warning. */ (void) connection; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ /* MHD hands out a non-blocking socket; this example wants to use plain blocking recv()/send() calls on it. */ make_blocking (sock); es.line_len = 0; /* The client may have pipelined payload directly behind the request header, in which case MHD has read it already. Those bytes are gone from the socket, so they must be processed first. */ done = echo_feed (sock, &es, extra_in, extra_in_size); while (0 == done) { got = recv (sock, buf, sizeof (buf), 0); if (0 > got) { if (EINTR == errno) continue; break; /* read error */ } if (0 == got) break; /* client closed the connection */ done = echo_feed (sock, &es, buf, (size_t) got); } /* Hand the socket back to MHD. This is the only legal way to get rid of it; never call close() on it ourselves, and note that the connection is not cleaned up before this call happens. */ MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); } /** * Answer an ordinary HTTP request from a static string. * * @param connection the connection to answer * @param status_code the HTTP status code to use * @param page the response body * @param offer_upgrade if true, advertise our protocol in an * "Upgrade:" header field * @return #MHD_YES on success, #MHD_NO on error */ static enum MHD_Result answer_plain (struct MHD_Connection *connection, unsigned int status_code, const char *page, int offer_upgrade) { struct MHD_Response *response; enum MHD_Result ret; response = MHD_create_response_from_buffer_static (strlen (page), page); if (NULL == response) return MHD_NO; if (offer_upgrade) (void) MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, PROTOCOL); ret = MHD_queue_response (connection, status_code, response); MHD_destroy_response (response); return ret; } static enum MHD_Result access_handler (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; enum MHD_Result ret; (void) cls; /* Unused. Silent compiler warning. */ (void) upload_data; /* Unused. Silent compiler warning. */ (void) upload_data_size; /* Unused. Silent compiler warning. */ (void) req_cls; /* Unused. Silent compiler warning. */ if (0 != strcmp (url, "/")) return answer_plain (connection, MHD_HTTP_NOT_FOUND, PAGE_NOT_FOUND, 0); /* Upgrading requires HTTP/1.1 and a request that actually asks for our protocol. A client that does not ask gets a plain 426. */ if ((0 != strcmp (method, MHD_HTTP_METHOD_GET)) || (0 != strcmp (version, MHD_HTTP_VERSION_1_1)) || (! has_token (MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONNECTION), "Upgrade")) || (! has_token (MHD_lookup_connection_value (connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_UPGRADE), PROTOCOL))) return answer_plain (connection, MHD_HTTP_UPGRADE_REQUIRED, PAGE_UPGRADE_REQUIRED, 1); /* The request is fine, switch protocols. MHD already put "Connection: Upgrade" into the response for us, we only have to name the protocol we switch to. */ response = MHD_create_response_for_upgrade (&upgrade_handler, NULL); if (NULL == response) return MHD_NO; if (MHD_YES != MHD_add_response_header (response, MHD_HTTP_HEADER_UPGRADE, PROTOCOL)) { MHD_destroy_response (response); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_SWITCHING_PROTOCOLS, response); /* The response may be destroyed right away: MHD keeps its own reference until the upgrade handler has been called. */ MHD_destroy_response (response); return ret; } int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_ALLOW_UPGRADE | MHD_USE_ERROR_LOG, PORT, NULL, NULL, &access_handler, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; (void) getchar (); MHD_stop_daemon (daemon); return 0; }  Tag Table: Node: Top880 Node: Introduction2035 Node: Hello browser example3340 Node: Exploring requests15307 Node: Response headers20835 Node: Supporting basic authentication28169 Node: Processing POST data38545 Node: Improved processing of POST data47472 Node: Session management59717 Node: Generating responses on the fly63414 Node: Answering from another thread82089 Node: Adding a layer of security101122 Node: Upgrading connections116114 Node: Bibliography134581 Node: License text135901 Node: Example programs161060 Node: hellobrowser.c161430 Node: logging.c163561 Node: responseheaders.c165725 Node: basicauthentication.c169256 Node: simplepost.c173194 Node: largepost.c180403 Node: sessions.c191718 Node: callbackresponse.c219130 Node: asyncresponse.c228980 Node: tlsauthentication.c268825 Node: upgrade.c274892  End Tag Table  Local Variables: coding: utf-8 End: libmicrohttpd-1.0.10/doc/version.texi0000664000175000017500000000013715235437004013251 @set UPDATED 29 July 2026 @set UPDATED-MONTH July 2026 @set EDITION 1.0.10 @set VERSION 1.0.10 libmicrohttpd-1.0.10/doc/gpl-2.0.texi0000644000175000017500000004362714674632555012672 @c The GNU General Public License. @center Version 2, June 1991 @c This file is intended to be included within another document, @c hence no sectioning command or @node. @display Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @end display @heading Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software---to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. @heading TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION @enumerate 0 @item This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The ``Program'', below, refers to any such program or work, and a ``work based on the Program'' means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term ``modification''.) Each licensee is addressed as ``you''. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. @item You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. @item You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: @enumerate a @item You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. @item You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. @item If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) @end enumerate These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. @item You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: @enumerate a @item Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, @item Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, @item Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) @end enumerate The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. @item You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. @item You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. @item Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. @item If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. @item If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. @item The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and ``any later version'', you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. @item If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. @iftex @heading NO WARRANTY @end iftex @ifinfo @center NO WARRANTY @end ifinfo @item BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. @item IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. @end enumerate @iftex @heading END OF TERMS AND CONDITIONS @end iftex @ifinfo @center END OF TERMS AND CONDITIONS @end ifinfo @page @heading Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the ``copyright'' line and a pointer to where the full notice is found. @smallexample @var{one line to give the program's name and a brief idea of what it does.} Copyright (C) @var{yyyy} @var{name of author} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. @end smallexample Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: @smallexample Gnomovision version 69, Copyright (C) @var{year} @var{name of author} Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. @end smallexample The hypothetical commands @samp{show w} and @samp{show c} should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than @samp{show w} and @samp{show c}; they could even be mouse-clicks or menu items---whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a ``copyright disclaimer'' for the program, if necessary. Here is a sample; alter the names: @example Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. @var{signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice @end example This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. libmicrohttpd-1.0.10/doc/libmicrohttpd.info0000664000175000017500000071143515235437006014426 This is libmicrohttpd.info, produced by makeinfo version 7.1.1 from libmicrohttpd.texi. This manual is for GNU libmicrohttpd (version 1.0.10, 29 July 2026), a library for embedding an HTTP(S) server into C applications. Copyright © 2007-2019 Christian Grothoff Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". INFO-DIR-SECTION Software libraries START-INFO-DIR-ENTRY * libmicrohttpd: (libmicrohttpd). Embedded HTTP server library. END-INFO-DIR-ENTRY  File: libmicrohttpd.info, Node: Top, Next: microhttpd-intro, Up: (dir) The GNU libmicrohttpd Library ***************************** This manual is for GNU libmicrohttpd (version 1.0.10, 29 July 2026), a library for embedding an HTTP(S) server into C applications. Copyright © 2007-2019 Christian Grothoff Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". * Menu: * microhttpd-intro:: Introduction. * microhttpd-const:: Constants. * microhttpd-struct:: Structures type definition. * microhttpd-cb:: Callback functions definition. * microhttpd-init:: Starting and stopping the server. * microhttpd-inspect:: Implementing external ‘select’. * microhttpd-requests:: Handling requests. * microhttpd-responses:: Building responses to requests. * microhttpd-flow:: Flow control. * microhttpd-dauth:: Utilizing Authentication. * microhttpd-post:: Adding a ‘POST’ processor. * microhttpd-info:: Obtaining and modifying status information. * microhttpd-util:: Utilities. Appendices * GNU-LGPL:: The GNU Lesser General Public License says how you can copy and share almost all of 'libmicrohttpd'. * eCos License:: The eCos License says how you can copy and share some parts of 'libmicrohttpd'. * GNU-GPL:: The GNU General Public License (with eCos extension) says how you can copy and share some parts of 'libmicrohttpd'. * GNU-FDL:: The GNU Free Documentation License says how you can copy and share the documentation of 'libmicrohttpd'. Indices * Concept Index:: Index of concepts and programs. * Function and Data Index:: Index of functions, variables and data types. * Type Index:: Index of data types.  File: libmicrohttpd.info, Node: microhttpd-intro, Next: microhttpd-const, Prev: Top, Up: Top 1 Introduction ************** All symbols defined in the public API start with ‘MHD_’. MHD is a small HTTP daemon library. As such, it does not have any API for logging errors (you can only enable or disable logging to stderr). Also, it may not support all of the HTTP features directly, where applicable, portions of HTTP may have to be handled by clients of the library. The library is supposed to handle everything that it must handle (because the API would not allow clients to do this), such as basic connection management. However, detailed interpretations of headers, such as range requests, are left to the main application. In particular, if an application developer wants to support range requests, he needs to explicitly indicate support in responses and also explicitly parse the range header and generate a response (for example, using the ‘MHD_create_response_from_fd_at_offset’ call to serve ranges from a file). MHD does understands headers that control connection management (specifically, ‘Connection: close’ and ‘Expect: 100 continue’ are understood and handled automatically). ‘Connection: upgrade’ is supported by passing control over the socket (or something that behaves like the real socket in the case of TLS) to the application (after sending the desired HTTP response header). MHD largely ignores the semantics of the different HTTP methods, so clients are left to handle those. One exception is that MHD does understand ‘HEAD’ and will only send the headers of the response and not the body, even if the client supplied a body. (In fact, clients do need to construct a response with the correct length, even for ‘HEAD’ request.) MHD understands ‘POST’ data and is able to decode certain formats (at the moment only ‘application/x-www-form-urlencoded’ and ‘multipart/form-data’) using the post processor API. The data stream of a POST is also provided directly to the main application, so unsupported encodings could still be processed, just not conveniently by MHD. The header file defines various constants used by the HTTP protocol. This does not mean that MHD actually interprets all of these values. The provided constants are exported as a convenience for users of the library. MHD does not verify that transmitted HTTP headers are part of the standard specification; users of the library are free to define their own extensions of the HTTP standard and use those with MHD. All functions are guaranteed to be completely reentrant and thread-safe. MHD checks for allocation failures and tries to recover gracefully (for example, by closing the connection). Additionally, clients can specify resource limits on the overall number of connections, number of connections per IP address and memory used per connection to avoid resource exhaustion. 1.1 Scope ========= MHD is currently used in a wide range of implementations. Examples based on reports we've received from developers include: • Embedded HTTP server on a cortex M3 (128 KB code space) • Large-scale multimedia server (reportedly serving at the simulator limit of 7.5 GB/s) • Administrative console (via HTTP/HTTPS) for network appliances 1.2 Thread modes and event loops ================================ MHD supports four basic thread modes and up to three event loop styles. The four basic thread modes are external sockets polling (MHD creates no threads, event loop is fully managed by the application), internal polling (MHD creates one thread for all connections), polling in thread pool (MHD creates a thread pool which is used to process all connections) and thread-per-connection (MHD creates one thread for listen sockets and then one thread per accepted connection). These thread modes are then combined with the evet loop styles (polling function type). MHD support select, poll and epoll. select is available on all platforms, epoll and poll may not be available on some platforms. Note that it is possible to combine MHD using epoll with an external select-based event loop. The default (if no other option is passed) is "external select". The highest performance can typically be obtained with a thread pool using ‘epoll’. Apache Benchmark (ab) was used to compare the performance of ‘select’ and ‘epoll’ when using a thread pool and a large number of connections. *note Figure 1.1: fig:performance. shows the resulting plot from the ‘benchmark.c’ example, which measures the latency between an incoming request and the completion of the transmission of the response. In this setting, the ‘epoll’ thread pool with four threads was able to handle more than 45,000 connections per second on loopback (with Apache Benchmark running three processes on the same machine). [image src="libmicrohttpd_performance_data.png" alt="Data"] Figure 1.1: Performance measurements for select vs. epoll (with thread-pool). Not all combinations of thread modes and event loop styles are supported. This is partially to keep the API simple, and partially because some combinations simply make no sense as others are strictly superior. Note that the choice of style depends first of all on the application logic, and then on the performance requirements. Applications that perform a blocking operation while handling a request within the callbacks from MHD must use a thread per connection. This is typically rather costly. Applications that do not support threads or that must run on embedded devices without thread-support must use the external mode. Using ‘epoll’ is only supported on some platform, thus portable applications must at least have a fallback option available. *note Table 1.1: tbl:supported. lists the sane combinations. select poll epoll external yes no yes internal yes yes yes thread pool yes yes yes thread-per-connection yes yes no Table 1.1: Supported combinations of event styles and thread modes. 1.3 Compiling GNU libmicrohttpd =============================== MHD uses the standard GNU system where the usual build process involves running $ ./configure $ make $ make install MHD supports various options to be given to configure to tailor the binary to a specific situation. Note that some of these options will remove portions of the MHD code that are required for binary-compatibility. They should only be used on embedded systems with tight resource constraints and no concerns about library versioning. Standard distributions including MHD are expected to always ship with all features enabled, otherwise unexpected incompatibilities can arise! Here is a list of MHD-specific options that can be given to configure (canonical configure options such as "-prefix" are also supported, for a full list of options run "./configure -help"): ‘``--disable-curl''’ disable running testcases using libcurl ‘``--disable-largefile''’ disable support for 64-bit files ‘``--disable-messages''’ disable logging of error messages (smaller binary size, not so much fun for debugging) ‘``--disable-https''’ disable HTTPS support, even if GNUtls is found; this option must be used if eCOS license is desired as an option (in all cases the resulting binary falls under a GNU LGPL-only license) ‘``--disable-postprocessor''’ do not include the post processor API (results in binary incompatibility) ‘``--disable-dauth''’ do not include the authentication APIs (results in binary incompatibility) ‘``--disable-httpupgrade''’ do not build code for HTTP "Upgrade" (smaller binary size, binary incompatible library) ‘``--disable-epoll''’ do not include epoll support, even if it supported (minimally smaller binary size, good for portability testing) ‘``--enable-coverage''’ set flags for analysis of code-coverage with gcc/gcov (results in slow, large binaries) ‘``--with-threads=posix,w32,none,auto''’ sets threading library to use. With use "none" to not support threads. In this case, MHD will only support the "external" threading modes and not perform any locking of data structures! Use ‘MHD_is_feature_supported(MHD_FEATURE_THREADS)’ to test if threads are available. Default is "auto". ‘``--with-gcrypt=PATH''’ specifies path to libgcrypt installation ‘``--with-gnutls=PATH''’ specifies path to libgnutls installation To cross-compile MHD for Android, install the Android NDK and use: ./configure --target=arm-linux-androideabi --host=arm-linux-androideabi --disable-doc --disable-examples make Similar build commands should work for cross-compilation to other platforms. Note that you may have to first cross-compile GnuTLS to get MHD with TLS support. 1.4 Validity of pointers ======================== MHD will give applications access to its internal data structures via pointers via arguments and return values from its API. This creates the question as to how long those pointers are assured to stay valid. Most MHD data structures are associated with the connection of an HTTP client. Thus, pointers associated with a connection are typically valid until the connection is finished, at which point MHD will call the ‘MHD_RequestCompletedCallback’ if one is registered. Applications that have such a callback registered may assume that keys and values from the ‘MHD_KeyValueIterator’, return values from ‘MHD_lookup_connection_value’ and the ‘url’, ‘method’ and ‘version’ arguments to the ‘MHD_AccessHandlerCallback’ will remain valid until the respective ‘MHD_RequestCompletedCallback’ is invoked. In contrast, the ‘upload_data’ argument of ‘MHD_RequestCompletedCallback’ as well as all pointers from the ‘MHD_PostDataIterator’ are only valid for the duration of the callback. Pointers returned from ‘MHD_get_response_header’ are valid as long as the response itself is valid. 1.5 Including the microhttpd.h header ===================================== Ideally, before including "microhttpd.h" you should add the necessary includes to define the ‘va_list’, ‘size_t’, ‘ssize_t’, ‘intptr_t’, ‘off_t’, ‘uint8_t’, ‘uint16_t’, ‘int32_t’, ‘uint32_t’, ‘int64_t’, ‘uint64_t’, ‘fd_set’, ‘socklen_t’ and ‘struct sockaddr’ data types. Which specific headers are needed may depend on your platform and your build system might include some tests to provide you with the necessary conditional operations. For possible suggestions consult ‘platform.h’ and ‘configure.ac’ in the MHD distribution. Once you have ensured that you manually (!) included the right headers for your platform before "microhttpd.h", you should also add a line with ‘#define MHD_PLATFORM_H’ which will prevent the "microhttpd.h" header from trying (and, depending on your platform, failing) to include the right headers. If you do not define MHD_PLATFORM_H, the "microhttpd.h" header will automatically include headers needed on GNU/Linux systems (possibly causing problems when porting to other platforms). 1.6 SIGPIPE =========== MHD does not install a signal handler for SIGPIPE. On platforms where this is possible (such as GNU/Linux), it disables SIGPIPE for its I/O operations (by passing MSG_NOSIGNAL or similar). On other platforms, SIGPIPE signals may be generated from network operations by MHD and will cause the process to die unless the developer explicitly installs a signal handler for SIGPIPE. Hence portable code using MHD must install a SIGPIPE handler or explicitly block the SIGPIPE signal. MHD does not do so in order to avoid messing with other parts of the application that may need to handle SIGPIPE in a particular way. You can make your application handle SIGPIPE by calling the following function in ‘main’: static void catcher (int sig) { } static void ignore_sigpipe () { struct sigaction oldsig; struct sigaction sig; sig.sa_handler = &catcher; sigemptyset (&sig.sa_mask); #ifdef SA_INTERRUPT sig.sa_flags = SA_INTERRUPT; /* SunOS */ #else sig.sa_flags = SA_RESTART; #endif if (0 != sigaction (SIGPIPE, &sig, &oldsig)) fprintf (stderr, "Failed to install SIGPIPE handler: %s\n", strerror (errno)); } 1.7 MHD_UNSIGNED_LONG_LONG ========================== Some platforms do not support ‘long long’. Hence MHD defines a macro ‘MHD_UNSIGNED LONG_LONG’ which will default to ‘unsigned long long’. For standard desktop operating systems, this is all you need to know. However, if your platform does not support ‘unsigned long long’, you should change "platform.h" to define ‘MHD_LONG_LONG’ and ‘MHD_UNSIGNED_LONG_LONG’ to an appropriate alternative type and also define ‘MHD_LONG_LONG_PRINTF’ and ‘MHD_UNSIGNED_LONG_LONG_PRINTF’ to the corresponding format string for printing such a data type. Note that the "signed" versions are deprecated. Also, for historical reasons, ‘MHD_LONG_LONG_PRINTF’ is without the percent sign, whereas ‘MHD_UNSIGNED_LONG_LONG_PRINTF’ is with the percent sign. Newly written code should only use the unsigned versions. However, you need to define both in "platform.h" if you need to change the definition for the specific platform. 1.8 Portability to W32 ====================== libmicrohttpd in general ported well to W32. Most libmicrohttpd features are supported. W32 do not support some functions, like epoll and corresponding MHD features are not available on W32. 1.9 Portability to z/OS ======================= To compile MHD on z/OS, extract the archive and run iconv -f UTF-8 -t IBM-1047 contrib/ascebc > /tmp/ascebc.sh chmod +x /tmp/ascebc.sh for n in `find * -type f` do /tmp/ascebc.sh $n done to convert all source files to EBCDIC. Note that you must run ‘configure’ from the directory where the configure script is located. Otherwise, configure will fail to find the ‘contrib/xcc’ script (which is a wrapper around the z/OS c89 compiler).  File: libmicrohttpd.info, Node: microhttpd-const, Next: microhttpd-struct, Prev: microhttpd-intro, Up: Top 2 Constants *********** -- Enumeration: MHD_FLAG Options for the MHD daemon. Note that MHD will run automatically in background thread(s) only if ‘MHD_USE_INTERNAL_POLLING_THREAD’ is used. Otherwise caller (application) must use ‘MHD_run’ or ‘MHD_run_from_select’ to have MHD processed network connections and data. Starting the daemon may also fail if a particular option is not implemented or not supported on the target platform (i.e. no support for TLS, threads or IPv6). TLS support generally depends on options given during MHD compilation. ‘MHD_NO_FLAG’ No options selected. ‘MHD_USE_ERROR_LOG’ If this flag is used, the library should print error messages and warnings to stderr (or to custom error printer if it's specified by options). Note that for this run-time option to have any effect, MHD needs to be compiled with messages enabled. This is done by default except you ran configure with the ‘--disable-messages’ flag set. ‘MHD_USE_DEBUG’ Currently the same as ‘MHD_USE_ERROR_LOG’. ‘MHD_USE_TLS’ Run in HTTPS-mode. If you specify ‘MHD_USE_TLS’ and MHD was compiled without SSL support, ‘MHD_start_daemon’ will return NULL. ‘MHD_USE_THREAD_PER_CONNECTION’ Run using one thread per connection. ‘MHD_USE_INTERNAL_POLLING_THREAD’ Run using an internal thread doing ‘SELECT’. ‘MHD_USE_IPv6’ Run using the IPv6 protocol (otherwise, MHD will just support IPv4). If you specify ‘MHD_USE_IPV6’ and the local platform does not support it, ‘MHD_start_daemon’ will return NULL. If you want MHD to support IPv4 and IPv6 using a single socket, pass MHD_USE_DUAL_STACK, otherwise, if you only pass this option, MHD will try to bind to IPv6-only (resulting in no IPv4 support). ‘MHD_USE_DUAL_STACK’ Use a single socket for IPv4 and IPv6. Note that this will mean that IPv4 addresses are returned by MHD in the IPv6-mapped format (the 'struct sockaddr_in6' format will be used for IPv4 and IPv6). ‘MHD_USE_PEDANTIC_CHECKS’ Deprecated (use ‘MHD_OPTION_STRICT_FOR_CLIENT’). Be pedantic about the protocol. Specifically, at the moment, this flag causes MHD to reject HTTP 1.1 connections without a ‘Host’ header. This is required by the standard, but of course in violation of the "be as liberal as possible in what you accept" norm. It is recommended to turn this *ON* if you are testing clients against MHD, and *OFF* in production. ‘MHD_USE_POLL’ Use ‘poll()’ instead of ‘select()’. This allows sockets with descriptors ‘>= FD_SETSIZE’. This option currently only works in conjunction with ‘MHD_USE_INTERNAL_POLLING_THREAD’ (at this point). If you specify ‘MHD_USE_POLL’ and the local platform does not support it, ‘MHD_start_daemon’ will return NULL. ‘MHD_USE_EPOLL’ Use ‘epoll()’ instead of ‘poll()’ or ‘select()’. This allows sockets with descriptors ‘>= FD_SETSIZE’. This option is only available on some systems and does not work in conjunction with ‘MHD_USE_THREAD_PER_CONNECTION’ (at this point). If you specify ‘MHD_USE_EPOLL’ and the local platform does not support it, ‘MHD_start_daemon’ will return NULL. Using ‘epoll()’ instead of ‘select()’ or ‘poll()’ can in some situations result in significantly higher performance as the system call has fundamentally lower complexity (O(1) for ‘epoll()’ vs. O(n) for ‘select()’/‘poll()’ where n is the number of open connections). ‘MHD_USE_TURBO’ Enable optimizations to aggressively improve performance. Currently, the optimizations this option enables are based on opportunistic reads and writes. Basically, MHD will simply try to read or write or accept on a socket before checking that the socket is ready for IO using the event loop mechanism. As the sockets are non-blocking, this may fail (at a loss of performance), but generally MHD does this in situations where the operation is likely to succeed, in which case performance is improved. Setting the flag should generally be safe (even though the code is slightly more experimental). You may want to benchmark your application to see if this makes any difference for you. ‘MHD_USE_SUPPRESS_DATE_NO_CLOCK’ Suppress (automatically) adding the 'Date:' header to HTTP responses. This option should ONLY be used on systems that do not have a clock and that DO provide other mechanisms for cache control. See also RFC 2616, section 14.18 (exception 3). ‘MHD_USE_NO_LISTEN_SOCKET’ Run the HTTP server without any listen socket. This option only makes sense if ‘MHD_add_connection’ is going to be used exclusively to connect HTTP clients to the HTTP server. This option is incompatible with using a thread pool; if it is used, ‘MHD_OPTION_THREAD_POOL_SIZE’ is ignored. ‘MHD_USE_ITC’ Force MHD to use a signal inter-thread communication channel to notify the event loop (of threads) of our shutdown and other events. This is required if an application uses ‘MHD_USE_INTERNAL_POLLING_THREAD’ and then performs ‘MHD_quiesce_daemon’ (which eliminates our ability to signal termination via the listen socket). In these modes, ‘MHD_quiesce_daemon’ will fail if this option was not set. Also, use of this option is automatic (as in, you do not even have to specify it), if ‘MHD_USE_NO_LISTEN_SOCKET’ is specified. In "external" select mode, this option is always simply ignored. Using this option also guarantees that MHD will not call ‘shutdown()’ on the listen socket, which means a parent process can continue to use the socket. ‘MHD_ALLOW_SUSPEND_RESUME’ Enables using ‘MHD_suspend_connection’ and ‘MHD_resume_connection’, as performing these calls requires some additional inter-thred communication channels to be created, and code not using these calls should not pay the cost. ‘MHD_USE_TCP_FASTOPEN’ Enable TCP_FASTOPEN on the listen socket. TCP_FASTOPEN is currently supported on Linux >= 3.6. On other systems using this option with cause ‘MHD_start_daemon’ to fail. ‘MHD_ALLOW_UPGRADE’ This option must be set if you want to upgrade connections (via "101 Switching Protocols" responses). This requires MHD to allocate additional resources, and hence we require this special flag so we only use the resources that are really needed. ‘MHD_USE_AUTO’ Automatically select best event loop style (polling function) depending on requested mode by other MHD flags and functions available on platform. If application doesn't have requirements for any specific polling function, it's recommended to use this flag. This flag is very convenient for multiplatform applications. ‘MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT’ Tell the TLS library to support post handshake client authentication. Only useful in combination with ‘MHD_USE_TLS’. This option will only work if the underlying TLS library supports it (i.e. GnuTLS after 3.6.3). If the TLS library does not support it, MHD may ignore the option and proceed without supporting this features. ‘MHD_USE_INSECURE_TLS_EARLY_DATA’ Tell the TLS library to support TLS v1.3 early data (0-RTT) with the resulting security drawbacks. Only enable this if you really know what you are doing. MHD currently does NOT enforce that this only affects GET requests! You have been warned. This option will only work if the underlying TLS library supports it (i.e. GnuTLS after 3.6.3). If the TLS library does not support it, MHD may ignore the option and proceed without supporting this features. -- Enumeration: MHD_OPTION MHD options. Passed in the varargs portion of ‘MHD_start_daemon()’. ‘MHD_OPTION_END’ No more options / last option. This is used to terminate the VARARGs list. ‘MHD_OPTION_CONNECTION_MEMORY_LIMIT’ Maximum memory size per connection (followed by a ‘size_t’). The default is 32 kB (32*1024 bytes) as defined by the internal constant ‘MHD_POOL_SIZE_DEFAULT’. Values above 128k are unlikely to result in much benefit, as half of the memory will be typically used for IO, and TCP buffers are unlikely to support window sizes above 64k on most systems. ‘MHD_OPTION_CONNECTION_MEMORY_INCREMENT’ Increment to use for growing the read buffer (followed by a ‘size_t’). The default is 1024 (bytes). Increasing this value will make MHD use memory for reading more aggressively, which can reduce the number of ‘recvfrom’ calls but may increase the number of ‘sendto’ calls. The given value must fit within MHD_OPTION_CONNECTION_MEMORY_LIMIT. ‘MHD_OPTION_CONNECTION_LIMIT’ Maximum number of concurrent connections to accept (followed by an ‘unsigned int’). The default is ‘FD_SETSIZE - 4’ (the maximum number of file descriptors supported by ‘select’ minus four for ‘stdin’, ‘stdout’, ‘stderr’ and the server socket). In other words, the default is as large as possible. If the connection limit is reached, MHD's behavior depends a bit on other options. If ‘MHD_USE_ITC’ was given, MHD will stop accepting connections on the listen socket. This will cause the operating system to queue connections (up to the ‘listen()’ limit) above the connection limit. Those connections will be held until MHD is done processing at least one of the active connections. If ‘MHD_USE_ITC’ is not set, then MHD will continue to ‘accept()’ and immediately ‘close()’ these connections. Note that if you set a low connection limit, you can easily get into trouble with browsers doing request pipelining. For example, if your connection limit is "1", a browser may open a first connection to access your "index.html" file, keep it open but use a second connection to retrieve CSS files, images and the like. In fact, modern browsers are typically by default configured for up to 15 parallel connections to a single server. If this happens, MHD will refuse to even accept the second connection until the first connection is closed -- which does not happen until timeout. As a result, the browser will fail to render the page and seem to hang. If you expect your server to operate close to the connection limit, you should first consider using a lower timeout value and also possibly add a "Connection: close" header to your response to ensure that request pipelining is not used and connections are closed immediately after the request has completed: MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "close"); ‘MHD_OPTION_CONNECTION_TIMEOUT’ After how many seconds of inactivity should a connection automatically be timed out? (followed by an ‘unsigned int’; use zero for no timeout). The default is zero (no timeout). ‘MHD_OPTION_NOTIFY_COMPLETED’ Register a function that should be called whenever a request has been completed (this can be used for application-specific clean up). Requests that have never been presented to the application (via ‘MHD_AccessHandlerCallback()’) will not result in notifications. This option should be followed by *TWO* pointers. First a pointer to a function of type ‘MHD_RequestCompletedCallback()’ and second a pointer to a closure to pass to the request completed callback. The second pointer maybe ‘NULL’. ‘MHD_OPTION_NOTIFY_CONNECTION’ Register a function that should be called when the TCP connection to a client is opened or closed. The registered callback is called twice per TCP connection, with ‘MHD_CONNECTION_NOTIFY_STARTED’ and ‘MHD_CONNECTION_NOTIFY_CLOSED’ respectively. An additional argument can be used to store TCP connection specific information, which can be retrieved using ‘MHD_CONNECTION_INFO_SOCKET_CONTEXT’ during the lifetime of the TCP connection. Note ‘MHD_OPTION_NOTIFY_COMPLETED’ and the ‘req_cls’ argument to the ‘MHD_AccessHandlerCallback’ are per HTTP request (and there can be multiple HTTP requests per TCP connection). This option should be followed by *TWO* pointers. First a pointer to a function of type ‘MHD_NotifyConnectionCallback()’ and second a pointer to a closure to pass to the request completed callback. The second pointer maybe ‘NULL’. ‘MHD_OPTION_PER_IP_CONNECTION_LIMIT’ Limit on the number of (concurrent) connections made to the server from the same IP address. Can be used to prevent one IP from taking over all of the allowed connections. If the same IP tries to establish more than the specified number of connections, they will be immediately rejected. The option should be followed by an ‘unsigned int’. The default is zero, which means no limit on the number of connections from the same IP address. ‘MHD_OPTION_LISTEN_BACKLOG_SIZE’ Set the size of the ‘listen()’ back log queue of the TCP socket. Takes an ‘unsigned int’ as the argument. Default is the platform-specific value of ‘SOMAXCONN’. ‘MHD_OPTION_STRICT_FOR_CLIENT’ Specify how strict we should enforce the HTTP protocol. Takes an ‘int’ as the argument. Default is zero. If set to 1, MHD will be strict about the protocol. Specifically, at the moment, this flag uses MHD to reject HTTP 1.1 connections without a "Host" header. This is required by the standard, but of course in violation of the "be as liberal as possible in what you accept" norm. It is recommended to set this to 1 if you are testing clients against MHD, and 0 in production. If set to -1 MHD will be permissive about the protocol, allowing slight deviations that are technically not allowed by the RFC. Specifically, at the moment, this flag causes MHD to allow spaces in header field names. This is disallowed by the standard. It is not recommended to set it to -1 on publicly available servers as it may potentially lower level of protection. ‘MHD_OPTION_SERVER_INSANITY’ Allows the application to disable certain sanity precautions in MHD. With these, the client can break the HTTP protocol, so this should never be used in production. The options are, however, useful for testing HTTP clients against "broken" server implementations. This argument must be followed by an ‘unsigned int’, corresponding to an ‘enum MHD_DisableSanityCheck’. Right now, no sanity checks can be disabled. ‘MHD_OPTION_SOCK_ADDR’ Bind daemon to the supplied socket address. This option should be followed by a ‘struct sockaddr *’. If ‘MHD_USE_IPv6’ is specified, the ‘struct sockaddr*’ should point to a ‘struct sockaddr_in6’, otherwise to a ‘struct sockaddr_in’. If this option is not specified, the daemon will listen to incoming connections from anywhere. If you use this option, the 'port' argument from ‘MHD_start_daemon’ is ignored and the port from the given ‘struct sockaddr *’ will be used instead. ‘MHD_OPTION_URI_LOG_CALLBACK’ Specify a function that should be called before parsing the URI from the client. The specified callback function can be used for processing the URI (including the options) before it is parsed. The URI after parsing will no longer contain the options, which maybe inconvenient for logging. This option should be followed by two arguments, the first one must be of the form void * my_logger(void * cls, const char * uri, struct MHD_Connection *con) where the return value will be passed as ‘*req_cls’ in calls to the ‘MHD_AccessHandlerCallback’ when this request is processed later; returning a value of ‘NULL’ has no special significance; (however, note that if you return non-‘NULL’, you can no longer rely on the first call to the access handler having ‘NULL == *req_cls’ on entry) ‘cls’ will be set to the second argument following MHD_OPTION_URI_LOG_CALLBACK. Finally, ‘uri’ will be the 0-terminated URI of the request. Note that during the time of this call, most of the connection's state is not initialized (as we have not yet parsed he headers). However, information about the connecting client (IP, socket) is available. ‘MHD_OPTION_HTTPS_MEM_KEY’ Memory pointer to the private key to be used by the HTTPS daemon. This option should be followed by an "const char*" argument. This should be used in conjunction with 'MHD_OPTION_HTTPS_MEM_CERT'. ‘MHD_OPTION_HTTPS_KEY_PASSWORD’ Memory pointer to the password that decrypts the private key to be used by the HTTPS daemon. This option should be followed by an "const char*" argument. This should be used in conjunction with 'MHD_OPTION_HTTPS_MEM_KEY'. The password (or passphrase) is only used immediately during ‘MHD_start_daemon()’. Thus, the application may want to erase it from memory afterwards for additional security. ‘MHD_OPTION_HTTPS_MEM_CERT’ Memory pointer to the certificate to be used by the HTTPS daemon. This option should be followed by an "const char*" argument. This should be used in conjunction with 'MHD_OPTION_HTTPS_MEM_KEY'. ‘MHD_OPTION_HTTPS_MEM_TRUST’ Memory pointer to the CA certificate to be used by the HTTPS daemon to authenticate and trust clients certificates. This option should be followed by an "const char*" argument. The presence of this option activates the request of certificate to the client. The request to the client is marked optional, and it is the responsibility of the server to check the presence of the certificate if needed. Note that most browsers will only present a client certificate only if they have one matching the specified CA, not sending any certificate otherwise. ‘MHD_OPTION_HTTPS_CRED_TYPE’ Daemon credentials type. Either certificate or anonymous, this option should be followed by one of the values listed in "enum gnutls_credentials_type_t". ‘MHD_OPTION_HTTPS_PRIORITIES’ SSL/TLS protocol version and ciphers. This option must be followed by an "const char *" argument specifying the SSL/TLS protocol versions and ciphers that are acceptable for the application. The string is passed unchanged to gnutls_priority_init. If this option is not specified, "NORMAL" is used. ‘MHD_OPTION_HTTPS_CERT_CALLBACK’ Use a callback to determine which X.509 certificate should be used for a given HTTPS connection. This option should be followed by a argument of type "gnutls_certificate_retrieve_function2 *". This option provides an alternative to MHD_OPTION_HTTPS_MEM_KEY and MHD_OPTION_HTTPS_MEM_CERT. You must use this version if multiple domains are to be hosted at the same IP address using TLS's Server Name Indication (SNI) extension. In this case, the callback is expected to select the correct certificate based on the SNI information provided. The callback is expected to access the SNI data using gnutls_server_name_get(). Using this option requires GnuTLS 3.0 or higher. ‘MHD_OPTION_HTTPS_CERT_CALLBACK2’ Use a callback to determine which X.509 certificate should be used for a given HTTPS connection. This option should be followed by a argument of type 'gnutls_certificate_retrieve_function3 *'. This option provides an alternative/extension to #MHD_OPTION_HTTPS_CERT_CALLBACK. You must use this version if you want to use OCSP stapling. Using this option requires GnuTLS 3.6.3 or higher. ‘MHD_OPTION_GNUTLS_PSK_CRED_HANDLER’ Use pre-shared key for TLS credentials. Pass a pointer to callback of type ‘MHD_PskServerCredentialsCallback’ and a closure. The function will be called to retrieve the shared key for a given username. The key must be at least 16 bytes long, as required by RFC 4279 section 7.1; MHD fails the authentication for a shorter one. ‘MHD_OPTION_DIGEST_AUTH_RANDOM’ Digest Authentication nonce's seed. This option should be followed by two arguments. First an integer of type "size_t" which specifies the size of the buffer pointed to by the second argument in bytes. Note that the application must ensure that the buffer of the second argument remains allocated and unmodified while the daemon is running. For security, you SHOULD provide a fresh random nonce when using MHD with Digest Authentication. ‘MHD_OPTION_NONCE_NC_SIZE’ Size of an array of nonce and nonce counter map. This option must be followed by an "unsigned int" argument that have the size (number of elements) of a map of a nonce and a nonce-counter. If this option is not specified, a default value of 4 will be used (which might be too small for servers handling many requests). If you do not use digest authentication at all, you can specify a value of zero to save some memory. You should calculate the value of NC_SIZE based on the number of connections per second multiplied by your expected session duration plus a factor of about two for hash table collisions. For example, if you expect 100 digest-authenticated connections per second and the average user to stay on your site for 5 minutes, then you likely need a value of about 60000. On the other hand, if you can only expect only 10 digest-authenticated connections per second, tolerate browsers getting a fresh nonce for each request and expect a HTTP request latency of 250 ms, then a value of about 5 should be fine. ‘MHD_OPTION_LISTEN_SOCKET’ Listen socket to use. Pass a listen socket for MHD to use (systemd-style). If this option is used, MHD will not open its own listen socket(s). The argument passed must be of type "int" and refer to an existing socket that has been bound to a port and is listening. ‘MHD_OPTION_EXTERNAL_LOGGER’ Use the given function for logging error messages. This option must be followed by two arguments; the first must be a pointer to a function of type 'void fun(void * arg, const char * fmt, va_list ap)' and the second a pointer of type 'void*' which will be passed as the "arg" argument to "fun". Note that MHD will not generate any log messages without the MHD_USE_ERROR_LOG flag set and if MHD was compiled with the "-disable-messages" flag. ‘MHD_OPTION_THREAD_POOL_SIZE’ Number (unsigned int) of threads in thread pool. Enable thread pooling by setting this value to to something greater than 1. Currently, thread mode must be MHD_USE_INTERNAL_POLLING_THREAD if thread pooling is enabled (‘MHD_start_daemon’ returns ‘NULL’ for an unsupported thread mode). ‘MHD_OPTION_ARRAY’ This option can be used for initializing MHD using options from an array. A common use for this is writing an FFI for MHD. The actual options given are in an array of 'struct MHD_OptionItem', so this option requires a single argument of type 'struct MHD_OptionItem'. The array must be terminated with an entry ‘MHD_OPTION_END’. An example for code using MHD_OPTION_ARRAY is: struct MHD_OptionItem ops[] = { { MHD_OPTION_CONNECTION_LIMIT, 100, NULL }, { MHD_OPTION_CONNECTION_TIMEOUT, 10, NULL }, { MHD_OPTION_END, 0, NULL } }; d = MHD_start_daemon(0, 8080, NULL, NULL, dh, NULL, MHD_OPTION_ARRAY, ops, MHD_OPTION_END); For options that expect a single pointer argument, the second member of the ‘struct MHD_OptionItem’ is ignored. For options that expect two pointer arguments, the first argument must be cast to ‘intptr_t’. ‘MHD_OPTION_UNESCAPE_CALLBACK’ Specify a function that should be called for unescaping escape sequences in URIs and URI arguments. Note that this function will NOT be used by the MHD_PostProcessor. If this option is not specified, the default method will be used which decodes escape sequences of the form "%HH". This option should be followed by two arguments, the first one must be of the form size_t my_unescaper(void * cls, struct MHD_Connection *c, char *s) where the return value must be ‘strlen(s)’ and ‘s’ should be updated. Note that the unescape function must not lengthen ‘s’ (the result must be shorter than the input and still be 0-terminated). ‘cls’ will be set to the second argument following MHD_OPTION_UNESCAPE_CALLBACK. ‘MHD_OPTION_THREAD_STACK_SIZE’ Maximum stack size for threads created by MHD. This option must be followed by a ‘size_t’). Not specifying this option or using a value of zero means using the system default (which is likely to differ based on your platform). ‘MHD_OPTION_TCP_FASTQUEUE_QUEUE_SIZE’ When the flag ‘MHD_USE_TCP_FASTOPEN’ is used, this option sets the connection handshake queue size for the TCP FASTOPEN connections. Note that a TCP FASTOPEN connection handshake occupies more resources than a TCP handshake as the SYN packets also contain DATA which is kept in the associate state until handshake is completed. If this option is not given the queue size is set to a default value of 10. This option must be followed by a ‘unsigned int’. ‘MHD_OPTION_HTTPS_MEM_DHPARAMS’ Memory pointer for the Diffie-Hellman parameters (dh.pem) to be used by the HTTPS daemon for key exchange. This option must be followed by a ‘const char *’ argument. The argument would be a zero-terminated string with a PEM encoded PKCS3 DH parameters structure suitable for passing to ‘gnutls_dh_parms_import_pkcs3’. ‘MHD_OPTION_LISTENING_ADDRESS_REUSE’ This option must be followed by a ‘unsigned int’ argument. If this option is present and true (nonzero) parameter is given, allow reusing the address:port of the listening socket (using ‘SO_REUSEPORT’ on most platforms, and ‘SO_REUSEADDR’ on Windows). If a false (zero) parameter is given, disallow reusing the the address:port of the listening socket (this usually requires no special action, but ‘SO_EXCLUSIVEADDRUSE’ is needed on Windows). If this option is not present ‘SO_REUSEADDR’ is used on all platforms except Windows so reusing of address:port is disallowed. -- C Struct: MHD_OptionItem Entry in an MHD_OPTION_ARRAY. See the ‘MHD_OPTION_ARRAY’ option argument for its use. The ‘option’ member is used to specify which option is specified in the array. The other members specify the respective argument. Note that for options taking only a single pointer, the ‘ptr_value’ member should be set. For options taking two pointer arguments, the first pointer must be cast to ‘intptr_t’ and both the ‘value’ and the ‘ptr_value’ members should be used to pass the two pointers. -- Enumeration: MHD_ValueKind The ‘MHD_ValueKind’ specifies the source of the key-value pairs in the HTTP protocol. ‘MHD_HEADER_KIND’ HTTP header. ‘MHD_COOKIE_KIND’ Cookies. Note that the original HTTP header containing the cookie(s) will still be available and intact. ‘MHD_POSTDATA_KIND’ ‘POST’ data. This is available only if a content encoding supported by MHD is used (currently only URL encoding), and only if the posted content fits within the available memory pool. Note that in that case, the upload data given to the ‘MHD_AccessHandlerCallback()’ will be empty (since it has already been processed). ‘MHD_GET_ARGUMENT_KIND’ ‘GET’ (URI) arguments. ‘MHD_FOOTER_KIND’ HTTP footer (only for http 1.1 chunked encodings). -- Enumeration: MHD_RequestTerminationCode The ‘MHD_RequestTerminationCode’ specifies reasons why a request has been terminated (or completed). ‘MHD_REQUEST_TERMINATED_COMPLETED_OK’ We finished sending the response. ‘MHD_REQUEST_TERMINATED_WITH_ERROR’ Error handling the connection (resources exhausted, other side closed connection, application error accepting request, etc.) ‘MHD_REQUEST_TERMINATED_TIMEOUT_REACHED’ No activity on the connection for the number of seconds specified using ‘MHD_OPTION_CONNECTION_TIMEOUT’. ‘MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN’ We had to close the session since MHD was being shut down. -- Enumeration: MHD_ResponseMemoryMode The ‘MHD_ResponeMemoryMode’ specifies how MHD should treat the memory buffer given for the response in ‘MHD_create_response_from_buffer’. ‘MHD_RESPMEM_PERSISTENT’ Buffer is a persistent (static/global) buffer that won't change for at least the lifetime of the response, MHD should just use it, not free it, not copy it, just keep an alias to it. ‘MHD_RESPMEM_MUST_FREE’ Buffer is heap-allocated with ‘malloc’ (or equivalent) and should be freed by MHD after processing the response has concluded (response reference counter reaches zero). ‘MHD_RESPMEM_MUST_COPY’ Buffer is in transient memory, but not on the heap (for example, on the stack or non-malloc allocated) and only valid during the call to ‘MHD_create_response_from_buffer’. MHD must make its own private copy of the data for processing. -- Enumeration: MHD_ResponseFlags Response-specific flags. Passed as an argument to ‘MHD_set_response_options()’. ‘MHD_RF_NONE’ No special handling. ‘MHD_RF_HTTP_VERSION_1_0_ONLY’ Only respond in conservative HTTP 1.0-mode. In particular, do not (automatically) sent "Connection" headers and always close the connection after generating the response. By default, MHD will respond using the same HTTP version which was set in the request. You can also set the ‘MHD_RF_HTTP_VERSION_1_0_RESPONSE’ flag to force version 1.0 in the response. ‘MHD_RF_HTTP_VERSION_1_0_RESPONSE’ Only respond in HTTP 1.0-mode. Contrary to the ‘MHD_RF_HTTP_VERSION_1_0_ONLY’ flag, the response's HTTP version will always be set to 1.0 and "Connection" headers are still supported. You can even combine this option with MHD_RF_HTTP_VERSION_1_0_ONLY to change the response's HTTP version while maintaining strict compliance with HTTP 1.0 regarding connection management. This solution is not perfect as this flag is set on the response which is created after header processing. So MHD will behave as a HTTP 1.1 server until the response is queued. It means that an invalid HTTP 1.1 request will fail even if the response is sent with HTTP 1.0 and the request would be valid if interpreted with this version. For example, this request will fail in strict mode: GET / HTTP/1.1 as the "Host" header is missing and is mandatory in HTTP 1.1, but it should succeed when interpreted with HTTP 1.0. ‘MHD_RF_INSANITY_HEADER_CONTENT_LENGTH’ Disable sanity check preventing clients from manually setting the HTTP content length option. -- Enumeration: MHD_ResponseOptions Response-specific options. Passed in the varargs portion of ‘MHD_set_response_options()’. ‘MHD_RO_END’ No more options / last option. This is used to terminate the VARARGs list.  File: libmicrohttpd.info, Node: microhttpd-struct, Next: microhttpd-cb, Prev: microhttpd-const, Up: Top 3 Structures type definition **************************** -- C Struct: MHD_Daemon Handle for the daemon (listening on a socket for HTTP traffic). -- C Struct: MHD_Connection Handle for a connection / HTTP request. With HTTP/1.1, multiple requests can be run over the same connection. However, MHD will only show one request per TCP connection to the client at any given time. -- C Struct: MHD_Response Handle for a response. -- C Struct: MHD_IoVec An element of an array of memory buffers. -- C Struct: MHD_PostProcessor Handle for ‘POST’ processing. -- C Union: MHD_ConnectionInfo Information about a connection. -- C Union: MHD_DaemonInfo Information about an MHD daemon.  File: libmicrohttpd.info, Node: microhttpd-cb, Next: microhttpd-init, Prev: microhttpd-struct, Up: Top 4 Callback functions definition ******************************* -- Function Pointer: enum MHD_Result *MHD_AcceptPolicyCallback (void *cls, const struct sockaddr * addr, socklen_t addrlen) Invoked in the context of a connection to allow or deny a client to connect. This callback return ‘MHD_YES’ if connection is allowed, ‘MHD_NO’ if not. CLS custom value selected at callback registration time; ADDR address information from the client; ADDRLEN length of the address information. -- Function Pointer: enum MHD_Result *MHD_AccessHandlerCallback (void *cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) Invoked in the context of a connection to answer a request from the client. This callback must call MHD functions (example: the ‘MHD_Response’ ones) to provide content to give back to the client and return an HTTP status code (i.e. ‘200’ for OK, ‘404’, etc.). *note microhttpd-post::, for details on how to code this callback. Must return ‘MHD_YES’ if the connection was handled successfully, ‘MHD_NO’ if the socket must be closed due to a serious error while handling the request CLS custom value selected at callback registration time; URL the URL requested by the client; METHOD the HTTP method used by the client (‘GET’, ‘PUT’, ‘DELETE’, ‘POST’, etc.); VERSION the HTTP version string (i.e. ‘HTTP/1.1’); UPLOAD_DATA the data being uploaded (excluding headers): ‘POST’ data *will* be made available incrementally in UPLOAD_DATA; even if ‘POST’ data is available, the first time the callback is invoked there won't be upload data, as this is done just after MHD parses the headers. If supported by the client and the HTTP version, the application can at this point queue an error response to possibly avoid the upload entirely. If no response is generated, MHD will (if required) automatically send a 100 CONTINUE reply to the client. Afterwards, POST data will be passed to the callback to be processed incrementally by the application. The application may return ‘MHD_NO’ to forcefully terminate the TCP connection without generating a proper HTTP response. Once all of the upload data has been provided to the application, the application will be called again with 0 bytes of upload data. At this point, a response should be queued to complete the handling of the request. UPLOAD_DATA_SIZE set initially to the size of the UPLOAD_DATA provided; this callback must update this value to the number of bytes *NOT* processed; unless external select is used, the callback maybe required to process at least some data. If the callback fails to process data in multi-threaded or internal-select mode and if the read-buffer is already at the maximum size that MHD is willing to use for reading (about half of the maximum amount of memory allowed for the connection), then MHD will abort handling the connection and return an internal server error to the client. In order to avoid this, clients must be able to process upload data incrementally and reduce the value of ‘upload_data_size’. REQ_CLS reference to a pointer, initially set to ‘NULL’, that this callback can set to some address and that will be preserved by MHD for future calls for this request; since the access handler may be called many times (i.e., for a ‘PUT’/‘POST’ operation with plenty of upload data) this allows the application to easily associate some request-specific state; if necessary, this state can be cleaned up in the global ‘MHD_RequestCompletedCallback’ (which can be set with the ‘MHD_OPTION_NOTIFY_COMPLETED’). -- Function Pointer: void *MHD_RequestCompletedCallback (void *cls, struct MHD_Connectionconnection, void **req_cls, enum MHD_RequestTerminationCode toe) Signature of the callback used by MHD to notify the application about completed requests. CLS custom value selected at callback registration time; CONNECTION connection handle; REQ_CLS value as set by the last call to the ‘MHD_AccessHandlerCallback’; TOE reason for request termination see ‘MHD_OPTION_NOTIFY_COMPLETED’. -- Function Pointer: enum MHD_Result *MHD_KeyValueIterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *value, size_t value_size) Iterator over key-value pairs. This iterator can be used to iterate over all of the cookies, headers, or ‘POST’-data fields of a request, and also to iterate over the headers that have been added to a response. CLS custom value specified when iteration was triggered; KIND kind of the header we are looking at KEY key for the value, can be an empty string VALUE value corresponding value, can be NULL VALUE_SIZE number of bytes in ‘value’. This argument was introduced in ‘MHD_VERSION’ 0x00096301 to allow applications to use binary zeros in values. Applications using this argument must ensure that they are using a sufficiently recent version of MHD, i.e. by testing ‘MHD_get_version()’ for values above or equal to 0.9.64. Applications that do not need zeros in values and that want to compile without warnings against newer versions of MHD should not declare this argument and cast the function pointer argument to ‘MHD_KeyValueIterator’. Return ‘MHD_YES’ to continue iterating, ‘MHD_NO’ to abort the iteration. -- Function Pointer: ssize_t *MHD_ContentReaderCallback (void *cls, uint64_t pos, char *buf, size_t max) Callback used by MHD in order to obtain content. The callback has to copy at most MAX bytes of content into BUF. The total number of bytes that has been placed into BUF should be returned. Note that returning zero will cause MHD to try again. Thus, returning zero should only be used in conjunction with ‘MHD_suspend_connection()’ to avoid busy waiting. While usually the callback simply returns the number of bytes written into BUF, there are two special return value: ‘MHD_CONTENT_READER_END_OF_STREAM’ (-1) should be returned for the regular end of transmission (with chunked encoding, MHD will then terminate the chunk and send any HTTP footers that might be present; without chunked encoding and given an unknown response size, MHD will simply close the connection; note that while returning ‘MHD_CONTENT_READER_END_OF_STREAM’ is not technically legal if a response size was specified, MHD accepts this and treats it just as ‘MHD_CONTENT_READER_END_WITH_ERROR’. ‘MHD_CONTENT_READER_END_WITH_ERROR’ (-2) is used to indicate a server error generating the response; this will cause MHD to simply close the connection immediately. If a response size was given or if chunked encoding is in use, this will indicate an error to the client. Note, however, that if the client does not know a response size and chunked encoding is not in use, then clients will not be able to tell the difference between ‘MHD_CONTENT_READER_END_WITH_ERROR’ and ‘MHD_CONTENT_READER_END_OF_STREAM’. This is not a limitation of MHD but rather of the HTTP protocol. CLS custom value selected at callback registration time; POS position in the datastream to access; note that if an ‘MHD_Response’ object is re-used, it is possible for the same content reader to be queried multiple times for the same data; however, if an ‘MHD_Response’ is not re-used, MHD guarantees that POS will be the sum of all non-negative return values obtained from the content reader so far. Return ‘-1’ on error (MHD will no longer try to read content and instead close the connection with the client). -- Function Pointer: void *MHD_ContentReaderFreeCallback (void *cls) This method is called by MHD if we are done with a content reader. It should be used to free resources associated with the content reader. -- Function Pointer: enum MHD_Result *MHD_PostDataIterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) Iterator over key-value pairs where the value maybe made available in increments and/or may not be zero-terminated. Used for processing ‘POST’ data. CLS custom value selected at callback registration time; KIND type of the value; KEY zero-terminated key for the value; FILENAME name of the uploaded file, ‘NULL’ if not known; CONTENT_TYPE mime-type of the data, ‘NULL’ if not known; TRANSFER_ENCODING encoding of the data, ‘NULL’ if not known; DATA pointer to size bytes of data at the specified offset; OFF offset of data in the overall value; SIZE number of bytes in data available. Return ‘MHD_YES’ to continue iterating, ‘MHD_NO’ to abort the iteration.  File: libmicrohttpd.info, Node: microhttpd-init, Next: microhttpd-inspect, Prev: microhttpd-cb, Up: Top 5 Starting and stopping the server ********************************** -- Function: void MHD_set_panic_func (MHD_PanicCallback cb, void *cls) Set a handler for fatal errors. CB function to call if MHD encounters a fatal internal error. If no handler was set explicitly, MHD will call ‘abort’. CLS closure argument for cb; the other arguments are the name of the source file, line number and a string describing the nature of the fatal error (which can be ‘NULL’) -- Function: struct MHD_Daemon * MHD_start_daemon (unsigned int flags, unsigned short port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, ...) Start a webserver on the given port. FLAGS OR-ed combination of ‘MHD_FLAG’ values; PORT port to bind to; APC callback to call to check which clients will be allowed to connect; you can pass ‘NULL’ in which case connections from any IP will be accepted; APC_CLS extra argument to APC; DH default handler for all URIs; DH_CLS extra argument to DH. Additional arguments are a list of options (type-value pairs, terminated with ‘MHD_OPTION_END’). It is mandatory to use ‘MHD_OPTION_END’ as last argument, even when there are no additional arguments. Return ‘NULL’ on error, handle to daemon on success. -- Function: MHD_socket MHD_quiesce_daemon (struct MHD_Daemon *daemon) Stop accepting connections from the listening socket. Allows clients to continue processing, but stops accepting new connections. Note that the caller is responsible for closing the returned socket; however, if MHD is run using threads (anything but external select mode), it must not be closed until AFTER ‘MHD_stop_daemon’ has been called (as it is theoretically possible that an existing thread is still using it). This function is useful in the special case that a listen socket is to be migrated to another process (i.e. a newer version of the HTTP server) while existing connections should continue to be processed until they are finished. Return ‘-1’ on error (daemon not listening), the handle to the listen socket otherwise. -- Function: void MHD_stop_daemon (struct MHD_Daemon *daemon) Shutdown an HTTP daemon. -- Function: enum MHD_Result MHD_run (struct MHD_Daemon *daemon) Run webserver operations (without blocking unless in client callbacks). This method should be called by clients in combination with ‘MHD_get_fdset()’ if the client-controlled ‘select’-method is used. This function will work for external ‘poll’ and ‘select’ mode. However, if using external ‘select’ mode, you may want to instead use ‘MHD_run_from_select’, as it is more efficient. DAEMON daemon to process connections of Return ‘MHD_YES’ on success, ‘MHD_NO’ if this daemon was not started with the right options for this call. -- Function: enum MHD_Result MHD_run_from_select (struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set) Run webserver operations given sets of ready socket handles. This method should be called by clients in combination with ‘MHD_get_fdset’ if the client-controlled (external) select method is used. You can use this function instead of ‘MHD_run’ if you called ‘select’ on the result from ‘MHD_get_fdset’. File descriptors in the sets that are not controlled by MHD will be ignored. Calling this function instead of ‘MHD_run’ is more efficient as MHD will not have to call ‘select’ again to determine which operations are ready. DAEMON daemon to process connections of READ_FD_SET set of descriptors that must be ready for reading without blocking WRITE_FD_SET set of descriptors that must be ready for writing without blocking EXCEPT_FD_SET ignored, can be NULL Return ‘MHD_YES’ on success, ‘MHD_NO’ on serious internal errors. -- Function: void MHD_add_connection (struct MHD_Daemon *daemon, int client_socket, const struct sockaddr *addr, socklen_t addrlen) Add another client connection to the set of connections managed by MHD. This API is usually not needed (since MHD will accept inbound connections on the server socket). Use this API in special cases, for example if your HTTP server is behind NAT and needs to connect out to the HTTP client, or if you are building a proxy. If you use this API in conjunction with a internal select or a thread pool, you must set the option ‘MHD_USE_ITC’ to ensure that the freshly added connection is immediately processed by MHD. The given client socket will be managed (and closed!) by MHD after this call and must no longer be used directly by the application afterwards. DAEMON daemon that manages the connection CLIENT_SOCKET socket to manage (MHD will expect to receive an HTTP request from this socket next). ADDR IP address of the client ADDRLEN number of bytes in addr This function will return ‘MHD_YES’ on success, ‘MHD_NO’ if this daemon could not handle the connection (i.e. malloc failed, etc). The socket will be closed in any case; 'errno' is set to indicate further details about the error.  File: libmicrohttpd.info, Node: microhttpd-inspect, Next: microhttpd-requests, Prev: microhttpd-init, Up: Top 6 Implementing external ‘select’ ******************************** -- Function: enum MHD_Result MHD_get_fdset (struct MHD_Daemon *daemon, fd_set * read_fd_set, fd_set * write_fd_set, fd_set * except_fd_set, int *max_fd) Obtain the ‘select()’ sets for this daemon. The daemon's socket is added to READ_FD_SET. The list of currently existent connections is scanned and their file descriptors added to the correct set. When calling this function, FD_SETSIZE is assumed to be platform's default. If you changed FD_SETSIZE for your application, you should use ‘MHD_get_fdset2()’ instead. This function should only be called in when MHD is configured to use external select with ‘select()’ or with ‘epoll()’. In the latter case, it will only add the single ‘epoll()’ file descriptor used by MHD to the sets. After the call completed successfully: the variable referenced by MAX_FD references the file descriptor with highest integer identifier. The variable must be set to zero before invoking this function. Return ‘MHD_YES’ on success, ‘MHD_NO’ if: the arguments are invalid (example: ‘NULL’ pointers); this daemon was not started with the right options for this call. -- Function: enum MHD_Result MHD_get_fdset2 (struct MHD_Daemon *daemon, fd_set * read_fd_set, fd_set * write_fd_set, fd_set * except_fd_set, int *max_fd, unsigned int fd_setsize) Like ‘MHD_get_fdset()’, except that you can manually specify the value of FD_SETSIZE used by your application. -- Function: enum MHD_Result MHD_get_timeout (struct MHD_Daemon *daemon, unsigned long long *timeout) Obtain timeout value for select for this daemon (only needed if connection timeout is used). The returned value is how many milliseconds ‘select’ should at most block, not the timeout value set for connections. This function must not be called if the ‘MHD_USE_THREAD_PER_CONNECTION’ mode is in use (since then it is not meaningful to ask for a timeout, after all, there is concurrenct activity). The function must also not be called by user-code if ‘MHD_USE_INTERNAL_POLLING_THREAD’ is in use. In the latter case, the behavior is undefined. DAEMON which daemon to obtain the timeout from. TIMEOUT will be set to the timeout (in milliseconds). Return ‘MHD_YES’ on success, ‘MHD_NO’ if timeouts are not used (or no connections exist that would necessitate the use of a timeout right now).  File: libmicrohttpd.info, Node: microhttpd-requests, Next: microhttpd-responses, Prev: microhttpd-inspect, Up: Top 7 Handling requests ******************* -- Function: int MHD_get_connection_values (struct MHD_Connection *connection, enum MHD_ValueKind kind, MHD_KeyValueIterator iterator, void *iterator_cls) Get all the headers matching KIND from the request. The KIND argument can be a bitmask, ORing the various header kinds that are requested. The ITERATOR callback is invoked once for each header, with ITERATOR_CLS as first argument. After version 0.9.19, the headers are iterated in the same order as they were received from the network; previous versions iterated over the headers in reverse order. ‘MHD_get_connection_values’ returns the number of entries iterated over; this can be less than the number of headers if, while iterating, ITERATOR returns ‘MHD_NO’. ITERATOR can be ‘NULL’: in this case this function just counts and returns the number of headers. In the case of ‘MHD_GET_ARGUMENT_KIND’, the VALUE argument will be ‘NULL’ if the URL contained a key without an equals operator. For example, for a HTTP request to the URL "http://foo/bar?key", the VALUE argument is ‘NULL’; in contrast, a HTTP request to the URL "http://foo/bar?key=", the VALUE argument is the empty string. The normal case is that the URL contains "http://foo/bar?key=value" in which case VALUE would be the string "value" and KEY would contain the string "key". -- Function: enum MHD_Result MHD_set_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, const char *value) This function can be used to append an entry to the list of HTTP headers of a connection (so that the ‘MHD_get_connection_values function’ will return them - and the MHD PostProcessor will also see them). This maybe required in certain situations (see Mantis #1399) where (broken) HTTP implementations fail to supply values needed by the post processor (or other parts of the application). This function MUST only be called from within the MHD_AccessHandlerCallback (otherwise, access maybe improperly synchronized). Furthermore, the client must guarantee that the key and value arguments are 0-terminated strings that are NOT freed until the connection is closed. (The easiest way to do this is by passing only arguments to permanently allocated strings.). CONNECTION is the connection for which the entry for KEY of the given KIND should be set to the given VALUE. The function returns ‘MHD_NO’ if the operation could not be performed due to insufficient memory and ‘MHD_YES’ on success. -- Function: const char * MHD_lookup_connection_value (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key) Get a particular header value. If multiple values match the KIND, return one of them (the "first", whatever that means). KEY must reference a zero-terminated ASCII-coded string representing the header to look for: it is compared against the headers using (basically) ‘strcasecmp()’, so case is ignored. -- Function: const char * MHD_lookup_connection_value_n (struct MHD_Connection *connection, enum MHD_ValueKind kind, const char *key, size_t key_size, const char **value_ptr, size_t *value_size_ptr) Get a particular header value. If multiple values match the KIND, return one of them (the "first", whatever that means). KEY must reference an ASCII-coded string representing the header to look for: it is compared against the headers using (basically) ‘strncasecmp()’, so case is ignored. The VALUE_PTR is set to the address of the value found, and VALUE_SIZE_PTR is set to the number of bytes in the value.  File: libmicrohttpd.info, Node: microhttpd-responses, Next: microhttpd-flow, Prev: microhttpd-requests, Up: Top 8 Building responses to requests ******************************** Response objects handling by MHD is asynchronous with respect to the application execution flow. Instances of the ‘MHD_Response’ structure are not associated to a daemon and neither to a client connection: they are managed with reference counting. In the simplest case: we allocate a new ‘MHD_Response’ structure for each response, we use it once and finally we destroy it. MHD allows more efficient resources usages. Example: we allocate a new ‘MHD_Response’ structure for each response *kind*, we use it every time we have to give that response and we finally destroy it only when the daemon shuts down. * Menu: * microhttpd-response enqueue:: Enqueuing a response. * microhttpd-response create:: Creating a response object. * microhttpd-response headers:: Adding headers to a response. * microhttpd-response options:: Setting response options. * microhttpd-response inspect:: Inspecting a response object. * microhttpd-response upgrade:: Creating a response for protocol upgrades.  File: libmicrohttpd.info, Node: microhttpd-response enqueue, Next: microhttpd-response create, Up: microhttpd-responses 8.1 Enqueuing a response ======================== -- Function: enum MHD_Result MHD_queue_response (struct MHD_Connection *connection, unsigned int status_code, struct MHD_Response *response) Queue a response to be transmitted to the client as soon as possible but only after MHD_AccessHandlerCallback returns. This function checks that it is legal to queue a response at this time for the given connection. It also increments the internal reference counter for the response object (the counter will be decremented automatically once the response has been transmitted). CONNECTION the connection identifying the client; STATUS_CODE HTTP status code (i.e. ‘200’ for OK); RESPONSE response to transmit. Return ‘MHD_YES’ on success or if message has been queued. Return ‘MHD_NO’: if arguments are invalid (example: ‘NULL’ pointer); on error (i.e. reply already sent). -- Function: void MHD_destroy_response (struct MHD_Response *response) Destroy a response object and associated resources (decrement the reference counter). Note that MHD may keep some of the resources around if the response is still in the queue for some clients, so the memory may not necessarily be freed immediately. An explanation of reference counting(1): 1. a ‘MHD_Response’ object is allocated: struct MHD_Response * response = MHD_create_response_from_buffer(...); /* here: reference counter = 1 */ 2. the ‘MHD_Response’ object is enqueued in a ‘MHD_Connection’: MHD_queue_response(connection, , response); /* here: reference counter = 2 */ 3. the creator of the response object discharges responsibility for it: MHD_destroy_response(response); /* here: reference counter = 1 */ 4. the daemon handles the connection sending the response's data to the client then decrements the reference counter by calling ‘MHD_destroy_response()’: the counter's value drops to zero and the ‘MHD_Response’ object is released. ---------- Footnotes ---------- (1) Note to readers acquainted to the Tcl API: reference counting on ‘MHD_Connection’ structures is handled in the same way as Tcl handles ‘Tcl_Obj’ structures through ‘Tcl_IncrRefCount()’ and ‘Tcl_DecrRefCount()’.  File: libmicrohttpd.info, Node: microhttpd-response create, Next: microhttpd-response headers, Prev: microhttpd-response enqueue, Up: microhttpd-responses 8.2 Creating a response object ============================== -- Function: struct MHD_Response * MHD_create_response_from_callback (uint64_t size, size_t block_size, MHD_ContentReaderCallback crc, void *crc_cls, MHD_ContentReaderFreeCallback crfc) Create a response object. The response object can be extended with header information and then it can be used any number of times. SIZE size of the data portion of the response, ‘-1’ for unknown; BLOCK_SIZE preferred block size for querying CRC (advisory only, MHD may still call CRC using smaller chunks); this is essentially the buffer size used for IO, clients should pick a value that is appropriate for IO and memory performance requirements; CRC callback to use to obtain response data; CRC_CLS extra argument to CRC; CRFC callback to call to free CRC_CLS resources. Return ‘NULL’ on error (i.e. invalid arguments, out of memory). -- Function: struct MHD_Response * MHD_create_response_from_fd (uint64_t size, int fd) Create a response object. The response object can be extended with header information and then it can be used any number of times. SIZE size of the data portion of the response (should be smaller or equal to the size of the file) FD file descriptor referring to a file on disk with the data; will be closed when response is destroyed; note that 'fd' must be an actual file descriptor (not a pipe or socket) since MHD might use 'sendfile' or 'seek' on it. The descriptor should be in blocking-IO mode. Return ‘NULL’ on error (i.e. invalid arguments, out of memory). -- Function: struct MHD_Response * MHD_create_response_from_pipe (int fd) Create a response object. The response object can be extended with header information and then it can be used ONLY ONCE. FD file descriptor of the read-end of the pipe; will be closed when response is destroyed. The descriptor should be in blocking-IO mode. Return ‘NULL’ on error (i.e. out of memory). -- Function: struct MHD_Response * MHD_create_response_from_fd_at_offset (size_t size, int fd, off_t offset) Create a response object. The response object can be extended with header information and then it can be used any number of times. Note that you need to be a bit careful about ‘off_t’ when writing this code. Depending on your platform, MHD is likely to have been compiled with support for 64-bit files. When you compile your own application, you must make sure that ‘off_t’ is also a 64-bit value. If not, your compiler may pass a 32-bit value as ‘off_t’, which will result in 32-bits of garbage. If you use the autotools, use the ‘AC_SYS_LARGEFILE’ autoconf macro and make sure to include the generated ‘config.h’ file before ‘microhttpd.h’ to avoid problems. If you do not have a build system and only want to run on a GNU/Linux system, you could also use #define _FILE_OFFSET_BITS 64 #include #include #include #include to ensure 64-bit ‘off_t’. Note that if your operating system does not support 64-bit files, MHD will be compiled with a 32-bit ‘off_t’ (in which case the above would be wrong). SIZE size of the data portion of the response (number of bytes to transmit from the file starting at offset). FD file descriptor referring to a file on disk with the data; will be closed when response is destroyed; note that 'fd' must be an actual file descriptor (not a pipe or socket) since MHD might use 'sendfile' or 'seek' on it. The descriptor should be in blocking-IO mode. OFFSET offset to start reading from in the file Return ‘NULL’ on error (i.e. invalid arguments, out of memory). -- Function: struct MHD_Response * MHD_create_response_from_buffer (size_t size, void *data, enum MHD_ResponseMemoryMode mode) Create a response object. The response object can be extended with header information and then it can be used any number of times. SIZE size of the data portion of the response; BUFFER the data itself; MODE memory management options for buffer; use MHD_RESPMEM_PERSISTENT if the buffer is static/global memory, use MHD_RESPMEM_MUST_FREE if the buffer is heap-allocated and should be freed by MHD and MHD_RESPMEM_MUST_COPY if the buffer is in transient memory (i.e. on the stack) and must be copied by MHD; Return ‘NULL’ on error (i.e. invalid arguments, out of memory). -- Function: struct MHD_Response * MHD_create_response_from_buffer_with_free_callback (size_t size, void *data, MHD_ContentReaderFreeCallback crfc) Create a response object. The buffer at the end must be free'd by calling the CRFC function. SIZE size of the data portion of the response; BUFFER the data itself; CRFC function to call at the end to free memory allocated at BUFFER. Return ‘NULL’ on error (i.e. invalid arguments, out of memory). -- Function: struct MHD_Response * MHD_create_response_from_data (size_t size, void *data, int must_free, int must_copy) Create a response object. The response object can be extended with header information and then it can be used any number of times. This function is deprecated, use ‘MHD_create_response_from_buffer’ instead. SIZE size of the data portion of the response; DATA the data itself; MUST_FREE if true: MHD should free data when done; MUST_COPY if true: MHD allocates a block of memory and use it to make a copy of DATA embedded in the returned ‘MHD_Response’ structure; handling of the embedded memory is responsibility of MHD; DATA can be released anytime after this call returns. Return ‘NULL’ on error (i.e. invalid arguments, out of memory). Example: create a response from a statically allocated string: const char * data = "

      Error!

      "; struct MHD_Connection * connection = ...; struct MHD_Response * response; response = MHD_create_response_from_buffer (strlen(data), data, MHD_RESPMEM_PERSISTENT); MHD_queue_response(connection, 404, response); MHD_destroy_response(response); -- Function: struct MHD_Response * MHD_create_response_from_iovec (const struct MHD_IoVec *iov, int iovcnt, MHD_ContentReaderFreeCallback crfc, void *cls) Create a response object from an array of memory buffers. The response object can be extended with header information and then be used any number of times. IOV the array for response data buffers, an internal copy of this will be made; however, note that the data pointed to by the IOV is not copied and must be preserved unchanged at the given locations until the response is no longer in use and the CRFC is called; IOVCNT the number of elements in IOV; CRFC the callback to call to free resources associated with IOV; CLS the argument to CRFC; Return ‘NULL’ on error (i.e. invalid arguments, out of memory).  File: libmicrohttpd.info, Node: microhttpd-response headers, Next: microhttpd-response options, Prev: microhttpd-response create, Up: microhttpd-responses 8.3 Adding headers to a response ================================ -- Function: enum MHD_Result MHD_add_response_header (struct MHD_Response *response, const char *header, const char *content) Add a header line to the response. The strings referenced by HEADER and CONTENT must be zero-terminated and they are duplicated into memory blocks embedded in RESPONSE. Notice that the strings must not hold newlines, carriage returns or tab chars. MHD_add_response_header() prevents applications from setting a "Transfer-Encoding" header to values other than "identity" or "chunked" as other transfer encodings are not supported by MHD. Note that usually MHD will pick the transfer encoding correctly automatically, but applications can use the header to force a particular behavior. MHD_add_response_header() also prevents applications from setting a "Content-Length" header. MHD will automatically set a correct "Content-Length" header if it is possible and allowed. Return ‘MHD_NO’ on error (i.e. invalid header or content format or memory allocation error). -- Function: enum MHD_Result MHD_add_response_footer (struct MHD_Response *response, const char *footer, const char *content) Add a footer line to the response. The strings referenced by FOOTER and CONTENT must be zero-terminated and they are duplicated into memory blocks embedded in RESPONSE. Notice that the strings must not hold newlines, carriage returns or tab chars. You can add response footers at any time before signalling the end of the response to MHD (not just before calling 'MHD_queue_response'). Footers are useful for adding cryptographic checksums to the reply or to signal errors encountered during data generation. This call was introduced in MHD 0.9.3. Return ‘MHD_NO’ on error (i.e. invalid header or content format or memory allocation error). -- Function: enum MHD_Result MHD_del_response_header (struct MHD_Response *response, const char *header, const char *content) Delete a header (or footer) line from the response. Return ‘MHD_NO’ on error (arguments are invalid or no such header known).  File: libmicrohttpd.info, Node: microhttpd-response options, Next: microhttpd-response inspect, Prev: microhttpd-response headers, Up: microhttpd-responses 8.4 Setting response options ============================ -- Function: enum MHD_Result MHD_set_response_options (struct MHD_Response *response, enum MHD_ResponseFlags flags, ...) Set special flags and options for a response. Calling this functions sets the given flags and options for the response. RESPONSE which response should be modified; FLAGS flags to set for the response; Additional arguments are a list of options (type-value pairs, terminated with ‘MHD_RO_END’). It is mandatory to use ‘MHD_RO_END’ as last argument, even when there are no additional arguments. Return ‘MHD_NO’ on error, ‘MHD_YES’ on success.  File: libmicrohttpd.info, Node: microhttpd-response inspect, Next: microhttpd-response upgrade, Prev: microhttpd-response options, Up: microhttpd-responses 8.5 Inspecting a response object ================================ -- Function: int MHD_get_response_headers (struct MHD_Response *response, MHD_KeyValueIterator iterator, void *iterator_cls) Get all of the headers added to a response. Invoke the ITERATOR callback for each header in the response, using ITERATOR_CLS as first argument. Return number of entries iterated over. ITERATOR can be ‘NULL’: in this case the function just counts headers. ITERATOR should not modify the its key and value arguments, unless we know what we are doing. -- Function: const char * MHD_get_response_header (struct MHD_Response *response, const char *key) Find and return a pointer to the value of a particular header from the response. KEY must reference a zero-terminated string representing the header to look for. The search is case sensitive. Return ‘NULL’ if header does not exist or KEY is ‘NULL’. We should not modify the value, unless we know what we are doing.  File: libmicrohttpd.info, Node: microhttpd-response upgrade, Prev: microhttpd-response inspect, Up: microhttpd-responses 8.6 Creating a response for protocol upgrades ============================================= With RFC 2817 a mechanism to switch protocols within HTTP was introduced. Here, a client sends a request with a "Connection: Upgrade" header. The server responds with a "101 Switching Protocols" response header, after which the two parties begin to speak a different (non-HTTP) protocol over the TCP connection. This mechanism is used for upgrading HTTP 1.1 connections to HTTP2 or HTTPS, as well as for implementing WebSockets. Which protocol upgrade is performed is negotiated between server and client in additional headers, in particular the "Upgrade" header. MHD supports switching protocols using this mechanism only if the ‘MHD_ALLOW_SUSPEND_RESUME’ flag has been set when starting the daemon. If this flag has been set, applications can upgrade a connection by queueing a response (using the ‘MHD_HTTP_SWITCHING_PROTOCOLS’ status code) which must have been created with the following function: -- Function: enum MHD_Result MHD_create_response_for_upgrade (MHD_UpgradeHandler upgrade_handler, void *upgrade_handler_cls) Create a response suitable for switching protocols. Returns ‘MHD_YES’ on success. ‘upgrade_handler’ must not be ‘NULL’. When creating this type of response, the "Connection: Upgrade" header will be set automatically for you. MHD requires that you additionally set an "Upgrade:" header. The "Upgrade" header must simply exist, the specific value is completely up to the application. The ‘upgrade_handler’ argument to the above has the following type: -- Function Pointer: void *MHD_UpgradeHandler (void *cls, struct MHD_Connection *connection, const char *extra_in, size_t extra_in_size, MHD_socket sock, struct MHD_UpgradeResponseHandle *urh) This function will be called once MHD has transmitted the header of the response to the connection that is being upgraded. At this point, the application is expected to take over the socket ‘sock’ and speak the non-HTTP protocol to which the connection was upgraded. MHD will no longer use the socket; this includes handling timeouts. The application must call ‘MHD_upgrade_action’ with an upgrade action of ‘MHD_UPGRADE_ACTION_CLOSE’ when it is done processing the connection to close the socket. The application must not call ‘MHD_stop_daemon’ on the respective daemon as long as it is still handling the connection. The arguments given to the ‘upgrade_handler’ have the following meaning: CLS matches the ‘upgrade_handler_cls’ that was given to ‘MHD_create_response_for_upgrade’ CONNECTION identifies the connection that is being upgraded; REQ_CLS last value left in '*req_cls' in the 'MHD_AccessHandlerCallback' EXTRA_IN buffer of bytes MHD read "by accident" from the socket already. This can happen if the client eagerly transmits more than just the HTTP request. The application should treat these as if it had read them from the socket. EXTRA_IN_SIZE number of bytes in ‘extra_in’ SOCK the socket which the application can now use directly for some bi-directional communication with the client. The application can henceforth use ‘recv()’ and ‘send()’ or ‘read()’ and ‘write()’ system calls on the socket. However, ‘ioctl()’ and ‘setsockopt()’ functions will not work as expected when using HTTPS. Such operations may be supported in the future via ‘MHD_upgrade_action’. Most importantly, the application must never call ‘close()’ on this socket. Closing the socket must be done using ‘MHD_upgrade_action’. However, while close is forbidden, the application may call ‘shutdown()’ on the socket. URH argument for calls to ‘MHD_upgrade_action’. Applications must eventually use this function to perform the ‘close()’ action on the socket. -- Function: enum MHD_Result MHD_upgrade_action (struct MHD_UpgradeResponseHandle *urh, enum MHD_UpgradeAction action, ...) Perform special operations related to upgraded connections. URH identifies the upgraded connection to perform an action on ACTION specifies the action to perform; further arguments to the function depend on the specifics of the action. -- Enumeration: MHD_UpgradeAction Set of actions to be performed on upgraded connections. Passed as an argument to ‘MHD_upgrade_action()’. ‘MHD_UPGRADE_ACTION_CLOSE’ Closes the connection. Must be called once the application is done with the client. Takes no additional arguments. ‘MHD_UPGRADE_ACTION_CORK_ON’ Enable corking on the underlying socket. ‘MHD_UPGRADE_ACTION_CORK_OFF’ Disable corking on the underlying socket.  File: libmicrohttpd.info, Node: microhttpd-flow, Next: microhttpd-dauth, Prev: microhttpd-responses, Up: Top 9 Flow control. *************** Sometimes it may be possible that clients upload data faster than an application can process it, or that an application needs an extended period of time to generate a response. If ‘MHD_USE_THREAD_PER_CONNECTION’ is used, applications can simply deal with this by performing their logic within the thread and thus effectively blocking connection processing by MHD. In all other modes, blocking logic must not be placed within the callbacks invoked by MHD as this would also block processing of other requests, as a single thread may be responsible for tens of thousands of connections. Instead, applications using thread modes other than ‘MHD_USE_THREAD_PER_CONNECTION’ should use the following functions to perform flow control. -- Function: enum MHD_Result MHD_suspend_connection (struct MHD_Connection *connection) Suspend handling of network data for a given connection. This can be used to dequeue a connection from MHD's event loop (external select, internal select or thread pool; not applicable to thread-per-connection!) for a while. If you use this API in conjunction with a internal select or a thread pool, you must set the option ‘MHD_ALLOW_SUSPEND_RESUME’ to ensure that a resumed connection is immediately processed by MHD. Suspended connections continue to count against the total number of connections allowed (per daemon, as well as per IP, if such limits are set). Suspended connections will NOT time out; timeouts will restart when the connection handling is resumed. While a connection is suspended, MHD will not detect disconnects by the client. The only safe time to suspend a connection is from the ‘MHD_AccessHandlerCallback’ or from the respective ‘MHD_ContentReaderCallback’ (but in this case the response object must not be shared among multiple connections). When suspending from the ‘MHD_AccessHandlerCallback’ you MUST afterwards return ‘MHD_YES’ from the access handler callback (as MHD_NO would imply to both close and suspend the connection, which is not allowed). Finally, it is an API violation to call ‘MHD_stop_daemon’ while having suspended connections (this will at least create memory and socket leaks or lead to undefined behavior). You must explicitly resume all connections before stopping the daemon. CONNECTION the connection to suspend -- Function: enum MHD_Result MHD_resume_connection (struct MHD_Connection *connection) Resume handling of network data for suspended connection. It is safe to resume a suspended connection at any time. Calling this function on a connection that was not previously suspended will result in undefined behavior. If you are using this function in "external" select mode, you must make sure to run ‘MHD_run’ afterwards (before again calling ‘MHD_get_fdset’), as otherwise the change may not be reflected in the set returned by ‘MHD_get_fdset’ and you may end up with a connection that is stuck until the next network activity. This function may be called from any thread, which is what makes it usable to hand work to threads of your own. In "external" select mode it writes to the inter-thread communication channel that ‘MHD_ALLOW_SUSPEND_RESUME’ sets up, and since ‘MHD_get_fdset’ adds the reading end of that channel to the read set, a call from another thread interrupts a ‘select’ that your application is blocked in. That matters because ‘MHD_get_timeout’ reports no timeout at all while every connection is suspended, so your application would otherwise block indefinitely. The channel is level triggered, so a resume issued between ‘MHD_get_fdset’ and ‘select’ cannot be lost. You can check whether a connection is currently suspended using ‘MHD_get_connection_info’ by querying for ‘MHD_CONNECTION_INFO_CONNECTION_SUSPENDED’. A worked example of suspending connections while worker threads produce the answers, driven by an external ‘select’ loop, is given in the chapter "Answering from another thread" of the MHD tutorial. CONNECTION the connection to resume  File: libmicrohttpd.info, Node: microhttpd-dauth, Next: microhttpd-post, Prev: microhttpd-flow, Up: Top 10 Utilizing Authentication *************************** MHD support three types of client authentication. Basic authentication uses a simple authentication method based on BASE64 algorithm. Username and password are exchanged in clear between the client and the server, so this method must only be used for non-sensitive content or when the session is protected with https. When using basic authentication MHD will have access to the clear password, possibly allowing to create a chained authentication toward an external authentication server. Digest authentication uses a one-way authentication method based on MD5 hash algorithm. Only the hash will transit over the network, hence protecting the user password. The nonce will prevent replay attacks. This method is appropriate for general use, especially when https is not used to encrypt the session. Client certificate authentication uses a X.509 certificate from the client. This is the strongest authentication mechanism but it requires the use of HTTPS. Client certificate authentication can be used simultaneously with Basic or Digest Authentication in order to provide a two levels authentication (like for instance separate machine and user authentication). A code example for using client certificates is presented in the MHD tutorial. * Menu: * microhttpd-dauth basic:: Using Basic Authentication. * microhttpd-dauth digest:: Using Digest Authentication.  File: libmicrohttpd.info, Node: microhttpd-dauth basic, Next: microhttpd-dauth digest, Up: microhttpd-dauth 10.1 Using Basic Authentication =============================== -- Function: void MHD_free (void *ptr) Free the memory given at ‘ptr’. Used to free data structures allocated by MHD. Calls ‘free(ptr)’. -- Function: char * MHD_basic_auth_get_username_password3 (struct MHD_Connection *connection) Get the username and password from the basic authorization header sent by the client. Return ‘NULL’ if no Basic Authorization header set by the client or if Base64 encoding is invalid; a pointer to the structure with username and password if found values set by the client. If returned value is not ‘NULL’, the value must be ‘MHD_free()’'ed. -- Function: enum MHD_Result MHD_queue_basic_auth_fail_response3 (struct MHD_Connection *connection, const char *realm, int prefer_utf8, struct MHD_Response *response) Queues a response to request basic authentication from the client. Return ‘MHD_YES’ if successful, otherwise ‘MHD_NO’. REALM must reference to a zero-terminated string representing the realm. PREFER_UTF8 if set to ‘MHD_YES’ then parameter ‘charset’ with value ‘UTF-8’ will be added to the response authentication header which indicates that UTF-8 encoding is preferred for username and password. RESPONSE a response structure to specify what shall be presented to the client with a 401 HTTP status.  File: libmicrohttpd.info, Node: microhttpd-dauth digest, Prev: microhttpd-dauth basic, Up: microhttpd-dauth 10.2 Using Digest Authentication ================================ MHD supports MD5 (deprecated by IETF) and SHA-256 hash algorithms for digest authentication. The ‘MHD_DigestAuthAlgorithm’ enumeration is used to specify which algorithm should be used. -- Enumeration: MHD_DigestAuthAlgorithm Which digest algorithm should be used. Must be used consistently. ‘MHD_DIGEST_ALG_AUTO’ Have MHD pick an algorithm currently considered secure. For now defaults to SHA-256. ‘MHD_DIGEST_ALG_MD5’ Force use of (deprecated, ancient, insecure) MD5. ‘MHD_DIGEST_ALG_SHA256’ Force use of SHA-256. -- Enumeration: MHD_DigestAuthResult The result of digest authentication of the client. ‘MHD_DAUTH_OK’ Authentication OK. ‘MHD_DAUTH_ERROR’ General error, like "out of memory". ‘MHD_DAUTH_WRONG_HEADER’ No "Authorization" header or wrong format of the header. ‘MHD_DAUTH_WRONG_USERNAME’ Wrong "username". ‘MHD_DAUTH_WRONG_REALM’ Wrong "realm". ‘MHD_DAUTH_WRONG_URI’ Wrong "URI" (or URI parameters). ‘MHD_DAUTH_NONCE_STALE’ The "nonce" is too old. Suggest the client to retry with the same username and password to get the fresh "nonce". The validity of the "nonce" may not be checked. ‘MHD_DAUTH_NONCE_WRONG’ The "nonce" is wrong. May indicate an attack attempt. ‘MHD_DAUTH_RESPONSE_WRONG’ The "response" is wrong. May indicate an attack attempt. -- Function: char * MHD_digest_auth_get_username (struct MHD_Connection *connection) Find and return a pointer to the username value from the request header. Return ‘NULL’ if the value is not found or header does not exist. If returned value is not ‘NULL’, the value must be ‘MHD_free()’'ed. -- Function: enum MHD_DigestAuthResult MHD_digest_auth_check3 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC7616. If valid return ‘MHD_DAUTH_OK’, otherwise return the error code. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. PASSWORD must reference to a zero-terminated string representing the password, most probably it will be the result of a lookup of the username against a local database. NONCE_TIMEOUT the nonce validity duration in seconds. Most of the time it is sound to specify 300 seconds as its values. ALGO which digest algorithm should we use. -- Function: int MHD_digest_auth_check2 (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC2716. If valid return ‘MHD_YES’, otherwise return ‘MHD_NO’. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. PASSWORD must reference to a zero-terminated string representing the password, most probably it will be the result of a lookup of the username against a local database. NONCE_TIMEOUT is the amount of time in seconds for a nonce to be invalid. Most of the time it is sound to specify 300 seconds as its values. ALGO which digest algorithm should we use. -- Function: int MHD_digest_auth_check (struct MHD_Connection *connection, const char *realm, const char *username, const char *password, unsigned int nonce_timeout) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC2716. If valid return ‘MHD_YES’, otherwise return ‘MHD_NO’. Deprecated, use ‘MHD_digest_auth_check2’ instead. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. PASSWORD must reference to a zero-terminated string representing the password, most probably it will be the result of a lookup of the username against a local database. NONCE_TIMEOUT is the amount of time in seconds for a nonce to be invalid. Most of the time it is sound to specify 300 seconds as its values. -- Function: enum MHD_DigestAuthResult MHD_digest_auth_check_digest3 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC7616. If valid return ‘MHD_DAUTH_OK’, otherwise return the error code. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. DIGEST the pointer to the binary digest for the precalculated hash value "username:realm:password" with specified ALGO. DIGEST_SIZE the number of bytes in DIGEST (the size must match ALGO!) NONCE_TIMEOUT the nonce validity duration in seconds. Most of the time it is sound to specify 300 seconds as its values. ALGO digest authentication algorithm to use. -- Function: int MHD_digest_auth_check_digest2 (struct MHD_Connection *connection, const char *realm, const char *username, const uint8_t *digest, unsigned int nonce_timeout, enum MHD_DigestAuthAlgorithm algo) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC2716. If valid return ‘MHD_YES’, otherwise return ‘MHD_NO’. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. DIGEST pointer to the binary MD5 sum for the precalculated hash value "userame:realm:password". The size must match the selected ALGO! NONCE_TIMEOUT is the amount of time in seconds for a nonce to be invalid. Most of the time it is sound to specify 300 seconds as its values. ALGO digest authentication algorithm to use. -- Function: int MHD_digest_auth_check_digest (struct MHD_Connection *connection, const char *realm, const char *username, const unsigned char digest[MHD_MD5_DIGEST_SIZE], unsigned int nonce_timeout) Checks if the provided values in the WWW-Authenticate header are valid and sound according to RFC2716. If valid return ‘MHD_YES’, otherwise return ‘MHD_NO’. Deprecated, use ‘MHD_digest_auth_check_digest2’ instead. REALM must reference to a zero-terminated string representing the realm. USERNAME must reference to a zero-terminated string representing the username, it is usually the returned value from MHD_digest_auth_get_username. DIGEST pointer to the binary MD5 sum for the precalculated hash value "userame:realm:password" of ‘MHD_MD5_DIGEST_SIZE’ bytes. NONCE_TIMEOUT is the amount of time in seconds for a nonce to be invalid. Most of the time it is sound to specify 300 seconds as its values. -- Function: enum MHD_Result MHD_queue_auth_fail_response2 (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale, enum MHD_DigestAuthAlgorithm algo) Queues a response to request authentication from the client, return ‘MHD_YES’ if successful, otherwise ‘MHD_NO’. REALM must reference to a zero-terminated string representing the realm. OPAQUE must reference to a zero-terminated string representing a value that gets passed to the client and expected to be passed again to the server as-is. This value can be a hexadecimal or base64 string. RESPONSE a response structure to specify what shall be presented to the client with a 401 HTTP status. SIGNAL_STALE a value that signals "stale=true" in the response header to indicate the invalidity of the nonce and no need to ask for authentication parameters and only a new nonce gets generated. ‘MHD_YES’ to generate a new nonce, ‘MHD_NO’ to ask for authentication parameters. ALGO which digest algorithm should we use. The same algorithm must then be selected when checking digests received from clients! -- Function: enum MHD_Result MHD_queue_auth_fail_response (struct MHD_Connection *connection, const char *realm, const char *opaque, struct MHD_Response *response, int signal_stale) Queues a response to request authentication from the client, return ‘MHD_YES’ if successful, otherwise ‘MHD_NO’. REALM must reference to a zero-terminated string representing the realm. OPAQUE must reference to a zero-terminated string representing a value that gets passed to the client and expected to be passed again to the server as-is. This value can be a hexadecimal or base64 string. RESPONSE a response structure to specify what shall be presented to the client with a 401 HTTP status. SIGNAL_STALE a value that signals "stale=true" in the response header to indicate the invalidity of the nonce and no need to ask for authentication parameters and only a new nonce gets generated. ‘MHD_YES’ to generate a new nonce, ‘MHD_NO’ to ask for authentication parameters. Example: handling digest authentication requests and responses. #define PAGE "libmicrohttpd demoAccess granted" #define DENIED "libmicrohttpd demoAccess denied" #define OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" static int ahc_echo (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr) { struct MHD_Response *response; char *username; const char *password = "testpass"; const char *realm = "test@example.com"; int ret; static int already_called_marker; if (&already_called_marker != *req_cls) { /* Called for the first time, request not fully read yet */ *req_cls = &already_called_marker; /* Wait for complete request */ return MHD_YES; } username = MHD_digest_auth_get_username (connection); if (username == NULL) { response = MHD_create_response_from_buffer(strlen (DENIED), DENIED, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_auth_fail_response2 (connection, realm, OPAQUE, response, MHD_NO, MHD_DIGEST_ALG_SHA256); MHD_destroy_response(response); return ret; } ret = MHD_digest_auth_check2 (connection, realm, username, password, 300, MHD_DIGEST_ALG_SHA256); MHD_free(username); if ( (ret == MHD_INVALID_NONCE) || (ret == MHD_NO) ) { response = MHD_create_response_from_buffer(strlen (DENIED), DENIED, MHD_RESPMEM_PERSISTENT); if (NULL == response) return MHD_NO; ret = MHD_queue_auth_fail_response2 (connection, realm, OPAQUE, response, (ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO, MHD_DIGEST_ALG_SHA256); MHD_destroy_response(response); return ret; } response = MHD_create_response_from_buffer (strlen(PAGE), PAGE, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response(response); return ret; }  File: libmicrohttpd.info, Node: microhttpd-post, Next: microhttpd-info, Prev: microhttpd-dauth, Up: Top 11 Adding a ‘POST’ processor **************************** * Menu: * microhttpd-post api:: Programming interface for the ‘POST’ processor. MHD provides the post processor API to make it easier for applications to parse the data of a client's ‘POST’ request: the ‘MHD_AccessHandlerCallback’ will be invoked multiple times to process data as it arrives; at each invocation a new chunk of data must be processed. The arguments UPLOAD_DATA and UPLOAD_DATA_SIZE are used to reference the chunk of data. When ‘MHD_AccessHandlerCallback’ is invoked for a new request: its ‘*REQ_CLS’ argument is set to ‘NULL’. When ‘POST’ data comes in the upload buffer it is *mandatory* to use the REQ_CLS to store a reference to per-request data. The fact that the pointer was initially ‘NULL’ can be used to detect that this is a new request. One method to detect that a new request was started is to set ‘*req_cls’ to an unused integer: int access_handler (void *cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { static int old_connection_marker; int new_connection = (NULL == *req_cls); if (new_connection) { /* new connection with POST */ *req_cls = &old_connection_marker; } ... } In contrast to the previous example, for ‘POST’ requests in particular, it is more common to use the value of ‘*req_cls’ to keep track of actual state used during processing, such as the post processor (or a struct containing a post processor): int access_handler (void *cls, struct MHD_Connection * connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_PostProcessor * pp = *req_cls; if (pp == NULL) { pp = MHD_create_post_processor(connection, ...); *req_cls = pp; return MHD_YES; } if (*upload_data_size) { MHD_post_process(pp, upload_data, *upload_data_size); *upload_data_size = 0; return MHD_YES; } else { MHD_destroy_post_processor(pp); return MHD_queue_response(...); } } Note that the callback from ‘MHD_OPTION_NOTIFY_COMPLETED’ should be used to destroy the post processor. This cannot be done inside of the access handler since the connection may not always terminate normally.  File: libmicrohttpd.info, Node: microhttpd-post api, Up: microhttpd-post 11.1 Programming interface for the ‘POST’ processor =================================================== -- Function: struct MHD_PostProcessor * MHD_create_post_processor (struct MHD_Connection *connection, size_t buffer_size, MHD_PostDataIterator iterator, void *iterator_cls) Create a PostProcessor. A PostProcessor can be used to (incrementally) parse the data portion of a ‘POST’ request. CONNECTION the connection on which the ‘POST’ is happening (used to determine the ‘POST’ format); BUFFER_SIZE maximum number of bytes to use for internal buffering (used only for the parsing, specifically the parsing of the keys). A tiny value (256-1024) should be sufficient; do *NOT* use a value smaller than 256; for good performance, use 32k or 64k (i.e. 65536). ITERATOR iterator to be called with the parsed data; must *NOT* be ‘NULL’; ITERATOR_CLS custom value to be used as first argument to ITERATOR. Return ‘NULL’ on error (out of memory, unsupported encoding), otherwise a PP handle. -- Function: enum MHD_Result MHD_post_process (struct MHD_PostProcessor *pp, const char *post_data, size_t post_data_len) Parse and process ‘POST’ data. Call this function when ‘POST’ data is available (usually during an ‘MHD_AccessHandlerCallback’) with the UPLOAD_DATA and UPLOAD_DATA_SIZE. Whenever possible, this will then cause calls to the ‘MHD_IncrementalKeyValueIterator’. PP the post processor; POST_DATA POST_DATA_LEN bytes of ‘POST’ data; POST_DATA_LEN length of POST_DATA. Return ‘MHD_YES’ on success, ‘MHD_NO’ on error (out-of-memory, iterator aborted, parse error). -- Function: enum MHD_Result MHD_destroy_post_processor (struct MHD_PostProcessor *pp) Release PostProcessor resources. After this function is being called, the PostProcessor is guaranteed to no longer call its iterator. There is no special call to the iterator to indicate the end of the post processing stream. After destroying the PostProcessor, the programmer should perform any necessary work to complete the processing of the iterator. Return ‘MHD_YES’ if processing completed nicely, ‘MHD_NO’ if there were spurious characters or formatting problems with the post request. It is common to ignore the return value of this function.  File: libmicrohttpd.info, Node: microhttpd-info, Next: microhttpd-util, Prev: microhttpd-post, Up: Top 12 Obtaining and modifying status information. ********************************************** * Menu: * microhttpd-info daemon:: State information about an MHD daemon * microhttpd-info conn:: State information about a connection * microhttpd-option conn:: Modify per-connection options  File: libmicrohttpd.info, Node: microhttpd-info daemon, Next: microhttpd-info conn, Up: microhttpd-info 12.1 Obtaining state information about an MHD daemon ==================================================== -- Function: const union MHD_DaemonInfo * MHD_get_daemon_info (struct MHD_Daemon *daemon, enum MHD_DaemonInfoType infoType, ...) Obtain information about the given daemon. This function is currently not fully implemented. DAEMON the daemon about which information is desired; INFOTYPE type of information that is desired ... additional arguments about the desired information (depending on infoType) Returns a union with the respective member (depending on infoType) set to the desired information), or ‘NULL’ in case the desired information is not available or applicable. -- Enumeration: MHD_DaemonInfoType Values of this enum are used to specify what information about a daemon is desired. ‘MHD_DAEMON_INFO_KEY_SIZE’ Request information about the key size for a particular cipher algorithm. The cipher algorithm should be passed as an extra argument (of type 'enum MHD_GNUTLS_CipherAlgorithm'). No longer supported, using this value will cause ‘MHD_get_daemon_info’ to return NULL. ‘MHD_DAEMON_INFO_MAC_KEY_SIZE’ Request information about the key size for a particular cipher algorithm. The cipher algorithm should be passed as an extra argument (of type 'enum MHD_GNUTLS_HashAlgorithm'). No longer supported, using this value will cause ‘MHD_get_daemon_info’ to return NULL. ‘MHD_DAEMON_INFO_LISTEN_FD’ Request the file-descriptor number that MHD is using to listen to the server socket. This can be useful if no port was specified and a client needs to learn what port is actually being used by MHD. No extra arguments should be passed. ‘MHD_DAEMON_INFO_EPOLL_FD’ Request the file-descriptor number that MHD is using for epoll. If the build is not supporting epoll, NULL is returned; if we are using a thread pool or this daemon was not started with ‘MHD_USE_EPOLL’, (a pointer to) -1 is returned. If we are using ‘MHD_USE_INTERNAL_POLLING_THREAD’ or are in 'external' select mode, the internal epoll FD is returned. This function must be used in external select mode with epoll to obtain the FD to call epoll on. No extra arguments should be passed. ‘MHD_DAEMON_INFO_CURRENT_CONNECTIONS’ Request the number of current connections handled by the daemon. No extra arguments should be passed and a pointer to a ‘union MHD_DaemonInfo’ value is returned, with the ‘num_connections’ member of type ‘unsigned int’ set to the number of active connections. Note that in multi-threaded or internal-select mode, the real number of current connections may already be different when ‘MHD_get_daemon_info’ returns. The number of current connections can be used (even in multi-threaded and internal-select mode) after ‘MHD_quiesce_daemon’ to detect whether all connections have been handled.  File: libmicrohttpd.info, Node: microhttpd-info conn, Next: microhttpd-option conn, Prev: microhttpd-info daemon, Up: microhttpd-info 12.2 Obtaining state information about a connection =================================================== -- Function: const union MHD_ConnectionInfo * MHD_get_connection_info (struct MHD_Connection *connection, enum MHD_ConnectionInfoType infoType, ...) Obtain information about the given connection. CONNECTION the connection about which information is desired; INFOTYPE type of information that is desired ... additional arguments about the desired information (depending on infoType) Returns a union with the respective member (depending on infoType) set to the desired information), or ‘NULL’ in case the desired information is not available or applicable. -- Enumeration: MHD_ConnectionInfoType Values of this enum are used to specify what information about a connection is desired. ‘MHD_CONNECTION_INFO_CIPHER_ALGO’ What cipher algorithm is being used (HTTPS connections only). ‘NULL’ is returned for non-HTTPS connections. Takes no extra arguments. ‘MHD_CONNECTION_INFO_PROTOCOL,’ Allows finding out the TLS/SSL protocol used (HTTPS connections only). ‘NULL’ is returned for non-HTTPS connections. Takes no extra arguments. ‘MHD_CONNECTION_INFO_CLIENT_ADDRESS’ Returns information about the address of the client. Returns essentially a ‘struct sockaddr **’ (since the API returns a ‘union MHD_ConnectionInfo *’ and that union contains a ‘struct sockaddr *’). Takes no extra arguments. ‘MHD_CONNECTION_INFO_GNUTLS_SESSION,’ Takes no extra arguments. Allows access to the underlying GNUtls session, including access to the underlying GNUtls client certificate (HTTPS connections only). Takes no extra arguments. ‘NULL’ is returned for non-HTTPS connections. Takes no extra arguments. ‘MHD_CONNECTION_INFO_GNUTLS_CLIENT_CERT,’ Dysfunctional (never implemented, deprecated). Use MHD_CONNECTION_INFO_GNUTLS_SESSION to get the ‘gnutls_session_t’ and then call ‘gnutls_certificate_get_peers()’. ‘MHD_CONNECTION_INFO_DAEMON’ Returns information about ‘struct MHD_Daemon’ which manages this connection. Takes no extra arguments. ‘MHD_CONNECTION_INFO_CONNECTION_FD’ Returns the file descriptor (usually a TCP socket) associated with this connection (in the "connect-fd" member of the returned struct). Note that manipulating the descriptor directly can have problematic consequences (as in, break HTTP). Applications might use this access to manipulate TCP options, for example to set the "TCP-NODELAY" option for COMET-like applications. Note that MHD will set TCP-CORK after sending the HTTP header and clear it after finishing the footers automatically (if the platform supports it). As the connection callbacks are invoked in between, those might be used to set different values for TCP-CORK and TCP-NODELAY in the meantime. Takes no extra arguments. ‘MHD_CONNECTION_INFO_CONNECTION_SUSPENDED’ Returns pointer to an integer that is ‘MHD_YES’ if the connection is currently suspended (and thus can be safely resumed) and ‘MHD_NO’ otherwise. Takes no extra arguments. ‘MHD_CONNECTION_INFO_SOCKET_CONTEXT’ Returns the client-specific pointer to a ‘void *’ that was (possibly) set during a ‘MHD_NotifyConnectionCallback’ when the socket was first accepted. Note that this is NOT the same as the ‘req_cls’ argument of the ‘MHD_AccessHandlerCallback’. The ‘req_cls’ is fresh for each HTTP request, while the ‘socket_context’ is fresh for each socket. Takes no extra arguments. ‘MHD_CONNECTION_INFO_CONNECTION_TIMEOUT’ Returns pointer to an ‘unsigned int’ that is the current timeout used for the connection (in seconds, 0 for no timeout). Note that while suspended connections will not timeout, the timeout value returned for suspended connections will be the timeout that the connection will use after it is resumed, and thus might not be zero. Takes no extra arguments. ‘MHD_CONNECTION_INFO_REQUEST_HEADER_SIZE’ Returns pointer to an ‘size_t’ that represents the size of the HTTP header received from the client. Only valid after the first callback to the access handler. Takes no extra arguments. ‘MHD_CONNECTION_INFO_HTTP_STATUS’ Returns the HTTP status code of the response that was queued. Returns NULL if no response was queued yet. Takes no extra arguments.  File: libmicrohttpd.info, Node: microhttpd-option conn, Prev: microhttpd-info conn, Up: microhttpd-info 12.3 Setting custom options for an individual connection ======================================================== -- Function: int MHD_set_connection_option (struct MHD_Connection *daemon, enum MHD_CONNECTION_OPTION option, ...) Set a custom option for the given connection. CONNECTION the connection for which an option should be set or modified; OPTION option to set ... additional arguments for the option (depending on option) Returns ‘MHD_YES’ on success, ‘MHD_NO’ for errors (i.e. option argument invalid or option unknown). -- Enumeration: MHD_CONNECTION_OPTION Values of this enum are used to specify which option for a connection should be changed. ‘MHD_CONNECTION_OPTION_TIMEOUT’ Set a custom timeout for the given connection. Specified as the number of seconds, given as an ‘unsigned int’. Use zero for no timeout.  File: libmicrohttpd.info, Node: microhttpd-util, Next: GNU-LGPL, Prev: microhttpd-info, Up: Top 13 Utility functions. ********************* * Menu: * microhttpd-util feature:: Test supported MHD features * microhttpd-util unescape:: Unescape strings  File: libmicrohttpd.info, Node: microhttpd-util feature, Next: microhttpd-util unescape, Up: microhttpd-util 13.1 Testing for supported MHD features ======================================= -- Enumeration: MHD_FEATURE Values of this enum are used to specify what information about a daemon is desired. ‘MHD_FEATURE_MESSAGES’ Get whether messages are supported. If supported then in debug mode messages can be printed to stderr or to external logger. ‘MHD_FEATURE_SSL’ Get whether HTTPS is supported. If supported then flag MHD_USE_SSL and options MHD_OPTION_HTTPS_MEM_KEY, MHD_OPTION_HTTPS_MEM_CERT, MHD_OPTION_HTTPS_MEM_TRUST, MHD_OPTION_HTTPS_MEM_DHPARAMS, MHD_OPTION_HTTPS_CRED_TYPE, MHD_OPTION_HTTPS_PRIORITIES can be used. ‘MHD_FEATURE_HTTPS_CERT_CALLBACK’ Get whether option #MHD_OPTION_HTTPS_CERT_CALLBACK is supported. ‘MHD_FEATURE_IPv6’ Get whether IPv6 is supported. If supported then flag MHD_USE_IPv6 can be used. ‘MHD_FEATURE_IPv6_ONLY’ Get whether IPv6 without IPv4 is supported. If not supported then IPv4 is always enabled in IPv6 sockets and flag MHD_USE_DUAL_STACK if always used when MHD_USE_IPv6 is specified. ‘MHD_FEATURE_POLL’ Get whether ‘poll()’ is supported. If supported then flag MHD_USE_POLL can be used. ‘MHD_FEATURE_EPOLL’ Get whether ‘epoll()’ is supported. If supported then Flags MHD_USE_EPOLL and MHD_USE_EPOLL_INTERNAL_THREAD can be used. ‘MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET’ Get whether shutdown on listen socket to signal other threads is supported. If not supported flag MHD_USE_ITC is automatically forced. ‘MHD_FEATURE_SOCKETPAIR’ Get whether a ‘socketpair()’ is used internally instead of a ‘pipe()’ to signal other threads. ‘MHD_FEATURE_TCP_FASTOPEN’ Get whether TCP Fast Open is supported. If supported then flag MHD_USE_TCP_FASTOPEN and option MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE can be used. ‘MHD_FEATURE_BASIC_AUTH’ Get whether HTTP Basic authorization is supported. If supported then functions ‘MHD_basic_auth_get_username_password()’ and ‘MHD_queue_basic_auth_fail_response()’ can be used. ‘MHD_FEATURE_DIGEST_AUTH’ Get whether HTTP Digest authorization is supported. If supported then options MHD_OPTION_DIGEST_AUTH_RANDOM, MHD_OPTION_NONCE_NC_SIZE and functions ‘MHD_digest_auth_check()’, can be used. ‘MHD_FEATURE_POSTPROCESSOR’ Get whether postprocessor is supported. If supported then functions ‘MHD_create_post_processor()’, ‘MHD_post_process()’, ‘MHD_destroy_post_processor()’ can be used. ‘MHD_FEATURE_SENDFILE’ Get whether ‘sendfile()’ is supported. -- Function: int MHD_is_feature_supported (enum MHD_FEATURE feature) Get information about supported MHD features. Indicate that MHD was compiled with or without support for particular feature. Some features require additional support by the kernel. However, kernel support is not checked by this function. FEATURE type of requested information Returns ‘MHD_YES’ if the feature is supported, and ‘MHD_NO’ if not.  File: libmicrohttpd.info, Node: microhttpd-util unescape, Prev: microhttpd-util feature, Up: microhttpd-util 13.2 Unescape strings ===================== -- Function: size_t MHD_http_unescape (char *val) Process escape sequences ('%HH') Updates val in place; the result should be UTF-8 encoded and cannot be larger than the input. The result must also still be 0-terminated. VAL value to unescape (modified in the process), must be a 0-terminated UTF-8 string. Returns length of the resulting val (‘strlen(val)’ may be shorter afterwards due to elimination of escape sequences).  File: libmicrohttpd.info, Node: GNU-LGPL, Next: eCos License, Prev: microhttpd-util, Up: Top GNU-LGPL ******** Version 2.1, February 1999 Copyright © 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble -------- The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the “Lesser” General Public License because it does _Less_ to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION --------------------------------------------------------------- 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a. The modified work must itself be a software library. b. You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c. You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d. If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a. Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b. Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c. Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d. If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e. Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a. Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b. Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS --------------------------- How to Apply These Terms to Your New Libraries ---------------------------------------------- If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. ONE LINE TO GIVE THE LIBRARY'S NAME AND AN IDEA OF WHAT IT DOES. Copyright (C) YEAR NAME OF AUTHOR This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. SIGNATURE OF TY COON, 1 April 1990 Ty Coon, President of Vice That's all there is to it!  File: libmicrohttpd.info, Node: eCos License, Next: GNU-GPL, Prev: GNU-LGPL, Up: Top eCos License ************ GNU libmicrohttpd is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 or (at your option) any later version. GNU libmicrohttpd is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU libmicrohttpd; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other works to produce a work based on this file, this file does not by itself cause the resulting work to be covered by the GNU General Public License. However the source code for this file must still be made available in accordance with section (3) of the GNU General Public License v2. This exception does not invalidate any other reasons why a work based on this file might be covered by the GNU General Public License.  File: libmicrohttpd.info, Node: GNU-GPL, Next: GNU-FDL, Prev: eCos License, Up: Top GNU General Public License ************************** Version 2, June 1991 Copyright © 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble ======== The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION =============================================================== 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a. You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b. You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c. If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a. Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b. Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c. Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs ======================================================= If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES. Copyright (C) YYYY NAME OF AUTHOR This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) YEAR NAME OF AUTHOR Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands ‘show w’ and ‘show c’ should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than ‘show w’ and ‘show c’; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. SIGNATURE OF TY COON, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.  File: libmicrohttpd.info, Node: GNU-FDL, Next: Concept Index, Prev: GNU-GPL, Up: Top GNU-FDL ******* Version 1.3, 3 November 2008 Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 0. PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document “free” in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of "copyleft", which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 1. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transparent" is called "Opaque". Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text. The "publisher" means any person or entity that distributes copies of the Document to the public. A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. 2. VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. 3. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 4. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. B. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. C. State on the Title page the name of the publisher of the Modified Version, as the publisher. D. Preserve all the copyright notices of the Document. E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. G. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice. H. Include an unaltered copy of this License. I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. M. Delete any section Entitled "Endorsements". Such a section may not be included in the Modified Version. N. Do not retitle any existing section to be Entitled "Endorsements" or to conflict in title with any Invariant Section. O. Preserve any Warranty Disclaimers. If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles. You may add a section Entitled "Endorsements", provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 5. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements." 6. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. 7. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. 8. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. 9. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it. 10. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See . Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Document. 11. RELICENSING "Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site. "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. "Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. ADDENDUM: How to use this License for your documents ==================================================== To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: Copyright (C) YEAR YOUR NAME. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the "with...Texts." line with this: with the Invariant Sections being LIST THEIR TITLES, with the Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.  File: libmicrohttpd.info, Node: Concept Index, Next: Function and Data Index, Prev: GNU-FDL, Up: Top Concept Index ************* [index] * Menu: * ARM: microhttpd-intro. (line 285) * bind, restricting bind: microhttpd-const. (line 330) * bind, restricting bind <1>: microhttpd-const. (line 567) * cipher: microhttpd-const. (line 403) * clock: microhttpd-const. (line 105) * compilation: microhttpd-intro. (line 123) * connection, limiting number of connections: microhttpd-const. (line 209) * connection, limiting number of connections <1>: microhttpd-info daemon. (line 60) * cookie: microhttpd-const. (line 599) * cortex m3: microhttpd-intro. (line 285) * date: microhttpd-const. (line 105) * debugging: microhttpd-const. (line 31) * debugging <1>: microhttpd-const. (line 341) * deprecated: microhttpd-const. (line 61) * DH: microhttpd-const. (line 559) * digest auth: microhttpd-const. (line 444) * digest auth <1>: microhttpd-const. (line 455) * eCos, GNU General Public License with eCos Extension: eCos License. (line 6) * embedded systems: microhttpd-intro. (line 123) * embedded systems <1>: microhttpd-intro. (line 285) * embedded systems <2>: microhttpd-const. (line 105) * embedded systems <3>: microhttpd-const. (line 112) * embedded systems <4>: microhttpd-const. (line 543) * epoll: microhttpd-intro. (line 67) * epoll <1>: microhttpd-const. (line 77) * epoll <2>: microhttpd-info daemon. (line 49) * escaping: microhttpd-const. (line 526) * FD_SETSIZE: microhttpd-const. (line 70) * FD_SETSIZE <1>: microhttpd-const. (line 77) * foreign-function interface: microhttpd-const. (line 504) * HTTP2: microhttpd-response upgrade. (line 6) * IAR: microhttpd-intro. (line 285) * internationalization: microhttpd-const. (line 526) * IPv6: microhttpd-const. (line 45) * IPv6 <1>: microhttpd-const. (line 55) * license: GNU-LGPL. (line 6) * license <1>: eCos License. (line 6) * license <2>: GNU-GPL. (line 6) * license <3>: GNU-FDL. (line 6) * listen: microhttpd-const. (line 112) * listen <1>: microhttpd-const. (line 143) * listen <2>: microhttpd-const. (line 549) * listen <3>: microhttpd-info daemon. (line 43) * logging: microhttpd-const. (line 341) * logging <1>: microhttpd-const. (line 485) * long long: microhttpd-intro. (line 285) * memory: microhttpd-const. (line 201) * memory, limiting memory utilization: microhttpd-const. (line 193) * MHD_LONG_LONG: microhttpd-intro. (line 285) * microhttpd.h: microhttpd-intro. (line 224) * OCSP: microhttpd-const. (line 426) * options: microhttpd-const. (line 504) * performance: microhttpd-intro. (line 91) * performance <1>: microhttpd-const. (line 90) * performance <2>: microhttpd-const. (line 496) * performance <3>: microhttpd-info conn. (line 114) * poll: microhttpd-intro. (line 67) * poll <1>: microhttpd-const. (line 70) * poll <2>: microhttpd-init. (line 74) * portability: microhttpd-intro. (line 123) * portability <1>: microhttpd-intro. (line 224) * POST method: microhttpd-const. (line 603) * POST method <1>: microhttpd-struct. (line 22) * POST method <2>: microhttpd-cb. (line 48) * POST method <3>: microhttpd-post. (line 6) * POST method <4>: microhttpd-post api. (line 6) * proxy: microhttpd-const. (line 112) * PSK: microhttpd-const. (line 436) * pthread: microhttpd-const. (line 543) * PUT method: microhttpd-cb. (line 48) * query string: microhttpd-const. (line 341) * quiesce: microhttpd-const. (line 119) * quiesce <1>: microhttpd-init. (line 51) * random: microhttpd-const. (line 444) * replay attack: microhttpd-const. (line 455) * reusing listening address: microhttpd-const. (line 567) * RFC2817: microhttpd-response upgrade. (line 6) * select: microhttpd-intro. (line 67) * select <1>: microhttpd-const. (line 70) * select <2>: microhttpd-const. (line 77) * select <3>: microhttpd-init. (line 74) * select <4>: microhttpd-init. (line 89) * signals: microhttpd-intro. (line 246) * SNI: microhttpd-const. (line 411) * SNI <1>: microhttpd-const. (line 426) * SSL: microhttpd-const. (line 34) * SSL <1>: microhttpd-const. (line 364) * SSL <2>: microhttpd-const. (line 370) * SSL <3>: microhttpd-const. (line 380) * SSL <4>: microhttpd-const. (line 386) * SSL <5>: microhttpd-const. (line 398) * SSL <6>: microhttpd-const. (line 403) * SSL <7>: microhttpd-const. (line 411) * SSL <8>: microhttpd-const. (line 426) * SSL <9>: microhttpd-const. (line 436) * SSL <10>: microhttpd-const. (line 559) * stack: microhttpd-const. (line 543) * systemd: microhttpd-const. (line 478) * testing: microhttpd-const. (line 319) * thread: microhttpd-const. (line 543) * timeout: microhttpd-const. (line 247) * timeout <1>: microhttpd-inspect. (line 39) * timeout <2>: microhttpd-option conn. (line 6) * TLS: microhttpd-const. (line 34) * TLS <1>: microhttpd-const. (line 364) * TLS <2>: microhttpd-const. (line 370) * TLS <3>: microhttpd-const. (line 380) * TLS <4>: microhttpd-const. (line 386) * TLS <5>: microhttpd-const. (line 398) * TLS <6>: microhttpd-const. (line 403) * TLS <7>: microhttpd-const. (line 411) * TLS <8>: microhttpd-const. (line 426) * TLS <9>: microhttpd-const. (line 436) * TLS <10>: microhttpd-const. (line 559) * upgrade: microhttpd-const. (line 148) * Upgrade: microhttpd-response upgrade. (line 6) * WebSockets: microhttpd-response upgrade. (line 6)  File: libmicrohttpd.info, Node: Function and Data Index, Next: Type Index, Prev: Concept Index, Up: Top Function and Data Index *********************** [index] * Menu: * *MHD_ContentReaderCallback: microhttpd-cb. (line 150) * *MHD_ContentReaderFreeCallback: microhttpd-cb. (line 197) * *MHD_RequestCompletedCallback: microhttpd-cb. (line 96) * *MHD_UpgradeHandler: microhttpd-response upgrade. (line 37) * MHD_add_connection: microhttpd-init. (line 115) * MHD_basic_auth_get_username_password3: microhttpd-dauth basic. (line 10) * MHD_create_post_processor: microhttpd-post api. (line 6) * MHD_create_response_from_buffer: microhttpd-response create. (line 104) * MHD_create_response_from_buffer_with_free_callback: microhttpd-response create. (line 125) * MHD_create_response_from_callback: microhttpd-response create. (line 6) * MHD_create_response_from_data: microhttpd-response create. (line 143) * MHD_create_response_from_fd: microhttpd-response create. (line 32) * MHD_create_response_from_fd_at_offset: microhttpd-response create. (line 62) * MHD_create_response_from_iovec: microhttpd-response create. (line 179) * MHD_create_response_from_pipe: microhttpd-response create. (line 50) * MHD_destroy_response: microhttpd-response enqueue. (line 29) * MHD_digest_auth_check: microhttpd-dauth digest. (line 111) * MHD_digest_auth_check_digest: microhttpd-dauth digest. (line 185) * MHD_digest_auth_check_digest2: microhttpd-dauth digest. (line 160) * MHD_digest_auth_check2: microhttpd-dauth digest. (line 86) * MHD_digest_auth_get_username: microhttpd-dauth digest. (line 55) * MHD_DigestAuthResult: microhttpd-dauth digest. (line 62) * MHD_DigestAuthResult <1>: microhttpd-dauth digest. (line 134) * MHD_free: microhttpd-dauth basic. (line 6) * MHD_get_connection_info: microhttpd-info conn. (line 6) * MHD_get_connection_values: microhttpd-requests. (line 6) * MHD_get_daemon_info: microhttpd-info daemon. (line 6) * MHD_get_response_header: microhttpd-response inspect. (line 18) * MHD_get_response_headers: microhttpd-response inspect. (line 6) * MHD_http_unescape: microhttpd-util unescape. (line 6) * MHD_is_feature_supported: microhttpd-util feature. (line 77) * MHD_lookup_connection_value: microhttpd-requests. (line 58) * MHD_lookup_connection_value_n: microhttpd-requests. (line 67) * MHD_queue_basic_auth_fail_response3: microhttpd-dauth basic. (line 19) * MHD_quiesce_daemon: microhttpd-init. (line 50) * MHD_Result: microhttpd-cb. (line 6) * MHD_Result <1>: microhttpd-cb. (line 19) * MHD_Result <2>: microhttpd-cb. (line 116) * MHD_Result <3>: microhttpd-cb. (line 202) * MHD_Result <4>: microhttpd-init. (line 70) * MHD_Result <5>: microhttpd-init. (line 86) * MHD_Result <6>: microhttpd-inspect. (line 6) * MHD_Result <7>: microhttpd-inspect. (line 31) * MHD_Result <8>: microhttpd-inspect. (line 37) * MHD_Result <9>: microhttpd-requests. (line 35) * MHD_Result <10>: microhttpd-response enqueue. (line 6) * MHD_Result <11>: microhttpd-response headers. (line 6) * MHD_Result <12>: microhttpd-response headers. (line 30) * MHD_Result <13>: microhttpd-response headers. (line 47) * MHD_Result <14>: microhttpd-response options. (line 6) * MHD_Result <15>: microhttpd-response upgrade. (line 23) * MHD_Result <16>: microhttpd-response upgrade. (line 91) * MHD_Result <17>: microhttpd-flow. (line 20) * MHD_Result <18>: microhttpd-flow. (line 56) * MHD_Result <19>: microhttpd-dauth digest. (line 208) * MHD_Result <20>: microhttpd-dauth digest. (line 235) * MHD_Result <21>: microhttpd-post api. (line 33) * MHD_Result <22>: microhttpd-post api. (line 52) * MHD_set_connection_option: microhttpd-option conn. (line 6) * MHD_set_panic_func: microhttpd-init. (line 6) * MHD_start_daemon: microhttpd-init. (line 18) * MHD_stop_daemon: microhttpd-init. (line 67)  File: libmicrohttpd.info, Node: Type Index, Prev: Function and Data Index, Up: Top Type Index ********** [index] * Menu: * MHD_Connection: microhttpd-struct. (line 9) * MHD_CONNECTION_OPTION: microhttpd-option conn. (line 22) * MHD_ConnectionInfo: microhttpd-struct. (line 24) * MHD_ConnectionInfoType: microhttpd-info conn. (line 25) * MHD_Daemon: microhttpd-struct. (line 6) * MHD_DaemonInfo: microhttpd-struct. (line 27) * MHD_DaemonInfoType: microhttpd-info daemon. (line 25) * MHD_DigestAuthAlgorithm: microhttpd-dauth digest. (line 10) * MHD_DigestAuthResult: microhttpd-dauth digest. (line 23) * MHD_FEATURE: microhttpd-util feature. (line 6) * MHD_FLAG: microhttpd-const. (line 6) * MHD_IoVec: microhttpd-struct. (line 18) * MHD_OPTION: microhttpd-const. (line 184) * MHD_OptionItem: microhttpd-const. (line 578) * MHD_PostProcessor: microhttpd-struct. (line 21) * MHD_RequestTerminationCode: microhttpd-const. (line 616) * MHD_Response: microhttpd-struct. (line 15) * MHD_ResponseFlags: microhttpd-const. (line 656) * MHD_ResponseMemoryMode: microhttpd-const. (line 634) * MHD_ResponseOptions: microhttpd-const. (line 701) * MHD_UpgradeAction: microhttpd-response upgrade. (line 103) * MHD_ValueKind: microhttpd-const. (line 591)  Tag Table: Node: Top814 Node: microhttpd-intro3101 Ref: fig:performance8012 Ref: tbl:supported8984 Node: microhttpd-const17409 Node: microhttpd-struct53245 Node: microhttpd-cb54101 Node: microhttpd-init64359 Node: microhttpd-inspect70237 Node: microhttpd-requests73014 Node: microhttpd-responses77064 Node: microhttpd-response enqueue78263 Ref: microhttpd-response enqueue-Footnote-180588 Node: microhttpd-response create80823 Node: microhttpd-response headers88833 Node: microhttpd-response options91307 Node: microhttpd-response inspect92190 Node: microhttpd-response upgrade93411 Node: microhttpd-flow98753 Node: microhttpd-dauth103266 Node: microhttpd-dauth basic104826 Node: microhttpd-dauth digest106417 Node: microhttpd-post120028 Node: microhttpd-post api123012 Node: microhttpd-info125680 Node: microhttpd-info daemon126096 Node: microhttpd-info conn129544 Node: microhttpd-option conn134803 Node: microhttpd-util135883 Node: microhttpd-util feature136150 Node: microhttpd-util unescape139736 Node: GNU-LGPL140380 Node: eCos License168473 Node: GNU-GPL169864 Node: GNU-FDL189126 Node: Concept Index214195 Node: Function and Data Index223641 Node: Type Index230799  End Tag Table  Local Variables: coding: utf-8 End: libmicrohttpd-1.0.10/doc/chapters/0000775000175000017500000000000015235437006012563 5libmicrohttpd-1.0.10/doc/chapters/exploringrequests.inc0000664000175000017500000001250715232165355017010 This chapter will deal with the information which the client sends to the server at every request. We are going to examine the most useful fields of such a request and print them out in a readable manner. This could be useful for logging facilities. The starting point is the @emph{hellobrowser} program with the former response removed. This time, we just want to collect information in the callback function, thus we will just return MHD_NO after we have probed the request. This way, the connection is closed without much ado by the server. @verbatim static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { ... return MHD_NO; } @end verbatim @noindent The ellipsis marks the position where the following instructions shall be inserted. We begin with the most obvious information available to the server, the request line. You should already have noted that a request consists of a command (or "HTTP method") and a URI (e.g. a filename). It also contains a string for the version of the protocol which can be found in @code{version}. To call it a "new request" is justified because we return only @code{MHD_NO}, thus ensuring the function will not be called again for this connection. @verbatim printf ("New %s request for %s using version %s\n", method, url, version); @end verbatim @noindent The rest of the information is a bit more hidden. Nevertheless, there is a lot of it sent from common Internet browsers. It is stored in "key-value" pairs and we want to list what we find in the header. As there is no mandatory set of keys a client has to send, each key-value pair is printed out one by one until there are no more left. We do this by writing a separate function which will be called for each pair just like the above function is called for each HTTP request. It can then print out the content of this pair. @verbatim static enum MHD_Result print_out_key (void *cls, enum MHD_ValueKind kind, const char *key, const char *value) { printf ("%s: %s\n", key, value); return MHD_YES; } @end verbatim @noindent To start the iteration process that calls our new function for every key, the line @verbatim MHD_get_connection_values (connection, MHD_HEADER_KIND, &print_out_key, NULL); @end verbatim @noindent needs to be inserted in the connection callback function too. The second parameter tells the function that we are only interested in keys from the general HTTP header of the request. Our iterating function @code{print_out_key} does not rely on any additional information to fulfill its duties so the last parameter can be NULL. All in all, this constitutes the complete @code{logging.c} program for this chapter which can be found in the @code{examples} section. Connecting with any modern Internet browser should yield a handful of keys. You should try to interpret them with the aid of @emph{RFC 9110}. Especially worth mentioning is the "Host" key which is often used to serve several different websites hosted under one single IP address but reachable by different domain names (this is called virtual hosting). @heading Conclusion The introduced capabilities to itemize the content of a simple GET request---especially the URI---should already allow the server to satisfy clients' requests for small specific resources (e.g. files) or even induce alteration of server state. However, the latter is not recommended as the GET method (including its header data) is by convention considered a "safe" operation, which should not change the server's state in a significant way. By convention, GET operations can thus be performed by crawlers and other automatic software. Naturally actions like searching for a passed string are fine. Of course, no transmission can occur while the return value is still set to @code{MHD_NO} in the callback function. @heading Exercises @itemize @bullet @item By parsing the @code{url} string and delivering responses accordingly, implement a small server for "virtual" files. When asked for @code{/index.htm@{l@}}, let the response consist of a HTML page containing a link to @code{/another.html} page which is also to be created "on the fly" in case of being requested. If neither of these two pages are requested, @code{MHD_HTTP_NOT_FOUND} shall be returned accompanied by an informative message. @item A very interesting information has still been ignored by our logger---the client's IP address. Implement a callback function @verbatim static enum MHD_Result on_client_connect (void *cls, const struct sockaddr *addr, socklen_t addrlen) @end verbatim @noindent that prints out the IP address in an appropriate format. You might want to use the POSIX function @code{inet_ntoa} but bear in mind that @code{addr} is actually just a structure containing other substructures and is @emph{not} the variable this function expects. Make sure to return @code{MHD_YES} so that the library knows the client is allowed to connect (and to then process the request). If one wanted to limit access basing on IP addresses, this would be the place to do it. The address of your @code{on_client_connect} function must be passed as the third parameter to the @code{MHD_start_daemon} call. @end itemize libmicrohttpd-1.0.10/doc/chapters/callbackresponse.inc0000664000175000017500000004445615232212544016521 All responses we have built so far were complete before they were queued. @code{MHD_create_response_from_buffer()} needs the whole answer to be sitting in memory already, and @code{MHD_create_response_from_fd()} needs it to be a file that the operating system can read for us. Neither fits an answer that is computed while it is being sent: the output of a long-running report, a log file that is filtered on the fly, the result of a database cursor, or simply a document that is far too large to be worth assembling in a buffer first. For those cases @emph{libmicrohttpd} lets the application hand over a callback instead of the data. Whenever @emph{MHD} has room on the socket, it calls that function and asks for the next few bytes. The application only ever needs one modest buffer, and the client starts receiving the answer long before the last byte has been produced. @heading Creating the response The response object is created with @verbatim struct MHD_Response * MHD_create_response_from_callback (uint64_t size, size_t block_size, MHD_ContentReaderCallback crc, void *crc_cls, MHD_ContentReaderFreeCallback crfc); @end verbatim @noindent The five arguments are: @table @code @item size The total length of the body in bytes, or the constant @code{MHD_SIZE_UNKNOWN} if the application does not know it in advance. If a concrete number is given, @emph{MHD} announces it as @code{Content-Length} and expects the callback to deliver exactly that many bytes. @item block_size The buffer size @emph{MHD} should use when it queries the callback. The value must not be zero---@code{MHD_create_response_from_callback()} returns @code{NULL} otherwise. @emph{MHD} allocates a buffer of that size together with the response object. Note that this buffer is only used for responses of known size; when chunked transfer encoding is in use (see below) the data is collected in the connection's own memory pool instead, and @code{block_size} has no influence on how much @emph{MHD} asks for. In either case the value is advisory: the callback must always look at the @code{max} argument it is passed and never write more than that. @item crc The content reader callback itself, described in the next section. @item crc_cls An arbitrary pointer that is passed back to @code{crc} on every invocation. This is where the per-request state goes. @item crfc A callback that is invoked once, when the response object is destroyed, so that @code{crc_cls} can be released. May be @code{NULL} if there is nothing to clean up. @end table @heading The content reader callback The callback has the following signature: @verbatim typedef ssize_t (*MHD_ContentReaderCallback) (void *cls, uint64_t pos, char *buf, size_t max); @end verbatim @noindent @code{cls} is the @code{crc_cls} pointer given at creation time. @code{buf} points to the memory @emph{MHD} wants filled and @code{max} is the number of bytes that may be written there. The @code{pos} argument deserves a closer look, because its meaning depends on how the response is used. For a response created from a file descriptor, @emph{MHD} uses it as a file offset and reads with @code{pread()}; that is what makes such a response object reusable for many connections. For a response that is created fresh for each request---which is what we do here---@emph{MHD} guarantees that @code{pos} is simply the sum of all non-negative values the callback has returned so far. In other words: for a stream, @code{pos} is a monotonically increasing count of the bytes already produced, and the callback will never be asked to go back. A generator that has no use for random access can ignore @code{pos} completely. Do note that the guarantee only holds as long as the response object is used for one request; if the same object is queued for several connections, the same content reader may be asked for the same data more than once, and sharing one mutable buffer between them would be wrong. The return value tells @emph{MHD} what happened: @table @asis @item a positive number That many bytes were written to @code{buf}. Returning more than @code{max} is a fatal application error and makes @emph{MHD} close the connection. @item @code{MHD_CONTENT_READER_END_OF_STREAM} The body is complete. With chunked encoding @emph{MHD} terminates the chunk sequence properly and appends any footers; without chunked encoding and an unknown size it simply closes the connection. If a concrete @code{size} was announced, ending the stream early is not legal, and @emph{MHD} treats it essentially like an error---the client receives fewer bytes than the @code{Content-Length} promised. @item @code{MHD_CONTENT_READER_END_WITH_ERROR} Something went wrong while generating the data; see below. @item @code{0} No data is available @emph{right now}, but the stream is not over. @end table @noindent That last case is the dangerous one. The header file states that returning zero is legal only when @emph{MHD} is @emph{not} using an internal sockets polling mode, and this is not a formality: @emph{MHD} does not diagnose the situation, it simply arranges for the next poll to time out immediately and calls the callback again. A callback that returns zero while a request is stalled for a third of a second is called several million times in that period and pins a CPU core at 100%. In external polling mode the effect is milder---the callback is retried whenever the application calls one of the @code{MHD_run*()} functions---but it is still a spin. The proper answer for "no data yet" is to suspend the connection, which is covered further down. @heading Keeping state per request Because the callback is a plain C function, everything it needs to know has to travel through @code{crc_cls}. The natural shape of a streaming handler is therefore: allocate a context on the heap, allocate its data buffer, create the response with that context as @code{crc_cls}, and let the free callback dispose of both. @verbatim struct ResponseContext { char *buf; /* heap buffer, refilled again and again */ size_t fill; /* number of valid bytes in buf */ size_t off; /* number of bytes of buf given to MHD */ unsigned int block; /* number of blocks produced so far */ }; @end verbatim @noindent The two offsets are what make the buffer independent of @emph{MHD}'s appetite. A block is generated once and may then be handed out over several invocations, because @code{max} can be smaller than what we have ready: @verbatim static ssize_t content_reader (void *cls, uint64_t pos, char *buf, size_t max) { struct ResponseContext *ctx = cls; size_t ready; (void) pos; if (ctx->off == ctx->fill) { /* Everything we had was passed on, produce the next block. */ if (BLOCK_COUNT == ctx->block) return MHD_CONTENT_READER_END_OF_STREAM; generate_block (ctx); } ready = ctx->fill - ctx->off; if (ready > max) ready = max; memcpy (buf, &ctx->buf[ctx->off], ready); ctx->off += ready; return (ssize_t) ready; } @end verbatim @noindent @code{generate_block()} is the place where a real application would run its expensive computation, query, or network fetch. The important property is that the same buffer is reused every time, so the memory the server needs does not grow with the size of the document. The handler assembles all of this and, from that moment on, hands ownership of the context to the response object: @verbatim ctx = malloc (sizeof (struct ResponseContext)); if (NULL == ctx) return MHD_NO; ctx->buf = malloc (BUFFER_SIZE); if (NULL == ctx->buf) { free (ctx); return MHD_NO; } ctx->fill = 0; ctx->off = 0; ctx->block = 0; response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, IO_BLOCK_SIZE, &content_reader, ctx, &free_context); if (NULL == response) { /* No response object exists, so nobody will call the free callback for us. */ free_context (ctx); return MHD_NO; } ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); @end verbatim @noindent Note the error path: as long as @code{MHD_create_response_from_callback()} has not returned a response, the free callback will never run and the application must clean up itself. @heading Releasing the state The free callback is trivial: @verbatim static void free_context (void *cls) { struct ResponseContext *ctx = cls; free (ctx->buf); free (ctx); } @end verbatim @noindent @emph{MHD} invokes it when the last reference to the response object goes away. The call to @code{MHD_destroy_response()} in the handler does not trigger it, because queuing the response took a reference; the callback runs when the connection is finished with the response. That happens after a completed body, but equally after a client that closed the socket in the middle of the download, after a timeout, and when the daemon is stopped. This is precisely what makes the free callback the right place for the cleanup: there is no other hook that covers all of these cases. @heading Unknown size and chunked encoding Passing @code{MHD_SIZE_UNKNOWN} as the size leaves @emph{MHD} with the problem of telling the client where the body ends. For an HTTP/1.1 client it solves it by switching to chunked transfer encoding: it adds a @code{Transfer-Encoding: chunked} header and frames every piece the callback returns as one chunk, terminating the body with a zero-length chunk when the callback reports the end of the stream. Nothing has to be done for this; it is a consequence of the unknown size. @verbatim < HTTP/1.1 200 OK < Content-Type: text/plain < Transfer-Encoding: chunked @end verbatim @noindent An HTTP/1.0 client cannot be sent chunks. In that case @emph{MHD} falls back to the only other framing the protocol offers and marks the connection as one that must be closed: the body is sent raw, without @code{Content-Length}, and its end is the end of the connection. The data arrives intact, but the client has no way to distinguish a complete answer from one that was cut short. If the size @emph{is} known---and in the example program the URL @code{/sized} shows this variant---it should be announced, simply by passing the number instead of @code{MHD_SIZE_UNKNOWN}. @emph{MHD} then emits a normal @code{Content-Length} header, no chunk framing is added, and the callback is queried with @code{max} limited by both @code{block_size} and the number of bytes still outstanding. The callback must produce exactly the announced number of bytes. @heading Aborting a response Generating data can fail halfway through---the database connection drops, a file disappears, an allocation fails. Since the response headers, and probably a good part of the body, have already been sent, there is no way to turn the answer into an error page any more. Returning @code{MHD_CONTENT_READER_END_WITH_ERROR} is the way to give up: @emph{MHD} logs the condition and closes the connection immediately, without writing the terminating chunk. What the client sees depends on the framing. With chunked encoding it is an abnormally terminated chunk stream, and a well-behaved client reports it as such---@code{curl} for instance fails with "transfer closed with outstanding read data remaining" and a non-zero exit status. With an announced @code{Content-Length} the client notices that the body is shorter than promised. Only in the HTTP/1.0 case discussed above, where the end of the body is the end of the connection, is the failure indistinguishable from a normal ending; that is a property of the protocol and not something @emph{MHD} can repair. The URL @code{/error} of the example program aborts the stream after a few blocks so that this can be observed. @heading When the data is not ready yet So far the generator could always produce the next block on the spot. If it cannot---because the data is coming from another thread, another process, or the network---then, as explained above, returning @code{0} in an internal polling mode turns the daemon into a busy loop. The supported answer is to take the connection out of the event loop until the data has arrived, with the pair @verbatim void MHD_suspend_connection (struct MHD_Connection *connection); void MHD_resume_connection (struct MHD_Connection *connection); @end verbatim @noindent The daemon has to be started with the @code{MHD_ALLOW_SUSPEND_RESUME} flag; both functions call @code{MHD_PANIC()} and abort the process otherwise. The flag implies @code{MHD_USE_ITC}, so that a resumed connection wakes the polling thread up instead of waiting for the next timeout. Suspending is not available for daemons running with @code{MHD_USE_THREAD_PER_CONNECTION}, and the daemon must not be stopped while connections are still suspended. @code{MHD_suspend_connection()} may only be called from the access handler or from the content reader callback, which means the connection handle has to be stored in the context struct so that the callback can reach it. The pattern is then: @verbatim if (! ctx->data_available) { MHD_suspend_connection (ctx->connection); return 0; } @end verbatim @noindent @code{MHD_resume_connection()}, in contrast, may be called from any thread and at any time. In particular it is explicitly allowed to call it before the suspension has taken effect: the producer may already be done by the time the callback gets around to suspending. @emph{MHD} handles this by remembering the resume request and, when the suspension is finally processed, cancelling it instead of parking the connection, so the wakeup can never be lost. This is what makes the "check, suspend, return 0" sequence above safe without a lock of its own. The difference is dramatic in practice. A callback that stalls for three hundred milliseconds and returns @code{0} is entered several million times and burns a full core; the same callback suspending the connection is entered exactly once more and the daemon uses no measurable CPU time at all. Suspending brings requirements of its own---on who may call what from which thread, on how a worker thread wakes up a blocked event loop, and on who releases the shared state when a client disappears halfway through. @ref{Answering from another thread} works all of that out on a complete program. @heading Trailers Chunked responses may carry trailers, that is header fields that are transmitted after the body. They are added with @verbatim MHD_add_response_footer (response, "X-Checksum", "deadbeef"); @end verbatim @noindent @emph{MHD} writes them out after the terminating zero-length chunk: @verbatim 0 X-Checksum: deadbeef @end verbatim @noindent Footers may still be added while the body is being generated---even from inside the content reader callback, immediately before returning @code{MHD_CONTENT_READER_END_OF_STREAM}---which is what makes them useful in the first place: a checksum or a row count over data that has only just been produced cannot be put into the headers, because those are long gone. This is safe as long as the response object belongs to a single request, as it does in the pattern used here. @emph{MHD} does not generate a @code{Trailer} response header by itself; if the client should be told in advance which fields to expect, add it with @code{MHD_add_response_header()}. Be aware that many clients discard trailers silently. @heading Example code The complete program is available as @code{callbackresponse.c}. It serves a document of sixty-four blocks that are produced one at a time into a single heap buffer. @code{GET /} streams it with @code{MHD_SIZE_UNKNOWN} and thus with chunked encoding, @code{GET /sized} streams the same bytes with a @code{Content-Length} announced up front, and @code{GET /error} aborts in the middle. @heading Remarks Calls into the content reader of one response object are serialized by @emph{MHD}, so a per-request context needs no locking of its own as long as no other thread touches it. As soon as a producer thread is involved---the suspend/resume case---the shared fields do need protection. The chunk boundaries are not under the application's control and carry no meaning: a client may receive the bytes of one callback invocation spread over several chunks or, in other configurations, several invocations combined. Chunked encoding is a transport detail, and any record structure the application needs must be part of the body itself. Finally, returning very small amounts of data per invocation is correct but wasteful, since every invocation may become its own chunk with its own framing overhead. If the producer has more data ready, it should fill as much of @code{buf} as @code{max} permits. @heading Exercises @itemize @bullet @item Add a URL that reports how far the transfer has progressed by writing the value of @code{pos} into every line, and confirm with a slow client (@code{curl --limit-rate}) that it really is the number of bytes already sent, and not a block counter. @item Register a request completion callback with @code{MHD_OPTION_NOTIFY_COMPLETED} and print the termination code. Then download the document, interrupt the client in the middle, and watch in which order the completion callback and the content reader's free callback are invoked, and that the free callback runs in both cases. @item Turn the generator into an asynchronous one. Start a thread that appends a line to a shared buffer once per second, keep the connection handle in the context struct, and suspend the connection whenever the buffer is empty. Do not forget @code{MHD_ALLOW_SUSPEND_RESUME} when starting the daemon. Then remove the call to @code{MHD_suspend_connection()}, leaving only the @code{return 0}, and compare the CPU usage of the server process. A complete solution, together with the ownership rules that a shared buffer between a worker and the event loop needs, is the subject of @ref{Answering from another thread}. @item Compute a checksum over the generated document while it is being sent and append it as a trailer. Watch it on the wire---most command line clients will not show it to you, so a raw @code{nc} or a small script speaking HTTP by hand is the easier tool here. @end itemize libmicrohttpd-1.0.10/doc/chapters/tlsauthentication.inc0000664000175000017500000003520115232165355016743 We left the basic authentication chapter with the unsatisfactory conclusion that any traffic, including the credentials, could be intercepted by anyone between the browser client and the server. Protecting the data while it is sent over unsecured lines will be the goal of this chapter. The @emph{MHD} library includes support for encrypting the traffic by employing TLS (the protocol formerly known as SSL). If @emph{GNU libmicrohttpd} has been configured to support this, encryption and decryption can be applied transparently on the data being sent, with only minimal changes to the actual source code of the example. @heading Preparation First, a private key for the server will be generated. With this key, the server will later be able to authenticate itself to the client---preventing anyone else from stealing the password by faking its identity. The @emph{OpenSSL} suite, which is available on many operating systems, can generate such a key. 1024 bit keys are no longer considered secure, so we use a 2048 bit key: @verbatim > openssl genrsa -out server.key 2048 @end verbatim @noindent In addition to the key, a certificate describing the server in human readable tokens is also needed. This certificate will be attested with our aforementioned key. In this way, we obtain a self-signed certificate, valid for one year. To avoid unnecessary error messages in the browser, the certificate needs to carry a @emph{subjectAltName} that matches the @emph{URI}, for example, "localhost" or the domain (current browsers ignore the common name and look at the @emph{subjectAltName} only). @verbatim > openssl req -days 365 -out server.pem -new -x509 -key server.key \ -addext "subjectAltName=DNS:localhost" @end verbatim @noindent If you plan to have a publicly reachable server, you will need to ask a trusted third party, called @emph{Certificate Authority}, or @emph{CA}, to attest the certificate for you. This way, any visitor can make sure the server's identity is real. Whether the server's certificate is signed by us or a third party, once it has been accepted by the client, both sides will be communicating over encrypted channels. From this point on, it is the client's turn to authenticate itself. But this has already been implemented in the basic authentication scheme. @heading Changing the source code We merely have to extend the server program so that it loads the two files into memory, @verbatim int main (void) { struct MHD_Daemon *daemon; char *key_pem; char *cert_pem; key_pem = load_file (SERVERKEYFILE); cert_pem = load_file (SERVERCERTFILE); if ((key_pem == NULL) || (cert_pem == NULL)) { printf ("The key/certificate files could not be read.\n"); return 1; } @end verbatim @noindent and then we point the @emph{MHD} daemon to it upon initialization. @verbatim daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_END); if (NULL == daemon) { printf ("%s\n", cert_pem); free (key_pem); free (cert_pem); return 1; } @end verbatim @noindent The rest consists of little new besides some additional memory cleanups. @verbatim getchar (); MHD_stop_daemon (daemon); free (key_pem); free (cert_pem); return 0; } @end verbatim @noindent The rather unexciting file loader can be found in the complete example @code{tlsauthentication.c}. @heading Remarks @itemize @bullet @item While the standard @emph{HTTP} port is 80, it is 443 for @emph{HTTPS}. The common internet browsers assume standard @emph{HTTP} if they are asked to access other ports than these. Therefore, you will have to type @code{https://localhost:8888} explicitly when you test the example, or the browser will not know how to handle the answer properly. @item The remaining weak point is the question how the server will be trusted initially. Either a @emph{CA} signs the certificate or the client obtains the key over secure means. Anyway, the clients have to be aware (or configured) that they should not accept certificates of unknown origin. @item The introduced method of certificates makes it mandatory to set an expiration date---making it less feasible to hardcode certificates in embedded devices. @item The cryptographic facilities consume memory space and computing time. For this reason, websites usually consists both of uncritically @emph{HTTP} parts and secured @emph{HTTPS}. @end itemize @heading Client authentication You can also use MHD to authenticate the client via SSL/TLS certificates (as an alternative to using the password-based Basic or Digest authentication). To do this, you will need to link your application against @emph{gnutls}. Next, when you start the MHD daemon, you must specify the root CA that you're willing to trust: @verbatim daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_MEM_KEY, key_pem, MHD_OPTION_HTTPS_MEM_CERT, cert_pem, MHD_OPTION_HTTPS_MEM_TRUST, root_ca_pem, MHD_OPTION_END); @end verbatim With this, you can then obtain client certificates for each session. In order to obtain the identity of the client, you first need to obtain the raw GnuTLS session handle from @emph{MHD} using @code{MHD_get_connection_info}. @verbatim #include #include gnutls_session_t tls_session; const union MHD_ConnectionInfo *ci; ci = MHD_get_connection_info (connection, MHD_CONNECTION_INFO_GNUTLS_SESSION); tls_session = (gnutls_session_t) ci->tls_session; @end verbatim You can then extract the client certificate: @verbatim /** * Get the client's certificate * * @param tls_session the TLS session * @return NULL if no valid client certificate could be found, a pointer * to the certificate if found */ static gnutls_x509_crt_t get_client_certificate (gnutls_session_t tls_session) { unsigned int listsize; const gnutls_datum_t * pcert; gnutls_certificate_status_t client_cert_status; gnutls_x509_crt_t client_cert; if (tls_session == NULL) return NULL; if (gnutls_certificate_verify_peers2(tls_session, &client_cert_status)) return NULL; if (0 != client_cert_status) { fprintf (stderr, "Failed client certificate invalid: %d\n", client_cert_status); return NULL; } pcert = gnutls_certificate_get_peers(tls_session, &listsize); if ( (pcert == NULL) || (listsize == 0)) { fprintf (stderr, "Failed to retrieve client certificate chain\n"); return NULL; } if (gnutls_x509_crt_init(&client_cert)) { fprintf (stderr, "Failed to initialize client certificate\n"); return NULL; } /* Note that by passing values between 0 and listsize here, you can get access to the CA's certs */ if (gnutls_x509_crt_import(client_cert, &pcert[0], GNUTLS_X509_FMT_DER)) { fprintf (stderr, "Failed to import client certificate\n"); gnutls_x509_crt_deinit(client_cert); return NULL; } return client_cert; } @end verbatim Using the client certificate, you can then get the client's distinguished name and alternative names: @verbatim /** * Get the distinguished name from the client's certificate * * @param client_cert the client certificate * @return NULL if no dn or certificate could be found, a pointer * to the dn if found */ char * cert_auth_get_dn(gnutls_x509_crt_t client_cert) { char* buf; size_t lbuf; lbuf = 0; gnutls_x509_crt_get_dn(client_cert, NULL, &lbuf); buf = malloc(lbuf); if (buf == NULL) { fprintf (stderr, "Failed to allocate memory for certificate dn\n"); return NULL; } gnutls_x509_crt_get_dn(client_cert, buf, &lbuf); return buf; } /** * Get the alternative name of specified type from the client's certificate * * @param client_cert the client certificate * @param nametype The requested name type * @param index The position of the alternative name if multiple names are * matching the requested type, 0 for the first matching name * @return NULL if no matching alternative name could be found, a pointer * to the alternative name if found */ char * MHD_cert_auth_get_alt_name(gnutls_x509_crt_t client_cert, int nametype, unsigned int index) { char* buf; size_t lbuf; unsigned int seq; unsigned int subseq; unsigned int type; int result; subseq = 0; for (seq=0;;seq++) { lbuf = 0; result = gnutls_x509_crt_get_subject_alt_name2(client_cert, seq, NULL, &lbuf, &type, NULL); if (result == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) return NULL; if (nametype != (int) type) continue; if (subseq == index) break; subseq++; } buf = malloc(lbuf); if (buf == NULL) { fprintf (stderr, "Failed to allocate memory for certificate alt name\n"); return NULL; } result = gnutls_x509_crt_get_subject_alt_name2(client_cert, seq, buf, &lbuf, NULL, NULL); if (result != nametype) { fprintf (stderr, "Unexpected return value from gnutls: %d\n", result); free (buf); return NULL; } return buf; } @end verbatim Finally, you should release the memory associated with the client certificate: @verbatim gnutls_x509_crt_deinit (client_cert); @end verbatim @heading Using TLS Server Name Indication (SNI) SNI enables hosting multiple domains under one IP address with TLS. So SNI is the TLS-equivalent of virtual hosting. To use SNI with MHD, you need at least GnuTLS 3.0. The main change compared to the simple hosting of one domain is that you need to provide a callback instead of the key and certificate. For example, when you start the MHD daemon, you could do this: @verbatim daemon = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback, MHD_OPTION_END); @end verbatim Here, @code{sni_callback} is the name of a function that you will have to implement to retrieve the X.509 certificate for an incoming connection. The callback has type @code{gnutls_certificate_retrieve_function2} and is documented in the GnuTLS API for the @code{gnutls_certificate_set_retrieve_function2} as follows: @deftypefn {Function Pointer} int {*gnutls_certificate_retrieve_function2} (gnutls_session_t, const gnutls_datum_t* req_ca_dn, int nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert, unsigned int *pcert_length, gnutls_privkey_t * pkey) @table @var @item req_ca_dn is only used in X.509 certificates. Contains a list with the CA names that the server considers trusted. Normally we should send a certificate that is signed by one of these CAs. These names are DER encoded. To get a more meaningful value use the function @code{gnutls_x509_rdn_get()}. @item pk_algos contains a list with server's acceptable signature algorithms. The certificate returned should support the server's given algorithms. @item pcert should contain a single certificate and public or a list of them. @item pcert_length is the size of the previous list. @item pkey is the private key. @end table @end deftypefn A possible implementation of this callback would look like this: @verbatim struct Hosts { struct Hosts *next; const char *hostname; gnutls_pcert_st pcrt; gnutls_privkey_t key; }; static struct Hosts *hosts; int sni_callback (gnutls_session_t session, const gnutls_datum_t* req_ca_dn, int nreqs, const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert, unsigned int *pcert_length, gnutls_privkey_t * pkey) { char name[256]; size_t name_len; struct Hosts *host; unsigned int type; name_len = sizeof (name); if (GNUTLS_E_SUCCESS != gnutls_server_name_get (session, name, &name_len, &type, 0 /* index */)) return -1; for (host = hosts; NULL != host; host = host->next) if (0 == strncmp (name, host->hostname, name_len)) break; if (NULL == host) { fprintf (stderr, "Need certificate for %.*s\n", (int) name_len, name); return -1; } fprintf (stderr, "Returning certificate for %.*s\n", (int) name_len, name); *pkey = host->key; *pcert_length = 1; *pcert = &host->pcrt; return 0; } @end verbatim Note that MHD cannot offer passing a closure or any other additional information to this callback, as the GnuTLS API unfortunately does not permit this at this point. The @code{hosts} list can be initialized by loading the private keys and X.509 certificates from disk as follows: @verbatim static void load_keys(const char *hostname, const char *CERT_FILE, const char *KEY_FILE) { int ret; gnutls_datum_t data; struct Hosts *host; host = malloc (sizeof (struct Hosts)); host->hostname = hostname; host->next = hosts; hosts = host; ret = gnutls_load_file (CERT_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading certificate file %s.\n", CERT_FILE); exit(1); } ret = gnutls_pcert_import_x509_raw (&host->pcrt, &data, GNUTLS_X509_FMT_PEM, 0); if (ret < 0) { fprintf(stderr, "*** Error loading certificate file: %s\n", gnutls_strerror (ret)); exit(1); } gnutls_free (data.data); ret = gnutls_load_file (KEY_FILE, &data); if (ret < 0) { fprintf (stderr, "*** Error loading key file %s.\n", KEY_FILE); exit(1); } gnutls_privkey_init (&host->key); ret = gnutls_privkey_import_x509_raw (host->key, &data, GNUTLS_X509_FMT_PEM, NULL, 0); if (ret < 0) { fprintf (stderr, "*** Error loading key file: %s\n", gnutls_strerror (ret)); exit(1); } gnutls_free (data.data); } @end verbatim The code above was largely lifted from GnuTLS. You can find other methods for initializing certificates and keys in the GnuTLS manual and source code. libmicrohttpd-1.0.10/doc/chapters/introduction.inc0000644000175000017500000000225214674632555015732 This tutorial is for developers who want to learn how they can add HTTP serving capabilities to their applications with the @emph{GNU libmicrohttpd} library, abbreviated @emph{MHD}. The reader will learn how to implement basic HTTP functions from simple executable sample programs that implement various features. The text is supposed to be a supplement to the API reference manual of @emph{GNU libmicrohttpd} and for that reason does not explain many of the parameters. Therefore, the reader should always consult the manual to find the exact meaning of the functions used in the tutorial. Furthermore, the reader is encouraged to study the relevant @emph{RFCs}, which document the HTTP standard. @emph{GNU libmicrohttpd} is assumed to be already installed. This tutorial is written for version @value{VERSION}. At the time being, this tutorial has only been tested on @emph{GNU/Linux} machines even though efforts were made not to rely on anything that would prevent the samples from being built on similar systems. @section History This tutorial was originally written by Sebastian Gerhardt for MHD 0.4.0. It was slightly polished and updated to MHD 0.9.0 by Christian Grothoff.libmicrohttpd-1.0.10/doc/chapters/sessions.inc0000664000175000017500000000670015232165355015051 This chapter discusses how one should manage sessions, that is, share state between multiple HTTP requests from the same user. We use a simple example where the user submits multiple forms and the server is supposed to accumulate state from all of these forms. Naturally, as this is a network protocol, our session mechanism must support having many users with many concurrent sessions at the same time. In order to track users, we use a simple session cookie. A session cookie expires when the user closes the browser. Changing from session cookies to persistent cookies only requires adding an expiration time to the cookie. The server creates a fresh session cookie whenever a request without a cookie is received, or if the supplied session cookie is not known to the server. @heading Looking up the cookie Since MHD parses the HTTP cookie header for us, looking up an existing cookie is straightforward: @verbatim const char *value; value = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, "KEY"); @end verbatim Here, "KEY" is the name we chose for our session cookie. @heading Setting the cookie header MHD requires the user to provide the full cookie format string in order to set cookies. In order to generate a unique cookie, our example creates a random 32-character text string to be used as the value of the cookie: @verbatim char value[128]; char raw_value[33]; for (unsigned int i=0;i got) { if (EINTR == errno) continue; break; /* read error */ } if (0 == got) break; /* client closed the connection */ done = echo_feed (sock, &es, buf, (size_t) got); } MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); @end verbatim @noindent @heading Blocking or not blocking The call to @code{make_blocking()} deserves a warning, because the current behaviour is the opposite of what the threading modes suggest. @emph{MHD} puts every accepted client socket into non-blocking mode, and it does so regardless of the threading mode --- in fact the library refuses to perform the switch at all, logging @code{Cannot execute "upgrade" as the socket is in the blocking mode}, if it finds the socket blocking. So even under @code{MHD_USE_THREAD_PER_CONNECTION}, where you are perfectly entitled to block, the socket you are handed is non-blocking and a @code{recv()} on an idle connection returns @code{-1} with @code{EAGAIN} instead of waiting. If you want the simple blocking loop shown above, you therefore have to ask for it. The example does so with a small @code{make_blocking()} helper --- @code{fcntl()} clearing @code{O_NONBLOCK} on POSIX systems, @code{ioctlsocket()} on W32 --- which is the only operating-system-dependent code in the whole program. Under any other threading mode you leave the socket alone, keep it non-blocking, and add it to your own event loop instead. @heading Closing the connection The last obligation of the callback is to hand the socket back: @verbatim MHD_upgrade_action (urh, MHD_UPGRADE_ACTION_CLOSE); @end verbatim @noindent This is not a formality. An upgraded connection is put into an internal ``suspended'' state, and it stays there --- socket open, connection structure allocated, slot counted against the connection limit --- until the application says it is done. Only @code{MHD_UPGRADE_ACTION_CLOSE} says that. Calling @code{close()} on the socket yourself does not, and additionally leaves @emph{MHD} holding a file descriptor number that the operating system may already have handed to somebody else. Call the action exactly once, on every path out of the callback, including the error paths. @code{MHD_upgrade_action()} takes two further actions in the current release, @code{MHD_UPGRADE_ACTION_CORK_ON} and @code{MHD_UPGRADE_ACTION_CORK_OFF}. They switch @code{TCP_CORK} (or @code{TCP_NOPUSH}) on the underlying socket so that several small writes can be coalesced into a single segment. They are a hint, not a guarantee: the call returns @code{MHD_NO} if the platform has no such option or if the socket is not a TCP socket, which is the normal case for HTTPS connections. The header file marks this part of the API as not yet finalised, so do not build anything load-bearing on it. @heading Remarks @code{MHD_stop_daemon()} does @emph{not} interrupt an upgraded connection. It marks the connection as closed internally and logs @code{Initiated daemon shutdown while "upgraded" connection was not closed}, but it neither shuts down nor closes the socket --- and then it waits for the connection's thread, which means it blocks until your callback has returned. A callback parked in a blocking @code{recv()} therefore hangs the shutdown for as long as the client keeps the connection open. Any server that wants to terminate on demand needs its own way out of that loop: a global shutdown flag combined with a @code{shutdown()} on the sockets you are holding, a self-pipe added to a @code{select()} in the loop, or a receive timeout on the socket. Our example sidesteps the problem by only stopping the daemon when the user presses return at a moment when nothing is connected. Error handling in the callback is entirely yours. @emph{MHD} will not tell you that a client vanished and will not time an upgraded connection out --- @code{MHD_OPTION_CONNECTION_TIMEOUT} stops applying the moment the connection is upgraded. Treat @code{0} from @code{recv()} as a clean disconnect and a negative return as a broken one, and remember that a peer which disappears without a FIN produces neither until the TCP stack gives up, which can take a very long time. Whatever happens, end by calling @code{MHD_upgrade_action()} with @code{MHD_UPGRADE_ACTION_CLOSE}. Finally, keep in mind that an upgraded connection is a connection that @emph{MHD} can no longer recycle, and that intermediaries are entitled to be unhelpful: @code{Upgrade:} is listed in @code{Connection:} and is therefore a hop-by-hop header field. A proxy that does not understand your protocol is allowed to drop it, in which case your server never sees an upgrade request at all and the client gets an ordinary HTTP response where it expected a 101. This is the main reason why deployed protocols on top of this mechanism --- Websockets above all --- make the handshake verifiable by both ends instead of trusting that the request arrived intact. The complete program is available as @code{upgrade.c} in the @code{examples} section. Start it and talk to it with any tool that lets you type raw bytes at a socket --- @code{telnet localhost 8888} will do --- by sending @verbatim GET / HTTP/1.1 Host: localhost Connection: Upgrade Upgrade: echo @end verbatim @noindent followed by an empty line. The server answers with @verbatim HTTP/1.1 101 Switching Protocols Date: ... Connection: Upgrade Upgrade: echo @end verbatim @noindent and from then on echoes every line back until you type @code{QUIT}. Note the absence of a @code{Content-Length:} field: a 101 response has no body, and everything after the empty line already belongs to the new protocol. For a real-world protocol built on exactly this API, read @emph{RFC 6455} and note how much of it exists only to make the handshake and the framing verifiable --- none of which the upgrade API itself has an opinion about. @heading Exercises @itemize @bullet @item Point a browser at the server. The browser sends a plain @code{GET /} and receives the @code{426} page. Now add a second resource that serves a small HTML page and switch the upgrade to a different URL, so that the same server can be both browsed and upgraded. @item Make the echo server useful: keep a list of the sockets of all upgraded connections and forward every line one client sends to all the others, turning the example into a minimal chat server. You will need a mutex around the list, and you will discover why the closing rules matter --- a socket must leave the list before its callback returns. @item Fix the shutdown behaviour discussed in the remarks. Add a global ``quitting'' flag and a list of active sockets, have @code{main()} set the flag and call @code{shutdown (sock, SHUT_RDWR)} on every entry before it calls @code{MHD_stop_daemon()}, and verify that the daemon now stops even while a client is connected and silent. @item Change the daemon flags to plain @code{MHD_USE_INTERNAL_POLLING_THREAD} without @code{MHD_USE_THREAD_PER_CONNECTION} and observe that the server now serves exactly one upgraded client and stops answering everybody else. Then repair it: leave the socket non-blocking, start a thread from within the callback, and return immediately. @item Have the client send a line longer than @code{LINE_SIZE}. The example silently drops the excess. What should a real protocol do instead, and which status code would you have used if the problem had been detectable during the handshake? @end itemize libmicrohttpd-1.0.10/doc/chapters/responseheaders.inc0000664000175000017500000001611215232165355016373 Now that we are able to inspect the incoming request in great detail, this chapter discusses the means to enrich the outgoing responses likewise. As you have learned in the @emph{Hello, Browser} chapter, some obligatory header fields are added and set automatically for simple responses by the library itself but if more advanced features are desired, additional fields have to be created. One of the possible fields is the content type field and an example will be developed around it. This will lead to an application capable of correctly serving different types of files. When we responded with HTML page packed in the static string previously, the client had no choice but guessing about how to handle the response, because the server had not told him. What if we had sent a picture or a sound file? Would the message have been understood or merely been displayed as an endless stream of random characters in the browser? This is what the mime content types are for. The header of the response is extended by certain information about how the data is to be interpreted. To introduce the concept, a picture of the format @emph{PNG} will be sent to the client and labeled accordingly with @code{image/png}. Once again, we can base the new example on the @code{hellobrowser} program. @verbatim #define FILENAME "picture.png" #define MIMETYPE "image/png" static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_Response *response; @end verbatim @noindent We want the program to open the file for reading and determine its size: @verbatim int fd; enum MHD_Result ret; struct stat sbuf; if (0 != strcmp (method, "GET")) return MHD_NO; if ( (-1 == (fd = open (FILENAME, O_RDONLY))) || (0 != fstat (fd, &sbuf)) ) { /* error accessing file */ /* ... (see below) */ } /* ... (see below) */ @end verbatim @noindent When dealing with files, there is a lot that could go wrong on the server side and if so, the client should be informed with @code{MHD_HTTP_INTERNAL_SERVER_ERROR}. @verbatim /* error accessing file */ if (fd != -1) close (fd); const char *errorstr = "An internal server error has occurred!\ "; response = MHD_create_response_from_buffer_static (strlen (errorstr), errorstr); if (NULL != response) { ret = MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response); MHD_destroy_response (response); return ret; } else return MHD_NO; @end verbatim @noindent Note that we nevertheless have to create a response object even for sending a simple error code. Otherwise, the connection would just be closed without comment, leaving the client curious about what has happened. But in the case of success a response will be constructed directly from the file descriptor: @verbatim /* error accessing file */ /* ... (see above) */ } response = MHD_create_response_from_fd_at_offset64 ((uint64_t) sbuf.st_size, fd, 0); MHD_add_response_header (response, "Content-Type", MIMETYPE); @end verbatim @noindent Note that the response object will take care of closing the file descriptor for us. Up to this point, there was little new. The actual novelty is that we enhance the header with the meta data about the content. Aware of the field's name we want to add, it is as easy as that: @verbatim MHD_add_response_header(response, "Content-Type", MIMETYPE); @end verbatim @noindent We do not have to append a colon expected by the protocol behind the first field---@emph{GNU libmicrohttpd} will take care of this. The function finishes with the well-known lines @verbatim ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } @end verbatim @noindent The complete program @code{responseheaders.c} is in the @code{examples} section as usual. Find a @emph{PNG} file you like and save it to the directory the example is run from under the name @code{picture.png}. You should find the image displayed on your browser if everything worked well. @heading Remarks The include file of the @emph{MHD} library comes with the header types mentioned in @emph{RFC 9110} already defined as macros. Thus, we could have written @code{MHD_HTTP_HEADER_CONTENT_TYPE} instead of @code{"Content-Type"} as well. However, one is not limited to these standard headers and could add custom response headers without violating the protocol. Whether, and how, the client would react to these custom header is up to the receiver. Likewise, the client is allowed to send custom request headers to the server as well, opening up yet more possibilities how client and server could communicate with each other. The method of creating the response from a file on disk only works for static content. Serving dynamically created responses will be a topic of a future chapter. @heading Exercises @itemize @bullet @item Remember that the original program was written under a few assumptions---a static response using a local file being one of them. In order to simulate a very large or hard to reach file that cannot be provided instantly, postpone the queuing in the callback with the @code{sleep} function for 30 seconds @emph{if} the file @code{/big.png} is requested (but deliver the same as above). A request for @code{/picture.png} should provide just the same but without any artificial delays. Now start two instances of your browser (or even use two machines) and see how the second client is put on hold while the first waits for his request on the slow file to be fulfilled. Finally, change the sourcecode to add @code{MHD_USE_THREAD_PER_CONNECTION} to the daemon's flags (this flag must be combined with @code{MHD_USE_INTERNAL_POLLING_THREAD}) and try again. @item Did you succeed in implementing the clock exercise yet? This time, let the server save the program's start time @code{t} and implement a response simulating a countdown that reaches 0 at @code{t+60}. Returning a message saying on which point the countdown is, the response should ultimately be to reply "Done" if the program has been running long enough, An unofficial, but widely understood, response header line is @code{Refresh: DELAY; url=URL} with the uppercase words substituted to tell the client it should request the given resource after the given delay again. Improve your program in that the browser (any modern browser should work) automatically reconnects and asks for the status again every 5 seconds or so. The URL would have to be composed so that it begins with "http://", followed by the @emph{URI} the server is reachable from the client's point of view. Maybe you want also to visualize the countdown as a status bar by creating a @code{
      } consisting of one row and @code{n} columns whose fields contain small images of either a red or a green light. @end itemize libmicrohttpd-1.0.10/doc/chapters/asyncresponses.inc0000664000175000017500000004524015232212544016255 The previous chapter left one question open. A content reader that has no data ready may return @code{0}, but doing so turns the daemon into a busy loop, and the honest answer---suspend the connection---was only sketched there. This chapter builds the thing itself: a server whose slow work happens in threads of its own, whose connections are parked while that work is under way, and which is driven by an external @code{select()} loop so that the application stays in charge of its own event handling. The combination is a common one. Most requests are cheap and can be answered on the spot; a few of them start a report, a backup or a query that runs for seconds. Handling the slow ones inline would block every other client for as long as they take. Giving every connection its own thread---@code{MHD_USE_THREAD_PER_CONNECTION}---is no answer either, both because it scales badly and because suspending is not available in that mode at all. What is wanted is a single event loop that never blocks, plus a worker per slow job. @heading Who may call what Almost every difficulty in this design comes from one rule, so it is worth stating before any code: @table @asis @item @code{MHD_queue_response()} Must be called from the thread that runs the daemon, from inside the access handler. A worker thread must never queue a response. @item @code{MHD_suspend_connection()} May only be called from the access handler or from a content reader callback---that is, from @emph{MHD}'s own thread, while @emph{MHD} is calling into the application. @item @code{MHD_resume_connection()} May be called from any thread at any time, and this is the exception that makes the whole design work. It is the only @emph{MHD} function a worker thread ever needs. @end table @noindent So the split is: the worker computes and, when it has something, resumes. Everything that touches the connection or the response happens on the daemon's thread, where @emph{MHD} calls the application back. The worker and the daemon share exactly one object, a per-request context, and the only thing the worker does with the connection handle it holds is pass it to @code{MHD_resume_connection()}. The daemon has to be started with @code{MHD_ALLOW_SUSPEND_RESUME}; both suspend and resume call @code{MHD_PANIC()} and abort the process otherwise. Note also that suspending does not work with a thread pool: @code{MHD_resume_connection()} asserts that the daemon has none. @heading The event loop Leaving out @code{MHD_USE_INTERNAL_POLLING_THREAD} puts @emph{MHD} into external polling mode: it starts no thread of its own and does nothing until the application asks it to. The loop is the usual one, and the example adds its own descriptor to the very same sets---there is nothing special about @emph{MHD}'s: @verbatim FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); max = 0; if (MHD_YES != MHD_get_fdset (daemon, &rs, &ws, &es, &max)) break; /* fatal internal error */ FD_SET (wake_pipe[0], &rs); /* our own wakeup pipe */ if (max < wake_pipe[0]) max = wake_pipe[0]; if (MHD_YES == MHD_get_timeout64 (daemon, &mhd_timeout)) { ...fill tv...; tvp = &tv; } else tvp = NULL; /* nothing to wait for */ select ((int) max + 1, &rs, &ws, &es, tvp); MHD_run_from_select (daemon, &rs, &ws, &es); @end verbatim @noindent The interesting branch is the one that sets @code{tvp} to @code{NULL}. @code{MHD_get_timeout64()} returns @code{MHD_NO} when @emph{MHD} has nothing whatsoever to wait for, and with every connection suspended that is precisely the situation: suspended connections do not time out, so there is no deadline to wake up for. The loop then blocks in @code{select()} indefinitely. Whether the server works at all depends on something waking it up. @heading Waking the loop up That something is @emph{MHD}'s inter-thread communication channel. @code{MHD_ALLOW_SUSPEND_RESUME} is defined as @code{8192 | MHD_USE_ITC}, so requesting suspend support requests the ITC as well; @code{MHD_get_fdset()} puts the reading end of that channel into the read set, ahead of everything else; and @code{MHD_resume_connection()} writes a byte to it. A worker thread that resumes a connection therefore breaks the main thread out of @code{select()}, even though the two share nothing but the daemon handle. This deserves emphasis because the header file is misleading about it: the comment on @code{MHD_USE_ITC} says the flag is ignored with external polling. That is true for the flag in isolation, but not for the channel: @code{MHD_ALLOW_SUSPEND_RESUME} creates it regardless of the polling mode, and in external mode it is the application's own @code{select()} that watches it. Without that, a resumed connection would sit untouched until some unrelated event happened to wake the loop. There is no race to guard against here. If the worker resumes in the window between @code{MHD_get_fdset()} and @code{select()}, the byte is already in the channel when @code{select()} is entered, and @code{select()} returns immediately---the channel is level triggered, so a wakeup cannot be missed. The same property makes it safe for a worker to resume a connection that has not finished suspending yet: @emph{MHD} remembers the request and cancels the pending suspension instead of parking the connection. Neither side needs to know what the other is doing. @heading Answering in one piece The simplest of the two patterns is for an answer that is only useful as a whole---a generated report, the result of a query. Nothing can be sent before it is finished, so the connection is suspended in the access handler and the response is queued when @emph{MHD} comes back: @verbatim static enum MHD_Result handle_slow (struct MHD_Connection *connection, void **req_cls) { struct Job *job = *req_cls; if (NULL == job) { /* First call for this request: start the work and ask MHD to come back to us. */ job = job_create (connection, 0); if (NULL == job) return MHD_NO; if (MHD_NO == job_start (job)) { job_unref (job); job_unref (job); return MHD_NO; } *req_cls = job; return MHD_YES; } pthread_mutex_lock (&job->lock); if (0 == job->finished) { job->suspended = 1; MHD_suspend_connection (connection); pthread_mutex_unlock (&job->lock); return MHD_YES; } ...copy the result out from under the lock... pthread_mutex_unlock (&job->lock); ...MHD_create_response_from_buffer_copy() and MHD_queue_response()... } @end verbatim @noindent The control flow is worth following, because it is not obvious that it terminates. @emph{MHD} calls the access handler for a request more than once; the first call is the one where @code{*req_cls} is still @code{NULL}, and returning @code{MHD_YES} without queueing anything tells @emph{MHD} to carry on. On the second call the worker is running but not finished, so the connection is suspended and the handler returns again. When the worker resumes the connection, @emph{MHD} calls the handler a third time---on its own thread, with the same @code{*req_cls}---and this time @code{finished} is set and the response is queued. That third call is the answer to the question this pattern exists for. The worker never queues anything; it merely makes the daemon call the application back at a moment when the answer is ready. @heading Answering as it is produced The second pattern is the more useful one when the answer is long, and it is what makes a browser show results as they appear rather than after a long blank pause. Here the response is queued @emph{immediately}, with a content reader and an unknown size, so the headers go out at once and the body follows as the worker fills it in: @verbatim job = job_create (connection, 1); response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, IO_BLOCK_SIZE, &stream_reader, job, &stream_done); ... MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/event-stream"); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); @end verbatim @noindent Because the size is unknown, @emph{MHD} uses chunked transfer encoding, and every piece the content reader hands back is framed as its own chunk and goes out on the wire straight away. The content reader is where suspending happens: @verbatim static ssize_t stream_reader (void *cls, uint64_t pos, char *buf, size_t max) { struct Job *job = cls; size_t ready; pthread_mutex_lock (&job->lock); if (job->off == job->fill) { job->off = 0; job->fill = 0; if (0 != job->finished) { pthread_mutex_unlock (&job->lock); return MHD_CONTENT_READER_END_OF_STREAM; } /* Nothing to send yet. Take the connection out of the event loop; the worker will put it back in. */ job->suspended = 1; MHD_suspend_connection (job->connection); pthread_mutex_unlock (&job->lock); return 0; } ready = job->fill - job->off; if (ready > max) ready = max; memcpy (buf, &job->payload[job->off], ready); job->off += ready; pthread_mutex_unlock (&job->lock); return (ssize_t) ready; } @end verbatim @noindent The return value is still @code{0}, exactly as in the busy-waiting version the previous chapter warned about. The difference is the line above it. Suspending removes the connection from the event loop, so @emph{MHD} has no reason to come back until the worker says so, and the process goes to sleep. The example ships with a test that measures this: streaming a document that takes one second to produce costs the server no measurable CPU time at all while the connection is suspended, and very nearly a full second---one core, saturated---when the @code{MHD_suspend_connection()} call is removed and only the @code{return 0} is left. The bytes that arrive are identical in both cases, which is what makes this such an easy mistake to keep. @heading The shared state Everything the two threads share sits in one structure per request: @verbatim struct Job { pthread_mutex_t lock; pthread_cond_t cond; struct MHD_Connection *connection; char payload[MAX_PAYLOAD]; size_t fill; size_t off; unsigned int rc; int finished; int suspended; int abandoned; ... }; @end verbatim @noindent There is no registry of pending requests involved in answering them, and no lookup: the pointer travels in @code{*req_cls} for the first pattern and in the content reader's @code{crc_cls} for the second, and both the daemon and the worker are handed it directly. A shared list of all jobs is still useful, but only for shutting down in an orderly fashion, and it is protected by a lock of its own that is always taken before any job's lock, never after. The structure is reference counted, with one reference held by @emph{MHD} and one by the worker. The @emph{MHD} side lets go in the free callback of the response for a streamed answer, and in the @code{MHD_OPTION_NOTIFY_COMPLETED} callback for the other pattern; the worker lets go when it returns. Dropping the last reference does not free the job, though, because the worker still has to be joined and only the main thread may do that. The main loop therefore ends with a sweep that joins and frees whatever has no references left. @heading When the client goes away This is the part that is easy to get wrong, because it does not happen during development and does happen constantly in production. A client that closes the connection halfway through a download leaves a worker running with a pointer to a connection @emph{MHD} is about to free. The two callbacks that tell the application a request is over---the response's free callback and @code{MHD_OPTION_NOTIFY_COMPLETED}---are therefore where the worker is cut loose: @verbatim static void job_detach (struct Job *job) { pthread_mutex_lock (&job->lock); job->abandoned = 1; job->connection = NULL; pthread_cond_signal (&job->cond); pthread_mutex_unlock (&job->lock); job_unref (job); } @end verbatim @noindent and the worker checks that flag before every resume: @verbatim static void job_resume_locked (struct Job *job) { if ( (0 == job->suspended) || (0 != job->abandoned) ) return; job->suspended = 0; MHD_resume_connection (job->connection); } @end verbatim @noindent Note that this function is called with the job's lock @emph{held}, and calls into @emph{MHD} without releasing it. That is deliberate and it is what makes the pattern safe. @emph{MHD} destroys the connection only after the completion callback has returned, and that callback cannot run while the worker holds the lock; so for as long as the worker is inside @code{MHD_resume_connection()}, the connection it passes is guaranteed to still exist. Dropping the lock first and resuming afterwards would open exactly the window this is meant to close. The reverse order never occurs: @emph{MHD} invokes the free and completion callbacks without holding the internal locks that @code{MHD_resume_connection()} acquires, so there is no way for the two to deadlock. The condition variable in the same function is a convenience rather than a necessity. Signalling it wakes a worker that is asleep between steps, so that the work stops within microseconds of the client disappearing instead of running to completion for nobody. @heading Shutting down Stopping a daemon that still has suspended connections is an API violation, and a suspended connection is one that only a worker can release. The order is therefore fixed: @enumerate @item Stop handing out new jobs. @item Tell every worker to give up, and @emph{join} them. After this point no connection can be suspended any more: the workers resume before they exit, and the content reader only ever suspends while a worker is running. @item Keep running the event loop until the connections have drained, so that the last bytes actually reach the clients. @item @code{MHD_stop_daemon()}. @end enumerate @noindent Skipping the join in step two is the tempting shortcut, and it is the one that leaves a connection parked forever with nothing left alive to wake it. @heading Example code The complete program is available as @code{asyncresponse.c}. It runs one external @code{select()} loop and serves four URLs: @table @code @item / A small page whose JavaScript opens the stream below and appends a row for every event as it arrives. The rows visibly trickle in, one per step, which is the most direct demonstration of what the chapter is about. @item /events The stream: a response is queued at once, and the content reader suspends between steps. The body is a sequence of server-sent events, which needs no library on the browser side. @item /slow The other pattern: the connection is suspended in the access handler and a complete answer is queued once the worker is done. @item /fast Answered on the spot. The page has a button that requests it and reports the round trip time; it stays in the low milliseconds while jobs are running, which is the point of suspending rather than blocking. @end table @noindent The program takes the port, the duration of a step in milliseconds and the number of steps on the command line. Passing @code{0} as the port makes the operating system choose a free one, which the program then reports via @code{MHD_DAEMON_INFO_BIND_PORT}: @verbatim $ ./asyncresponse 0 250 20 Listening on port 44321 @end verbatim @noindent The accompanying @code{test_asyncresponse.c} starts exactly that binary and checks over HTTP that @code{/slow} waits for its worker, that the body of @code{/events} really arrives in pieces spread over the lifetime of the request rather than in one burst at the end, that @code{/fast} is still served promptly while jobs are parked, that a client which hangs up in the middle takes neither the server nor the worker with it, and that the process exits cleanly when it is signalled while a connection is suspended. It also compares the server's CPU time against the wall clock time of a transfer, which is the only one of those checks that notices the difference between a suspended connection and a busy-waiting one. @heading Remarks @emph{MHD} does not detect that a client has disconnected while a connection is suspended, and the connection timeout does not run either. A suspended connection stays suspended until somebody resumes it, without exception. Any timeout on the work itself is therefore the application's responsibility. Suspended connections still count against the connection limits, both the global one and the per-IP one. A server that parks connections for minutes needs its limits sized for the number of jobs it expects to have in flight, not for the number it expects to be transmitting. If the client vanishes in the middle of a chunked response, the next write fails and @emph{MHD} logs it---with @code{MHD_USE_ERROR_LOG} enabled the example prints @code{Failed to send the chunked response body ... The socket is no longer available for sending}. That is the normal course of events for an aborted download and not a sign of a problem. Finally, none of this is specific to @code{select()}. The same argument holds for @code{poll()} and for @code{epoll}, where the daemon's descriptor can be obtained with @code{MHD_DAEMON_INFO_EPOLL_FD} and added to an epoll set of the application's own; @code{suspend_resume_epoll.c} among the distribution's examples shows that variant. @heading Exercises @itemize @bullet @item Give the jobs a deadline. Since a suspended connection never times out on its own, add a check to the main loop that resumes---and answers with @code{503}---any job that has been running for too long, and confirm with a step duration long enough to trigger it. @item Remove the @code{MHD_suspend_connection()} call from the content reader, leaving only the @code{return 0}, and watch the server process with @code{top} while a single client downloads the stream. Then put it back and watch again. Both servers send the same bytes. @item Take the resume out of the worker's final block, so that a finished job leaves its connection parked, and then stop the server while a job is in flight. Watch what the shutdown does---and what @code{valgrind} has to say about it---and work out which of the four steps above was violated. @item Replace the per-request thread with a fixed pool of worker threads and a queue of pending jobs. The reference counting and the @code{abandoned} flag should not need to change at all; if they do, the ownership rules were not as clean as they looked. @item Serve the stream to two browser windows at once and confirm from the timestamps that the two jobs run concurrently and are interleaved by a single-threaded event loop. @end itemize libmicrohttpd-1.0.10/doc/chapters/basicauthentication.inc0000664000175000017500000002360515232165355017227 With the small exception of IP address based access control, requests from all connecting clients where served equally until now. This chapter discusses a first method of client's authentication and its limits. A very simple approach feasible with the means already discussed would be to expect the password in the @emph{URI} string before granting access to the secured areas. The password could be separated from the actual resource identifier by a certain character, thus the request line might look like @verbatim GET /picture.png?mypassword @end verbatim @noindent In the rare situation where the client is customized enough and the connection occurs through secured lines (e.g., a embedded device directly attached to another via wire) and where the ability to embed a password in the URI or to pass on a URI with a password are desired, this can be a reasonable choice. But when it is assumed that the user connecting does so with an ordinary Internet browser, this implementation brings some problems about. For example, the URI including the password stays in the address field or at least in the history of the browser for anybody near enough to see. It will also be inconvenient to add the password manually to any new URI when the browser does not know how to compose this automatically. At least the convenience issue can be addressed by employing the simplest built-in password facilities of HTTP compliant browsers, hence we want to start there. It will, however, turn out to have still severe weaknesses in terms of security which need consideration. Before we will start implementing @emph{Basic Authentication} as described in @emph{RFC 7617}, we will also abandon the simplistic and generally problematic practice of responding every request the first time our callback is called for a given connection. Queuing a response upon the first request is akin to generating an error response (even if it is a "200 OK" reply!). The reason is that MHD usually calls the callback in three phases: @enumerate @item First, to initially tell the application about the connection and inquire whether it is OK to proceed. This call typically happens before the client could upload the request body, and can be used to tell the client to not proceed with the upload (if the client requested "Expect: 100 Continue"). Applications may queue a reply at this point, but it will force the connection to be closed and thus prevent keep-alive / pipelining, which is generally a bad idea. Applications wanting to proceed with the request throughout the other phases should just return "MHD_YES" and not queue any response. Note that when an application suspends a connection in this callback, the phase does not advance and the application will be called again in this first phase. @item Next, to tell the application about upload data provided by the client. In this phase, the application may not queue replies, and trying to do so will result in MHD returning an error code from @code{MHD_queue_response}. If there is no upload data, this phase is skipped. @item Finally, to obtain a regular response from the application. This can be almost any type of response, including ones indicating failures. The one exception is a "100 Continue" response, which applications must never generate: MHD generates that response automatically when necessary in the first phase. If the application does not queue a response, MHD may call the callback repeatedly (depending a bit on the threading model, the application should suspend the connection). @end enumerate But how can we tell whether the callback has been called before for the particular request? This is what the @code{req_cls} parameter of the callback is for: initially, the pointer it references is set to NULL by @emph{MHD}. But whatever we store there will be "remembered" on the next call (for the same request). Thus, we can use the @code{req_cls} location to keep track of the request state. For now, we will simply generate no response until the parameter is non-null---implying the callback was called before at least once. We do not need to share information between different calls of the callback, so we can set the parameter to any address that is assured to be not null. The pointer to the @code{connection} structure will be pointing to a legal address, so we take this. The first time @code{answer_to_connection} is called, we will not even look at the headers. @verbatim static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if (0 != strcmp(method, "GET")) return MHD_NO; if (NULL == *req_cls) {*req_cls = connection; return MHD_YES;} ... /* else respond accordingly */ ... } @end verbatim @noindent Note how we lop off the connection on the first condition (no "GET" request), but return asking for more on the other one with @code{MHD_YES}. With this minor change, we can proceed to implement the actual authentication process. @heading Request for authentication Let us assume we had only files not intended to be handed out without the correct username/password, so every "GET" request will be challenged. @emph{RFC 7617} describes how the server shall ask for authentication by adding a @emph{WWW-Authenticate} response header with the name of the @emph{realm} protected. MHD can generate and queue such a failure response for you using the @code{MHD_queue_basic_auth_required_response3} API. The only thing you need to do is construct a response with the error page to be shown to the user if he aborts basic authentication. But first, you should check if the proper credentials were already supplied using the @code{MHD_basic_auth_get_username_password3} call. (The older @code{MHD_queue_basic_auth_fail_response} and @code{MHD_basic_auth_get_username_password} calls are deprecated.) Your code would then look like this: @verbatim static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { struct MHD_BasicAuthInfo *auth_info; enum MHD_Result ret; struct MHD_Response *response; if (0 != strcmp (method, "GET")) return MHD_NO; if (NULL == *req_cls) { *req_cls = connection; return MHD_YES; } auth_info = MHD_basic_auth_get_username_password3 (connection); if (NULL == auth_info) { static const char *page = "Authorization required"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_required_response3 (connection, "admins", MHD_YES, response); } else if ((strlen ("root") != auth_info->username_len) || (0 != memcmp (auth_info->username, "root", auth_info->username_len)) || /* The next check against NULL is optional, * if 'password' is NULL then 'password_len' is always zero. */ (NULL == auth_info->password) || (strlen ("pa$$w0rd") != auth_info->password_len) || (0 != memcmp (auth_info->password, "pa$$w0rd", auth_info->password_len))) { static const char *page = "Wrong username or password"; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_basic_auth_required_response3 (connection, "admins", MHD_YES, response); } else { static const char *page = "A secret."; response = MHD_create_response_from_buffer_static (strlen (page), page); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); } if (NULL != auth_info) MHD_free (auth_info); MHD_destroy_response (response); return ret; } @end verbatim See the @code{examples} directory for the complete example file. @heading Remarks For a proper server, the conditional statements leading to a return of @code{MHD_NO} should yield a response with a more precise status code instead of silently closing the connection. For example, failures of memory allocation are best reported as @emph{internal server error} and unexpected authentication methods as @emph{400 bad request}. @heading Exercises @itemize @bullet @item Make the server respond to wrong credentials (but otherwise well-formed requests) with the recommended @emph{401 unauthorized} status code. If the client still does not authenticate correctly within the same connection, close it and store the client's IP address for a certain time. (It is OK to check for expiration not until the main thread wakes up again on the next connection.) If the client fails authenticating three times during this period, add it to another list for which the @code{AcceptPolicyCallback} function denies connection (temporally). @item With the network utility @code{netcat} connect and log the response of a "GET" request as you did in the exercise of the first example, this time to a file. Now stop the server and let @emph{netcat} listen on the same port the server used to listen on and have it fake being the proper server by giving the file's content as the response (e.g. @code{cat log | nc -l -p 8888}). Pretending to think your were connecting to the actual server, browse to the eavesdropper and give the correct credentials. Copy and paste the encoded string you see in @code{netcat}'s output to some of the Base64 decode tools available online and see how both the user's name and password could be completely restored. @end itemize libmicrohttpd-1.0.10/doc/chapters/hellobrowser.inc0000664000175000017500000002727115232165355015720 The most basic task for a HTTP server is to deliver a static text message to any client connecting to it. Given that this is also easy to implement, it is an excellent problem to start with. For now, the particular URI the client asks for shall have no effect on the message that will be returned. In addition, the server shall end the connection after the message has been sent so that the client will know there is nothing more to expect. The C program @code{hellobrowser.c}, which is to be found in the examples section, does just that. If you are very eager, you can compile and start it right away but it is advisable to type the lines in by yourself as they will be discussed and explained in detail. After the necessary includes and the definition of the port which our server should listen on @verbatim #include #include #include #include #include #include #define PORT 8888 @end verbatim @noindent the desired behaviour of our server when HTTP request arrive has to be implemented. We already have agreed that it should not care about the particular details of the request, such as who is requesting what. The server will respond merely with the same small HTML page to every request. The function we are going to write now will be called by @emph{GNU libmicrohttpd} every time an appropriate request comes in. While the name of this callback function is arbitrary, its parameter list has to follow a certain layout. So please, ignore the lot of parameters for now, they will be explained at the point they are needed. We have to use only one of them, @code{struct MHD_Connection *connection}, for the minimalistic functionality we want to achieve at the moment. This parameter is set by the @emph{libmicrohttpd} daemon and holds the necessary information to relate the call with a certain connection. Keep in mind that a server might have to satisfy hundreds of concurrent connections and we have to make sure that the correct data is sent to the destined client. Therefore, this variable is a means to refer to a particular connection if we ask the daemon to sent the reply. Talking about the reply, it is defined as a string right after the function header @verbatim static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { const char *page = "Hello, browser!"; @end verbatim @noindent HTTP is a rather strict protocol and the client would certainly consider it "inappropriate" if we just sent the answer string "as is". Instead, it has to be wrapped with additional information stored in so-called headers and footers. Most of the work in this area is done by the library for us---we just have to ask. Our reply string packed in the necessary layers will be called a "response". To obtain such a response we hand our data (the reply--string) and its size over to the @code{MHD_create_response_from_buffer_static} function. By using the @code{_static} variant we tell @emph{MHD} that the buffer will stay valid and unchanged for at least as long as the response lives, so that @emph{MHD} neither has to free the message data for us when it has been sent nor has to make an internal copy of it---which is exactly the case for our @emph{constant} string. @verbatim struct MHD_Response *response; enum MHD_Result ret; response = MHD_create_response_from_buffer_static (strlen (page), page); @end verbatim @noindent Now that the response has been laced up, it is ready for delivery and can be queued for sending. This is done by passing it to another @emph{GNU libmicrohttpd} function. As all our work was done in the scope of one function, the recipient is without doubt the one associated with the local variable @code{connection} and consequently this variable is given to the queue function. Every HTTP response is accompanied by a status code, here "OK", so that the client knows this response is the intended result of his request and not due to some error or malfunction. Finally, the packet is destroyed and the return value from the queue returned, already being set at this point to either MHD_YES or MHD_NO in case of success or failure. @verbatim ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); return ret; } @end verbatim @noindent With the primary task of our server implemented, we can start the actual server daemon which will listen on @code{PORT} for connections. This is done in the main function. @verbatim int main (void) { struct MHD_Daemon *daemon; daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_END); if (NULL == daemon) return 1; @end verbatim @noindent The first parameter is a bit-wise OR of flags selecting, among other things, the mode of operation. With @code{MHD_USE_INTERNAL_POLLING_THREAD} we want the daemon to run in a separate thread and to manage all incoming connections in the same thread. This means that while producing the response for one connection, the other connections will be put on hold. In this example, where the reply is already known and therefore the request is served quickly, this poses no problem. The additional @code{MHD_USE_AUTO} flag simply lets @emph{MHD} pick the best polling function (@code{epoll}, @code{poll} or @code{select}) available on the platform. We will allow all clients to connect regardless of their name or location, therefore we do not check them on connection and set the third and fourth parameter to NULL. Parameter five is the address of the function we want to be called whenever a new request has been received. Our @code{answer_to_connection} knows best what the client wants and needs no additional information (which could be passed via the next parameter) so the next (sixth) parameter is NULL. Likewise, we do not need to pass extra options to the daemon so we just write the MHD_OPTION_END as the last parameter. As the server daemon runs in the background in its own thread, the execution flow in our main function will continue right after the call. Because of this, we must delay the execution flow in the main thread or else the program will terminate prematurely. We let it pause in a processing-time friendly manner by waiting for the enter key to be pressed. In the end, we stop the daemon so it can do its cleanup tasks. @verbatim getchar (); MHD_stop_daemon (daemon); return 0; } @end verbatim @noindent The first example is now complete. Compile it with @verbatim cc hellobrowser.c -o hellobrowser -I$PATH_TO_LIBMHD_INCLUDES -L$PATH_TO_LIBMHD_LIBS -lmicrohttpd @end verbatim with the two paths set accordingly and run it. Now open your favorite Internet browser and go to the address @code{http://localhost:8888/}, provided that 8888 is the port you chose. If everything works as expected, the browser will present the message of the static HTML page it got from our minimal server. @heading Remarks To keep this first example as small as possible, some drastic shortcuts were taken and are to be discussed now. Firstly, there is no distinction made between the kinds of requests a client could send. We implied that the client sends a GET request, that means, that he actually asked for some data. Even when it is not intended to accept POST requests, a good server should at least recognize that this request does not constitute a legal request and answer with an error code. This can be easily implemented by checking if the parameter @code{method} equals the string "GET" and returning a @code{MHD_NO} if not so. Secondly, the above practice of queuing a response upon the first call of the callback function brings with it some limitations. This is because the content of the message body will not be received if a response is queued in the first iteration. Furthermore, the connection will be closed right after the response has been transferred then. This is typically not what you want as it disables HTTP pipelining. The correct approach is to simply not queue a message on the first callback unless there is an error. The @code{void**} argument to the callback provides a location for storing information about the history of the connection; for the first call, the pointer will point to NULL. A simplistic way to differentiate the first call from others is to check if the pointer is NULL and set it to a non-NULL value during the first call. Both of these issues you will find addressed in the official @code{minimal_example.c} residing in the @code{src/examples} directory of the @emph{MHD} package. The source code of this program should look very familiar to you by now and easy to understand. For our example, we create the response from a static (persistent) buffer in memory and thus use @code{MHD_create_response_from_buffer_static}. In the usual case, responses are not transmitted immediately after being queued. For example, there might be other data on the system that needs to be sent with a higher priority. Nevertheless, the queue function will return successfully---raising the problem that the data we have pointed to may be invalid by the time it is about being sent. This is not an issue here because we can expect the @code{page} string, which is a constant @emph{string literal} here, to be static. That means it will be present and unchanged for as long as the program runs. For dynamic data, one could choose to either have @emph{MHD} free the memory @code{page} points to itself when it is no longer needed (by using @code{MHD_create_response_from_buffer_with_free_callback} with @code{&free}) or, alternatively, have the library make and manage its own copy of it (by using @code{MHD_create_response_from_buffer_copy}). Naturally, this last option is the most expensive. @heading Exercises @itemize @bullet @item While the server is running, use a program like @code{telnet} or @code{netcat} to connect to it. Try to form a valid HTTP 1.1 request yourself like @verbatim GET /dontcare HTTP/1.1 Host: itsme @end verbatim @noindent and see what the server returns to you. @item Also, try other requests, like POST, and see how our server does not mind and why. How far in malforming a request can you go before the builtin functionality of @emph{MHD} intervenes and an altered response is sent? Make sure you read about the status codes in the @emph{RFC}. @item Add the option @code{MHD_OPTION_CLIENT_DISCIPLINE_LVL} with a value of @code{1} to the start function of the daemon in @code{main} (this option supersedes the deprecated @code{MHD_USE_PEDANTIC_CHECKS} flag). Mind the special format of the parameter list here which is described in the manual: the option is followed by its @code{int} value, and @code{MHD_OPTION_END} still terminates the list. How indulgent is the server now to your input? @item Let the main function take a string as the first command line argument and pass @code{argv[1]} to the @code{MHD_start_daemon} function as the sixth parameter. The address of this string will be passed to the callback function via the @code{cls} variable. Decorate the text given at the command line when the server is started with proper HTML tags and send it as the response instead of the former static string. @item @emph{Demanding:} Write a separate function returning a string containing some useful information, for example, the time. Pass the function's address as the sixth parameter and evaluate this function on every request anew in @code{answer_to_connection}. Remember to free the memory of the string every time after satisfying the request. @end itemize libmicrohttpd-1.0.10/doc/chapters/largerpost.inc0000664000175000017500000003045415232165355015370 The previous chapter introduced a way to upload data to the server, but the developed example program has some shortcomings, such as not being able to handle larger chunks of data. In this chapter, we are going to discuss a more advanced server program that allows clients to upload a file in order to have it stored on the server's filesystem. The server shall also watch and limit the number of clients concurrently uploading, responding with a proper busy message if necessary. @heading Prepared answers We choose to operate the server with the @code{MHD_USE_INTERNAL_POLLING_THREAD} method. This makes it easier to synchronize the global states at the cost of possible delays for other connections if the processing of a request is too slow. One of these variables that needs to be shared for all connections is the total number of clients that are uploading. @verbatim #define MAXCLIENTS 2 static unsigned int nr_of_uploading_clients = 0; @end verbatim @noindent If there are too many clients uploading, we want the server to respond to all requests with a busy message. @verbatim const char* busypage = "This server is busy, please try again later."; @end verbatim @noindent Otherwise, the server will send a @emph{form} that informs the user of the current number of uploading clients, and ask her to pick a file on her local filesystem which is to be uploaded. @verbatim const char* askpage = "\n\ Upload a file, please!
      \n\ There are %u clients uploading at the moment.
      \n\ \n\ \n\ \n\ "; @end verbatim @noindent If the upload has succeeded, the server will respond with a message saying so. @verbatim const char* completepage = "The upload has been completed."; @end verbatim @noindent We want the server to report malformed requests and internal errors, such as file access problems, adequately. @verbatim const char* servererrorpage = "Invalid request."; const char* fileexistspage = "This file already exists."; const char* fileioerror = "IO error writing to disk."; const char* postprocerror = "Error processing POST data."; @end verbatim @noindent It would be tolerable to send all these responses undifferentiated with a @code{200 HTTP_OK} status code but in order to improve the @code{HTTP} conformance of our server a bit, we extend the @code{send_page} function so that it accepts individual status codes. @verbatim static enum MHD_Result send_page (struct MHD_Connection *connection, const char* page, unsigned int status_code) { enum MHD_Result ret; struct MHD_Response *response; response = MHD_create_response_from_buffer_copy (strlen (page), page); if (!response) return MHD_NO; ret = MHD_queue_response (connection, status_code, response); MHD_destroy_response (response); return ret; } @end verbatim @noindent Note how we ask @emph{MHD} to make its own copy of the message data---that is what the @code{_copy} suffix stands for. The reason behind this will become clear later. @heading Connection cycle The decision whether the server is busy or not is made right at the beginning of the connection. To do that at this stage is especially important for @emph{POST} requests because if no response is queued at this point, and @code{MHD_YES} returned, @emph{MHD} will not send any queued messages until a postprocessor has been created and the post iterator is called at least once. @verbatim static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if (NULL == *req_cls) { struct connection_info_struct *con_info; if (nr_of_uploading_clients >= MAXCLIENTS) return send_page(connection, busypage, MHD_HTTP_SERVICE_UNAVAILABLE); @end verbatim @noindent If the server is not busy, the @code{connection_info} structure is initialized as usual, with the addition of a filepointer for each connection. The status code is set to zero, which we use as the marker for "no answer decided yet". @verbatim con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->answercode = 0; con_info->fp = NULL; if (0 == strcmp (method, "POST")) { ... } else con_info->connectiontype = GET; *req_cls = (void*) con_info; return MHD_YES; } @end verbatim @noindent For @emph{POST} requests, the postprocessor is created and we register a new uploading client. From this point on, there are many possible places for errors to occur that make it necessary to interrupt the uploading process. We need a means of having the proper response message ready at all times. Therefore, the @code{connection_info} structure is extended to hold the most current response message so that whenever a response is sent, the client will get the most informative message. @verbatim if (0 == strcmp (method, "POST")) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, iterate_post, (void*) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } nr_of_uploading_clients++; con_info->connectiontype = POST; } else con_info->connectiontype = GET; @end verbatim @noindent If the connection handler is called for the second time, @emph{GET} requests will be answered with the @emph{form}. We can keep the buffer under function scope, because we asked @emph{MHD} to make its own copy of it for as long as it is needed. @verbatim if (0 == strcmp (method, "GET")) { char buffer[1024]; snprintf (buffer, sizeof (buffer), askpage, nr_of_uploading_clients); return send_page (connection, buffer, MHD_HTTP_OK); } @end verbatim @noindent The rest of the @code{answer_to_connection} function is very similar to the @code{simplepost.c} example, except the more flexible content of the responses. The @emph{POST} data is processed until there is none left and the execution falls through to return an error page if the connection constituted no expected request method. Note that once we know the answer---because something went wrong---we no longer feed the data to the post processor, but we still have to consume it, or the client would never get to read our response. @verbatim if (0 == strcmp (method, "POST")) { struct connection_info_struct *con_info = *req_cls; if (0 != *upload_data_size) { if (0 == con_info->answercode) { if (MHD_YES != MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size)) { con_info->answerstring = postprocerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; } } *upload_data_size = 0; return MHD_YES; } if (NULL != con_info->fp) { fclose (con_info->fp); con_info->fp = NULL; } if (0 == con_info->answercode) { con_info->answerstring = completepage; con_info->answercode = MHD_HTTP_OK; } return send_page (connection, con_info->answerstring, con_info->answercode); } return send_page(connection, errorpage, MHD_HTTP_BAD_REQUEST); } @end verbatim @noindent @heading Storing the data Unlike the @code{simplepost.c} example, here it is to be expected that post iterator will be called several times now. This means that for any given connection (there might be several concurrent of them) the posted data has to be written to the correct file. That is why we store a file handle in every @code{connection_info}, so that it is preserved between successive iterations. @verbatim static enum MHD_Result iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; FILE *fp; @end verbatim @noindent Because the following actions depend heavily on correct file processing, which might be error prone, we record the page to answer with as soon as anything goes wrong. Note that the iterator always returns @code{MHD_YES}: returning @code{MHD_NO} would abort the post processor and thus make it impossible to send our carefully chosen error page to the client. In the "askpage" @emph{form}, we told the client to label its post data with the "file" key. Anything else would be an error. @verbatim if (0 != strcmp (key, "file")) { con_info->answerstring = servererrorpage; con_info->answercode = MHD_HTTP_BAD_REQUEST; return MHD_YES; } @end verbatim @noindent If the iterator is called for the first time, no file will have been opened yet. The @code{filename} string contains the name of the file (without any paths) the user selected on his system. We want to take this as the name the file will be stored on the server and make sure no file of that name exists (or is being uploaded) before we create one (note that the code below technically contains a race between the two "fopen" calls, but we will overlook this for portability sake). @verbatim if (!con_info->fp) { if (0 != con_info->answercode) /* something went wrong before */ return MHD_YES; if (NULL != (fp = fopen (filename, "rb")) ) { fclose (fp); con_info->answerstring = fileexistspage; con_info->answercode = MHD_HTTP_FORBIDDEN; return MHD_YES; } con_info->fp = fopen (filename, "ab"); if (!con_info->fp) { con_info->answerstring = fileioerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; return MHD_YES; } } @end verbatim @noindent Occasionally, the iterator function will be called even when there are 0 new bytes to process. The server only needs to write data to the file if there is some. @verbatim if (size > 0) { if (!fwrite (data, sizeof (char), size, con_info->fp)) { con_info->answerstring = fileioerror; con_info->answercode = MHD_HTTP_INTERNAL_SERVER_ERROR; } } @end verbatim @noindent If this point has been reached without setting an answer code, everything worked well for this iteration. If the upload has finished, this iterator function will not be called again and @code{answer_to_connection} will declare success. @verbatim return MHD_YES; } @end verbatim @noindent The new client was registered when the postprocessor was created. Likewise, we unregister the client on destroying the postprocessor when the request is completed. @verbatim static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; if (NULL == con_info) return; if (con_info->connectiontype == POST) { if (NULL != con_info->postprocessor) { MHD_destroy_post_processor (con_info->postprocessor); nr_of_uploading_clients--; } if (con_info->fp) fclose (con_info->fp); } free (con_info); *req_cls = NULL; } @end verbatim @noindent This is essentially the whole example @code{largepost.c}. @heading Remarks Now that the clients are able to create files on the server, security aspects are becoming even more important than before. Aside from proper client authentication, the server should always make sure explicitly that no files will be created outside of a dedicated upload directory. In particular, filenames must be checked to not contain strings like "../". libmicrohttpd-1.0.10/doc/chapters/processingpost.inc0000664000175000017500000002167615232165355016276 The previous chapters already have demonstrated a variety of possibilities to send information to the HTTP server, but it is not recommended that the @emph{GET} method is used to alter the way the server operates. To induce changes on the server, the @emph{POST} method is preferred over and is much more powerful than @emph{GET} and will be introduced in this chapter. We are going to write an application that asks for the visitor's name and, after the user has posted it, composes an individual response text. Even though it was not mandatory to use the @emph{POST} method here, as there is no permanent change caused by the POST, it is an illustrative example on how to share data between different functions for the same connection. Furthermore, the reader should be able to extend it easily. @heading GET request When the first @emph{GET} request arrives, the server shall respond with a HTML page containing an edit field for the name. @verbatim const char* askpage = "\ What's your name, Sir?
      \
      \ \ \ "; @end verbatim @noindent The @code{action} entry is the @emph{URI} to be called by the browser when posting, and the @code{name} will be used later to be sure it is the editbox's content that has been posted. We also prepare the answer page, where the name is to be filled in later, and an error page as the response for anything but proper @emph{GET} and @emph{POST} requests: @verbatim const char* greetingpage="

      Welcome, %s!

      "; const char* errorpage="This doesn't seem to be right."; @end verbatim @noindent Whenever we need to send a page, we use an extra function @code{int send_page(struct MHD_Connection *connection, const char* page)} for this, which does not contain anything new and whose implementation is therefore not discussed further in the tutorial. @heading POST request Posted data can be of arbitrary and considerable size; for example, if a user uploads a big image to the server. Similar to the case of the header fields, there may also be different streams of posted data, such as one containing the text of an editbox and another the state of a button. Likewise, we will have to register an iterator function that is going to be called maybe several times not only if there are different POSTs but also if one POST has only been received partly yet and needs processing before another chunk can be received. Such an iterator function is called by a @emph{postprocessor}, which must be created upon arriving of the post request. We want the iterator function to read the first post data which is tagged @code{name} and to create an individual greeting string based on the template and the name. But in order to pass this string to other functions and still be able to differentiate different connections, we must first define a structure to share the information, holding the most import entries. @verbatim struct connection_info_struct { int connectiontype; char *answerstring; struct MHD_PostProcessor *postprocessor; }; @end verbatim @noindent With these information available to the iterator function, it is able to fulfill its task. Once it has composed the greeting string, it returns @code{MHD_YES} so that the post processor keeps parsing the remainder of the upload. Returning @code{MHD_NO} would instead abort the parsing and make the next call to @code{MHD_post_process} fail. Note that this function does not handle processing of data for the same @code{key}. If we were to expect that the name will be posted in several chunks, we had to expand the namestring dynamically as additional parts of it with the same @code{key} came in. But in this example, the name is assumed to fit entirely inside one single packet. @verbatim static enum MHD_Result iterate_post (void *coninfo_cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct connection_info_struct *con_info = coninfo_cls; if (0 == strcmp (key, "name")) { if ((size > 0) && (size <= MAXNAMESIZE)) { char *answerstring; answerstring = malloc (MAXANSWERSIZE); if (!answerstring) return MHD_NO; snprintf (answerstring, MAXANSWERSIZE, greetingpage, data); con_info->answerstring = answerstring; } else con_info->answerstring = NULL; } return MHD_YES; } @end verbatim @noindent Once a connection has been established, it can be terminated for many reasons. As these reasons include unexpected events, we have to register another function that cleans up any resources that might have been allocated for that connection by us, namely the post processor and the greetings string. This cleanup function must take into account that it will also be called for finished requests other than @emph{POST} requests. @verbatim static void request_completed (void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe) { struct connection_info_struct *con_info = *req_cls; if (NULL == con_info) return; if (con_info->connectiontype == POST) { MHD_destroy_post_processor (con_info->postprocessor); if (con_info->answerstring) free (con_info->answerstring); } free (con_info); *req_cls = NULL; } @end verbatim @noindent @emph{GNU libmicrohttpd} is informed that it shall call the above function when the daemon is started in the main function. @verbatim ... daemon = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL, &answer_to_connection, NULL, MHD_OPTION_NOTIFY_COMPLETED, &request_completed, NULL, MHD_OPTION_END); ... @end verbatim @noindent @heading Request handling With all other functions prepared, we can now discuss the actual request handling. On the first iteration for a new request, we start by allocating a new instance of a @code{struct connection_info_struct} structure, which will store all necessary information for later iterations and other functions. @verbatim static enum MHD_Result answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls) { if(NULL == *req_cls) { struct connection_info_struct *con_info; con_info = malloc (sizeof (struct connection_info_struct)); if (NULL == con_info) return MHD_NO; con_info->answerstring = NULL; @end verbatim @noindent If the new request is a @emph{POST}, the postprocessor must be created now. In addition, the type of the request is stored for convenience. @verbatim if (0 == strcmp (method, "POST")) { con_info->postprocessor = MHD_create_post_processor (connection, POSTBUFFERSIZE, iterate_post, (void*) con_info); if (NULL == con_info->postprocessor) { free (con_info); return MHD_NO; } con_info->connectiontype = POST; } else con_info->connectiontype = GET; @end verbatim @noindent The address of our structure will both serve as the indicator for successive iterations and to remember the particular details about the connection. @verbatim *req_cls = (void*) con_info; return MHD_YES; } @end verbatim @noindent The rest of the function will not be executed on the first iteration. A @emph{GET} request is easily satisfied by sending the question form. @verbatim if (0 == strcmp (method, "GET")) { return send_page (connection, askpage); } @end verbatim @noindent In case of @emph{POST}, we invoke the post processor for as long as data keeps incoming, setting @code{*upload_data_size} to zero in order to indicate that we have processed---or at least have considered---all of it. @verbatim if (0 == strcmp (method, "POST")) { struct connection_info_struct *con_info = *req_cls; if (*upload_data_size != 0) { if (MHD_YES != MHD_post_process (con_info->postprocessor, upload_data, *upload_data_size)) return MHD_NO; *upload_data_size = 0; return MHD_YES; } else if (NULL != con_info->answerstring) return send_page (connection, con_info->answerstring); } @end verbatim @noindent Finally, if they are neither @emph{GET} nor @emph{POST} requests, the error page is returned. @verbatim return send_page(connection, errorpage); } @end verbatim @noindent These were the important parts of the program @code{simplepost.c}. libmicrohttpd-1.0.10/doc/chapters/bibliography.inc0000664000175000017500000000221415232165355015652 @heading API reference @itemize @bullet @item The @emph{GNU libmicrohttpd} manual by Marco Maggi and Christian Grothoff @uref{https://www.gnu.org/software/libmicrohttpd/manual/libmicrohttpd.html} @item All referenced RFCs can be found on the website of @emph{The Internet Engineering Task Force} @uref{https://www.ietf.org/} @item @emph{RFC 2616}: Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P., and T. Berners-Lee, "Hypertext Transfer Protocol -- HTTP/1.1", RFC 2616, June 1999. @item @emph{RFC 2617}: Franks, J., Hallam-Baker, P., Hostetler, J., Lawrence, S., Leach, P., Luotonen, A., and L. Stewart, "HTTP Authentication: Basic and Digest Access Authentication", RFC 2617, June 1999. @item @emph{RFC 6455}: Fette, I., Melnikov, A., "The WebSocket Protocol", RFC 6455, December 2011. @item A well--structured @emph{HTML} reference can be found on @uref{http://www.echoecho.com/html.htm} For those readers understanding German, there is an excellent document both for learning @emph{HTML} and for reference, whose English and French versions unfortunately have been discontinued. @uref{https://wiki.selfhtml.org/} @end itemize libmicrohttpd-1.0.10/doc/doxygen/0000775000175000017500000000000015235437006012427 5libmicrohttpd-1.0.10/doc/doxygen/libmicrohttpd.doxy.in0000644000175000017500000032217414674632555016550 # Doxyfile 1.8.13 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a double hash (##) is considered a comment and is placed in # front of the TAG it is preceding. # # All text after a single hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists, items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (\" \"). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all text # before the first occurrence of this tag. Doxygen uses libiconv (or the iconv # built into libc) for the transcoding. See http://www.gnu.org/software/libiconv # for the list of possible encodings. # The default value is: UTF-8. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded by # double-quotes, unless you are using Doxywizard) that should identify the # project for which the documentation is generated. This name is used in the # title of most generated pages and in a few other places. # The default value is: My Project. PROJECT_NAME = "GNU libmicrohttpd" # The PROJECT_NUMBER tag can be used to enter a project or revision number. This # could be handy for archiving the generated documentation or if some version # control system is used. PROJECT_NUMBER = @PACKAGE_VERSION@ # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer a # quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = # With the PROJECT_LOGO tag one can specify a logo or an icon that is included # in the documentation. The maximum height of the logo should not exceed 55 # pixels and the maximum width should not exceed 200 pixels. Doxygen will copy # the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path # into which the generated documentation will be written. If a relative path is # entered, it will be relative to the location where doxygen was started. If # left blank the current directory will be used. OUTPUT_DIRECTORY = . # If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- # directories (in 2 levels) under the output directory of each output format and # will distribute the generated files over these directories. Enabling this # option can be useful when feeding doxygen a huge amount of source files, where # putting all generated files in the same directory would otherwise causes # performance problems for the file system. # The default value is: NO. CREATE_SUBDIRS = YES # If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII # characters to appear in the names of generated files. If set to NO, non-ASCII # characters will be escaped, for example _xE3_x81_x84 will be used for Unicode # U+3044. # The default value is: NO. ALLOW_UNICODE_NAMES = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, # Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), # Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, # Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), # Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, # Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, # Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, # Ukrainian and Vietnamese. # The default value is: English. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member # descriptions after the members that are listed in the file and class # documentation (similar to Javadoc). Set to NO to disable this. # The default value is: YES. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief # description of a member or function before the detailed description # # Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. # The default value is: YES. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator that is # used to form the text in various listings. Each string in this list, if found # as the leading text of the brief description, will be stripped from the text # and the result, after processing the whole list, is used as the annotated # text. Otherwise, the brief description is used as-is. If left blank, the # following values are used ($name is automatically replaced with the name of # the entity):The $name class, The $name widget, The $name file, is, provides, # specifies, contains, represents, a, an and the. ABBREVIATE_BRIEF = "The $name class" \ "The $name widget" \ "The $name file" \ is \ provides \ specifies \ contains \ represents \ a \ an \ the # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # doxygen will generate a detailed section even if there is only a brief # description. # The default value is: NO. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. # The default value is: NO. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path # before files name in the file list and in the header files. If set to NO the # shortest path that makes the file name unique will be used # The default value is: YES. FULL_PATH_NAMES = YES # The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. # Stripping is only done if one of the specified strings matches the left-hand # part of the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the path to # strip. # # Note that you can specify absolute paths here, but also relative paths, which # will be relative from the directory where doxygen is started. # This tag requires that the tag FULL_PATH_NAMES is set to YES. STRIP_FROM_PATH = ../.. # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the # path mentioned in the documentation of a class, which tells the reader which # header file to include in order to use a class. If left blank only the name of # the header file containing the class definition is used. Otherwise one should # specify the list of include paths that are normally passed to the compiler # using the -I flag. STRIP_FROM_INC_PATH = ../../src/include \ src/include # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but # less readable) file names. This can be useful is your file systems doesn't # support long names like on DOS, Mac, or CD-ROM. # The default value is: NO. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the # first line (until the first dot) of a Javadoc-style comment as the brief # description. If set to NO, the Javadoc-style will behave just like regular Qt- # style comments (thus requiring an explicit @brief command for a brief # description.) # The default value is: NO. JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first # line (until the first dot) of a Qt-style comment as the brief description. If # set to NO, the Qt-style will behave just like regular Qt-style comments (thus # requiring an explicit \brief command for a brief description.) # The default value is: NO. QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a # multi-line C++ special comment block (i.e. a block of //! or /// comments) as # a brief description. This used to be the default behavior. The new default is # to treat a multi-line C++ comment block as a detailed description. Set this # tag to YES if you prefer the old behavior instead. # # Note that setting this tag to YES also means that rational rose comments are # not recognized any more. # The default value is: NO. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the # documentation from any documented member that it re-implements. # The default value is: YES. INHERIT_DOCS = NO # If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new # page for each member. If set to NO, the documentation of a member will be part # of the file/class/namespace that contains it. # The default value is: NO. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen # uses this value to replace tabs by spaces in code fragments. # Minimum value: 1, maximum value: 16, default value: 4. TAB_SIZE = 8 # This tag can be used to specify a number of aliases that act as commands in # the documentation. An alias has the form: # name=value # For example adding # "sideeffect=@par Side Effects:\n" # will allow you to put the command \sideeffect (or @sideeffect) in the # documentation, which will result in a user-defined paragraph with heading # "Side Effects:". You can put \n's in the value part of an alias to insert # newlines. ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding "class=itcl::class" # will allow you to use the command class in the itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources # only. Doxygen will then generate output that is more tailored for C. For # instance, some of the names that are used will be different. The list of all # members will be omitted, etc. # The default value is: NO. OPTIMIZE_OUTPUT_FOR_C = YES # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or # Python sources only. Doxygen will then generate output that is more tailored # for that language. For instance, namespaces will be presented as packages, # qualified scopes will look different, etc. # The default value is: NO. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources. Doxygen will then generate output that is tailored for Fortran. # The default value is: NO. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for VHDL. # The default value is: NO. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, and # language is one of the parsers supported by doxygen: IDL, Java, Javascript, # C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: # FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: # Fortran. In the later case the parser tries to guess whether the code is fixed # or free formatted code, this is the default for Fortran type files), VHDL. For # instance to make doxygen treat .inc files as Fortran files (default is PHP), # and .f files as C (default is Fortran), use: inc=Fortran f=C. # # Note: For files without extension you can use no_extension as a placeholder. # # Note that for custom extensions you also need to set FILE_PATTERNS otherwise # the files are not read by doxygen. EXTENSION_MAPPING = # If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments # according to the Markdown format, which allows for more readable # documentation. See http://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you can # mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in # case of backward compatibilities issues. # The default value is: YES. MARKDOWN_SUPPORT = YES # When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up # to that level are automatically included in the table of contents, even if # they do not have an id attribute. # Note: This feature currently applies only to Markdown headings. # Minimum value: 0, maximum value: 99, default value: 0. # This tag requires that the tag MARKDOWN_SUPPORT is set to YES. TOC_INCLUDE_HEADINGS = 0 # When enabled doxygen tries to link words that correspond to documented # classes, or namespaces to their corresponding documentation. Such a link can # be prevented in individual cases by putting a % sign in front of the word or # globally by setting AUTOLINK_SUPPORT to NO. # The default value is: YES. AUTOLINK_SUPPORT = YES # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should set this # tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); # versus func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. # The default value is: NO. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. # The default value is: NO. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip (see: # http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen # will parse them like normal C++ but will assume all classes use public instead # of private inheritance when no explicit protection keyword is present. # The default value is: NO. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate # getter and setter methods for a property. Setting this option to YES will make # doxygen to replace the get and set methods by a property in the documentation. # This will only work if the methods are indeed getting or setting a simple # type. If this is not the case, or you want to show the methods anyway, you # should set this option to NO. # The default value is: YES. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. # The default value is: NO. DISTRIBUTE_GROUP_DOC = NO # If one adds a struct or class to a group and this option is enabled, then also # any nested class or struct is added to the same group. By default this option # is disabled and one has to add nested compounds explicitly via \ingroup. # The default value is: NO. GROUP_NESTED_COMPOUNDS = NO # Set the SUBGROUPING tag to YES to allow class member groups of the same type # (for instance a group of public functions) to be put as a subgroup of that # type (e.g. under the Public Functions section). Set it to NO to prevent # subgrouping. Alternatively, this can be done per class using the # \nosubgrouping command. # The default value is: YES. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions # are shown inside the group in which they are included (e.g. using \ingroup) # instead of on a separate page (for HTML and Man pages) or section (for LaTeX # and RTF). # # Note that this feature does not work in combination with # SEPARATE_MEMBER_PAGES. # The default value is: NO. INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions # with only public data fields or simple typedef fields will be shown inline in # the documentation of the scope in which they are defined (i.e. file, # namespace, or group documentation), provided this scope is documented. If set # to NO, structs, classes, and unions are shown on a separate page (for HTML and # Man pages) or section (for LaTeX and RTF). # The default value is: NO. INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or # enum is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically be # useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. # The default value is: NO. TYPEDEF_HIDES_STRUCT = NO # The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This # cache is used to resolve symbols given their name and scope. Since this can be # an expensive process and often the same symbol appears multiple times in the # code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small # doxygen will become slower. If the cache is too large, memory is wasted. The # cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range # is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 # symbols. At the end of a run doxygen will report the cache usage and suggest # the optimal cache size from a speed point of view. # Minimum value: 0, maximum value: 9, default value: 0. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in # documentation are documented, even if no documentation was available. Private # class members and static file members will be hidden unless the # EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. # Note: This will also disable the warnings about undocumented members that are # normally produced when WARNINGS is set to YES. # The default value is: NO. EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will # be included in the documentation. # The default value is: NO. EXTRACT_PRIVATE = NO # If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal # scope will be included in the documentation. # The default value is: NO. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES, all static members of a file will be # included in the documentation. # The default value is: NO. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined # locally in source files will be included in the documentation. If set to NO, # only classes defined in header files are included. Does not have any effect # for Java sources. # The default value is: YES. EXTRACT_LOCAL_CLASSES = NO # This flag is only useful for Objective-C code. If set to YES, local methods, # which are defined in the implementation section but not in the interface are # included in the documentation. If set to NO, only methods in the interface are # included. # The default value is: NO. EXTRACT_LOCAL_METHODS = YES # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base name of # the file that contains the anonymous namespace. By default anonymous namespace # are hidden. # The default value is: NO. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all # undocumented members inside documented classes or files. If set to NO these # members will be included in the various overviews, but no documentation # section is generated. This option has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. If set # to NO, these classes will be included in the various overviews. This option # has no effect if EXTRACT_ALL is enabled. # The default value is: NO. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend # (class|struct|union) declarations. If set to NO, these declarations will be # included in the documentation. # The default value is: NO. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any # documentation blocks found inside the body of a function. If set to NO, these # blocks will be appended to the function's detailed documentation block. # The default value is: NO. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation that is typed after a # \internal command is included. If the tag is set to NO then the documentation # will be excluded. Set it to YES to include the internal documentation. # The default value is: NO. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file # names in lower-case letters. If set to YES, upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. # The default value is: system dependent. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with # their full class and namespace scopes in the documentation. If set to YES, the # scope will be hidden. # The default value is: NO. HIDE_SCOPE_NAMES = NO # If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will # append additional text to a page's title, such as Class Reference. If set to # YES the compound reference will be hidden. # The default value is: NO. HIDE_COMPOUND_REFERENCE= NO # If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of # the files that are included by a file in the documentation of that file. # The default value is: YES. SHOW_INCLUDE_FILES = YES # If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each # grouped member an include statement to the documentation, telling the reader # which file to include in order to use the member. # The default value is: NO. SHOW_GROUPED_MEMB_INC = NO # If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include # files with double quotes in the documentation rather than with sharp brackets. # The default value is: NO. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the # documentation for inline members. # The default value is: YES. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the # (detailed) documentation of file and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. # The default value is: YES. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief # descriptions of file, namespace and class members alphabetically by member # name. If set to NO, the members will appear in declaration order. Note that # this will also influence the order of the classes in the class list. # The default value is: NO. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the # (brief and detailed) documentation of class members so that constructors and # destructors are listed first. If set to NO the constructors will appear in the # respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. # Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief # member documentation. # Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting # detailed member documentation. # The default value is: NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy # of group names into alphabetical order. If set to NO the group names will # appear in their defined order. # The default value is: NO. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by # fully-qualified names, including namespaces. If set to NO, the class list will # be sorted only by class name, not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the alphabetical # list. # The default value is: NO. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper # type resolution of all parameters of a function it will reject a match between # the prototype and the implementation of a member function even if there is # only one candidate or it is obvious which candidate to choose by doing a # simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still # accept a match between prototype and implementation in such cases. # The default value is: NO. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo # list. This list is created by putting \todo commands in the documentation. # The default value is: YES. GENERATE_TODOLIST = NO # The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test # list. This list is created by putting \test commands in the documentation. # The default value is: YES. GENERATE_TESTLIST = NO # The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug # list. This list is created by putting \bug commands in the documentation. # The default value is: YES. GENERATE_BUGLIST = NO # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) # the deprecated list. This list is created by putting \deprecated commands in # the documentation. # The default value is: YES. GENERATE_DEPRECATEDLIST= NO # The ENABLED_SECTIONS tag can be used to enable conditional documentation # sections, marked by \if ... \endif and \cond # ... \endcond blocks. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the # initial value of a variable or macro / define can have for it to appear in the # documentation. If the initializer consists of more lines than specified here # it will be hidden. Use a value of 0 to hide initializers completely. The # appearance of the value of individual variables and macros / defines can be # controlled using \showinitializer or \hideinitializer command in the # documentation regardless of this setting. # Minimum value: 0, maximum value: 10000, default value: 30. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated at # the bottom of the documentation of classes and structs. If set to YES, the # list will mention the files that were used to generate the documentation. # The default value is: YES. SHOW_USED_FILES = YES # Set the SHOW_FILES tag to NO to disable the generation of the Files page. This # will remove the Files entry from the Quick Index and from the Folder Tree View # (if specified). # The default value is: YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces # page. This will remove the Namespaces entry from the Quick Index and from the # Folder Tree View (if specified). # The default value is: YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command command input-file, where command is the value of the # FILE_VERSION_FILTER tag, and input-file is the name of an input file provided # by doxygen. Whatever the program writes to standard output is used as the file # version. For an example see the documentation. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. You can # optionally specify a file name after the option, if omitted DoxygenLayout.xml # will be used as the name of the layout file. # # Note that if you run doxygen from a directory containing a file called # DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE # tag is left empty. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files containing # the reference definitions. This must be a list of .bib files. The .bib # extension is automatically appended if omitted. This requires the bibtex tool # to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. # For LaTeX the style of the bibliography can be controlled using # LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the # search path. See also \cite for info how to create references. CITE_BIB_FILES = #--------------------------------------------------------------------------- # Configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated to # standard output by doxygen. If QUIET is set to YES this implies that the # messages are off. # The default value is: NO. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated to standard error (stderr) by doxygen. If WARNINGS is set to YES # this implies that the warnings are on. # # Tip: Turn warnings on while writing the documentation. # The default value is: YES. WARNINGS = YES # If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate # warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag # will automatically be disabled. # The default value is: YES. WARN_IF_UNDOCUMENTED = YES # If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some parameters # in a documented function, or documenting parameters that don't exist or using # markup commands wrongly. # The default value is: YES. WARN_IF_DOC_ERROR = YES # This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that # are documented, but have no documentation for their parameters or return # value. If set to NO, doxygen will only warn about wrong or incomplete # parameter documentation, but not about the absence of documentation. # The default value is: NO. WARN_NO_PARAMDOC = NO # If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when # a warning is encountered. # The default value is: NO. WARN_AS_ERROR = NO # The WARN_FORMAT tag determines the format of the warning messages that doxygen # can produce. The string should contain the $file, $line, and $text tags, which # will be replaced by the file and line number from which the warning originated # and the warning text. Optionally the format may contain $version, which will # be replaced by the version of the file (if it could be obtained via # FILE_VERSION_FILTER) # The default value is: $file:$line: $text. WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning and error # messages should be written. If left blank the output is written to standard # error (stderr). WARN_LOGFILE = #--------------------------------------------------------------------------- # Configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag is used to specify the files and/or directories that contain # documented source files. You may enter file names like myfile.cpp or # directories like /usr/src/myproject. Separate the files or directories with # spaces. See also FILE_PATTERNS and EXTENSION_MAPPING # Note: If this tag is empty the current directory is searched. INPUT = ../.. # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses # libiconv (or the iconv built into libc) for the transcoding. See the libiconv # documentation (see: http://www.gnu.org/software/libiconv) for the list of # possible encodings. # The default value is: UTF-8. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and # *.h) to filter out the source-files in the directories. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # read by doxygen. # # If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, # *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, # *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, # *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, # *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf. FILE_PATTERNS = *.c \ *.h # The RECURSIVE tag can be used to specify whether or not subdirectories should # be searched for input files as well. # The default value is: NO. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. # The default value is: NO. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories for example use the pattern */test/* EXCLUDE_PATTERNS = */test_* \ */.svn/* \ */perf_* \ */tls_test_* \ */examples/* \ */testcurl/* \ */testzzuf/* \ */platform/* \ */symbian/* \ MHD_config.h \ microhttpd2.h # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test # # Note that the wildcards are matched against the file with absolute path, so to # exclude all test directories use the pattern */test/* EXCLUDE_SYMBOLS = MHD_DLOG # The EXAMPLE_PATH tag can be used to specify one or more files or directories # that contain example code fragments that are included (see the \include # command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and # *.h) to filter out the source-files in the directories. If left blank all # files are included. EXAMPLE_PATTERNS = * # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude commands # irrespective of the value of the RECURSIVE tag. # The default value is: NO. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or directories # that contain images that are to be included in the documentation (see the # \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command: # # # # where is the value of the INPUT_FILTER tag, and is the # name of an input file. Doxygen will then use the output that the filter # program writes to standard output. If FILTER_PATTERNS is specified, this tag # will be ignored. # # Note that the filter must not add or remove lines; it is applied before the # code is scanned, but not when the output code is generated. If lines are added # or removed, the anchors will not be placed correctly. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. Doxygen will compare the file name with each pattern and apply the # filter if there is a match. The filters are a list of the form: pattern=filter # (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how # filters are used. If the FILTER_PATTERNS tag is empty or if none of the # patterns match the file name, INPUT_FILTER is applied. # # Note that for custom extensions or not directly supported extensions you also # need to set EXTENSION_MAPPING for the extension otherwise the files are not # properly processed by doxygen. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will also be used to filter the input files that are used for # producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). # The default value is: NO. FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) and # it is also possible to disable source filtering for a specific pattern using # *.ext= (so without naming a filter). # This tag requires that the tag FILTER_SOURCE_FILES is set to YES. FILTER_SOURCE_PATTERNS = # If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page # (index.html). This can be useful if you have a project on for instance GitHub # and want to reuse the introduction page also for the doxygen output. USE_MDFILE_AS_MAINPAGE = #--------------------------------------------------------------------------- # Configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will be # generated. Documented entities will be cross-referenced with these sources. # # Note: To get rid of all source code in the generated output, make sure that # also VERBATIM_HEADERS is set to NO. # The default value is: NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body of functions, # classes and enums directly into the documentation. # The default value is: NO. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any # special comment blocks from generated source code fragments. Normal C, C++ and # Fortran comments will always remain visible. # The default value is: YES. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES then for each documented # function all documented functions referencing it will be listed. # The default value is: NO. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES then for each documented function # all documented entities called/used by that function will be listed. # The default value is: NO. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set # to YES then the hyperlinks from functions in REFERENCES_RELATION and # REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will # link to the documentation. # The default value is: YES. REFERENCES_LINK_SOURCE = YES # If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the # source code will show a tooltip with additional information such as prototype, # brief description and links to the definition and documentation. Since this # will make the HTML file larger and loading of large files a bit slower, you # can opt to disable this feature. # The default value is: YES. # This tag requires that the tag SOURCE_BROWSER is set to YES. SOURCE_TOOLTIPS = YES # If the USE_HTAGS tag is set to YES then the references to source code will # point to the HTML generated by the htags(1) tool instead of doxygen built-in # source browser. The htags tool is part of GNU's global source tagging system # (see http://www.gnu.org/software/global/global.html). You will need version # 4.8.6 or higher. # # To use it do the following: # - Install the latest version of global # - Enable SOURCE_BROWSER and USE_HTAGS in the config file # - Make sure the INPUT points to the root of the source tree # - Run doxygen as normal # # Doxygen will invoke htags (and that will in turn invoke gtags), so these # tools must be available from the command line (i.e. in the search path). # # The result: instead of the source browser generated by doxygen, the links to # source code will now point to the output of htags. # The default value is: NO. # This tag requires that the tag SOURCE_BROWSER is set to YES. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a # verbatim copy of the header file for each class for which an include is # specified. Set to NO to disable this. # See also: Section \class. # The default value is: YES. VERBATIM_HEADERS = NO # If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the # clang parser (see: http://clang.llvm.org/) for more accurate parsing at the # cost of reduced performance. This can be particularly helpful with template # rich C++ code for which doxygen's built-in parser lacks the necessary type # information. # Note: The availability of this option depends on whether or not doxygen was # generated with the -Duse-libclang=ON option for CMake. # The default value is: NO. CLANG_ASSISTED_PARSING = NO # If clang assisted parsing is enabled you can provide the compiler with command # line options that you would normally use when invoking the compiler. Note that # the include paths will already be set by doxygen for the files and directories # specified with INPUT and INCLUDE_PATH. # This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. CLANG_OPTIONS = #--------------------------------------------------------------------------- # Configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all # compounds will be generated. Enable this if the project contains a lot of # classes, structs, unions or interfaces. # The default value is: YES. ALPHABETICAL_INDEX = YES # The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in # which the alphabetical index list will be split. # Minimum value: 1, maximum value: 20, default value: 5. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all classes will # be put under the same header in the alphabetical index. The IGNORE_PREFIX tag # can be used to specify a prefix (or a list of prefixes) that should be ignored # while generating the index headers. # This tag requires that the tag ALPHABETICAL_INDEX is set to YES. IGNORE_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output # The default value is: YES. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a # relative path is entered the value of OUTPUT_DIRECTORY will be put in front of # it. # The default directory is: html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for each # generated HTML page (for example: .htm, .php, .asp). # The default value is: .html. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a user-defined HTML header file for # each generated HTML page. If the tag is left blank doxygen will generate a # standard header. # # To get valid HTML the header file that includes any scripts and style sheets # that doxygen needs, which is dependent on the configuration options used (e.g. # the setting GENERATE_TREEVIEW). It is highly recommended to start with a # default header using # doxygen -w html new_header.html new_footer.html new_stylesheet.css # YourConfigFile # and then modify the file new_header.html. See also section "Doxygen usage" # for information on how to generate the default header that doxygen normally # uses. # Note: The header is subject to change so you typically have to regenerate the # default header when upgrading to a newer version of doxygen. For a description # of the possible markers and block names see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each # generated HTML page. If the tag is left blank doxygen will generate a standard # footer. See HTML_HEADER for more information on how to generate a default # footer and what special commands can be used inside the footer. See also # section "Doxygen usage" for information on how to generate the default footer # that doxygen normally uses. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading style # sheet that is used by each HTML page. It can be used to fine-tune the look of # the HTML output. If left blank doxygen will generate a default style sheet. # See also section "Doxygen usage" for information on how to generate the style # sheet that doxygen normally uses. # Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as # it is more robust and this tag (HTML_STYLESHEET) will in the future become # obsolete. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined # cascading style sheets that are included after the standard style sheets # created by doxygen. Using this option one can overrule certain style aspects. # This is preferred over using HTML_STYLESHEET since it does not replace the # standard style sheet and is therefore more robust against future updates. # Doxygen will copy the style sheet files to the output directory. # Note: The order of the extra style sheet files is of importance (e.g. the last # style sheet in the list overrules the setting of the previous ones in the # list). For an example see the documentation. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that the # files will be copied as-is; there are no commands or markers available. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen # will adjust the colors in the style sheet and background images according to # this color. Hue is specified as an angle on a colorwheel, see # http://en.wikipedia.org/wiki/Hue for more information. For instance the value # 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 # purple, and 360 is red again. # Minimum value: 0, maximum value: 359, default value: 220. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors # in the HTML output. For a value of 0 the output will use grayscales only. A # value of 255 will produce the most vivid colors. # Minimum value: 0, maximum value: 255, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the # luminance component of the colors in the HTML output. Values below 100 # gradually make the output lighter, whereas values above 100 make the output # darker. The value divided by 100 is the actual gamma applied, so 80 represents # a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not # change the gamma. # Minimum value: 40, maximum value: 240, default value: 80. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting this # to YES can help to show when doxygen was last run and thus if the # documentation is up to date. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_TIMESTAMP = NO # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_DYNAMIC_SECTIONS = NO # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries # shown in the various tree structured indices initially; the user can expand # and collapse entries dynamically later on. Doxygen will expand the tree to # such a level that at most the specified number of entries are visible (unless # a fully collapsed tree already exceeds this amount). So setting the number of # entries 1 will produce a full collapsed tree by default. 0 is a special value # representing an infinite number of entries and will result in a full expanded # tree by default. # Minimum value: 0, maximum value: 9999, default value: 100. # This tag requires that the tag GENERATE_HTML is set to YES. HTML_INDEX_NUM_ENTRIES = 100 # If the GENERATE_DOCSET tag is set to YES, additional index files will be # generated that can be used as input for Apple's Xcode 3 integrated development # environment (see: http://developer.apple.com/tools/xcode/), introduced with # OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a # Makefile in the HTML output directory. Running make will produce the docset in # that directory and running make install will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at # startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_DOCSET = NO # This tag determines the name of the docset feed. A documentation feed provides # an umbrella under which multiple documentation sets from a single provider # (such as a company or product suite) can be grouped. # The default value is: Doxygen generated docs. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_FEEDNAME = "Doxygen generated docs" # This tag specifies a string that should uniquely identify the documentation # set bundle. This should be a reverse domain-name style string, e.g. # com.mycompany.MyDocSet. Doxygen will append .docset to the name. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_BUNDLE_ID = org.doxygen.Project # The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. # The default value is: org.doxygen.Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. # The default value is: Publisher. # This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three # additional HTML index files: index.hhp, index.hhc, and index.hhk. The # index.hhp is a project file that can be read by Microsoft's HTML Help Workshop # (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on # Windows. # # The HTML Help Workshop contains a compiler that can convert all HTML output # generated by doxygen into a single compiled HTML file (.chm). Compiled HTML # files are now used as the Windows 98 help format, and will replace the old # Windows help format (.hlp) on all Windows platforms in the future. Compressed # HTML files also contain an index, a table of contents, and you can search for # words in the documentation. The HTML workshop also contains a viewer for # compressed HTML files. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_HTMLHELP = NO # The CHM_FILE tag can be used to specify the file name of the resulting .chm # file. You can add a path in front of the file if the result should not be # written to the html output directory. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_FILE = # The HHC_LOCATION tag can be used to specify the location (absolute path # including file name) of the HTML help compiler (hhc.exe). If non-empty, # doxygen will try to run the HTML help compiler on the generated index.hhp. # The file has to be specified with full path. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. HHC_LOCATION = # The GENERATE_CHI flag controls if a separate .chi index file is generated # (YES) or that it should be included in the master .chm file (NO). # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. GENERATE_CHI = NO # The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) # and project file content. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_INDEX_ENCODING = # The BINARY_TOC flag controls whether a binary table of contents is generated # (YES) or a normal table of contents (NO) in the .chm file. Furthermore it # enables the Previous and Next buttons. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members to # the table of contents of the HTML help documentation and to the tree view. # The default value is: NO. # This tag requires that the tag GENERATE_HTMLHELP is set to YES. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that # can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help # (.qch) of the generated HTML documentation. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify # the file name of the resulting .qch file. The path specified is relative to # the HTML output folder. # This tag requires that the tag GENERATE_QHP is set to YES. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help # Project output. For more information please see Qt Help Project / Namespace # (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt # Help Project output. For more information please see Qt Help Project / Virtual # Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- # folders). # The default value is: doc. # This tag requires that the tag GENERATE_QHP is set to YES. QHP_VIRTUAL_FOLDER = doc # If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom # filter to add. For more information please see Qt Help Project / Custom # Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- # filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_NAME = # The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see Qt Help Project / Custom # Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- # filters). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's filter section matches. Qt Help Project / Filter Attributes (see: # http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). # This tag requires that the tag GENERATE_QHP is set to YES. QHP_SECT_FILTER_ATTRS = # The QHG_LOCATION tag can be used to specify the location of Qt's # qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the # generated .qhp file. # This tag requires that the tag GENERATE_QHP is set to YES. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be # generated, together with the HTML files, they form an Eclipse help plugin. To # install this plugin and make it available under the help contents menu in # Eclipse, the contents of the directory containing the HTML and XML files needs # to be copied into the plugins directory of eclipse. The name of the directory # within the plugins directory should be the same as the ECLIPSE_DOC_ID value. # After copying Eclipse needs to be restarted before the help appears. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_ECLIPSEHELP = NO # A unique identifier for the Eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have this # name. Each documentation set should have its own identifier. # The default value is: org.doxygen.Project. # This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. ECLIPSE_DOC_ID = org.doxygen.Project # If you want full control over the layout of the generated HTML pages it might # be necessary to disable the index and replace it with your own. The # DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top # of each HTML page. A value of NO enables the index and the value YES disables # it. Since the tabs in the index contain the same information as the navigation # tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. DISABLE_INDEX = NO # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. If the tag # value is set to YES, a side panel will be generated containing a tree-like # index structure (just like the one that is generated for HTML Help). For this # to work a browser that supports JavaScript, DHTML, CSS and frames is required # (i.e. any modern browser). Windows users are probably better off using the # HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can # further fine-tune the look of the index. As an example, the default style # sheet generated by doxygen has an example that shows how to put an image at # the root of the tree instead of the PROJECT_NAME. Since the tree basically has # the same information as the tab index, you could consider setting # DISABLE_INDEX to YES when enabling this option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_TREEVIEW = YES # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that # doxygen will group on one line in the generated HTML documentation. # # Note that a value of 0 will completely suppress the enum values from appearing # in the overview section. # Minimum value: 0, maximum value: 20, default value: 4. # This tag requires that the tag GENERATE_HTML is set to YES. ENUM_VALUES_PER_LINE = 4 # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used # to set the initial width (in pixels) of the frame in which the tree is shown. # Minimum value: 0, maximum value: 1500, default value: 250. # This tag requires that the tag GENERATE_HTML is set to YES. TREEVIEW_WIDTH = 250 # If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to # external symbols imported via tag files in a separate window. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of LaTeX formulas included as images in # the HTML documentation. When you change the font size after a successful # doxygen run you need to manually remove any form_*.png images from the HTML # output directory to force them to be regenerated. # Minimum value: 8, maximum value: 50, default value: 10. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are not # supported properly for IE 6.0, but are supported on all modern browsers. # # Note that when changing this option you need to delete any form_*.png files in # the HTML output directory before the changes have effect. # The default value is: YES. # This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see # http://www.mathjax.org) which uses client side Javascript for the rendering # instead of using pre-rendered bitmaps. Use this if you do not have LaTeX # installed or if you want to formulas look prettier in the HTML output. When # enabled you may also need to install MathJax separately and configure the path # to it using the MATHJAX_RELPATH option. # The default value is: NO. # This tag requires that the tag GENERATE_HTML is set to YES. USE_MATHJAX = NO # When MathJax is enabled you can set the default output format to be used for # the MathJax output. See the MathJax site (see: # http://docs.mathjax.org/en/latest/output.html) for more details. # Possible values are: HTML-CSS (which is slower, but has the best # compatibility), NativeMML (i.e. MathML) and SVG. # The default value is: HTML-CSS. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_FORMAT = HTML-CSS # When MathJax is enabled you need to specify the location relative to the HTML # output directory using the MATHJAX_RELPATH option. The destination directory # should contain the MathJax.js script. For instance, if the mathjax directory # is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax # Content Delivery Network so you can quickly see the result without installing # MathJax. However, it is strongly recommended to install a local copy of # MathJax from http://www.mathjax.org before deployment. # The default value is: http://cdn.mathjax.org/mathjax/latest. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest # The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax # extension names that should be enabled during MathJax rendering. For example # MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_EXTENSIONS = # The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces # of code that will be used on startup of the MathJax code. See the MathJax site # (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an # example see the documentation. # This tag requires that the tag USE_MATHJAX is set to YES. MATHJAX_CODEFILE = # When the SEARCHENGINE tag is enabled doxygen will generate a search box for # the HTML output. The underlying search engine uses javascript and DHTML and # should work on any modern browser. Note that when using HTML help # (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) # there is already a search function so this one should typically be disabled. # For large projects the javascript based search engine can be slow, then # enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to # search using the keyboard; to jump to the search box use + S # (what the is depends on the OS and browser, but it is typically # , /