test.cc 182 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149
  1. #include <httplib.h>
  2. #include <signal.h>
  3. #include <gtest/gtest.h>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <future>
  7. #include <memory>
  8. #include <sstream>
  9. #include <stdexcept>
  10. #include <thread>
  11. #include <type_traits>
  12. #define SERVER_CERT_FILE "./cert.pem"
  13. #define SERVER_CERT2_FILE "./cert2.pem"
  14. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  15. #define CA_CERT_FILE "./ca-bundle.crt"
  16. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  17. #define CLIENT_CA_CERT_DIR "."
  18. #define CLIENT_CERT_FILE "./client.cert.pem"
  19. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  20. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  21. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  22. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  23. using namespace std;
  24. using namespace httplib;
  25. const char *HOST = "localhost";
  26. const int PORT = 1234;
  27. const string LONG_QUERY_VALUE = string(25000, '@');
  28. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  29. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  30. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  31. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  32. const char *key) {
  33. auto it = std::find_if(
  34. files.begin(), files.end(),
  35. [&](const MultipartFormData &file) { return file.name == key; });
  36. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  37. return *it;
  38. #else
  39. if (it != files.end()) { return *it; }
  40. throw std::runtime_error("invalid multipart form data name error");
  41. #endif
  42. }
  43. TEST(ConstructorTest, MoveConstructible) {
  44. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  45. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  46. }
  47. #ifdef _WIN32
  48. TEST(StartupTest, WSAStartup) {
  49. WSADATA wsaData;
  50. int ret = WSAStartup(0x0002, &wsaData);
  51. ASSERT_EQ(0, ret);
  52. }
  53. #endif
  54. TEST(DecodeURLTest, PercentCharacter) {
  55. EXPECT_EQ(
  56. detail::decode_url(
  57. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  58. false),
  59. R"(descrip=Gastos áéíóúñÑ 6)");
  60. }
  61. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  62. string unescapedCharacters = "-_.!~*'()";
  63. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  64. }
  65. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  66. string reservedCharacters = ";,/?:@&=+$";
  67. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  68. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  69. }
  70. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  71. string chineseCharacters = "中国語";
  72. string russianCharacters = "дом";
  73. string brazilianCharacters = "óculos";
  74. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  75. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  76. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  77. "%D0%B4%D0%BE%D0%BC");
  78. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  79. }
  80. TEST(TrimTests, TrimStringTests) {
  81. EXPECT_EQ("abc", detail::trim_copy("abc"));
  82. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  83. EXPECT_TRUE(detail::trim_copy("").empty());
  84. }
  85. TEST(SplitTest, ParseQueryString) {
  86. string s = "key1=val1&key2=val2&key3=val3";
  87. Params dic;
  88. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  89. [&](const char *b, const char *e) {
  90. string key, val;
  91. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  92. if (key.empty()) {
  93. key.assign(b2, e2);
  94. } else {
  95. val.assign(b2, e2);
  96. }
  97. });
  98. dic.emplace(key, val);
  99. });
  100. EXPECT_EQ("val1", dic.find("key1")->second);
  101. EXPECT_EQ("val2", dic.find("key2")->second);
  102. EXPECT_EQ("val3", dic.find("key3")->second);
  103. }
  104. TEST(SplitTest, ParseInvalidQueryTests) {
  105. {
  106. string s = " ";
  107. Params dict;
  108. detail::parse_query_text(s, dict);
  109. EXPECT_TRUE(dict.empty());
  110. }
  111. {
  112. string s = " = =";
  113. Params dict;
  114. detail::parse_query_text(s, dict);
  115. EXPECT_TRUE(dict.empty());
  116. }
  117. }
  118. TEST(ParseQueryTest, ParseQueryString) {
  119. string s = "key1=val1&key2=val2&key3=val3";
  120. Params dic;
  121. detail::parse_query_text(s, dic);
  122. EXPECT_EQ("val1", dic.find("key1")->second);
  123. EXPECT_EQ("val2", dic.find("key2")->second);
  124. EXPECT_EQ("val3", dic.find("key3")->second);
  125. }
  126. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  127. Params dic;
  128. EXPECT_EQ(detail::params_to_query_str(dic), "");
  129. dic.emplace("key1", "val1");
  130. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  131. dic.emplace("key2", "val2");
  132. dic.emplace("key3", "val3");
  133. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  134. }
  135. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  136. string content_type = "multipart/form-data; boundary=something";
  137. string boundary;
  138. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  139. EXPECT_TRUE(ret);
  140. EXPECT_EQ(boundary, "something");
  141. }
  142. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  143. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  144. string boundary;
  145. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  146. EXPECT_TRUE(ret);
  147. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  148. }
  149. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  150. string content_type =
  151. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  152. string boundary;
  153. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  154. EXPECT_TRUE(ret);
  155. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  156. }
  157. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  158. string content_type =
  159. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  160. string boundary;
  161. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  162. EXPECT_TRUE(ret);
  163. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  164. }
  165. TEST(GetHeaderValueTest, DefaultValue) {
  166. Headers headers = {{"Dummy", "Dummy"}};
  167. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  168. EXPECT_STREQ("text/plain", val);
  169. }
  170. TEST(GetHeaderValueTest, DefaultValueInt) {
  171. Headers headers = {{"Dummy", "Dummy"}};
  172. auto val =
  173. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 100);
  174. EXPECT_EQ(100ull, val);
  175. }
  176. TEST(GetHeaderValueTest, RegularValue) {
  177. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  178. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  179. EXPECT_STREQ("text/html", val);
  180. }
  181. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  182. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  183. auto val = detail::get_header_value(headers, "content-type", 0, "text/plain");
  184. EXPECT_STREQ("text/html", val);
  185. }
  186. TEST(GetHeaderValueTest, SetContent) {
  187. Response res;
  188. res.set_content("html", "text/html");
  189. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  190. res.set_content("text", "text/plain");
  191. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  192. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  193. }
  194. TEST(GetHeaderValueTest, RegularValueInt) {
  195. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  196. auto val =
  197. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 0);
  198. EXPECT_EQ(100ull, val);
  199. }
  200. TEST(GetHeaderValueTest, Range) {
  201. {
  202. Headers headers = {make_range_header({{1, -1}})};
  203. auto val = detail::get_header_value(headers, "Range", 0, 0);
  204. EXPECT_STREQ("bytes=1-", val);
  205. }
  206. {
  207. Headers headers = {make_range_header({{-1, 1}})};
  208. auto val = detail::get_header_value(headers, "Range", 0, 0);
  209. EXPECT_STREQ("bytes=-1", val);
  210. }
  211. {
  212. Headers headers = {make_range_header({{1, 10}})};
  213. auto val = detail::get_header_value(headers, "Range", 0, 0);
  214. EXPECT_STREQ("bytes=1-10", val);
  215. }
  216. {
  217. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  218. auto val = detail::get_header_value(headers, "Range", 0, 0);
  219. EXPECT_STREQ("bytes=1-10, 100-", val);
  220. }
  221. {
  222. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  223. auto val = detail::get_header_value(headers, "Range", 0, 0);
  224. EXPECT_STREQ("bytes=1-10, 100-200", val);
  225. }
  226. {
  227. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  228. auto val = detail::get_header_value(headers, "Range", 0, 0);
  229. EXPECT_STREQ("bytes=0-0, -1", val);
  230. }
  231. }
  232. TEST(ParseHeaderValueTest, Range) {
  233. {
  234. Ranges ranges;
  235. auto ret = detail::parse_range_header("bytes=1-", ranges);
  236. EXPECT_TRUE(ret);
  237. EXPECT_EQ(1u, ranges.size());
  238. EXPECT_EQ(1u, ranges[0].first);
  239. EXPECT_EQ(-1, ranges[0].second);
  240. }
  241. {
  242. Ranges ranges;
  243. auto ret = detail::parse_range_header("bytes=-1", ranges);
  244. EXPECT_TRUE(ret);
  245. EXPECT_EQ(1u, ranges.size());
  246. EXPECT_EQ(-1, ranges[0].first);
  247. EXPECT_EQ(1u, ranges[0].second);
  248. }
  249. {
  250. Ranges ranges;
  251. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  252. EXPECT_TRUE(ret);
  253. EXPECT_EQ(1u, ranges.size());
  254. EXPECT_EQ(1u, ranges[0].first);
  255. EXPECT_EQ(10u, ranges[0].second);
  256. }
  257. {
  258. Ranges ranges;
  259. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  260. EXPECT_FALSE(ret);
  261. }
  262. {
  263. Ranges ranges;
  264. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  265. EXPECT_TRUE(ret);
  266. EXPECT_EQ(2u, ranges.size());
  267. EXPECT_EQ(1u, ranges[0].first);
  268. EXPECT_EQ(10u, ranges[0].second);
  269. EXPECT_EQ(100u, ranges[1].first);
  270. EXPECT_EQ(-1, ranges[1].second);
  271. }
  272. {
  273. Ranges ranges;
  274. auto ret =
  275. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  276. EXPECT_TRUE(ret);
  277. EXPECT_EQ(3u, ranges.size());
  278. EXPECT_EQ(1u, ranges[0].first);
  279. EXPECT_EQ(10u, ranges[0].second);
  280. EXPECT_EQ(100u, ranges[1].first);
  281. EXPECT_EQ(200u, ranges[1].second);
  282. EXPECT_EQ(300u, ranges[2].first);
  283. EXPECT_EQ(400u, ranges[2].second);
  284. }
  285. }
  286. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  287. Request req;
  288. req.set_header("Accept-Encoding", "gzip");
  289. Response res;
  290. res.set_header("Content-Type", "text/plain");
  291. auto ret = detail::encoding_type(req, res);
  292. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  293. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  294. #else
  295. EXPECT_TRUE(ret == detail::EncodingType::None);
  296. #endif
  297. }
  298. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  299. Request req;
  300. req.set_header("Accept-Encoding", "gzip, deflate, br");
  301. Response res;
  302. res.set_header("Content-Type", "text/plain");
  303. auto ret = detail::encoding_type(req, res);
  304. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  305. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  306. #elif CPPHTTPLIB_ZLIB_SUPPORT
  307. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  308. #else
  309. EXPECT_TRUE(ret == detail::EncodingType::None);
  310. #endif
  311. }
  312. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  313. Request req;
  314. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  315. Response res;
  316. res.set_header("Content-Type", "text/plain");
  317. auto ret = detail::encoding_type(req, res);
  318. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  319. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  320. #elif CPPHTTPLIB_ZLIB_SUPPORT
  321. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  322. #else
  323. EXPECT_TRUE(ret == detail::EncodingType::None);
  324. #endif
  325. }
  326. TEST(BufferStreamTest, read) {
  327. detail::BufferStream strm1;
  328. Stream &strm = strm1;
  329. EXPECT_EQ(5, strm.write("hello"));
  330. char buf[512];
  331. EXPECT_EQ(2, strm.read(buf, 2));
  332. EXPECT_EQ('h', buf[0]);
  333. EXPECT_EQ('e', buf[1]);
  334. EXPECT_EQ(2, strm.read(buf, 2));
  335. EXPECT_EQ('l', buf[0]);
  336. EXPECT_EQ('l', buf[1]);
  337. EXPECT_EQ(1, strm.read(buf, 1));
  338. EXPECT_EQ('o', buf[0]);
  339. EXPECT_EQ(0, strm.read(buf, 1));
  340. }
  341. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  342. auto host = "www.httpwatch.com";
  343. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  344. auto port = 443;
  345. SSLClient cli(host, port);
  346. #else
  347. auto port = 80;
  348. Client cli(host, port);
  349. #endif
  350. cli.set_connection_timeout(2);
  351. auto res =
  352. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  353. ASSERT_TRUE(res);
  354. std::string out;
  355. detail::read_file("./image.jpg", out);
  356. EXPECT_EQ(200, res->status);
  357. EXPECT_EQ(out, res->body);
  358. }
  359. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  360. auto host = "www.httpwatch.com";
  361. auto ip = hosted_at(host);
  362. EXPECT_EQ("191.236.16.12", ip);
  363. std::vector<std::string> addrs;
  364. hosted_at(host, addrs);
  365. EXPECT_EQ(1u, addrs.size());
  366. }
  367. #if 0 // It depends on each test environment...
  368. TEST(HostnameToIPConversionTest, YouTube_Online) {
  369. auto host = "www.youtube.com";
  370. std::vector<std::string> addrs;
  371. hosted_at(host, addrs);
  372. EXPECT_EQ(20u, addrs.size());
  373. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  374. EXPECT_TRUE(it != addrs.end());
  375. }
  376. #endif
  377. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  378. auto host = "www.httpwatch.com";
  379. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  380. auto port = 443;
  381. SSLClient cli(host, port);
  382. #else
  383. auto port = 80;
  384. Client cli(host, port);
  385. #endif
  386. cli.set_connection_timeout(2);
  387. std::string body;
  388. auto res =
  389. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  390. [&](const char *data, size_t data_length) {
  391. body.append(data, data_length);
  392. return true;
  393. });
  394. ASSERT_TRUE(res);
  395. std::string out;
  396. detail::read_file("./image.jpg", out);
  397. EXPECT_EQ(200, res->status);
  398. EXPECT_EQ(out, body);
  399. }
  400. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  401. auto host = "www.httpwatch.com";
  402. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  403. auto port = 443;
  404. SSLClient cli(host, port);
  405. #else
  406. auto port = 80;
  407. Client cli(host, port);
  408. #endif
  409. cli.set_connection_timeout(2);
  410. std::string body;
  411. auto res = cli.Get(
  412. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  413. [&](const Response &response) {
  414. EXPECT_EQ(200, response.status);
  415. return true;
  416. },
  417. [&](const char *data, size_t data_length) {
  418. body.append(data, data_length);
  419. return true;
  420. });
  421. ASSERT_TRUE(res);
  422. std::string out;
  423. detail::read_file("./image.jpg", out);
  424. EXPECT_EQ(200, res->status);
  425. EXPECT_EQ(out, body);
  426. }
  427. TEST(RangeTest, FromHTTPBin_Online) {
  428. auto host = "httpbin.org";
  429. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  430. auto port = 443;
  431. SSLClient cli(host, port);
  432. #else
  433. auto port = 80;
  434. Client cli(host, port);
  435. #endif
  436. cli.set_connection_timeout(5);
  437. {
  438. auto res = cli.Get("/range/32");
  439. ASSERT_TRUE(res);
  440. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  441. EXPECT_EQ(200, res->status);
  442. }
  443. {
  444. Headers headers = {make_range_header({{1, -1}})};
  445. auto res = cli.Get("/range/32", headers);
  446. ASSERT_TRUE(res);
  447. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  448. EXPECT_EQ(206, res->status);
  449. }
  450. {
  451. Headers headers = {make_range_header({{1, 10}})};
  452. auto res = cli.Get("/range/32", headers);
  453. ASSERT_TRUE(res);
  454. EXPECT_EQ("bcdefghijk", res->body);
  455. EXPECT_EQ(206, res->status);
  456. }
  457. {
  458. Headers headers = {make_range_header({{0, 31}})};
  459. auto res = cli.Get("/range/32", headers);
  460. ASSERT_TRUE(res);
  461. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  462. EXPECT_EQ(200, res->status);
  463. }
  464. {
  465. Headers headers = {make_range_header({{0, -1}})};
  466. auto res = cli.Get("/range/32", headers);
  467. ASSERT_TRUE(res);
  468. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  469. EXPECT_EQ(200, res->status);
  470. }
  471. {
  472. Headers headers = {make_range_header({{0, 32}})};
  473. auto res = cli.Get("/range/32", headers);
  474. ASSERT_TRUE(res);
  475. EXPECT_EQ(416, res->status);
  476. }
  477. }
  478. TEST(ConnectionErrorTest, InvalidHost) {
  479. auto host = "-abcde.com";
  480. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  481. auto port = 443;
  482. SSLClient cli(host, port);
  483. #else
  484. auto port = 80;
  485. Client cli(host, port);
  486. #endif
  487. cli.set_connection_timeout(std::chrono::seconds(2));
  488. auto res = cli.Get("/");
  489. ASSERT_TRUE(!res);
  490. EXPECT_EQ(Error::Connection, res.error());
  491. }
  492. TEST(ConnectionErrorTest, InvalidHost2) {
  493. auto host = "httpbin.org/";
  494. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  495. SSLClient cli(host);
  496. #else
  497. Client cli(host);
  498. #endif
  499. cli.set_connection_timeout(std::chrono::seconds(2));
  500. auto res = cli.Get("/");
  501. ASSERT_TRUE(!res);
  502. EXPECT_EQ(Error::Connection, res.error());
  503. }
  504. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  505. auto host = "httpbin.org/";
  506. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  507. SSLClient cli(host);
  508. #else
  509. Client cli(host);
  510. #endif
  511. cli.set_connection_timeout(std::chrono::seconds(2));
  512. auto res = cli.Get("/");
  513. ASSERT_TRUE(!res);
  514. stringstream s;
  515. s << "error code: " << res.error();
  516. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  517. }
  518. TEST(ConnectionErrorTest, InvalidPort) {
  519. auto host = "localhost";
  520. auto port = 44380;
  521. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  522. SSLClient cli(host, port);
  523. #else
  524. Client cli(host, port);
  525. #endif
  526. cli.set_connection_timeout(std::chrono::seconds(2));
  527. auto res = cli.Get("/");
  528. ASSERT_TRUE(!res);
  529. EXPECT_TRUE(Error::Connection == res.error() ||
  530. Error::ConnectionTimeout == res.error());
  531. }
  532. TEST(ConnectionErrorTest, Timeout_Online) {
  533. auto host = "google.com";
  534. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  535. auto port = 44380;
  536. SSLClient cli(host, port);
  537. #else
  538. auto port = 8080;
  539. Client cli(host, port);
  540. #endif
  541. cli.set_connection_timeout(std::chrono::seconds(2));
  542. // only probe one address type so that the error reason
  543. // correlates to the timed-out IPv4, not the unsupported
  544. // IPv6 connection attempt
  545. cli.set_address_family(AF_INET);
  546. auto res = cli.Get("/");
  547. ASSERT_TRUE(!res);
  548. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  549. }
  550. TEST(CancelTest, NoCancel_Online) {
  551. auto host = "httpbin.org";
  552. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  553. auto port = 443;
  554. SSLClient cli(host, port);
  555. #else
  556. auto port = 80;
  557. Client cli(host, port);
  558. #endif
  559. cli.set_connection_timeout(std::chrono::seconds(5));
  560. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return true; });
  561. ASSERT_TRUE(res);
  562. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  563. EXPECT_EQ(200, res->status);
  564. }
  565. TEST(CancelTest, WithCancelSmallPayload_Online) {
  566. auto host = "httpbin.org";
  567. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  568. auto port = 443;
  569. SSLClient cli(host, port);
  570. #else
  571. auto port = 80;
  572. Client cli(host, port);
  573. #endif
  574. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return false; });
  575. cli.set_connection_timeout(std::chrono::seconds(5));
  576. ASSERT_TRUE(!res);
  577. EXPECT_EQ(Error::Canceled, res.error());
  578. }
  579. TEST(CancelTest, WithCancelLargePayload_Online) {
  580. auto host = "httpbin.org";
  581. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  582. auto port = 443;
  583. SSLClient cli(host, port);
  584. #else
  585. auto port = 80;
  586. Client cli(host, port);
  587. #endif
  588. cli.set_connection_timeout(std::chrono::seconds(5));
  589. uint32_t count = 0;
  590. auto res = cli.Get("/range/65536",
  591. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  592. ASSERT_TRUE(!res);
  593. EXPECT_EQ(Error::Canceled, res.error());
  594. }
  595. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  596. auto host = "httpbin.org";
  597. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  598. auto port = 443;
  599. SSLClient cli(host, port);
  600. #else
  601. auto port = 80;
  602. Client cli(host, port);
  603. #endif
  604. {
  605. auto res = cli.Get("/basic-auth/hello/world");
  606. ASSERT_TRUE(res);
  607. EXPECT_EQ(401, res->status);
  608. }
  609. {
  610. auto res = cli.Get("/basic-auth/hello/world",
  611. {make_basic_authentication_header("hello", "world")});
  612. ASSERT_TRUE(res);
  613. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  614. res->body);
  615. EXPECT_EQ(200, res->status);
  616. }
  617. {
  618. cli.set_basic_auth("hello", "world");
  619. auto res = cli.Get("/basic-auth/hello/world");
  620. ASSERT_TRUE(res);
  621. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  622. res->body);
  623. EXPECT_EQ(200, res->status);
  624. }
  625. {
  626. cli.set_basic_auth("hello", "bad");
  627. auto res = cli.Get("/basic-auth/hello/world");
  628. ASSERT_TRUE(res);
  629. EXPECT_EQ(401, res->status);
  630. }
  631. {
  632. cli.set_basic_auth("bad", "world");
  633. auto res = cli.Get("/basic-auth/hello/world");
  634. ASSERT_TRUE(res);
  635. EXPECT_EQ(401, res->status);
  636. }
  637. }
  638. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  639. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  640. auto host = "httpbin.org";
  641. auto port = 443;
  642. SSLClient cli(host, port);
  643. {
  644. auto res = cli.Get("/digest-auth/auth/hello/world");
  645. ASSERT_TRUE(res);
  646. EXPECT_EQ(401, res->status);
  647. }
  648. {
  649. std::vector<std::string> paths = {
  650. "/digest-auth/auth/hello/world/MD5",
  651. "/digest-auth/auth/hello/world/SHA-256",
  652. "/digest-auth/auth/hello/world/SHA-512",
  653. "/digest-auth/auth-int/hello/world/MD5",
  654. };
  655. cli.set_digest_auth("hello", "world");
  656. for (auto path : paths) {
  657. auto res = cli.Get(path.c_str());
  658. ASSERT_TRUE(res);
  659. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  660. res->body);
  661. EXPECT_EQ(200, res->status);
  662. }
  663. cli.set_digest_auth("hello", "bad");
  664. for (auto path : paths) {
  665. auto res = cli.Get(path.c_str());
  666. ASSERT_TRUE(res);
  667. EXPECT_EQ(401, res->status);
  668. }
  669. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  670. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  671. // cli.set_digest_auth("bad", "world");
  672. // for (auto path : paths) {
  673. // auto res = cli.Get(path.c_str());
  674. // ASSERT_TRUE(res);
  675. // EXPECT_EQ(400, res->status);
  676. // }
  677. }
  678. }
  679. #endif
  680. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  681. auto host = "google.com";
  682. auto another_host = "example.com";
  683. auto wrong_ip = "0.0.0.0";
  684. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  685. SSLClient cli(host);
  686. #else
  687. Client cli(host);
  688. #endif
  689. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  690. auto res = cli.Get("/");
  691. ASSERT_TRUE(res);
  692. ASSERT_EQ(301, res->status);
  693. }
  694. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  695. auto host = "google.com";
  696. auto wrong_ip = "0.0.0.0";
  697. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  698. SSLClient cli(host);
  699. #else
  700. Client cli(host);
  701. #endif
  702. cli.set_hostname_addr_map({{host, wrong_ip}});
  703. auto res = cli.Get("/");
  704. ASSERT_TRUE(!res);
  705. EXPECT_EQ(Error::Connection, res.error());
  706. }
  707. TEST(AbsoluteRedirectTest, Redirect_Online) {
  708. auto host = "nghttp2.org";
  709. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  710. SSLClient cli(host);
  711. #else
  712. Client cli(host);
  713. #endif
  714. cli.set_follow_location(true);
  715. auto res = cli.Get("/httpbin/absolute-redirect/3");
  716. ASSERT_TRUE(res);
  717. EXPECT_EQ(200, res->status);
  718. }
  719. TEST(RedirectTest, Redirect_Online) {
  720. auto host = "nghttp2.org";
  721. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  722. SSLClient cli(host);
  723. #else
  724. Client cli(host);
  725. #endif
  726. cli.set_follow_location(true);
  727. auto res = cli.Get("/httpbin/redirect/3");
  728. ASSERT_TRUE(res);
  729. EXPECT_EQ(200, res->status);
  730. }
  731. TEST(RelativeRedirectTest, Redirect_Online) {
  732. auto host = "nghttp2.org";
  733. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  734. SSLClient cli(host);
  735. #else
  736. Client cli(host);
  737. #endif
  738. cli.set_follow_location(true);
  739. auto res = cli.Get("/httpbin/relative-redirect/3");
  740. ASSERT_TRUE(res);
  741. EXPECT_EQ(200, res->status);
  742. }
  743. TEST(TooManyRedirectTest, Redirect_Online) {
  744. auto host = "nghttp2.org";
  745. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  746. SSLClient cli(host);
  747. #else
  748. Client cli(host);
  749. #endif
  750. cli.set_follow_location(true);
  751. auto res = cli.Get("/httpbin/redirect/21");
  752. ASSERT_TRUE(!res);
  753. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  754. }
  755. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  756. TEST(YahooRedirectTest, Redirect_Online) {
  757. Client cli("yahoo.com");
  758. auto res = cli.Get("/");
  759. ASSERT_TRUE(res);
  760. EXPECT_EQ(301, res->status);
  761. cli.set_follow_location(true);
  762. res = cli.Get("/");
  763. ASSERT_TRUE(res);
  764. EXPECT_EQ(200, res->status);
  765. EXPECT_EQ("https://yahoo.com/", res->location);
  766. }
  767. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  768. SSLClient cli("nghttp2.org");
  769. cli.set_follow_location(true);
  770. auto res = cli.Get(
  771. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  772. ASSERT_TRUE(res);
  773. EXPECT_EQ(200, res->status);
  774. }
  775. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  776. SSLClient cli("nghttp2.org");
  777. cli.set_follow_location(true);
  778. Params params;
  779. params.emplace("url", "http://www.google.com");
  780. params.emplace("status_code", "302");
  781. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  782. ASSERT_TRUE(res);
  783. EXPECT_EQ(200, res->status);
  784. }
  785. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  786. SSLClient cli("nghttp2.org");
  787. cli.set_follow_location(true);
  788. Params params;
  789. params.emplace("url", "http://www.google.com");
  790. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  791. ASSERT_TRUE(res);
  792. EXPECT_EQ(200, res->status);
  793. }
  794. TEST(UrlWithSpace, Redirect_Online) {
  795. SSLClient cli("edge.forgecdn.net");
  796. cli.set_follow_location(true);
  797. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  798. ASSERT_TRUE(res);
  799. EXPECT_EQ(200, res->status);
  800. EXPECT_EQ(18527U, res->get_header_value<uint64_t>("Content-Length"));
  801. }
  802. #endif
  803. #if !defined(_WIN32) && !defined(_WIN64)
  804. TEST(ReceiveSignals, Signal) {
  805. auto setupSignalHandlers = []() {
  806. struct sigaction act;
  807. sigemptyset(&act.sa_mask);
  808. act.sa_flags = SA_SIGINFO;
  809. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  810. switch (sig) {
  811. case SIGINT:
  812. default: break;
  813. }
  814. };
  815. ::sigaction(SIGINT, &act, nullptr);
  816. };
  817. Server svr;
  818. int port = 0;
  819. auto thread = std::thread([&]() {
  820. setupSignalHandlers();
  821. port = svr.bind_to_any_port("localhost");
  822. svr.listen_after_bind();
  823. });
  824. auto se = detail::scope_exit([&] {
  825. svr.stop();
  826. thread.join();
  827. ASSERT_FALSE(svr.is_running());
  828. });
  829. while (!svr.is_running()) {
  830. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  831. }
  832. ASSERT_TRUE(svr.is_running());
  833. pthread_kill(thread.native_handle(), SIGINT);
  834. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  835. ASSERT_TRUE(svr.is_running());
  836. }
  837. #endif
  838. TEST(RedirectToDifferentPort, Redirect) {
  839. Server svr1;
  840. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  841. res.set_content("Hello World!", "text/plain");
  842. });
  843. int svr1_port = 0;
  844. auto thread1 = std::thread([&]() {
  845. svr1_port = svr1.bind_to_any_port("localhost");
  846. svr1.listen_after_bind();
  847. });
  848. Server svr2;
  849. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  850. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  851. });
  852. int svr2_port = 0;
  853. auto thread2 = std::thread([&]() {
  854. svr2_port = svr2.bind_to_any_port("localhost");
  855. svr2.listen_after_bind();
  856. });
  857. auto se = detail::scope_exit([&] {
  858. svr2.stop();
  859. thread2.join();
  860. svr1.stop();
  861. thread1.join();
  862. ASSERT_FALSE(svr2.is_running());
  863. ASSERT_FALSE(svr1.is_running());
  864. });
  865. while (!svr1.is_running() || !svr2.is_running()) {
  866. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  867. }
  868. // Give GET time to get a few messages.
  869. std::this_thread::sleep_for(std::chrono::seconds(1));
  870. Client cli("localhost", svr2_port);
  871. cli.set_follow_location(true);
  872. auto res = cli.Get("/2");
  873. ASSERT_TRUE(res);
  874. EXPECT_EQ(200, res->status);
  875. EXPECT_EQ("Hello World!", res->body);
  876. }
  877. TEST(RedirectFromPageWithContent, Redirect) {
  878. Server svr;
  879. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  880. res.set_content("___", "text/plain");
  881. res.set_redirect("/2");
  882. });
  883. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  884. res.set_content("Hello World!", "text/plain");
  885. });
  886. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  887. auto se = detail::scope_exit([&] {
  888. svr.stop();
  889. th.join();
  890. ASSERT_FALSE(svr.is_running());
  891. });
  892. while (!svr.is_running()) {
  893. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  894. }
  895. // Give GET time to get a few messages.
  896. std::this_thread::sleep_for(std::chrono::seconds(1));
  897. {
  898. Client cli("localhost", PORT);
  899. cli.set_follow_location(true);
  900. std::string body;
  901. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  902. body.append(data, data_length);
  903. return true;
  904. });
  905. ASSERT_TRUE(res);
  906. EXPECT_EQ(200, res->status);
  907. EXPECT_EQ("Hello World!", body);
  908. }
  909. {
  910. Client cli("localhost", PORT);
  911. std::string body;
  912. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  913. body.append(data, data_length);
  914. return true;
  915. });
  916. ASSERT_TRUE(res);
  917. EXPECT_EQ(302, res->status);
  918. EXPECT_EQ("___", body);
  919. }
  920. }
  921. TEST(RedirectFromPageWithContentIP6, Redirect) {
  922. Server svr;
  923. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  924. res.set_content("___", "text/plain");
  925. // res.set_redirect("/2");
  926. res.set_redirect("http://[::1]:1234/2");
  927. });
  928. svr.Get("/2", [&](const Request &req, Response &res) {
  929. auto host_header = req.headers.find("Host");
  930. ASSERT_TRUE(host_header != req.headers.end());
  931. EXPECT_EQ("[::1]:1234", host_header->second);
  932. res.set_content("Hello World!", "text/plain");
  933. });
  934. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  935. auto se = detail::scope_exit([&] {
  936. svr.stop();
  937. th.join();
  938. ASSERT_FALSE(svr.is_running());
  939. });
  940. // When IPV6 support isn't available svr.listen("::1", 1234) never
  941. // actually starts anything, so the condition !svr.is_running() will
  942. // always remain true, and the loop never stops.
  943. // This basically counts how many milliseconds have passed since the
  944. // call to svr.listen(), and if after 5 seconds nothing started yet
  945. // aborts the test.
  946. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  947. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  948. ASSERT_LT(milliseconds, 5000U);
  949. }
  950. // Give GET time to get a few messages.
  951. std::this_thread::sleep_for(std::chrono::seconds(1));
  952. {
  953. Client cli("http://[::1]:1234");
  954. cli.set_follow_location(true);
  955. std::string body;
  956. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  957. body.append(data, data_length);
  958. return true;
  959. });
  960. ASSERT_TRUE(res);
  961. EXPECT_EQ(200, res->status);
  962. EXPECT_EQ("Hello World!", body);
  963. }
  964. {
  965. Client cli("http://[::1]:1234");
  966. std::string body;
  967. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  968. body.append(data, data_length);
  969. return true;
  970. });
  971. ASSERT_TRUE(res);
  972. EXPECT_EQ(302, res->status);
  973. EXPECT_EQ("___", body);
  974. }
  975. }
  976. TEST(PathUrlEncodeTest, PathUrlEncode) {
  977. Server svr;
  978. svr.Get("/foo", [](const Request &req, Response &res) {
  979. auto a = req.params.find("a");
  980. if (a != req.params.end()) {
  981. res.set_content((*a).second, "text/plain");
  982. res.status = 200;
  983. } else {
  984. res.status = 400;
  985. }
  986. });
  987. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. thread.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. // Give GET time to get a few messages.
  994. std::this_thread::sleep_for(std::chrono::seconds(1));
  995. {
  996. Client cli(HOST, PORT);
  997. cli.set_url_encode(false);
  998. auto res = cli.Get("/foo?a=explicitly+encoded");
  999. ASSERT_TRUE(res);
  1000. EXPECT_EQ(200, res->status);
  1001. // This expects it back with a space, as the `+` won't have been
  1002. // url-encoded, and server-side the params get decoded turning `+`
  1003. // into spaces.
  1004. EXPECT_EQ("explicitly encoded", res->body);
  1005. }
  1006. }
  1007. TEST(BindServerTest, DISABLED_BindDualStack) {
  1008. Server svr;
  1009. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1010. res.set_content("Hello World!", "text/plain");
  1011. });
  1012. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1013. auto se = detail::scope_exit([&] {
  1014. svr.stop();
  1015. thread.join();
  1016. ASSERT_FALSE(svr.is_running());
  1017. });
  1018. // Give GET time to get a few messages.
  1019. std::this_thread::sleep_for(std::chrono::seconds(1));
  1020. {
  1021. Client cli("127.0.0.1", PORT);
  1022. auto res = cli.Get("/1");
  1023. ASSERT_TRUE(res);
  1024. EXPECT_EQ(200, res->status);
  1025. EXPECT_EQ("Hello World!", res->body);
  1026. }
  1027. {
  1028. Client cli("::1", PORT);
  1029. auto res = cli.Get("/1");
  1030. ASSERT_TRUE(res);
  1031. EXPECT_EQ(200, res->status);
  1032. EXPECT_EQ("Hello World!", res->body);
  1033. }
  1034. }
  1035. TEST(BindServerTest, BindAndListenSeparately) {
  1036. Server svr;
  1037. int port = svr.bind_to_any_port("0.0.0.0");
  1038. ASSERT_TRUE(svr.is_valid());
  1039. ASSERT_TRUE(port > 0);
  1040. svr.stop();
  1041. }
  1042. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1043. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1045. CLIENT_CA_CERT_DIR);
  1046. int port = svr.bind_to_any_port("0.0.0.0");
  1047. ASSERT_TRUE(svr.is_valid());
  1048. ASSERT_TRUE(port > 0);
  1049. svr.stop();
  1050. }
  1051. #endif
  1052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1053. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1054. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1055. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1056. int port = svr.bind_to_any_port("0.0.0.0");
  1057. ASSERT_TRUE(svr.is_valid());
  1058. ASSERT_TRUE(port > 0);
  1059. svr.stop();
  1060. }
  1061. #endif
  1062. TEST(ErrorHandlerTest, ContentLength) {
  1063. Server svr;
  1064. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1065. res.status = 200;
  1066. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1067. "text/html"); // <= Content-Length still 13
  1068. });
  1069. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1070. res.set_content("Hello World!\n", "text/plain");
  1071. res.status = 524;
  1072. });
  1073. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1074. auto se = detail::scope_exit([&] {
  1075. svr.stop();
  1076. thread.join();
  1077. ASSERT_FALSE(svr.is_running());
  1078. });
  1079. // Give GET time to get a few messages.
  1080. std::this_thread::sleep_for(std::chrono::seconds(1));
  1081. {
  1082. Client cli(HOST, PORT);
  1083. auto res = cli.Get("/hi");
  1084. ASSERT_TRUE(res);
  1085. EXPECT_EQ(200, res->status);
  1086. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1087. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1088. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1089. }
  1090. }
  1091. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1092. TEST(ExceptionHandlerTest, ContentLength) {
  1093. Server svr;
  1094. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1095. std::exception_ptr ep) {
  1096. EXPECT_FALSE(ep == nullptr);
  1097. try {
  1098. std::rethrow_exception(ep);
  1099. } catch (std::exception &e) { EXPECT_EQ("abc", std::string(e.what())); }
  1100. res.status = 500;
  1101. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1102. "text/html"); // <= Content-Length still 13 at this point
  1103. });
  1104. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1105. res.set_content("Hello World!\n", "text/plain");
  1106. throw std::runtime_error("abc");
  1107. });
  1108. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1109. auto se = detail::scope_exit([&] {
  1110. svr.stop();
  1111. thread.join();
  1112. ASSERT_FALSE(svr.is_running());
  1113. });
  1114. // Give GET time to get a few messages.
  1115. std::this_thread::sleep_for(std::chrono::seconds(1));
  1116. for (size_t i = 0; i < 10; i++) {
  1117. Client cli(HOST, PORT);
  1118. for (size_t j = 0; j < 100; j++) {
  1119. auto res = cli.Get("/hi");
  1120. ASSERT_TRUE(res);
  1121. EXPECT_EQ(500, res->status);
  1122. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1123. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1124. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1125. }
  1126. cli.set_keep_alive(true);
  1127. for (size_t j = 0; j < 100; j++) {
  1128. auto res = cli.Get("/hi");
  1129. ASSERT_TRUE(res);
  1130. EXPECT_EQ(500, res->status);
  1131. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1132. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1133. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1134. }
  1135. }
  1136. }
  1137. #endif
  1138. TEST(NoContentTest, ContentLength) {
  1139. Server svr;
  1140. svr.Get("/hi",
  1141. [](const Request & /*req*/, Response &res) { res.status = 204; });
  1142. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1143. auto se = detail::scope_exit([&] {
  1144. svr.stop();
  1145. thread.join();
  1146. ASSERT_FALSE(svr.is_running());
  1147. });
  1148. // Give GET time to get a few messages.
  1149. std::this_thread::sleep_for(std::chrono::seconds(1));
  1150. {
  1151. Client cli(HOST, PORT);
  1152. auto res = cli.Get("/hi");
  1153. ASSERT_TRUE(res);
  1154. EXPECT_EQ(204, res->status);
  1155. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1156. }
  1157. }
  1158. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1159. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1160. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  1161. ASSERT_TRUE(svr.is_valid());
  1162. #else
  1163. Server svr;
  1164. #endif
  1165. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1166. if (req.path == "/routing_handler") {
  1167. res.set_header("PRE_ROUTING", "on");
  1168. res.set_content("Routing Handler", "text/plain");
  1169. return httplib::Server::HandlerResponse::Handled;
  1170. }
  1171. return httplib::Server::HandlerResponse::Unhandled;
  1172. });
  1173. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1174. res.set_content("Error", "text/html");
  1175. });
  1176. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1177. if (req.path == "/routing_handler") {
  1178. res.set_header("POST_ROUTING", "on");
  1179. }
  1180. });
  1181. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1182. res.set_content("Hello World!\n", "text/plain");
  1183. });
  1184. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1185. auto se = detail::scope_exit([&] {
  1186. svr.stop();
  1187. thread.join();
  1188. ASSERT_FALSE(svr.is_running());
  1189. });
  1190. // Give GET time to get a few messages.
  1191. std::this_thread::sleep_for(std::chrono::seconds(1));
  1192. {
  1193. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1194. SSLClient cli(HOST, PORT);
  1195. cli.enable_server_certificate_verification(false);
  1196. #else
  1197. Client cli(HOST, PORT);
  1198. #endif
  1199. auto res = cli.Get("/routing_handler");
  1200. ASSERT_TRUE(res);
  1201. EXPECT_EQ(200, res->status);
  1202. EXPECT_EQ("Routing Handler", res->body);
  1203. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1204. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1205. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1206. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1207. }
  1208. {
  1209. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1210. SSLClient cli(HOST, PORT);
  1211. cli.enable_server_certificate_verification(false);
  1212. #else
  1213. Client cli(HOST, PORT);
  1214. #endif
  1215. auto res = cli.Get("/hi");
  1216. ASSERT_TRUE(res);
  1217. EXPECT_EQ(200, res->status);
  1218. EXPECT_EQ("Hello World!\n", res->body);
  1219. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1220. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1221. }
  1222. {
  1223. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1224. SSLClient cli(HOST, PORT);
  1225. cli.enable_server_certificate_verification(false);
  1226. #else
  1227. Client cli(HOST, PORT);
  1228. #endif
  1229. auto res = cli.Get("/aaa");
  1230. ASSERT_TRUE(res);
  1231. EXPECT_EQ(404, res->status);
  1232. EXPECT_EQ("Error", res->body);
  1233. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1234. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1235. }
  1236. }
  1237. TEST(InvalidFormatTest, StatusCode) {
  1238. Server svr;
  1239. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1240. res.set_content("Hello World!\n", "text/plain");
  1241. res.status = 9999; // Status should be a three-digit code...
  1242. });
  1243. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1244. auto se = detail::scope_exit([&] {
  1245. svr.stop();
  1246. thread.join();
  1247. ASSERT_FALSE(svr.is_running());
  1248. });
  1249. // Give GET time to get a few messages.
  1250. std::this_thread::sleep_for(std::chrono::seconds(1));
  1251. {
  1252. Client cli(HOST, PORT);
  1253. auto res = cli.Get("/hi");
  1254. ASSERT_FALSE(res);
  1255. }
  1256. }
  1257. TEST(URLFragmentTest, WithFragment) {
  1258. Server svr;
  1259. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1260. EXPECT_TRUE(req.target == "/hi");
  1261. });
  1262. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1263. auto se = detail::scope_exit([&] {
  1264. svr.stop();
  1265. thread.join();
  1266. ASSERT_FALSE(svr.is_running());
  1267. });
  1268. std::this_thread::sleep_for(std::chrono::seconds(1));
  1269. {
  1270. Client cli(HOST, PORT);
  1271. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1272. EXPECT_TRUE(res);
  1273. EXPECT_EQ(200, res->status);
  1274. res = cli.Get("/hi%23key1=val1=key2=val2");
  1275. EXPECT_TRUE(res);
  1276. EXPECT_EQ(404, res->status);
  1277. }
  1278. }
  1279. class ServerTest : public ::testing::Test {
  1280. protected:
  1281. ServerTest()
  1282. : cli_(HOST, PORT)
  1283. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1284. ,
  1285. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1286. #endif
  1287. {
  1288. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1289. cli_.enable_server_certificate_verification(false);
  1290. #endif
  1291. }
  1292. virtual void SetUp() {
  1293. svr_.set_mount_point("/", "./www");
  1294. svr_.set_mount_point("/mount", "./www2");
  1295. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1296. svr_.Get("/hi",
  1297. [&](const Request & /*req*/, Response &res) {
  1298. res.set_content("Hello World!", "text/plain");
  1299. })
  1300. .Get("/http_response_splitting",
  1301. [&](const Request & /*req*/, Response &res) {
  1302. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1303. EXPECT_EQ(0U, res.headers.size());
  1304. EXPECT_FALSE(res.has_header("a"));
  1305. res.set_header("a", "1\nSet-Cookie: a=1");
  1306. EXPECT_EQ(0U, res.headers.size());
  1307. EXPECT_FALSE(res.has_header("a"));
  1308. res.set_header("a", "1\rSet-Cookie: a=1");
  1309. EXPECT_EQ(0U, res.headers.size());
  1310. EXPECT_FALSE(res.has_header("a"));
  1311. res.set_header("a\r\nb", "0");
  1312. EXPECT_EQ(0U, res.headers.size());
  1313. EXPECT_FALSE(res.has_header("a"));
  1314. res.set_header("a\rb", "0");
  1315. EXPECT_EQ(0U, res.headers.size());
  1316. EXPECT_FALSE(res.has_header("a"));
  1317. res.set_header("a\nb", "0");
  1318. EXPECT_EQ(0U, res.headers.size());
  1319. EXPECT_FALSE(res.has_header("a"));
  1320. res.set_redirect("1\r\nSet-Cookie: a=1");
  1321. EXPECT_EQ(0U, res.headers.size());
  1322. EXPECT_FALSE(res.has_header("Location"));
  1323. })
  1324. .Get("/slow",
  1325. [&](const Request & /*req*/, Response &res) {
  1326. std::this_thread::sleep_for(std::chrono::seconds(2));
  1327. res.set_content("slow", "text/plain");
  1328. })
  1329. #if 0
  1330. .Post("/slowpost",
  1331. [&](const Request & /*req*/, Response &res) {
  1332. std::this_thread::sleep_for(std::chrono::seconds(2));
  1333. res.set_content("slow", "text/plain");
  1334. })
  1335. #endif
  1336. .Get("/remote_addr",
  1337. [&](const Request &req, Response &res) {
  1338. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1339. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1340. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1341. EXPECT_EQ(req.remote_port,
  1342. std::stoi(req.get_header_value("REMOTE_PORT")));
  1343. res.set_content(remote_addr.c_str(), "text/plain");
  1344. })
  1345. .Get("/local_addr",
  1346. [&](const Request &req, Response &res) {
  1347. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  1348. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  1349. auto local_addr = req.get_header_value("LOCAL_ADDR");
  1350. auto local_port = req.get_header_value("LOCAL_PORT");
  1351. EXPECT_EQ(req.local_addr, local_addr);
  1352. EXPECT_EQ(req.local_port, std::stoi(local_port));
  1353. res.set_content(local_addr.append(":").append(local_port),
  1354. "text/plain");
  1355. })
  1356. .Get("/endwith%",
  1357. [&](const Request & /*req*/, Response &res) {
  1358. res.set_content("Hello World!", "text/plain");
  1359. })
  1360. .Get("/a\\+\\+b",
  1361. [&](const Request &req, Response &res) {
  1362. ASSERT_TRUE(req.has_param("a +b"));
  1363. auto val = req.get_param_value("a +b");
  1364. res.set_content(val, "text/plain");
  1365. })
  1366. .Get("/", [&](const Request & /*req*/,
  1367. Response &res) { res.set_redirect("/hi"); })
  1368. .Post("/1", [](const Request & /*req*/,
  1369. Response &res) { res.set_redirect("/2", 303); })
  1370. .Get("/2",
  1371. [](const Request & /*req*/, Response &res) {
  1372. res.set_content("redirected.", "text/plain");
  1373. res.status = 200;
  1374. })
  1375. .Post("/person",
  1376. [&](const Request &req, Response &res) {
  1377. if (req.has_param("name") && req.has_param("note")) {
  1378. persons_[req.get_param_value("name")] =
  1379. req.get_param_value("note");
  1380. } else {
  1381. res.status = 400;
  1382. }
  1383. })
  1384. .Put("/person",
  1385. [&](const Request &req, Response &res) {
  1386. if (req.has_param("name") && req.has_param("note")) {
  1387. persons_[req.get_param_value("name")] =
  1388. req.get_param_value("note");
  1389. } else {
  1390. res.status = 400;
  1391. }
  1392. })
  1393. .Get("/person/(.*)",
  1394. [&](const Request &req, Response &res) {
  1395. string name = req.matches[1];
  1396. if (persons_.find(name) != persons_.end()) {
  1397. auto note = persons_[name];
  1398. res.set_content(note, "text/plain");
  1399. } else {
  1400. res.status = 404;
  1401. }
  1402. })
  1403. .Post("/x-www-form-urlencoded-json",
  1404. [&](const Request &req, Response &res) {
  1405. auto json = req.get_param_value("json");
  1406. ASSERT_EQ(JSON_DATA, json);
  1407. res.set_content(json, "appliation/json");
  1408. res.status = 200;
  1409. })
  1410. .Get("/streamed-chunked",
  1411. [&](const Request & /*req*/, Response &res) {
  1412. res.set_chunked_content_provider(
  1413. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1414. sink.os << "123";
  1415. sink.os << "456";
  1416. sink.os << "789";
  1417. sink.done();
  1418. return true;
  1419. });
  1420. })
  1421. .Get("/streamed-chunked2",
  1422. [&](const Request & /*req*/, Response &res) {
  1423. auto i = new int(0);
  1424. res.set_chunked_content_provider(
  1425. "text/plain",
  1426. [i](size_t /*offset*/, DataSink &sink) {
  1427. switch (*i) {
  1428. case 0: sink.os << "123"; break;
  1429. case 1: sink.os << "456"; break;
  1430. case 2: sink.os << "789"; break;
  1431. case 3: sink.done(); break;
  1432. }
  1433. (*i)++;
  1434. return true;
  1435. },
  1436. [i](bool success) {
  1437. EXPECT_TRUE(success);
  1438. delete i;
  1439. });
  1440. })
  1441. .Get("/streamed-chunked-with-trailer",
  1442. [&](const Request & /*req*/, Response &res) {
  1443. auto i = new int(0);
  1444. res.set_header("Trailer", "Dummy1, Dummy2");
  1445. res.set_chunked_content_provider(
  1446. "text/plain",
  1447. [i](size_t /*offset*/, DataSink &sink) {
  1448. switch (*i) {
  1449. case 0: sink.os << "123"; break;
  1450. case 1: sink.os << "456"; break;
  1451. case 2: sink.os << "789"; break;
  1452. case 3: {
  1453. sink.done_with_trailer(
  1454. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  1455. } break;
  1456. }
  1457. (*i)++;
  1458. return true;
  1459. },
  1460. [i](bool success) {
  1461. EXPECT_TRUE(success);
  1462. delete i;
  1463. });
  1464. })
  1465. .Get("/streamed",
  1466. [&](const Request & /*req*/, Response &res) {
  1467. res.set_content_provider(
  1468. 6, "text/plain",
  1469. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1470. sink.os << (offset < 3 ? "a" : "b");
  1471. return true;
  1472. });
  1473. })
  1474. .Get("/streamed-with-range",
  1475. [&](const Request & /*req*/, Response &res) {
  1476. auto data = new std::string("abcdefg");
  1477. res.set_content_provider(
  1478. data->size(), "text/plain",
  1479. [data](size_t offset, size_t length, DataSink &sink) {
  1480. size_t DATA_CHUNK_SIZE = 4;
  1481. const auto &d = *data;
  1482. auto out_len =
  1483. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1484. auto ret =
  1485. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1486. EXPECT_TRUE(ret);
  1487. return true;
  1488. },
  1489. [data](bool success) {
  1490. EXPECT_TRUE(success);
  1491. delete data;
  1492. });
  1493. })
  1494. .Get("/streamed-cancel",
  1495. [&](const Request & /*req*/, Response &res) {
  1496. res.set_content_provider(
  1497. size_t(-1), "text/plain",
  1498. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1499. sink.os << "data_chunk";
  1500. return true;
  1501. });
  1502. })
  1503. .Get("/with-range",
  1504. [&](const Request & /*req*/, Response &res) {
  1505. res.set_content("abcdefg", "text/plain");
  1506. })
  1507. .Post("/chunked",
  1508. [&](const Request &req, Response & /*res*/) {
  1509. EXPECT_EQ(req.body, "dechunked post body");
  1510. })
  1511. .Post("/large-chunked",
  1512. [&](const Request &req, Response & /*res*/) {
  1513. std::string expected(6 * 30 * 1024u, 'a');
  1514. EXPECT_EQ(req.body, expected);
  1515. })
  1516. .Post("/multipart",
  1517. [&](const Request &req, Response & /*res*/) {
  1518. EXPECT_EQ(6u, req.files.size());
  1519. ASSERT_TRUE(!req.has_file("???"));
  1520. ASSERT_TRUE(req.body.empty());
  1521. {
  1522. const auto &file = req.get_file_value("text1");
  1523. EXPECT_TRUE(file.filename.empty());
  1524. EXPECT_EQ("text default", file.content);
  1525. }
  1526. {
  1527. const auto &file = req.get_file_value("text2");
  1528. EXPECT_TRUE(file.filename.empty());
  1529. EXPECT_EQ("aωb", file.content);
  1530. }
  1531. {
  1532. const auto &file = req.get_file_value("file1");
  1533. EXPECT_EQ("hello.txt", file.filename);
  1534. EXPECT_EQ("text/plain", file.content_type);
  1535. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1536. }
  1537. {
  1538. const auto &file = req.get_file_value("file3");
  1539. EXPECT_TRUE(file.filename.empty());
  1540. EXPECT_EQ("application/octet-stream", file.content_type);
  1541. EXPECT_EQ(0u, file.content.size());
  1542. }
  1543. {
  1544. const auto &file = req.get_file_value("file4");
  1545. EXPECT_TRUE(file.filename.empty());
  1546. EXPECT_EQ(0u, file.content.size());
  1547. EXPECT_EQ("application/json tmp-string", file.content_type);
  1548. }
  1549. })
  1550. .Post("/multipart/multi_file_values",
  1551. [&](const Request &req, Response & /*res*/) {
  1552. EXPECT_EQ(5u, req.files.size());
  1553. ASSERT_TRUE(!req.has_file("???"));
  1554. ASSERT_TRUE(req.body.empty());
  1555. {
  1556. const auto &text_value = req.get_file_values("text");
  1557. EXPECT_EQ(text_value.size(), 1);
  1558. auto &text = text_value[0];
  1559. EXPECT_TRUE(text.filename.empty());
  1560. EXPECT_EQ("default text", text.content);
  1561. }
  1562. {
  1563. const auto &text1_values = req.get_file_values("multi_text1");
  1564. EXPECT_EQ(text1_values.size(), 2);
  1565. EXPECT_EQ("aaaaa", text1_values[0].content);
  1566. EXPECT_EQ("bbbbb", text1_values[1].content);
  1567. }
  1568. {
  1569. const auto &file1_values = req.get_file_values("multi_file1");
  1570. EXPECT_EQ(file1_values.size(), 2);
  1571. auto file1 = file1_values[0];
  1572. EXPECT_EQ(file1.filename, "hello.txt");
  1573. EXPECT_EQ(file1.content_type, "text/plain");
  1574. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  1575. auto file2 = file1_values[1];
  1576. EXPECT_EQ(file2.filename, "world.json");
  1577. EXPECT_EQ(file2.content_type, "application/json");
  1578. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  1579. }
  1580. })
  1581. .Post("/empty",
  1582. [&](const Request &req, Response &res) {
  1583. EXPECT_EQ(req.body, "");
  1584. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1585. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1586. res.set_content("empty", "text/plain");
  1587. })
  1588. .Post("/empty-no-content-type",
  1589. [&](const Request &req, Response &res) {
  1590. EXPECT_EQ(req.body, "");
  1591. EXPECT_FALSE(req.has_header("Content-Type"));
  1592. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1593. res.set_content("empty-no-content-type", "text/plain");
  1594. })
  1595. .Post("/path-only",
  1596. [&](const Request &req, Response &res) {
  1597. EXPECT_EQ(req.body, "");
  1598. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1599. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1600. res.set_content("path-only", "text/plain");
  1601. })
  1602. .Post("/path-headers-only",
  1603. [&](const Request &req, Response &res) {
  1604. EXPECT_EQ(req.body, "");
  1605. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1606. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1607. EXPECT_EQ("world", req.get_header_value("hello"));
  1608. EXPECT_EQ("world2", req.get_header_value("hello2"));
  1609. res.set_content("path-headers-only", "text/plain");
  1610. })
  1611. .Post("/post-large",
  1612. [&](const Request &req, Response &res) {
  1613. EXPECT_EQ(req.body, LARGE_DATA);
  1614. res.set_content(req.body, "text/plain");
  1615. })
  1616. .Put("/empty-no-content-type",
  1617. [&](const Request &req, Response &res) {
  1618. EXPECT_EQ(req.body, "");
  1619. EXPECT_FALSE(req.has_header("Content-Type"));
  1620. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1621. res.set_content("empty-no-content-type", "text/plain");
  1622. })
  1623. .Put("/put",
  1624. [&](const Request &req, Response &res) {
  1625. EXPECT_EQ(req.body, "PUT");
  1626. res.set_content(req.body, "text/plain");
  1627. })
  1628. .Put("/put-large",
  1629. [&](const Request &req, Response &res) {
  1630. EXPECT_EQ(req.body, LARGE_DATA);
  1631. res.set_content(req.body, "text/plain");
  1632. })
  1633. .Patch("/patch",
  1634. [&](const Request &req, Response &res) {
  1635. EXPECT_EQ(req.body, "PATCH");
  1636. res.set_content(req.body, "text/plain");
  1637. })
  1638. .Delete("/delete",
  1639. [&](const Request & /*req*/, Response &res) {
  1640. res.set_content("DELETE", "text/plain");
  1641. })
  1642. .Delete("/delete-body",
  1643. [&](const Request &req, Response &res) {
  1644. EXPECT_EQ(req.body, "content");
  1645. res.set_content(req.body, "text/plain");
  1646. })
  1647. .Options(R"(\*)",
  1648. [&](const Request & /*req*/, Response &res) {
  1649. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1650. })
  1651. .Get("/request-target",
  1652. [&](const Request &req, Response & /*res*/) {
  1653. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1654. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1655. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1656. })
  1657. .Get("/long-query-value",
  1658. [&](const Request &req, Response & /*res*/) {
  1659. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1660. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1661. })
  1662. .Get("/array-param",
  1663. [&](const Request &req, Response & /*res*/) {
  1664. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1665. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1666. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1667. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1668. })
  1669. .Post("/validate-no-multiple-headers",
  1670. [&](const Request &req, Response & /*res*/) {
  1671. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1672. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1673. })
  1674. .Post("/content_receiver",
  1675. [&](const Request &req, Response &res,
  1676. const ContentReader &content_reader) {
  1677. if (req.is_multipart_form_data()) {
  1678. MultipartFormDataItems files;
  1679. content_reader(
  1680. [&](const MultipartFormData &file) {
  1681. files.push_back(file);
  1682. return true;
  1683. },
  1684. [&](const char *data, size_t data_length) {
  1685. files.back().content.append(data, data_length);
  1686. return true;
  1687. });
  1688. EXPECT_EQ(5u, files.size());
  1689. {
  1690. const auto &file = get_file_value(files, "text1");
  1691. EXPECT_TRUE(file.filename.empty());
  1692. EXPECT_EQ("text default", file.content);
  1693. }
  1694. {
  1695. const auto &file = get_file_value(files, "text2");
  1696. EXPECT_TRUE(file.filename.empty());
  1697. EXPECT_EQ("aωb", file.content);
  1698. }
  1699. {
  1700. const auto &file = get_file_value(files, "file1");
  1701. EXPECT_EQ("hello.txt", file.filename);
  1702. EXPECT_EQ("text/plain", file.content_type);
  1703. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1704. }
  1705. {
  1706. const auto &file = get_file_value(files, "file3");
  1707. EXPECT_TRUE(file.filename.empty());
  1708. EXPECT_EQ("application/octet-stream", file.content_type);
  1709. EXPECT_EQ(0u, file.content.size());
  1710. }
  1711. } else {
  1712. std::string body;
  1713. content_reader([&](const char *data, size_t data_length) {
  1714. EXPECT_EQ(7U, data_length);
  1715. body.append(data, data_length);
  1716. return true;
  1717. });
  1718. EXPECT_EQ(body, "content");
  1719. res.set_content(body, "text/plain");
  1720. }
  1721. })
  1722. .Put("/content_receiver",
  1723. [&](const Request & /*req*/, Response &res,
  1724. const ContentReader &content_reader) {
  1725. std::string body;
  1726. content_reader([&](const char *data, size_t data_length) {
  1727. body.append(data, data_length);
  1728. return true;
  1729. });
  1730. EXPECT_EQ(body, "content");
  1731. res.set_content(body, "text/plain");
  1732. })
  1733. .Patch("/content_receiver",
  1734. [&](const Request & /*req*/, Response &res,
  1735. const ContentReader &content_reader) {
  1736. std::string body;
  1737. content_reader([&](const char *data, size_t data_length) {
  1738. body.append(data, data_length);
  1739. return true;
  1740. });
  1741. EXPECT_EQ(body, "content");
  1742. res.set_content(body, "text/plain");
  1743. })
  1744. .Post("/query-string-and-body",
  1745. [&](const Request &req, Response & /*res*/) {
  1746. ASSERT_TRUE(req.has_param("key"));
  1747. EXPECT_EQ(req.get_param_value("key"), "value");
  1748. EXPECT_EQ(req.body, "content");
  1749. })
  1750. .Get("/last-request",
  1751. [&](const Request &req, Response & /*res*/) {
  1752. EXPECT_EQ("close", req.get_header_value("Connection"));
  1753. })
  1754. .Get(R"(/redirect/(\d+))",
  1755. [&](const Request &req, Response &res) {
  1756. auto num = std::stoi(req.matches[1]) + 1;
  1757. std::string url = "/redirect/" + std::to_string(num);
  1758. res.set_redirect(url);
  1759. })
  1760. .Post("/binary",
  1761. [&](const Request &req, Response &res) {
  1762. EXPECT_EQ(4U, req.body.size());
  1763. EXPECT_EQ("application/octet-stream",
  1764. req.get_header_value("Content-Type"));
  1765. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1766. res.set_content(req.body, "application/octet-stream");
  1767. })
  1768. .Put("/binary",
  1769. [&](const Request &req, Response &res) {
  1770. EXPECT_EQ(4U, req.body.size());
  1771. EXPECT_EQ("application/octet-stream",
  1772. req.get_header_value("Content-Type"));
  1773. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1774. res.set_content(req.body, "application/octet-stream");
  1775. })
  1776. .Patch("/binary",
  1777. [&](const Request &req, Response &res) {
  1778. EXPECT_EQ(4U, req.body.size());
  1779. EXPECT_EQ("application/octet-stream",
  1780. req.get_header_value("Content-Type"));
  1781. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1782. res.set_content(req.body, "application/octet-stream");
  1783. })
  1784. .Delete("/binary",
  1785. [&](const Request &req, Response &res) {
  1786. EXPECT_EQ(4U, req.body.size());
  1787. EXPECT_EQ("application/octet-stream",
  1788. req.get_header_value("Content-Type"));
  1789. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1790. res.set_content(req.body, "application/octet-stream");
  1791. })
  1792. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1793. .Get("/compress",
  1794. [&](const Request & /*req*/, Response &res) {
  1795. res.set_content(
  1796. "12345678901234567890123456789012345678901234567890123456789"
  1797. "01234567890123456789012345678901234567890",
  1798. "text/plain");
  1799. })
  1800. .Get("/nocompress",
  1801. [&](const Request & /*req*/, Response &res) {
  1802. res.set_content(
  1803. "12345678901234567890123456789012345678901234567890123456789"
  1804. "01234567890123456789012345678901234567890",
  1805. "application/octet-stream");
  1806. })
  1807. .Post("/compress-multipart",
  1808. [&](const Request &req, Response & /*res*/) {
  1809. EXPECT_EQ(2u, req.files.size());
  1810. ASSERT_TRUE(!req.has_file("???"));
  1811. {
  1812. const auto &file = req.get_file_value("key1");
  1813. EXPECT_TRUE(file.filename.empty());
  1814. EXPECT_EQ("test", file.content);
  1815. }
  1816. {
  1817. const auto &file = req.get_file_value("key2");
  1818. EXPECT_TRUE(file.filename.empty());
  1819. EXPECT_EQ("--abcdefg123", file.content);
  1820. }
  1821. })
  1822. #endif
  1823. ;
  1824. persons_["john"] = "programmer";
  1825. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1826. while (!svr_.is_running()) {
  1827. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1828. }
  1829. }
  1830. virtual void TearDown() {
  1831. svr_.stop();
  1832. if (!request_threads_.empty()) {
  1833. std::this_thread::sleep_for(std::chrono::seconds(1));
  1834. for (auto &t : request_threads_) {
  1835. t.join();
  1836. }
  1837. }
  1838. t_.join();
  1839. }
  1840. map<string, string> persons_;
  1841. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1842. SSLClient cli_;
  1843. SSLServer svr_;
  1844. #else
  1845. Client cli_;
  1846. Server svr_;
  1847. #endif
  1848. thread t_;
  1849. std::vector<thread> request_threads_;
  1850. };
  1851. TEST_F(ServerTest, GetMethod200) {
  1852. auto res = cli_.Get("/hi");
  1853. ASSERT_TRUE(res);
  1854. EXPECT_EQ("HTTP/1.1", res->version);
  1855. EXPECT_EQ(200, res->status);
  1856. EXPECT_EQ("OK", res->reason);
  1857. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1858. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1859. EXPECT_EQ("Hello World!", res->body);
  1860. }
  1861. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1862. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1863. ASSERT_TRUE(res);
  1864. EXPECT_EQ("HTTP/1.1", res->version);
  1865. EXPECT_EQ(200, res->status);
  1866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1867. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1868. EXPECT_EQ("Hello World!", res->body);
  1869. }
  1870. TEST_F(ServerTest, GetMethod302) {
  1871. auto res = cli_.Get("/");
  1872. ASSERT_TRUE(res);
  1873. EXPECT_EQ(302, res->status);
  1874. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1875. }
  1876. TEST_F(ServerTest, GetMethod302Redirect) {
  1877. cli_.set_follow_location(true);
  1878. auto res = cli_.Get("/");
  1879. ASSERT_TRUE(res);
  1880. EXPECT_EQ(200, res->status);
  1881. EXPECT_EQ("Hello World!", res->body);
  1882. EXPECT_EQ("/hi", res->location);
  1883. }
  1884. TEST_F(ServerTest, GetMethod404) {
  1885. auto res = cli_.Get("/invalid");
  1886. ASSERT_TRUE(res);
  1887. EXPECT_EQ(404, res->status);
  1888. }
  1889. TEST_F(ServerTest, HeadMethod200) {
  1890. auto res = cli_.Head("/hi");
  1891. ASSERT_TRUE(res);
  1892. EXPECT_EQ(200, res->status);
  1893. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1894. EXPECT_TRUE(res->body.empty());
  1895. }
  1896. TEST_F(ServerTest, HeadMethod200Static) {
  1897. auto res = cli_.Head("/mount/dir/index.html");
  1898. ASSERT_TRUE(res);
  1899. EXPECT_EQ(200, res->status);
  1900. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1901. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1902. EXPECT_TRUE(res->body.empty());
  1903. }
  1904. TEST_F(ServerTest, HeadMethod404) {
  1905. auto res = cli_.Head("/invalid");
  1906. ASSERT_TRUE(res);
  1907. EXPECT_EQ(404, res->status);
  1908. EXPECT_TRUE(res->body.empty());
  1909. }
  1910. TEST_F(ServerTest, GetMethodPersonJohn) {
  1911. auto res = cli_.Get("/person/john");
  1912. ASSERT_TRUE(res);
  1913. EXPECT_EQ(200, res->status);
  1914. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1915. EXPECT_EQ("programmer", res->body);
  1916. }
  1917. TEST_F(ServerTest, PostMethod1) {
  1918. auto res = cli_.Get("/person/john1");
  1919. ASSERT_TRUE(res);
  1920. ASSERT_EQ(404, res->status);
  1921. res = cli_.Post("/person", "name=john1&note=coder",
  1922. "application/x-www-form-urlencoded");
  1923. ASSERT_TRUE(res);
  1924. ASSERT_EQ(200, res->status);
  1925. res = cli_.Get("/person/john1");
  1926. ASSERT_TRUE(res);
  1927. ASSERT_EQ(200, res->status);
  1928. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1929. ASSERT_EQ("coder", res->body);
  1930. }
  1931. TEST_F(ServerTest, PostMethod2) {
  1932. auto res = cli_.Get("/person/john2");
  1933. ASSERT_TRUE(res);
  1934. ASSERT_EQ(404, res->status);
  1935. Params params;
  1936. params.emplace("name", "john2");
  1937. params.emplace("note", "coder");
  1938. res = cli_.Post("/person", params);
  1939. ASSERT_TRUE(res);
  1940. ASSERT_EQ(200, res->status);
  1941. res = cli_.Get("/person/john2");
  1942. ASSERT_TRUE(res);
  1943. ASSERT_EQ(200, res->status);
  1944. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1945. ASSERT_EQ("coder", res->body);
  1946. }
  1947. TEST_F(ServerTest, PutMethod3) {
  1948. auto res = cli_.Get("/person/john3");
  1949. ASSERT_TRUE(res);
  1950. ASSERT_EQ(404, res->status);
  1951. Params params;
  1952. params.emplace("name", "john3");
  1953. params.emplace("note", "coder");
  1954. res = cli_.Put("/person", params);
  1955. ASSERT_TRUE(res);
  1956. ASSERT_EQ(200, res->status);
  1957. res = cli_.Get("/person/john3");
  1958. ASSERT_TRUE(res);
  1959. ASSERT_EQ(200, res->status);
  1960. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1961. ASSERT_EQ("coder", res->body);
  1962. }
  1963. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1964. Params params;
  1965. params.emplace("json", JSON_DATA);
  1966. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1967. ASSERT_TRUE(res);
  1968. ASSERT_EQ(200, res->status);
  1969. ASSERT_EQ(JSON_DATA, res->body);
  1970. }
  1971. TEST_F(ServerTest, PostEmptyContent) {
  1972. auto res = cli_.Post("/empty", "", "text/plain");
  1973. ASSERT_TRUE(res);
  1974. ASSERT_EQ(200, res->status);
  1975. ASSERT_EQ("empty", res->body);
  1976. }
  1977. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1978. auto res = cli_.Post("/empty-no-content-type");
  1979. ASSERT_TRUE(res);
  1980. ASSERT_EQ(200, res->status);
  1981. ASSERT_EQ("empty-no-content-type", res->body);
  1982. }
  1983. TEST_F(ServerTest, PostPathOnly) {
  1984. auto res = cli_.Post("/path-only");
  1985. ASSERT_TRUE(res);
  1986. ASSERT_EQ(200, res->status);
  1987. ASSERT_EQ("path-only", res->body);
  1988. }
  1989. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  1990. auto res = cli_.Post("/path-headers-only",
  1991. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  1992. ASSERT_TRUE(res);
  1993. ASSERT_EQ(200, res->status);
  1994. ASSERT_EQ("path-headers-only", res->body);
  1995. }
  1996. TEST_F(ServerTest, PostLarge) {
  1997. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  1998. ASSERT_TRUE(res);
  1999. ASSERT_EQ(200, res->status);
  2000. EXPECT_EQ(LARGE_DATA, res->body);
  2001. }
  2002. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2003. auto res = cli_.Put("/empty-no-content-type");
  2004. ASSERT_TRUE(res);
  2005. ASSERT_EQ(200, res->status);
  2006. ASSERT_EQ("empty-no-content-type", res->body);
  2007. }
  2008. TEST_F(ServerTest, GetMethodDir) {
  2009. auto res = cli_.Get("/dir/");
  2010. ASSERT_TRUE(res);
  2011. EXPECT_EQ(200, res->status);
  2012. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2013. auto body = R"(<html>
  2014. <head>
  2015. </head>
  2016. <body>
  2017. <a href="/dir/test.html">Test</a>
  2018. <a href="/hi">hi</a>
  2019. </body>
  2020. </html>
  2021. )";
  2022. EXPECT_EQ(body, res->body);
  2023. }
  2024. TEST_F(ServerTest, GetMethodDirTest) {
  2025. auto res = cli_.Get("/dir/test.html");
  2026. ASSERT_TRUE(res);
  2027. EXPECT_EQ(200, res->status);
  2028. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2029. EXPECT_EQ("test.html", res->body);
  2030. }
  2031. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2032. auto res = cli_.Get("/dir/../dir/test.html");
  2033. ASSERT_TRUE(res);
  2034. EXPECT_EQ(200, res->status);
  2035. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2036. EXPECT_EQ("test.html", res->body);
  2037. }
  2038. TEST_F(ServerTest, GetMethodInvalidPath) {
  2039. auto res = cli_.Get("/dir/../test.html");
  2040. ASSERT_TRUE(res);
  2041. EXPECT_EQ(404, res->status);
  2042. }
  2043. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2044. auto res = cli_.Get("/../www/dir/test.html");
  2045. ASSERT_TRUE(res);
  2046. EXPECT_EQ(404, res->status);
  2047. }
  2048. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2049. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2050. ASSERT_TRUE(res);
  2051. EXPECT_EQ(404, res->status);
  2052. }
  2053. TEST_F(ServerTest, GetMethodDirMountTest) {
  2054. auto res = cli_.Get("/mount/dir/test.html");
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(200, res->status);
  2057. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2058. EXPECT_EQ("test.html", res->body);
  2059. }
  2060. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2061. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2062. ASSERT_TRUE(res);
  2063. EXPECT_EQ(200, res->status);
  2064. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2065. EXPECT_EQ("test.html", res->body);
  2066. }
  2067. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2068. auto res = cli_.Get("/mount/dir/../test.html");
  2069. ASSERT_TRUE(res);
  2070. EXPECT_EQ(404, res->status);
  2071. }
  2072. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2073. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2074. ASSERT_TRUE(res);
  2075. EXPECT_EQ(404, res->status);
  2076. }
  2077. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2078. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2079. ASSERT_TRUE(res);
  2080. EXPECT_EQ(404, res->status);
  2081. }
  2082. TEST_F(ServerTest, PostMethod303) {
  2083. auto res = cli_.Post("/1", "body", "text/plain");
  2084. ASSERT_TRUE(res);
  2085. EXPECT_EQ(303, res->status);
  2086. EXPECT_EQ("/2", res->get_header_value("Location"));
  2087. }
  2088. TEST_F(ServerTest, PostMethod303Redirect) {
  2089. cli_.set_follow_location(true);
  2090. auto res = cli_.Post("/1", "body", "text/plain");
  2091. ASSERT_TRUE(res);
  2092. EXPECT_EQ(200, res->status);
  2093. EXPECT_EQ("redirected.", res->body);
  2094. EXPECT_EQ("/2", res->location);
  2095. }
  2096. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2097. auto res = cli_.Get("/dir/test.abcde");
  2098. ASSERT_TRUE(res);
  2099. EXPECT_EQ(200, res->status);
  2100. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2101. EXPECT_EQ("abcde", res->body);
  2102. }
  2103. TEST_F(ServerTest, StaticFileRange) {
  2104. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2105. ASSERT_TRUE(res);
  2106. EXPECT_EQ(206, res->status);
  2107. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2108. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2109. EXPECT_EQ(true, res->has_header("Content-Range"));
  2110. EXPECT_EQ(std::string("cd"), res->body);
  2111. }
  2112. TEST_F(ServerTest, InvalidBaseDirMount) {
  2113. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2114. }
  2115. TEST_F(ServerTest, Binary) {
  2116. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2117. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2118. "application/octet-stream");
  2119. ASSERT_TRUE(res);
  2120. ASSERT_EQ(200, res->status);
  2121. ASSERT_EQ(4U, res->body.size());
  2122. res = cli_.Put("/binary", binary.data(), binary.size(),
  2123. "application/octet-stream");
  2124. ASSERT_TRUE(res);
  2125. ASSERT_EQ(200, res->status);
  2126. ASSERT_EQ(4U, res->body.size());
  2127. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2128. "application/octet-stream");
  2129. ASSERT_TRUE(res);
  2130. ASSERT_EQ(200, res->status);
  2131. ASSERT_EQ(4U, res->body.size());
  2132. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2133. "application/octet-stream");
  2134. ASSERT_TRUE(res);
  2135. ASSERT_EQ(200, res->status);
  2136. ASSERT_EQ(4U, res->body.size());
  2137. }
  2138. TEST_F(ServerTest, BinaryString) {
  2139. auto binary = std::string("\x00\x01\x02\x03", 4);
  2140. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2141. ASSERT_TRUE(res);
  2142. ASSERT_EQ(200, res->status);
  2143. ASSERT_EQ(4U, res->body.size());
  2144. res = cli_.Put("/binary", binary, "application/octet-stream");
  2145. ASSERT_TRUE(res);
  2146. ASSERT_EQ(200, res->status);
  2147. ASSERT_EQ(4U, res->body.size());
  2148. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2149. ASSERT_TRUE(res);
  2150. ASSERT_EQ(200, res->status);
  2151. ASSERT_EQ(4U, res->body.size());
  2152. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2153. ASSERT_TRUE(res);
  2154. ASSERT_EQ(200, res->status);
  2155. ASSERT_EQ(4U, res->body.size());
  2156. }
  2157. TEST_F(ServerTest, EmptyRequest) {
  2158. auto res = cli_.Get("");
  2159. ASSERT_TRUE(!res);
  2160. EXPECT_EQ(Error::Connection, res.error());
  2161. }
  2162. TEST_F(ServerTest, LongRequest) {
  2163. std::string request;
  2164. for (size_t i = 0; i < 545; i++) {
  2165. request += "/TooLongRequest";
  2166. }
  2167. request += "OK";
  2168. auto res = cli_.Get(request.c_str());
  2169. ASSERT_TRUE(res);
  2170. EXPECT_EQ(404, res->status);
  2171. }
  2172. TEST_F(ServerTest, TooLongRequest) {
  2173. std::string request;
  2174. for (size_t i = 0; i < 545; i++) {
  2175. request += "/TooLongRequest";
  2176. }
  2177. request += "_NG";
  2178. auto res = cli_.Get(request.c_str());
  2179. ASSERT_TRUE(res);
  2180. EXPECT_EQ(414, res->status);
  2181. }
  2182. TEST_F(ServerTest, LongHeader) {
  2183. Request req;
  2184. req.method = "GET";
  2185. req.path = "/hi";
  2186. std::string host_and_port;
  2187. host_and_port += HOST;
  2188. host_and_port += ":";
  2189. host_and_port += std::to_string(PORT);
  2190. req.headers.emplace("Host", host_and_port.c_str());
  2191. req.headers.emplace("Accept", "*/*");
  2192. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2193. req.headers.emplace(
  2194. "Header-Name",
  2195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2223. "@@@@@@@@@@@@@@@@");
  2224. auto res = std::make_shared<Response>();
  2225. auto error = Error::Success;
  2226. auto ret = cli_.send(req, *res, error);
  2227. ASSERT_TRUE(ret);
  2228. EXPECT_EQ(200, res->status);
  2229. }
  2230. TEST_F(ServerTest, LongQueryValue) {
  2231. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2232. ASSERT_TRUE(res);
  2233. EXPECT_EQ(414, res->status);
  2234. }
  2235. TEST_F(ServerTest, TooLongHeader) {
  2236. Request req;
  2237. req.method = "GET";
  2238. req.path = "/hi";
  2239. std::string host_and_port;
  2240. host_and_port += HOST;
  2241. host_and_port += ":";
  2242. host_and_port += std::to_string(PORT);
  2243. req.headers.emplace("Host", host_and_port.c_str());
  2244. req.headers.emplace("Accept", "*/*");
  2245. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2246. req.headers.emplace(
  2247. "Header-Name",
  2248. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2249. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2250. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2251. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2252. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2253. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2254. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2255. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2275. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2276. "@@@@@@@@@@@@@@@@@");
  2277. auto res = std::make_shared<Response>();
  2278. auto error = Error::Success;
  2279. auto ret = cli_.send(req, *res, error);
  2280. ASSERT_TRUE(ret);
  2281. EXPECT_EQ(200, res->status);
  2282. }
  2283. TEST_F(ServerTest, PercentEncoding) {
  2284. auto res = cli_.Get("/e%6edwith%");
  2285. ASSERT_TRUE(res);
  2286. EXPECT_EQ(200, res->status);
  2287. }
  2288. TEST_F(ServerTest, PercentEncodingUnicode) {
  2289. auto res = cli_.Get("/e%u006edwith%");
  2290. ASSERT_TRUE(res);
  2291. EXPECT_EQ(200, res->status);
  2292. }
  2293. TEST_F(ServerTest, InvalidPercentEncoding) {
  2294. auto res = cli_.Get("/%endwith%");
  2295. ASSERT_TRUE(res);
  2296. EXPECT_EQ(404, res->status);
  2297. }
  2298. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2299. auto res = cli_.Get("/%uendwith%");
  2300. ASSERT_TRUE(res);
  2301. EXPECT_EQ(404, res->status);
  2302. }
  2303. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2304. auto res = cli_.Get("/hello?aaa=bbb%");
  2305. ASSERT_TRUE(res);
  2306. EXPECT_EQ(404, res->status);
  2307. }
  2308. TEST_F(ServerTest, PlusSignEncoding) {
  2309. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2310. ASSERT_TRUE(res);
  2311. EXPECT_EQ(200, res->status);
  2312. EXPECT_EQ("a +b", res->body);
  2313. }
  2314. TEST_F(ServerTest, MultipartFormData) {
  2315. MultipartFormDataItems items = {
  2316. {"text1", "text default", "", ""},
  2317. {"text2", "aωb", "", ""},
  2318. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2319. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2320. {"file3", "", "", "application/octet-stream"},
  2321. {"file4", "", "", " application/json tmp-string "}};
  2322. auto res = cli_.Post("/multipart", items);
  2323. ASSERT_TRUE(res);
  2324. EXPECT_EQ(200, res->status);
  2325. }
  2326. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  2327. MultipartFormDataItems items = {
  2328. {"text", "default text", "", ""},
  2329. {"multi_text1", "aaaaa", "", ""},
  2330. {"multi_text1", "bbbbb", "", ""},
  2331. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2332. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  2333. "application/json"},
  2334. };
  2335. auto res = cli_.Post("/multipart/multi_file_values", items);
  2336. ASSERT_TRUE(res);
  2337. EXPECT_EQ(200, res->status);
  2338. }
  2339. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2340. auto res = cli_.Get("/hi");
  2341. ASSERT_TRUE(res);
  2342. EXPECT_EQ(200, res->status);
  2343. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2344. EXPECT_EQ("Hello World!", res->body);
  2345. }
  2346. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2347. Request req;
  2348. req.method = "POST";
  2349. req.path = "/chunked";
  2350. std::string host_and_port;
  2351. host_and_port += HOST;
  2352. host_and_port += ":";
  2353. host_and_port += std::to_string(PORT);
  2354. req.headers.emplace("Host", host_and_port.c_str());
  2355. req.headers.emplace("Accept", "*/*");
  2356. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2357. req.headers.emplace("Content-Type", "text/plain");
  2358. req.headers.emplace("Content-Length", "0");
  2359. req.headers.emplace(
  2360. "Transfer-Encoding",
  2361. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2362. // Client does not chunk, so make a chunked body manually.
  2363. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2364. auto res = std::make_shared<Response>();
  2365. auto error = Error::Success;
  2366. auto ret = cli_.send(req, *res, error);
  2367. ASSERT_TRUE(ret);
  2368. EXPECT_EQ(200, res->status);
  2369. }
  2370. TEST_F(ServerTest, GetStreamed2) {
  2371. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2372. ASSERT_TRUE(res);
  2373. EXPECT_EQ(206, res->status);
  2374. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2375. EXPECT_EQ(std::string("ab"), res->body);
  2376. }
  2377. TEST_F(ServerTest, GetStreamed) {
  2378. auto res = cli_.Get("/streamed");
  2379. ASSERT_TRUE(res);
  2380. EXPECT_EQ(200, res->status);
  2381. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2382. EXPECT_EQ(std::string("aaabbb"), res->body);
  2383. }
  2384. TEST_F(ServerTest, GetStreamedWithRange1) {
  2385. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2386. ASSERT_TRUE(res);
  2387. EXPECT_EQ(206, res->status);
  2388. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2389. EXPECT_EQ(true, res->has_header("Content-Range"));
  2390. EXPECT_EQ(std::string("def"), res->body);
  2391. }
  2392. TEST_F(ServerTest, GetStreamedWithRange2) {
  2393. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2394. ASSERT_TRUE(res);
  2395. EXPECT_EQ(206, res->status);
  2396. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2397. EXPECT_EQ(true, res->has_header("Content-Range"));
  2398. EXPECT_EQ(std::string("bcdefg"), res->body);
  2399. }
  2400. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2401. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(206, res->status);
  2404. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2405. EXPECT_EQ(true, res->has_header("Content-Range"));
  2406. EXPECT_EQ(std::string("efg"), res->body);
  2407. }
  2408. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2409. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2410. ASSERT_TRUE(res);
  2411. EXPECT_EQ(206, res->status);
  2412. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2413. EXPECT_EQ(true, res->has_header("Content-Range"));
  2414. EXPECT_EQ(std::string("abcdefg"), res->body);
  2415. }
  2416. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2417. auto res = cli_.Get("/streamed-with-range",
  2418. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2419. "92233720368547758079223372036854775807"}});
  2420. ASSERT_TRUE(res);
  2421. EXPECT_EQ(416, res->status);
  2422. }
  2423. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2424. auto res =
  2425. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2426. EXPECT_EQ(206, res->status);
  2427. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2428. EXPECT_EQ(true, res->has_header("Content-Range"));
  2429. EXPECT_EQ(std::string("abcdefg"), res->body);
  2430. }
  2431. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2432. auto res =
  2433. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2434. ASSERT_TRUE(res);
  2435. EXPECT_EQ(206, res->status);
  2436. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2437. EXPECT_EQ(false, res->has_header("Content-Range"));
  2438. EXPECT_EQ(269U, res->body.size());
  2439. }
  2440. TEST_F(ServerTest, GetStreamedEndless) {
  2441. uint64_t offset = 0;
  2442. auto res = cli_.Get("/streamed-cancel",
  2443. [&](const char * /*data*/, uint64_t data_length) {
  2444. if (offset < 100) {
  2445. offset += data_length;
  2446. return true;
  2447. }
  2448. return false;
  2449. });
  2450. ASSERT_TRUE(!res);
  2451. EXPECT_EQ(Error::Canceled, res.error());
  2452. }
  2453. TEST_F(ServerTest, ClientStop) {
  2454. std::atomic_size_t count{4};
  2455. std::vector<std::thread> threads;
  2456. for (auto i = count.load(); i != 0; --i) {
  2457. threads.emplace_back([&]() {
  2458. auto res = cli_.Get("/streamed-cancel",
  2459. [&](const char *, uint64_t) { return true; });
  2460. --count;
  2461. ASSERT_TRUE(!res);
  2462. EXPECT_TRUE(res.error() == Error::Canceled ||
  2463. res.error() == Error::Read || res.error() == Error::Write);
  2464. });
  2465. }
  2466. std::this_thread::sleep_for(std::chrono::seconds(2));
  2467. while (count != 0) {
  2468. cli_.stop();
  2469. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2470. }
  2471. for (auto &t : threads) {
  2472. t.join();
  2473. }
  2474. }
  2475. TEST_F(ServerTest, GetWithRange1) {
  2476. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2477. ASSERT_TRUE(res);
  2478. EXPECT_EQ(206, res->status);
  2479. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2480. EXPECT_EQ(true, res->has_header("Content-Range"));
  2481. EXPECT_EQ(std::string("def"), res->body);
  2482. }
  2483. TEST_F(ServerTest, GetWithRange2) {
  2484. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2485. ASSERT_TRUE(res);
  2486. EXPECT_EQ(206, res->status);
  2487. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2488. EXPECT_EQ(true, res->has_header("Content-Range"));
  2489. EXPECT_EQ(std::string("bcdefg"), res->body);
  2490. }
  2491. TEST_F(ServerTest, GetWithRange3) {
  2492. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2493. ASSERT_TRUE(res);
  2494. EXPECT_EQ(206, res->status);
  2495. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2496. EXPECT_EQ(true, res->has_header("Content-Range"));
  2497. EXPECT_EQ(std::string("a"), res->body);
  2498. }
  2499. TEST_F(ServerTest, GetWithRange4) {
  2500. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2501. ASSERT_TRUE(res);
  2502. EXPECT_EQ(206, res->status);
  2503. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2504. EXPECT_EQ(true, res->has_header("Content-Range"));
  2505. EXPECT_EQ(std::string("fg"), res->body);
  2506. }
  2507. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2508. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2509. ASSERT_TRUE(res);
  2510. EXPECT_EQ(416, res->status);
  2511. }
  2512. TEST_F(ServerTest, GetWithRangeMultipart) {
  2513. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(206, res->status);
  2516. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2517. EXPECT_EQ(false, res->has_header("Content-Range"));
  2518. EXPECT_EQ(269U, res->body.size());
  2519. }
  2520. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2521. auto res =
  2522. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2523. ASSERT_TRUE(res);
  2524. EXPECT_EQ(416, res->status);
  2525. }
  2526. TEST_F(ServerTest, GetStreamedChunked) {
  2527. auto res = cli_.Get("/streamed-chunked");
  2528. ASSERT_TRUE(res);
  2529. EXPECT_EQ(200, res->status);
  2530. EXPECT_EQ(std::string("123456789"), res->body);
  2531. }
  2532. TEST_F(ServerTest, GetStreamedChunked2) {
  2533. auto res = cli_.Get("/streamed-chunked2");
  2534. ASSERT_TRUE(res);
  2535. EXPECT_EQ(200, res->status);
  2536. EXPECT_EQ(std::string("123456789"), res->body);
  2537. }
  2538. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  2539. auto res = cli_.Get("/streamed-chunked-with-trailer");
  2540. ASSERT_TRUE(res);
  2541. EXPECT_EQ(200, res->status);
  2542. EXPECT_EQ(std::string("123456789"), res->body);
  2543. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  2544. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  2545. }
  2546. TEST_F(ServerTest, LargeChunkedPost) {
  2547. Request req;
  2548. req.method = "POST";
  2549. req.path = "/large-chunked";
  2550. std::string host_and_port;
  2551. host_and_port += HOST;
  2552. host_and_port += ":";
  2553. host_and_port += std::to_string(PORT);
  2554. req.headers.emplace("Host", host_and_port.c_str());
  2555. req.headers.emplace("Accept", "*/*");
  2556. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2557. req.headers.emplace("Content-Type", "text/plain");
  2558. req.headers.emplace("Content-Length", "0");
  2559. req.headers.emplace("Transfer-Encoding", "chunked");
  2560. std::string long_string(30 * 1024u, 'a');
  2561. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2562. // Attempt to make a large enough post to exceed OS buffers, to test that
  2563. // the server handles short reads if the full chunk data isn't available.
  2564. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2565. auto res = std::make_shared<Response>();
  2566. auto error = Error::Success;
  2567. auto ret = cli_.send(req, *res, error);
  2568. ASSERT_TRUE(ret);
  2569. EXPECT_EQ(200, res->status);
  2570. }
  2571. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2572. auto res = cli_.Get("/remote_addr");
  2573. ASSERT_TRUE(res);
  2574. EXPECT_EQ(200, res->status);
  2575. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2576. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2577. }
  2578. TEST_F(ServerTest, GetMethodLocalAddr) {
  2579. auto res = cli_.Get("/local_addr");
  2580. ASSERT_TRUE(res);
  2581. EXPECT_EQ(200, res->status);
  2582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2583. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  2584. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  2585. }
  2586. TEST_F(ServerTest, HTTPResponseSplitting) {
  2587. auto res = cli_.Get("/http_response_splitting");
  2588. ASSERT_TRUE(res);
  2589. EXPECT_EQ(200, res->status);
  2590. }
  2591. TEST_F(ServerTest, SlowRequest) {
  2592. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2593. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2594. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2595. }
  2596. #if 0
  2597. TEST_F(ServerTest, SlowPost) {
  2598. char buffer[64 * 1024];
  2599. memset(buffer, 0x42, sizeof(buffer));
  2600. auto res = cli_.Post(
  2601. "/slowpost", 64 * 1024 * 1024,
  2602. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2603. auto ret = sink.write(buffer, sizeof(buffer));
  2604. EXPECT_TRUE(ret);
  2605. return true;
  2606. },
  2607. "text/plain");
  2608. ASSERT_TRUE(res);
  2609. EXPECT_EQ(200, res->status);
  2610. }
  2611. TEST_F(ServerTest, SlowPostFail) {
  2612. char buffer[64 * 1024];
  2613. memset(buffer, 0x42, sizeof(buffer));
  2614. cli_.set_write_timeout(std::chrono::seconds(0));
  2615. auto res = cli_.Post(
  2616. "/slowpost", 64 * 1024 * 1024,
  2617. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2618. sink.write(buffer, sizeof(buffer));
  2619. return true;
  2620. },
  2621. "text/plain");
  2622. ASSERT_TRUE(!res);
  2623. EXPECT_EQ(Error::Write, res.error());
  2624. }
  2625. #endif
  2626. TEST_F(ServerTest, Put) {
  2627. auto res = cli_.Put("/put", "PUT", "text/plain");
  2628. ASSERT_TRUE(res);
  2629. EXPECT_EQ(200, res->status);
  2630. EXPECT_EQ("PUT", res->body);
  2631. }
  2632. TEST_F(ServerTest, PutWithContentProvider) {
  2633. auto res = cli_.Put(
  2634. "/put", 3,
  2635. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2636. sink.os << "PUT";
  2637. return true;
  2638. },
  2639. "text/plain");
  2640. ASSERT_TRUE(res);
  2641. EXPECT_EQ(200, res->status);
  2642. EXPECT_EQ("PUT", res->body);
  2643. }
  2644. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2645. auto res = cli_.Post(
  2646. "/post", 42,
  2647. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2648. return false;
  2649. },
  2650. "text/plain");
  2651. ASSERT_TRUE(!res);
  2652. EXPECT_EQ(Error::Canceled, res.error());
  2653. }
  2654. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2655. auto res = cli_.Put(
  2656. "/put",
  2657. [](size_t /*offset*/, DataSink &sink) {
  2658. sink.os << "PUT";
  2659. sink.done();
  2660. return true;
  2661. },
  2662. "text/plain");
  2663. ASSERT_TRUE(res);
  2664. EXPECT_EQ(200, res->status);
  2665. EXPECT_EQ("PUT", res->body);
  2666. }
  2667. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2668. auto res = cli_.Post(
  2669. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2670. "text/plain");
  2671. ASSERT_TRUE(!res);
  2672. EXPECT_EQ(Error::Canceled, res.error());
  2673. }
  2674. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2675. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2676. cli_.set_compress(true);
  2677. auto res = cli_.Put(
  2678. "/put", 3,
  2679. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2680. sink.os << "PUT";
  2681. return true;
  2682. },
  2683. "text/plain");
  2684. ASSERT_TRUE(res);
  2685. EXPECT_EQ(200, res->status);
  2686. EXPECT_EQ("PUT", res->body);
  2687. }
  2688. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2689. cli_.set_compress(true);
  2690. auto res = cli_.Post(
  2691. "/post", 42,
  2692. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2693. return false;
  2694. },
  2695. "text/plain");
  2696. ASSERT_TRUE(!res);
  2697. EXPECT_EQ(Error::Canceled, res.error());
  2698. }
  2699. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2700. cli_.set_compress(true);
  2701. auto res = cli_.Put(
  2702. "/put",
  2703. [](size_t /*offset*/, DataSink &sink) {
  2704. sink.os << "PUT";
  2705. sink.done();
  2706. return true;
  2707. },
  2708. "text/plain");
  2709. ASSERT_TRUE(res);
  2710. EXPECT_EQ(200, res->status);
  2711. EXPECT_EQ("PUT", res->body);
  2712. }
  2713. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2714. cli_.set_compress(true);
  2715. auto res = cli_.Post(
  2716. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2717. "text/plain");
  2718. ASSERT_TRUE(!res);
  2719. EXPECT_EQ(Error::Canceled, res.error());
  2720. }
  2721. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2722. cli_.set_compress(true);
  2723. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2724. ASSERT_TRUE(res);
  2725. EXPECT_EQ(200, res->status);
  2726. EXPECT_EQ(LARGE_DATA, res->body);
  2727. }
  2728. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2729. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2730. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2731. Client cli(s.c_str());
  2732. cli.enable_server_certificate_verification(false);
  2733. #else
  2734. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2735. Client cli(s.c_str());
  2736. #endif
  2737. cli.set_compress(true);
  2738. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2739. ASSERT_TRUE(res);
  2740. EXPECT_EQ(200, res->status);
  2741. EXPECT_EQ(LARGE_DATA, res->body);
  2742. EXPECT_EQ(101942u, res.get_request_header_value<uint64_t>("Content-Length"));
  2743. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2744. }
  2745. TEST_F(ServerTest, PutContentWithDeflate) {
  2746. cli_.set_compress(false);
  2747. Headers headers;
  2748. headers.emplace("Content-Encoding", "deflate");
  2749. // PUT in deflate format:
  2750. auto res = cli_.Put("/put", headers,
  2751. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2752. ASSERT_TRUE(res);
  2753. EXPECT_EQ(200, res->status);
  2754. EXPECT_EQ("PUT", res->body);
  2755. }
  2756. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2757. Headers headers;
  2758. headers.emplace("Accept-Encoding", "gzip, deflate");
  2759. auto res = cli_.Get("/streamed-chunked", headers);
  2760. ASSERT_TRUE(res);
  2761. EXPECT_EQ(200, res->status);
  2762. EXPECT_EQ(std::string("123456789"), res->body);
  2763. }
  2764. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2765. Headers headers;
  2766. headers.emplace("Accept-Encoding", "gzip, deflate");
  2767. auto res = cli_.Get("/streamed-chunked2", headers);
  2768. ASSERT_TRUE(res);
  2769. EXPECT_EQ(200, res->status);
  2770. EXPECT_EQ(std::string("123456789"), res->body);
  2771. }
  2772. TEST(GzipDecompressor, ChunkedDecompression) {
  2773. std::string data;
  2774. for (size_t i = 0; i < 32 * 1024; ++i) {
  2775. data.push_back(static_cast<char>('a' + i % 26));
  2776. }
  2777. std::string compressed_data;
  2778. {
  2779. httplib::detail::gzip_compressor compressor;
  2780. bool result = compressor.compress(
  2781. data.data(), data.size(),
  2782. /*last=*/true,
  2783. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  2784. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  2785. compressed_data_size);
  2786. return true;
  2787. });
  2788. ASSERT_TRUE(result);
  2789. }
  2790. std::string decompressed_data;
  2791. {
  2792. httplib::detail::gzip_decompressor decompressor;
  2793. // Chunk size is chosen specifically to have a decompressed chunk size equal
  2794. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2795. size_t chunk_size = 130;
  2796. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2797. chunk_begin += chunk_size) {
  2798. size_t current_chunk_size =
  2799. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2800. bool result = decompressor.decompress(
  2801. compressed_data.data() + chunk_begin, current_chunk_size,
  2802. [&](const char *decompressed_data_chunk,
  2803. size_t decompressed_data_chunk_size) {
  2804. decompressed_data.insert(decompressed_data.size(),
  2805. decompressed_data_chunk,
  2806. decompressed_data_chunk_size);
  2807. return true;
  2808. });
  2809. ASSERT_TRUE(result);
  2810. }
  2811. }
  2812. ASSERT_EQ(data, decompressed_data);
  2813. }
  2814. #ifdef _WIN32
  2815. TEST(GzipDecompressor, LargeRandomData) {
  2816. // prepare large random data that is difficult to be compressed and is
  2817. // expected to have large size even when compressed
  2818. std::random_device seed_gen;
  2819. std::mt19937 random(seed_gen());
  2820. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2821. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2822. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2823. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2824. // compress data over 4GiB
  2825. std::string compressed_data;
  2826. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2827. httplib::detail::gzip_compressor compressor;
  2828. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2829. data.size() * sizeof(std::uint32_t), true,
  2830. [&](const char *data, size_t size) {
  2831. compressed_data.insert(
  2832. compressed_data.size(), data, size);
  2833. return true;
  2834. });
  2835. ASSERT_TRUE(result);
  2836. // FIXME: compressed data size is expected to be greater than 4GiB,
  2837. // but there is no guarantee
  2838. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2839. // decompress data over 4GiB
  2840. std::string decompressed_data;
  2841. decompressed_data.reserve(data_size);
  2842. httplib::detail::gzip_decompressor decompressor;
  2843. result = decompressor.decompress(
  2844. compressed_data.data(), compressed_data.size(),
  2845. [&](const char *data, size_t size) {
  2846. decompressed_data.insert(decompressed_data.size(), data, size);
  2847. return true;
  2848. });
  2849. ASSERT_TRUE(result);
  2850. // compare
  2851. ASSERT_EQ(data_size, decompressed_data.size());
  2852. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2853. 0);
  2854. }
  2855. #endif
  2856. #endif
  2857. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2858. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2859. Headers headers;
  2860. headers.emplace("Accept-Encoding", "br");
  2861. auto res = cli_.Get("/streamed-chunked", headers);
  2862. ASSERT_TRUE(res);
  2863. EXPECT_EQ(200, res->status);
  2864. EXPECT_EQ(std::string("123456789"), res->body);
  2865. }
  2866. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2867. Headers headers;
  2868. headers.emplace("Accept-Encoding", "br");
  2869. auto res = cli_.Get("/streamed-chunked2", headers);
  2870. ASSERT_TRUE(res);
  2871. EXPECT_EQ(200, res->status);
  2872. EXPECT_EQ(std::string("123456789"), res->body);
  2873. }
  2874. #endif
  2875. TEST_F(ServerTest, Patch) {
  2876. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2877. ASSERT_TRUE(res);
  2878. EXPECT_EQ(200, res->status);
  2879. EXPECT_EQ("PATCH", res->body);
  2880. }
  2881. TEST_F(ServerTest, Delete) {
  2882. auto res = cli_.Delete("/delete");
  2883. ASSERT_TRUE(res);
  2884. EXPECT_EQ(200, res->status);
  2885. EXPECT_EQ("DELETE", res->body);
  2886. }
  2887. TEST_F(ServerTest, DeleteContentReceiver) {
  2888. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2889. ASSERT_TRUE(res);
  2890. EXPECT_EQ(200, res->status);
  2891. EXPECT_EQ("content", res->body);
  2892. }
  2893. TEST_F(ServerTest, Options) {
  2894. auto res = cli_.Options("*");
  2895. ASSERT_TRUE(res);
  2896. EXPECT_EQ(200, res->status);
  2897. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2898. EXPECT_TRUE(res->body.empty());
  2899. }
  2900. TEST_F(ServerTest, URL) {
  2901. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2902. ASSERT_TRUE(res);
  2903. EXPECT_EQ(200, res->status);
  2904. }
  2905. TEST_F(ServerTest, ArrayParam) {
  2906. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2907. ASSERT_TRUE(res);
  2908. EXPECT_EQ(200, res->status);
  2909. }
  2910. TEST_F(ServerTest, NoMultipleHeaders) {
  2911. Headers headers = {{"Content-Length", "5"}};
  2912. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2913. "text/plain");
  2914. ASSERT_TRUE(res);
  2915. EXPECT_EQ(200, res->status);
  2916. }
  2917. TEST_F(ServerTest, PostContentReceiver) {
  2918. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2919. ASSERT_TRUE(res);
  2920. ASSERT_EQ(200, res->status);
  2921. ASSERT_EQ("content", res->body);
  2922. }
  2923. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  2924. MultipartFormDataItems items = {
  2925. {"text1", "text default", "", ""},
  2926. {"text2", "aωb", "", ""},
  2927. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2928. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2929. {"file3", "", "", "application/octet-stream"},
  2930. };
  2931. auto res = cli_.Post("/content_receiver", items);
  2932. ASSERT_TRUE(res);
  2933. EXPECT_EQ(200, res->status);
  2934. }
  2935. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  2936. MultipartFormDataItems items = {
  2937. {"text1", "text default", "", ""},
  2938. {"text2", "aωb", "", ""},
  2939. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2940. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2941. {"file3", "", "", "application/octet-stream"},
  2942. };
  2943. auto boundary = std::string("+++++");
  2944. std::string body;
  2945. for (const auto &item : items) {
  2946. body += "--" + boundary + "\r\n";
  2947. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2948. if (!item.filename.empty()) {
  2949. body += "; filename=\"" + item.filename + "\"";
  2950. }
  2951. body += "\r\n";
  2952. if (!item.content_type.empty()) {
  2953. body += "Content-Type: " + item.content_type + "\r\n";
  2954. }
  2955. body += "\r\n";
  2956. body += item.content + "\r\n";
  2957. }
  2958. body += "--" + boundary + "--\r\n";
  2959. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2960. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2961. ASSERT_TRUE(res);
  2962. EXPECT_EQ(200, res->status);
  2963. }
  2964. TEST_F(ServerTest, PostContentReceiverGzip) {
  2965. cli_.set_compress(true);
  2966. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2967. ASSERT_TRUE(res);
  2968. ASSERT_EQ(200, res->status);
  2969. ASSERT_EQ("content", res->body);
  2970. }
  2971. TEST_F(ServerTest, PutContentReceiver) {
  2972. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2973. ASSERT_TRUE(res);
  2974. ASSERT_EQ(200, res->status);
  2975. ASSERT_EQ("content", res->body);
  2976. }
  2977. TEST_F(ServerTest, PatchContentReceiver) {
  2978. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2979. ASSERT_TRUE(res);
  2980. ASSERT_EQ(200, res->status);
  2981. ASSERT_EQ("content", res->body);
  2982. }
  2983. TEST_F(ServerTest, PostQueryStringAndBody) {
  2984. auto res =
  2985. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2986. ASSERT_TRUE(res);
  2987. ASSERT_EQ(200, res->status);
  2988. }
  2989. TEST_F(ServerTest, HTTP2Magic) {
  2990. Request req;
  2991. req.method = "PRI";
  2992. req.path = "*";
  2993. req.body = "SM";
  2994. auto res = std::make_shared<Response>();
  2995. auto error = Error::Success;
  2996. auto ret = cli_.send(req, *res, error);
  2997. ASSERT_TRUE(ret);
  2998. EXPECT_EQ(400, res->status);
  2999. }
  3000. TEST_F(ServerTest, KeepAlive) {
  3001. auto res = cli_.Get("/hi");
  3002. ASSERT_TRUE(res);
  3003. EXPECT_EQ(200, res->status);
  3004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3005. EXPECT_EQ("Hello World!", res->body);
  3006. res = cli_.Get("/hi");
  3007. ASSERT_TRUE(res);
  3008. EXPECT_EQ(200, res->status);
  3009. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3010. EXPECT_EQ("Hello World!", res->body);
  3011. res = cli_.Get("/hi");
  3012. ASSERT_TRUE(res);
  3013. EXPECT_EQ(200, res->status);
  3014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3015. EXPECT_EQ("Hello World!", res->body);
  3016. res = cli_.Get("/not-exist");
  3017. ASSERT_TRUE(res);
  3018. EXPECT_EQ(404, res->status);
  3019. res = cli_.Post("/empty", "", "text/plain");
  3020. ASSERT_TRUE(res);
  3021. EXPECT_EQ(200, res->status);
  3022. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3023. EXPECT_EQ("empty", res->body);
  3024. EXPECT_EQ("close", res->get_header_value("Connection"));
  3025. res = cli_.Post(
  3026. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3027. "text/plain");
  3028. ASSERT_TRUE(res);
  3029. EXPECT_EQ(200, res->status);
  3030. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3031. EXPECT_EQ("empty", res->body);
  3032. cli_.set_keep_alive(false);
  3033. res = cli_.Get("/last-request");
  3034. ASSERT_TRUE(res);
  3035. EXPECT_EQ(200, res->status);
  3036. EXPECT_EQ("close", res->get_header_value("Connection"));
  3037. }
  3038. TEST_F(ServerTest, TooManyRedirect) {
  3039. cli_.set_follow_location(true);
  3040. auto res = cli_.Get("/redirect/0");
  3041. ASSERT_TRUE(!res);
  3042. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3043. }
  3044. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3045. TEST_F(ServerTest, Gzip) {
  3046. Headers headers;
  3047. headers.emplace("Accept-Encoding", "gzip, deflate");
  3048. auto res = cli_.Get("/compress", headers);
  3049. ASSERT_TRUE(res);
  3050. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3052. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3053. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3054. "7890123456789012345678901234567890",
  3055. res->body);
  3056. EXPECT_EQ(200, res->status);
  3057. }
  3058. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3059. auto res = cli_.Get("/compress");
  3060. ASSERT_TRUE(res);
  3061. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3062. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3063. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3064. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3065. "7890123456789012345678901234567890",
  3066. res->body);
  3067. EXPECT_EQ(200, res->status);
  3068. }
  3069. TEST_F(ServerTest, GzipWithContentReceiver) {
  3070. Headers headers;
  3071. headers.emplace("Accept-Encoding", "gzip, deflate");
  3072. std::string body;
  3073. auto res = cli_.Get("/compress", headers,
  3074. [&](const char *data, uint64_t data_length) {
  3075. EXPECT_EQ(100U, data_length);
  3076. body.append(data, data_length);
  3077. return true;
  3078. });
  3079. ASSERT_TRUE(res);
  3080. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3081. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3082. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3083. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3084. "7890123456789012345678901234567890",
  3085. body);
  3086. EXPECT_EQ(200, res->status);
  3087. }
  3088. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3089. Headers headers;
  3090. headers.emplace("Accept-Encoding", "gzip, deflate");
  3091. cli_.set_decompress(false);
  3092. auto res = cli_.Get("/compress", headers);
  3093. ASSERT_TRUE(res);
  3094. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3095. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3096. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3097. EXPECT_EQ(33U, res->body.size());
  3098. EXPECT_EQ(200, res->status);
  3099. }
  3100. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3101. std::string body;
  3102. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3103. EXPECT_EQ(100U, data_length);
  3104. body.append(data, data_length);
  3105. return true;
  3106. });
  3107. ASSERT_TRUE(res);
  3108. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3110. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3111. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3112. "7890123456789012345678901234567890",
  3113. body);
  3114. EXPECT_EQ(200, res->status);
  3115. }
  3116. TEST_F(ServerTest, NoGzip) {
  3117. Headers headers;
  3118. headers.emplace("Accept-Encoding", "gzip, deflate");
  3119. auto res = cli_.Get("/nocompress", headers);
  3120. ASSERT_TRUE(res);
  3121. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3122. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3123. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3124. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3125. "7890123456789012345678901234567890",
  3126. res->body);
  3127. EXPECT_EQ(200, res->status);
  3128. }
  3129. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3130. Headers headers;
  3131. headers.emplace("Accept-Encoding", "gzip, deflate");
  3132. std::string body;
  3133. auto res = cli_.Get("/nocompress", headers,
  3134. [&](const char *data, uint64_t data_length) {
  3135. EXPECT_EQ(100U, data_length);
  3136. body.append(data, data_length);
  3137. return true;
  3138. });
  3139. ASSERT_TRUE(res);
  3140. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3141. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3142. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3143. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3144. "7890123456789012345678901234567890",
  3145. body);
  3146. EXPECT_EQ(200, res->status);
  3147. }
  3148. TEST_F(ServerTest, MultipartFormDataGzip) {
  3149. MultipartFormDataItems items = {
  3150. {"key1", "test", "", ""},
  3151. {"key2", "--abcdefg123", "", ""},
  3152. };
  3153. cli_.set_compress(true);
  3154. auto res = cli_.Post("/compress-multipart", items);
  3155. ASSERT_TRUE(res);
  3156. EXPECT_EQ(200, res->status);
  3157. }
  3158. #endif
  3159. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3160. TEST_F(ServerTest, Brotli) {
  3161. Headers headers;
  3162. headers.emplace("Accept-Encoding", "br");
  3163. auto res = cli_.Get("/compress", headers);
  3164. ASSERT_TRUE(res);
  3165. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3167. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3169. "7890123456789012345678901234567890",
  3170. res->body);
  3171. EXPECT_EQ(200, res->status);
  3172. }
  3173. #endif
  3174. // Sends a raw request to a server listening at HOST:PORT.
  3175. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3176. std::string *resp = nullptr) {
  3177. auto error = Error::Success;
  3178. auto client_sock = detail::create_client_socket(
  3179. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  3180. /*connection_timeout_sec=*/5, 0,
  3181. /*read_timeout_sec=*/5, 0,
  3182. /*write_timeout_sec=*/5, 0, std::string(), error);
  3183. if (client_sock == INVALID_SOCKET) { return false; }
  3184. auto ret = detail::process_client_socket(
  3185. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3186. if (req.size() !=
  3187. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3188. return false;
  3189. }
  3190. char buf[512];
  3191. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3192. while (line_reader.getline()) {
  3193. if (resp) { *resp += line_reader.ptr(); }
  3194. }
  3195. return true;
  3196. });
  3197. detail::close_socket(client_sock);
  3198. return ret;
  3199. }
  3200. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3201. Server svr;
  3202. std::string header_value;
  3203. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3204. header_value = req.get_header_value("foo");
  3205. res.set_content("ok", "text/plain");
  3206. });
  3207. thread t = thread([&] { svr.listen(HOST, PORT); });
  3208. auto se = detail::scope_exit([&] {
  3209. svr.stop();
  3210. t.join();
  3211. ASSERT_FALSE(svr.is_running());
  3212. });
  3213. while (!svr.is_running()) {
  3214. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3215. }
  3216. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3217. // like characters are not treated the same - use vertical tab and escape.
  3218. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3219. "foo: \t \v bar \x1B\t \r\n"
  3220. "Connection: close\r\n"
  3221. "\r\n";
  3222. ASSERT_TRUE(send_request(5, req));
  3223. EXPECT_EQ(header_value, "\v bar \x1B");
  3224. }
  3225. // Sends a raw request and verifies that there isn't a crash or exception.
  3226. static void test_raw_request(const std::string &req,
  3227. std::string *out = nullptr) {
  3228. Server svr;
  3229. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3230. res.set_content("ok", "text/plain");
  3231. });
  3232. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  3233. res.set_content("ok", "text/plain");
  3234. });
  3235. // Server read timeout must be longer than the client read timeout for the
  3236. // bug to reproduce, probably to force the server to process a request
  3237. // without a trailing blank line.
  3238. const time_t client_read_timeout_sec = 1;
  3239. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3240. bool listen_thread_ok = false;
  3241. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3242. auto se = detail::scope_exit([&] {
  3243. svr.stop();
  3244. t.join();
  3245. ASSERT_FALSE(svr.is_running());
  3246. EXPECT_TRUE(listen_thread_ok);
  3247. });
  3248. while (!svr.is_running()) {
  3249. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3250. }
  3251. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3252. }
  3253. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3254. // A certain header line causes an exception if the header property is parsed
  3255. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3256. test_raw_request(
  3257. "GET /hi HTTP/1.1\r\n"
  3258. " : "
  3259. " "
  3260. " ");
  3261. }
  3262. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3263. // A certain header line causes an exception if the header property *name* is
  3264. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3265. // greedy matcher and requires backtracking when there are a lot of ":"
  3266. // characters.
  3267. // This occurs with libc++ but not libstdc++.
  3268. test_raw_request(
  3269. "GET /hi HTTP/1.1\r\n"
  3270. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3271. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3272. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3273. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3274. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3275. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3276. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3277. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3278. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3279. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3280. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3281. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3282. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3283. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3284. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3285. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3286. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3287. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3288. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3289. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3290. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3291. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3292. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3293. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3294. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3295. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3296. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3297. "&&&%%%");
  3298. }
  3299. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  3300. // Make sure this doesn't crash the server.
  3301. // In a previous version of the header line regex, the "\r" rendered the line
  3302. // unparsable and the regex engine repeatedly backtracked, trying to look for
  3303. // a new position where the leading white space ended and the field value
  3304. // began.
  3305. // The crash occurs with libc++ but not libstdc++.
  3306. test_raw_request("GET /hi HTTP/1.1\r\n"
  3307. "a:" +
  3308. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3309. "\r\n"
  3310. "\r\n");
  3311. }
  3312. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3313. std::string out;
  3314. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3315. "Content-Type: text/plain\r\n"
  3316. "Transfer-Encoding: chunked\r\n"
  3317. "\r\n"
  3318. "nothex\r\n",
  3319. &out);
  3320. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3321. }
  3322. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3323. std::string out;
  3324. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3325. "Content-Type: text/plain\r\n"
  3326. "Transfer-Encoding: chunked\r\n"
  3327. "\r\n"
  3328. "3\r\n"
  3329. "xyz\r\n"
  3330. "NaN\r\n",
  3331. &out);
  3332. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3333. }
  3334. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3335. std::string out;
  3336. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3337. "Content-Type: text/plain\r\n"
  3338. "Transfer-Encoding: chunked\r\n"
  3339. "\r\n"
  3340. // Length is too large for 64 bits.
  3341. "1ffffffffffffffff\r\n"
  3342. "xyz\r\n",
  3343. &out);
  3344. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3345. }
  3346. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3347. test_raw_request("GET /hi HTTP/1.1\r\n"
  3348. "Content-Type: text/plain\r\n\r");
  3349. }
  3350. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3351. std::string out;
  3352. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3353. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3354. }
  3355. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3356. Server svr;
  3357. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3358. res.set_header("Cache-Control", "no-cache");
  3359. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  3360. DataSink &sink) {
  3361. char buffer[27];
  3362. auto size = static_cast<size_t>(sprintf(buffer, "data:%zd\n\n", offset));
  3363. auto ret = sink.write(buffer, size);
  3364. EXPECT_TRUE(ret);
  3365. std::this_thread::sleep_for(std::chrono::seconds(1));
  3366. return true;
  3367. });
  3368. });
  3369. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3370. while (!svr.is_running()) {
  3371. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3372. }
  3373. Client client(HOST, PORT);
  3374. const Headers headers = {{"Accept", "text/event-stream"}};
  3375. auto get_thread = std::thread([&client, &headers]() {
  3376. auto res = client.Get(
  3377. "/events", headers,
  3378. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3379. });
  3380. auto se = detail::scope_exit([&] {
  3381. svr.stop();
  3382. get_thread.join();
  3383. listen_thread.join();
  3384. ASSERT_FALSE(svr.is_running());
  3385. });
  3386. // Give GET time to get a few messages.
  3387. std::this_thread::sleep_for(std::chrono::seconds(2));
  3388. }
  3389. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  3390. httplib::Server svr;
  3391. svr.Post("/hi", [&](const httplib::Request & /*req*/,
  3392. httplib::Response &res) { res.status = 200; });
  3393. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3394. while (!svr.is_running()) {
  3395. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  3396. }
  3397. Client cli(HOST, PORT);
  3398. auto res = cli.Post("/hi", "data", "text/plain");
  3399. ASSERT_TRUE(res);
  3400. EXPECT_EQ(200, res->status);
  3401. svr.stop();
  3402. thread.join();
  3403. ASSERT_FALSE(svr.is_running());
  3404. res = cli.Post("/hi", "data", "text/plain");
  3405. ASSERT_FALSE(res);
  3406. }
  3407. TEST(StreamingTest, NoContentLengthStreaming) {
  3408. Server svr;
  3409. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3410. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3411. if (offset < 6) {
  3412. sink.os << (offset < 3 ? "a" : "b");
  3413. } else {
  3414. sink.done();
  3415. }
  3416. return true;
  3417. });
  3418. });
  3419. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3420. auto listen_se = detail::scope_exit([&] {
  3421. svr.stop();
  3422. listen_thread.join();
  3423. ASSERT_FALSE(svr.is_running());
  3424. });
  3425. while (!svr.is_running()) {
  3426. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3427. }
  3428. Client client(HOST, PORT);
  3429. auto get_thread = std::thread([&client]() {
  3430. std::string s;
  3431. auto res =
  3432. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3433. s += std::string(data, len);
  3434. return true;
  3435. });
  3436. EXPECT_EQ("aaabbb", s);
  3437. });
  3438. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  3439. // Give GET time to get a few messages.
  3440. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3441. }
  3442. TEST(MountTest, Unmount) {
  3443. Server svr;
  3444. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3445. auto se = detail::scope_exit([&] {
  3446. svr.stop();
  3447. listen_thread.join();
  3448. ASSERT_FALSE(svr.is_running());
  3449. });
  3450. while (!svr.is_running()) {
  3451. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3452. }
  3453. // Give GET time to get a few messages.
  3454. std::this_thread::sleep_for(std::chrono::seconds(1));
  3455. Client cli("localhost", PORT);
  3456. svr.set_mount_point("/mount2", "./www2");
  3457. auto res = cli.Get("/");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(404, res->status);
  3460. res = cli.Get("/mount2/dir/test.html");
  3461. ASSERT_TRUE(res);
  3462. EXPECT_EQ(200, res->status);
  3463. svr.set_mount_point("/", "./www");
  3464. res = cli.Get("/dir/");
  3465. ASSERT_TRUE(res);
  3466. EXPECT_EQ(200, res->status);
  3467. svr.remove_mount_point("/");
  3468. res = cli.Get("/dir/");
  3469. ASSERT_TRUE(res);
  3470. EXPECT_EQ(404, res->status);
  3471. svr.remove_mount_point("/mount2");
  3472. res = cli.Get("/mount2/dir/test.html");
  3473. ASSERT_TRUE(res);
  3474. EXPECT_EQ(404, res->status);
  3475. }
  3476. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3477. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3478. Server svr;
  3479. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3480. throw std::runtime_error("exception...");
  3481. });
  3482. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3483. throw std::runtime_error("exception\r\n...");
  3484. });
  3485. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3486. auto se = detail::scope_exit([&] {
  3487. svr.stop();
  3488. listen_thread.join();
  3489. ASSERT_FALSE(svr.is_running());
  3490. });
  3491. while (!svr.is_running()) {
  3492. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3493. }
  3494. // Give GET time to get a few messages.
  3495. std::this_thread::sleep_for(std::chrono::seconds(1));
  3496. Client cli("localhost", PORT);
  3497. {
  3498. auto res = cli.Get("/exception");
  3499. ASSERT_TRUE(res);
  3500. EXPECT_EQ(500, res->status);
  3501. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3502. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3503. }
  3504. {
  3505. auto res = cli.Get("/unknown");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(500, res->status);
  3508. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3509. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  3510. }
  3511. }
  3512. #endif
  3513. TEST(KeepAliveTest, ReadTimeout) {
  3514. Server svr;
  3515. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3516. std::this_thread::sleep_for(std::chrono::seconds(2));
  3517. res.set_content("a", "text/plain");
  3518. });
  3519. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3520. res.set_content("b", "text/plain");
  3521. });
  3522. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3523. auto se = detail::scope_exit([&] {
  3524. svr.stop();
  3525. listen_thread.join();
  3526. ASSERT_FALSE(svr.is_running());
  3527. });
  3528. while (!svr.is_running()) {
  3529. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3530. }
  3531. // Give GET time to get a few messages.
  3532. std::this_thread::sleep_for(std::chrono::seconds(1));
  3533. Client cli("localhost", PORT);
  3534. cli.set_keep_alive(true);
  3535. cli.set_read_timeout(std::chrono::seconds(1));
  3536. auto resa = cli.Get("/a");
  3537. ASSERT_FALSE(resa);
  3538. EXPECT_EQ(Error::Read, resa.error());
  3539. auto resb = cli.Get("/b");
  3540. ASSERT_TRUE(resb);
  3541. EXPECT_EQ(200, resb->status);
  3542. EXPECT_EQ("b", resb->body);
  3543. }
  3544. TEST(KeepAliveTest, Issue1041) {
  3545. Server svr;
  3546. svr.set_keep_alive_timeout(3);
  3547. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3548. res.set_content("Hello World!", "text/plain");
  3549. });
  3550. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3551. auto se = detail::scope_exit([&] {
  3552. svr.stop();
  3553. listen_thread.join();
  3554. ASSERT_FALSE(svr.is_running());
  3555. });
  3556. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3557. Client cli(HOST, PORT);
  3558. cli.set_keep_alive(true);
  3559. auto result = cli.Get("/hi");
  3560. ASSERT_TRUE(result);
  3561. EXPECT_EQ(200, result->status);
  3562. std::this_thread::sleep_for(std::chrono::seconds(5));
  3563. result = cli.Get("/hi");
  3564. ASSERT_TRUE(result);
  3565. EXPECT_EQ(200, result->status);
  3566. }
  3567. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3568. TEST(KeepAliveTest, SSLClientReconnection) {
  3569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3570. ASSERT_TRUE(svr.is_valid());
  3571. svr.set_keep_alive_timeout(1);
  3572. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3573. res.set_content("Hello World!", "text/plain");
  3574. });
  3575. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3576. auto se = detail::scope_exit([&] {
  3577. svr.stop();
  3578. listen_thread.join();
  3579. ASSERT_FALSE(svr.is_running());
  3580. });
  3581. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3582. SSLClient cli(HOST, PORT);
  3583. cli.enable_server_certificate_verification(false);
  3584. cli.set_keep_alive(true);
  3585. auto result = cli.Get("/hi");
  3586. ASSERT_TRUE(result);
  3587. EXPECT_EQ(200, result->status);
  3588. result = cli.Get("/hi");
  3589. ASSERT_TRUE(result);
  3590. EXPECT_EQ(200, result->status);
  3591. std::this_thread::sleep_for(std::chrono::seconds(2));
  3592. // Recoonect
  3593. result = cli.Get("/hi");
  3594. ASSERT_TRUE(result);
  3595. EXPECT_EQ(200, result->status);
  3596. result = cli.Get("/hi");
  3597. ASSERT_TRUE(result);
  3598. EXPECT_EQ(200, result->status);
  3599. }
  3600. #endif
  3601. TEST(ClientProblemDetectionTest, ContentProvider) {
  3602. Server svr;
  3603. size_t content_length = 1024 * 1024;
  3604. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3605. res.set_content_provider(
  3606. content_length, "text/plain",
  3607. [&](size_t offset, size_t length, DataSink &sink) {
  3608. auto out_len = std::min(length, static_cast<size_t>(1024));
  3609. std::string out(out_len, '@');
  3610. sink.write(out.data(), out_len);
  3611. return offset < 4096;
  3612. },
  3613. [](bool success) { ASSERT_FALSE(success); });
  3614. });
  3615. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3616. auto se = detail::scope_exit([&] {
  3617. svr.stop();
  3618. listen_thread.join();
  3619. ASSERT_FALSE(svr.is_running());
  3620. });
  3621. while (!svr.is_running()) {
  3622. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3623. }
  3624. // Give GET time to get a few messages.
  3625. std::this_thread::sleep_for(std::chrono::seconds(1));
  3626. Client cli("localhost", PORT);
  3627. auto res = cli.Get("/hi", [&](const char * /*data*/, size_t /*data_length*/) {
  3628. return false;
  3629. });
  3630. ASSERT_FALSE(res);
  3631. }
  3632. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3633. Server svr;
  3634. svr.set_error_handler([](Request const &, Response &res) -> void {
  3635. res.set_chunked_content_provider(
  3636. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3637. sink.os << "hello";
  3638. sink.os << "world";
  3639. sink.done();
  3640. return true;
  3641. });
  3642. });
  3643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3644. auto se = detail::scope_exit([&] {
  3645. svr.stop();
  3646. listen_thread.join();
  3647. ASSERT_FALSE(svr.is_running());
  3648. });
  3649. while (!svr.is_running()) {
  3650. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3651. }
  3652. // Give GET time to get a few messages.
  3653. std::this_thread::sleep_for(std::chrono::seconds(1));
  3654. Client cli("localhost", PORT);
  3655. auto res = cli.Get("/");
  3656. ASSERT_TRUE(res);
  3657. EXPECT_EQ(404, res->status);
  3658. EXPECT_EQ("helloworld", res->body);
  3659. }
  3660. TEST(GetWithParametersTest, GetWithParameters) {
  3661. Server svr;
  3662. svr.Get("/", [&](const Request &req, Response &) {
  3663. EXPECT_EQ("world", req.get_param_value("hello"));
  3664. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3665. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3666. });
  3667. svr.Get("/params", [&](const Request &req, Response &) {
  3668. EXPECT_EQ("world", req.get_param_value("hello"));
  3669. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3670. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3671. });
  3672. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3673. EXPECT_EQ("resource-id", req.matches[1]);
  3674. EXPECT_EQ("foo", req.get_param_value("param1"));
  3675. EXPECT_EQ("bar", req.get_param_value("param2"));
  3676. });
  3677. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3678. auto se = detail::scope_exit([&] {
  3679. svr.stop();
  3680. listen_thread.join();
  3681. ASSERT_FALSE(svr.is_running());
  3682. });
  3683. while (!svr.is_running()) {
  3684. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3685. }
  3686. std::this_thread::sleep_for(std::chrono::seconds(1));
  3687. {
  3688. Client cli(HOST, PORT);
  3689. Params params;
  3690. params.emplace("hello", "world");
  3691. params.emplace("hello2", "world2");
  3692. params.emplace("hello3", "world3");
  3693. auto res = cli.Get("/", params, Headers{});
  3694. ASSERT_TRUE(res);
  3695. EXPECT_EQ(200, res->status);
  3696. }
  3697. {
  3698. Client cli(HOST, PORT);
  3699. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(200, res->status);
  3702. }
  3703. {
  3704. Client cli(HOST, PORT);
  3705. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3706. ASSERT_TRUE(res);
  3707. EXPECT_EQ(200, res->status);
  3708. }
  3709. }
  3710. TEST(GetWithParametersTest, GetWithParameters2) {
  3711. Server svr;
  3712. svr.Get("/", [&](const Request &req, Response &res) {
  3713. auto text = req.get_param_value("hello");
  3714. res.set_content(text, "text/plain");
  3715. });
  3716. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3717. auto se = detail::scope_exit([&] {
  3718. svr.stop();
  3719. listen_thread.join();
  3720. ASSERT_FALSE(svr.is_running());
  3721. });
  3722. while (!svr.is_running()) {
  3723. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3724. }
  3725. std::this_thread::sleep_for(std::chrono::seconds(1));
  3726. Client cli("localhost", PORT);
  3727. Params params;
  3728. params.emplace("hello", "world");
  3729. std::string body;
  3730. auto res = cli.Get("/", params, Headers{},
  3731. [&](const char *data, size_t data_length) {
  3732. body.append(data, data_length);
  3733. return true;
  3734. });
  3735. ASSERT_TRUE(res);
  3736. EXPECT_EQ(200, res->status);
  3737. EXPECT_EQ("world", body);
  3738. }
  3739. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3740. Client cli("httpbin.org");
  3741. cli.set_default_headers({make_range_header({{1, 10}})});
  3742. cli.set_connection_timeout(5);
  3743. {
  3744. auto res = cli.Get("/range/32");
  3745. ASSERT_TRUE(res);
  3746. EXPECT_EQ("bcdefghijk", res->body);
  3747. EXPECT_EQ(206, res->status);
  3748. }
  3749. {
  3750. auto res = cli.Get("/range/32");
  3751. ASSERT_TRUE(res);
  3752. EXPECT_EQ("bcdefghijk", res->body);
  3753. EXPECT_EQ(206, res->status);
  3754. }
  3755. }
  3756. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3757. Server svr;
  3758. svr.set_default_headers({{"Hello", "World"}});
  3759. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3760. res.set_content("ok", "text/plain");
  3761. });
  3762. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3763. auto se = detail::scope_exit([&] {
  3764. svr.stop();
  3765. listen_thread.join();
  3766. ASSERT_FALSE(svr.is_running());
  3767. });
  3768. while (!svr.is_running()) {
  3769. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3770. }
  3771. std::this_thread::sleep_for(std::chrono::seconds(1));
  3772. Client cli("localhost", PORT);
  3773. auto res = cli.Get("/");
  3774. ASSERT_TRUE(res);
  3775. EXPECT_EQ(200, res->status);
  3776. EXPECT_EQ("ok", res->body);
  3777. EXPECT_EQ("World", res->get_header_value("Hello"));
  3778. }
  3779. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3780. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3782. ASSERT_TRUE(svr.is_valid());
  3783. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3784. std::this_thread::sleep_for(std::chrono::seconds(2));
  3785. res.set_content("a", "text/plain");
  3786. });
  3787. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3788. res.set_content("b", "text/plain");
  3789. });
  3790. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3791. auto se = detail::scope_exit([&] {
  3792. svr.stop();
  3793. listen_thread.join();
  3794. ASSERT_FALSE(svr.is_running());
  3795. });
  3796. while (!svr.is_running()) {
  3797. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3798. }
  3799. // Give GET time to get a few messages.
  3800. std::this_thread::sleep_for(std::chrono::seconds(1));
  3801. SSLClient cli("localhost", PORT);
  3802. cli.enable_server_certificate_verification(false);
  3803. cli.set_keep_alive(true);
  3804. cli.set_read_timeout(std::chrono::seconds(1));
  3805. auto resa = cli.Get("/a");
  3806. ASSERT_TRUE(!resa);
  3807. EXPECT_EQ(Error::Read, resa.error());
  3808. auto resb = cli.Get("/b");
  3809. ASSERT_TRUE(resb);
  3810. EXPECT_EQ(200, resb->status);
  3811. EXPECT_EQ("b", resb->body);
  3812. }
  3813. #endif
  3814. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3815. protected:
  3816. ServerTestWithAI_PASSIVE()
  3817. : cli_(HOST, PORT)
  3818. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3819. ,
  3820. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3821. #endif
  3822. {
  3823. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3824. cli_.enable_server_certificate_verification(false);
  3825. #endif
  3826. }
  3827. virtual void SetUp() {
  3828. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3829. res.set_content("Hello World!", "text/plain");
  3830. });
  3831. t_ = thread(
  3832. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  3833. while (!svr_.is_running()) {
  3834. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3835. }
  3836. }
  3837. virtual void TearDown() {
  3838. svr_.stop();
  3839. t_.join();
  3840. }
  3841. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3842. SSLClient cli_;
  3843. SSLServer svr_;
  3844. #else
  3845. Client cli_;
  3846. Server svr_;
  3847. #endif
  3848. thread t_;
  3849. };
  3850. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3851. auto res = cli_.Get("/hi");
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(200, res->status);
  3854. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3855. EXPECT_EQ("Hello World!", res->body);
  3856. }
  3857. class ServerUpDownTest : public ::testing::Test {
  3858. protected:
  3859. ServerUpDownTest() : cli_(HOST, PORT) {}
  3860. virtual void SetUp() {
  3861. t_ = thread([&]() {
  3862. svr_.bind_to_any_port(HOST);
  3863. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3864. ASSERT_TRUE(svr_.listen_after_bind());
  3865. });
  3866. while (!svr_.is_running()) {
  3867. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3868. }
  3869. }
  3870. virtual void TearDown() {
  3871. svr_.stop();
  3872. t_.join();
  3873. }
  3874. Client cli_;
  3875. Server svr_;
  3876. thread t_;
  3877. };
  3878. TEST_F(ServerUpDownTest, QuickStartStop) {
  3879. // Should not crash, especially when run with
  3880. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3881. }
  3882. class PayloadMaxLengthTest : public ::testing::Test {
  3883. protected:
  3884. PayloadMaxLengthTest()
  3885. : cli_(HOST, PORT)
  3886. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3887. ,
  3888. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3889. #endif
  3890. {
  3891. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3892. cli_.enable_server_certificate_verification(false);
  3893. #endif
  3894. }
  3895. virtual void SetUp() {
  3896. svr_.set_payload_max_length(8);
  3897. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  3898. res.set_content("test", "text/plain");
  3899. });
  3900. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3901. while (!svr_.is_running()) {
  3902. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3903. }
  3904. }
  3905. virtual void TearDown() {
  3906. svr_.stop();
  3907. t_.join();
  3908. }
  3909. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3910. SSLClient cli_;
  3911. SSLServer svr_;
  3912. #else
  3913. Client cli_;
  3914. Server svr_;
  3915. #endif
  3916. thread t_;
  3917. };
  3918. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  3919. auto res = cli_.Post("/test", "123456789", "text/plain");
  3920. ASSERT_TRUE(res);
  3921. EXPECT_EQ(413, res->status);
  3922. res = cli_.Post("/test", "12345678", "text/plain");
  3923. ASSERT_TRUE(res);
  3924. EXPECT_EQ(200, res->status);
  3925. }
  3926. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3927. TEST(SSLClientTest, UpdateCAStore) {
  3928. httplib::SSLClient httplib_client("www.google.com");
  3929. auto ca_store_1 = X509_STORE_new();
  3930. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  3931. nullptr);
  3932. httplib_client.set_ca_cert_store(ca_store_1);
  3933. auto ca_store_2 = X509_STORE_new();
  3934. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  3935. nullptr);
  3936. httplib_client.set_ca_cert_store(ca_store_2);
  3937. }
  3938. TEST(SSLClientTest, ServerNameIndication_Online) {
  3939. SSLClient cli("httpbin.org", 443);
  3940. auto res = cli.Get("/get");
  3941. ASSERT_TRUE(res);
  3942. ASSERT_EQ(200, res->status);
  3943. }
  3944. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  3945. Client cli("https://google.com");
  3946. auto res = cli.Get("/");
  3947. ASSERT_TRUE(res);
  3948. ASSERT_EQ(301, res->status);
  3949. }
  3950. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  3951. SSLClient cli("google.com");
  3952. cli.enable_server_certificate_verification(true);
  3953. cli.set_ca_cert_path("hello");
  3954. auto res = cli.Get("/");
  3955. ASSERT_TRUE(!res);
  3956. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  3957. }
  3958. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  3959. SSLClient cli("google.com");
  3960. cli.set_ca_cert_path(CA_CERT_FILE);
  3961. auto res = cli.Get("/");
  3962. ASSERT_TRUE(res);
  3963. ASSERT_EQ(301, res->status);
  3964. }
  3965. TEST(SSLClientTest, ServerCertificateVerification4) {
  3966. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3967. ASSERT_TRUE(svr.is_valid());
  3968. svr.Get("/test", [&](const Request &, Response &res) {
  3969. res.set_content("test", "text/plain");
  3970. svr.stop();
  3971. ASSERT_TRUE(true);
  3972. });
  3973. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3974. auto se = detail::scope_exit([&] {
  3975. t.join();
  3976. ASSERT_FALSE(svr.is_running());
  3977. });
  3978. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3979. SSLClient cli("127.0.0.1", PORT);
  3980. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3981. cli.enable_server_certificate_verification(true);
  3982. cli.set_connection_timeout(30);
  3983. auto res = cli.Get("/test");
  3984. ASSERT_TRUE(res);
  3985. ASSERT_EQ(200, res->status);
  3986. }
  3987. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  3988. SSLClient cli("www.youtube.com");
  3989. cli.set_ca_cert_path(CA_CERT_FILE);
  3990. cli.enable_server_certificate_verification(true);
  3991. cli.set_follow_location(true);
  3992. auto res = cli.Get("/");
  3993. ASSERT_TRUE(res);
  3994. ASSERT_EQ(200, res->status);
  3995. }
  3996. #if 0
  3997. TEST(SSLClientTest, SetInterfaceWithINET6) {
  3998. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  3999. ASSERT_TRUE(cli != nullptr);
  4000. cli->set_address_family(AF_INET6);
  4001. cli->set_interface("en0");
  4002. auto res = cli->Get("/get");
  4003. ASSERT_TRUE(res);
  4004. ASSERT_EQ(200, res->status);
  4005. }
  4006. #endif
  4007. TEST(SSLClientServerTest, ClientCertPresent) {
  4008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4009. CLIENT_CA_CERT_DIR);
  4010. ASSERT_TRUE(svr.is_valid());
  4011. svr.Get("/test", [&](const Request &req, Response &res) {
  4012. res.set_content("test", "text/plain");
  4013. svr.stop();
  4014. ASSERT_TRUE(true);
  4015. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4016. ASSERT_TRUE(peer_cert != nullptr);
  4017. auto subject_name = X509_get_subject_name(peer_cert);
  4018. ASSERT_TRUE(subject_name != nullptr);
  4019. std::string common_name;
  4020. {
  4021. char name[BUFSIZ];
  4022. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4023. name, sizeof(name));
  4024. common_name.assign(name, static_cast<size_t>(name_len));
  4025. }
  4026. EXPECT_EQ("Common Name", common_name);
  4027. X509_free(peer_cert);
  4028. });
  4029. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4030. auto se = detail::scope_exit([&] {
  4031. t.join();
  4032. ASSERT_FALSE(svr.is_running());
  4033. });
  4034. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4035. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4036. cli.enable_server_certificate_verification(false);
  4037. cli.set_connection_timeout(30);
  4038. auto res = cli.Get("/test");
  4039. ASSERT_TRUE(res);
  4040. ASSERT_EQ(200, res->status);
  4041. }
  4042. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  4043. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  4044. X509 *server_cert;
  4045. EVP_PKEY *server_private_key;
  4046. X509_STORE *client_ca_cert_store;
  4047. X509 *client_cert;
  4048. EVP_PKEY *client_private_key;
  4049. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  4050. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4051. fclose(f);
  4052. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  4053. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4054. fclose(f);
  4055. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  4056. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4057. client_ca_cert_store = X509_STORE_new();
  4058. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  4059. X509_free(client_cert);
  4060. fclose(f);
  4061. f = fopen(CLIENT_CERT_FILE, "r+");
  4062. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4063. fclose(f);
  4064. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  4065. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4066. fclose(f);
  4067. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  4068. ASSERT_TRUE(svr.is_valid());
  4069. svr.Get("/test", [&](const Request &req, Response &res) {
  4070. res.set_content("test", "text/plain");
  4071. svr.stop();
  4072. ASSERT_TRUE(true);
  4073. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4074. ASSERT_TRUE(peer_cert != nullptr);
  4075. auto subject_name = X509_get_subject_name(peer_cert);
  4076. ASSERT_TRUE(subject_name != nullptr);
  4077. std::string common_name;
  4078. {
  4079. char name[BUFSIZ];
  4080. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4081. name, sizeof(name));
  4082. common_name.assign(name, static_cast<size_t>(name_len));
  4083. }
  4084. EXPECT_EQ("Common Name", common_name);
  4085. X509_free(peer_cert);
  4086. });
  4087. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4088. auto se = detail::scope_exit([&] {
  4089. t.join();
  4090. ASSERT_FALSE(svr.is_running());
  4091. });
  4092. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4093. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  4094. cli.enable_server_certificate_verification(false);
  4095. cli.set_connection_timeout(30);
  4096. auto res = cli.Get("/test");
  4097. ASSERT_TRUE(res);
  4098. ASSERT_EQ(200, res->status);
  4099. X509_free(server_cert);
  4100. EVP_PKEY_free(server_private_key);
  4101. X509_free(client_cert);
  4102. EVP_PKEY_free(client_private_key);
  4103. }
  4104. #endif
  4105. TEST(SSLClientServerTest, ClientCertMissing) {
  4106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4107. CLIENT_CA_CERT_DIR);
  4108. ASSERT_TRUE(svr.is_valid());
  4109. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  4110. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. t.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4117. SSLClient cli(HOST, PORT);
  4118. auto res = cli.Get("/test");
  4119. cli.set_connection_timeout(30);
  4120. ASSERT_TRUE(!res);
  4121. EXPECT_EQ(Error::SSLServerVerification, res.error());
  4122. }
  4123. TEST(SSLClientServerTest, TrustDirOptional) {
  4124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4125. ASSERT_TRUE(svr.is_valid());
  4126. svr.Get("/test", [&](const Request &, Response &res) {
  4127. res.set_content("test", "text/plain");
  4128. svr.stop();
  4129. });
  4130. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4131. auto se = detail::scope_exit([&] {
  4132. t.join();
  4133. ASSERT_FALSE(svr.is_running());
  4134. });
  4135. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4136. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4137. cli.enable_server_certificate_verification(false);
  4138. cli.set_connection_timeout(30);
  4139. auto res = cli.Get("/test");
  4140. ASSERT_TRUE(res);
  4141. ASSERT_EQ(200, res->status);
  4142. }
  4143. TEST(SSLClientServerTest, SSLConnectTimeout) {
  4144. class NoListenSSLServer : public SSLServer {
  4145. public:
  4146. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  4147. const char *client_ca_cert_file_path,
  4148. const char *client_ca_cert_dir_path = nullptr)
  4149. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  4150. client_ca_cert_dir_path),
  4151. stop_(false) {}
  4152. bool stop_;
  4153. private:
  4154. bool process_and_close_socket(socket_t /*sock*/) override {
  4155. // Don't create SSL context
  4156. while (!stop_) {
  4157. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4158. }
  4159. return true;
  4160. }
  4161. };
  4162. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  4163. CLIENT_CA_CERT_FILE);
  4164. ASSERT_TRUE(svr.is_valid());
  4165. svr.Get("/test", [&](const Request &, Response &res) {
  4166. res.set_content("test", "text/plain");
  4167. });
  4168. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4169. auto se = detail::scope_exit([&] {
  4170. svr.stop_ = true;
  4171. svr.stop();
  4172. t.join();
  4173. ASSERT_FALSE(svr.is_running());
  4174. });
  4175. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4176. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4177. cli.enable_server_certificate_verification(false);
  4178. cli.set_connection_timeout(1);
  4179. auto res = cli.Get("/test");
  4180. ASSERT_TRUE(!res);
  4181. EXPECT_EQ(Error::SSLConnection, res.error());
  4182. }
  4183. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  4184. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  4185. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  4186. SSL_CTX_set_options(&ssl_ctx,
  4187. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4188. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  4189. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  4190. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  4191. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  4192. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  4193. "ECDHE-DSS-AES128-SHA256:"
  4194. "ECDHE-RSA-AES256-SHA256:"
  4195. "ECDHE-DSS-AES256-SHA256:";
  4196. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  4197. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  4198. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  4199. SSL_FILETYPE_PEM) != 1) {
  4200. return false;
  4201. }
  4202. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  4203. CLIENT_CA_CERT_DIR);
  4204. SSL_CTX_set_verify(
  4205. &ssl_ctx,
  4206. SSL_VERIFY_PEER |
  4207. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4208. nullptr);
  4209. return true;
  4210. };
  4211. SSLServer svr(setup_ssl_ctx_callback);
  4212. ASSERT_TRUE(svr.is_valid());
  4213. svr.Get("/test", [&](const Request &req, Response &res) {
  4214. res.set_content("test", "text/plain");
  4215. svr.stop();
  4216. ASSERT_TRUE(true);
  4217. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4218. ASSERT_TRUE(peer_cert != nullptr);
  4219. auto subject_name = X509_get_subject_name(peer_cert);
  4220. ASSERT_TRUE(subject_name != nullptr);
  4221. std::string common_name;
  4222. {
  4223. char name[BUFSIZ];
  4224. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4225. name, sizeof(name));
  4226. common_name.assign(name, static_cast<size_t>(name_len));
  4227. }
  4228. EXPECT_EQ("Common Name", common_name);
  4229. X509_free(peer_cert);
  4230. });
  4231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4232. auto se = detail::scope_exit([&] {
  4233. t.join();
  4234. ASSERT_FALSE(svr.is_running());
  4235. });
  4236. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4237. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4238. cli.enable_server_certificate_verification(false);
  4239. cli.set_connection_timeout(30);
  4240. auto res = cli.Get("/test");
  4241. ASSERT_TRUE(res);
  4242. ASSERT_EQ(200, res->status);
  4243. }
  4244. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  4245. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  4246. // prepare large data
  4247. std::random_device seed_gen;
  4248. std::mt19937 random(seed_gen());
  4249. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  4250. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  4251. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  4252. // server
  4253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4254. ASSERT_TRUE(svr.is_valid());
  4255. svr.Post("/binary", [&](const Request &req, Response &res) {
  4256. EXPECT_EQ(large_size_byte, req.body.size());
  4257. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  4258. res.set_content(req.body, "application/octet-stream");
  4259. });
  4260. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4261. auto se = detail::scope_exit([&] {
  4262. svr.stop();
  4263. listen_thread.join();
  4264. ASSERT_FALSE(svr.is_running());
  4265. });
  4266. while (!svr.is_running()) {
  4267. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4268. }
  4269. // client POST
  4270. SSLClient cli("localhost", PORT);
  4271. cli.enable_server_certificate_verification(false);
  4272. cli.set_read_timeout(std::chrono::seconds(100));
  4273. cli.set_write_timeout(std::chrono::seconds(100));
  4274. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  4275. large_size_byte, "application/octet-stream");
  4276. // compare
  4277. EXPECT_EQ(200, res->status);
  4278. EXPECT_EQ(large_size_byte, res->body.size());
  4279. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  4280. }
  4281. #endif
  4282. #ifdef _WIN32
  4283. TEST(CleanupTest, WSACleanup) {
  4284. int ret = WSACleanup();
  4285. ASSERT_EQ(0, ret);
  4286. }
  4287. #endif
  4288. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  4289. TEST(NoSSLSupport, SimpleInterface) {
  4290. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  4291. }
  4292. #endif
  4293. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4294. TEST(InvalidScheme, SimpleInterface) {
  4295. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  4296. }
  4297. #endif
  4298. TEST(NoScheme, SimpleInterface) {
  4299. Client cli("yahoo.com:80");
  4300. ASSERT_TRUE(cli.is_valid());
  4301. }
  4302. TEST(SendAPI, SimpleInterface_Online) {
  4303. Client cli("http://yahoo.com");
  4304. Request req;
  4305. req.method = "GET";
  4306. req.path = "/";
  4307. auto res = cli.send(req);
  4308. ASSERT_TRUE(res);
  4309. EXPECT_EQ(301, res->status);
  4310. }
  4311. TEST(ClientImplMethods, GetSocketTest) {
  4312. httplib::Server svr;
  4313. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4314. res.status = 200;
  4315. });
  4316. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  4317. auto se = detail::scope_exit([&] {
  4318. svr.stop();
  4319. thread.join();
  4320. ASSERT_FALSE(svr.is_running());
  4321. });
  4322. while (!svr.is_running()) {
  4323. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  4324. }
  4325. {
  4326. httplib::Client cli("http://127.0.0.1:3333");
  4327. cli.set_keep_alive(true);
  4328. // Use the behavior of cpp-httplib of opening the connection
  4329. // only when the first request happens. If that changes,
  4330. // this test would be obsolete.
  4331. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  4332. // This also implicitly tests the server. But other tests would fail much
  4333. // earlier than this one to be considered.
  4334. auto res = cli.Get("/");
  4335. ASSERT_TRUE(res);
  4336. EXPECT_EQ(200, res->status);
  4337. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  4338. }
  4339. }
  4340. // Disabled due to out-of-memory problem on GitHub Actions
  4341. #ifdef _WIN64
  4342. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  4343. // allocate content size larger than 2GB in memory
  4344. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  4345. char *content = (char *)malloc(content_size);
  4346. ASSERT_TRUE(content);
  4347. Server svr;
  4348. svr.Get("/foo", [=](const httplib::Request &req, httplib::Response &resp) {
  4349. resp.set_content(content, content_size, "application/octet-stream");
  4350. });
  4351. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4352. auto se = detail::scope_exit([&] {
  4353. svr.stop();
  4354. listen_thread.join();
  4355. if (content) free(content);
  4356. ASSERT_FALSE(svr.is_running());
  4357. });
  4358. while (!svr.is_running()) {
  4359. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4360. }
  4361. // Give GET time to get a few messages.
  4362. std::this_thread::sleep_for(std::chrono::seconds(1));
  4363. Client cli(HOST, PORT);
  4364. auto res = cli.Get("/foo");
  4365. ASSERT_TRUE(res);
  4366. EXPECT_EQ(200, res->status);
  4367. EXPECT_EQ(content_size, res->body.length());
  4368. }
  4369. #endif
  4370. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4371. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  4372. Client cli("http://yahoo.com");
  4373. auto res = cli.Get("/");
  4374. ASSERT_TRUE(res);
  4375. EXPECT_EQ(301, res->status);
  4376. cli.set_follow_location(true);
  4377. res = cli.Get("/");
  4378. ASSERT_TRUE(res);
  4379. EXPECT_EQ(200, res->status);
  4380. EXPECT_EQ("https://yahoo.com/", res->location);
  4381. }
  4382. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  4383. Client cli("https://yahoo.com");
  4384. auto res = cli.Get("/");
  4385. ASSERT_TRUE(res);
  4386. EXPECT_EQ(301, res->status);
  4387. cli.set_follow_location(true);
  4388. res = cli.Get("/");
  4389. ASSERT_TRUE(res);
  4390. EXPECT_EQ(200, res->status);
  4391. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4392. }
  4393. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  4394. Client cli("https://yahoo.com");
  4395. auto res = cli.Get("/");
  4396. ASSERT_TRUE(res);
  4397. ASSERT_FALSE(!res);
  4398. ASSERT_TRUE(res);
  4399. ASSERT_FALSE(res == nullptr);
  4400. ASSERT_TRUE(res != nullptr);
  4401. EXPECT_EQ(Error::Success, res.error());
  4402. EXPECT_EQ(301, res.value().status);
  4403. EXPECT_EQ(301, (*res).status);
  4404. EXPECT_EQ(301, res->status);
  4405. cli.set_follow_location(true);
  4406. res = cli.Get("/");
  4407. ASSERT_TRUE(res);
  4408. EXPECT_EQ(Error::Success, res.error());
  4409. EXPECT_EQ(200, res.value().status);
  4410. EXPECT_EQ(200, (*res).status);
  4411. EXPECT_EQ(200, res->status);
  4412. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4413. }
  4414. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4415. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  4416. Client cli("https://cdnjs.cloudflare.com");
  4417. auto res =
  4418. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  4419. ASSERT_TRUE(res);
  4420. EXPECT_EQ(200, res->status);
  4421. EXPECT_EQ(287630U, res->body.size());
  4422. EXPECT_EQ("application/javascript; charset=utf-8",
  4423. res->get_header_value("Content-Type"));
  4424. }
  4425. #endif
  4426. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  4427. Client cli("https://nghttp2.org");
  4428. cli.set_follow_location(true);
  4429. auto res =
  4430. cli.Get("/httpbin/"
  4431. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  4432. ASSERT_TRUE(res);
  4433. EXPECT_EQ(200, res->status);
  4434. }
  4435. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  4436. Client cli("https://nghttp2.org");
  4437. cli.set_follow_location(true);
  4438. Params params;
  4439. params.emplace("url", "http://www.google.com");
  4440. params.emplace("status_code", "302");
  4441. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  4442. ASSERT_TRUE(res);
  4443. EXPECT_EQ(200, res->status);
  4444. }
  4445. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4446. Client cli("https://nghttp2.org");
  4447. cli.set_follow_location(true);
  4448. Params params;
  4449. params.emplace("url", "http://www.google.com");
  4450. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4451. ASSERT_TRUE(res);
  4452. EXPECT_EQ(200, res->status);
  4453. }
  4454. TEST(HttpToHttpsRedirectTest, CertFile) {
  4455. Server svr;
  4456. ASSERT_TRUE(svr.is_valid());
  4457. svr.Get("/index", [&](const Request &, Response &res) {
  4458. res.set_redirect("https://127.0.0.1:1235/index");
  4459. svr.stop();
  4460. });
  4461. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4462. ASSERT_TRUE(ssl_svr.is_valid());
  4463. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4464. res.set_content("test", "text/plain");
  4465. ssl_svr.stop();
  4466. });
  4467. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4468. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4469. auto se = detail::scope_exit([&] {
  4470. t2.join();
  4471. t.join();
  4472. ASSERT_FALSE(svr.is_running());
  4473. });
  4474. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4475. Client cli("127.0.0.1", PORT);
  4476. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4477. cli.enable_server_certificate_verification(true);
  4478. cli.set_follow_location(true);
  4479. cli.set_connection_timeout(30);
  4480. auto res = cli.Get("/index");
  4481. ASSERT_TRUE(res);
  4482. ASSERT_EQ(200, res->status);
  4483. }
  4484. TEST(MultipartFormDataTest, LargeData) {
  4485. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4486. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4487. const ContentReader &content_reader) {
  4488. if (req.is_multipart_form_data()) {
  4489. MultipartFormDataItems files;
  4490. content_reader(
  4491. [&](const MultipartFormData &file) {
  4492. files.push_back(file);
  4493. return true;
  4494. },
  4495. [&](const char *data, size_t data_length) {
  4496. files.back().content.append(data, data_length);
  4497. return true;
  4498. });
  4499. EXPECT_TRUE(std::string(files[0].name) == "document");
  4500. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4501. EXPECT_TRUE(files[0].filename == "2MB_data");
  4502. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4503. EXPECT_TRUE(files[1].name == "hello");
  4504. EXPECT_TRUE(files[1].content == "world");
  4505. EXPECT_TRUE(files[1].filename == "");
  4506. EXPECT_TRUE(files[1].content_type == "");
  4507. } else {
  4508. std::string body;
  4509. content_reader([&](const char *data, size_t data_length) {
  4510. body.append(data, data_length);
  4511. return true;
  4512. });
  4513. }
  4514. });
  4515. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4516. auto se = detail::scope_exit([&] {
  4517. svr.stop();
  4518. t.join();
  4519. ASSERT_FALSE(svr.is_running());
  4520. });
  4521. while (!svr.is_running()) {
  4522. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4523. }
  4524. std::this_thread::sleep_for(std::chrono::seconds(1));
  4525. {
  4526. std::string data(1024 * 1024 * 2, '.');
  4527. std::stringstream buffer;
  4528. buffer << data;
  4529. Client cli("https://localhost:8080");
  4530. cli.enable_server_certificate_verification(false);
  4531. MultipartFormDataItems items{
  4532. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4533. {"hello", "world", "", ""},
  4534. };
  4535. auto res = cli.Post("/post", items);
  4536. ASSERT_TRUE(res);
  4537. ASSERT_EQ(200, res->status);
  4538. }
  4539. }
  4540. TEST(MultipartFormDataTest, DataProviderItems) {
  4541. std::random_device seed_gen;
  4542. std::mt19937 random(seed_gen());
  4543. std::string rand1;
  4544. rand1.resize(1000);
  4545. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  4546. std::string rand2;
  4547. rand2.resize(3000);
  4548. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  4549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4550. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  4551. const ContentReader &content_reader) {
  4552. ASSERT_FALSE(req.is_multipart_form_data());
  4553. std::string body;
  4554. content_reader([&](const char *data, size_t data_length) {
  4555. body.append(data, data_length);
  4556. return true;
  4557. });
  4558. EXPECT_EQ(body, "");
  4559. });
  4560. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  4561. const ContentReader &content_reader) {
  4562. ASSERT_TRUE(req.is_multipart_form_data());
  4563. MultipartFormDataItems files;
  4564. content_reader(
  4565. [&](const MultipartFormData &file) {
  4566. files.push_back(file);
  4567. return true;
  4568. },
  4569. [&](const char *data, size_t data_length) {
  4570. files.back().content.append(data, data_length);
  4571. return true;
  4572. });
  4573. ASSERT_TRUE(files.size() == 2);
  4574. EXPECT_EQ(std::string(files[0].name), "name1");
  4575. EXPECT_EQ(files[0].content, "Testing123");
  4576. EXPECT_EQ(files[0].filename, "filename1");
  4577. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4578. EXPECT_EQ(files[1].name, "name2");
  4579. EXPECT_EQ(files[1].content, "Testing456");
  4580. EXPECT_EQ(files[1].filename, "");
  4581. EXPECT_EQ(files[1].content_type, "");
  4582. });
  4583. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  4584. const ContentReader &content_reader) {
  4585. ASSERT_TRUE(req.is_multipart_form_data());
  4586. MultipartFormDataItems files;
  4587. content_reader(
  4588. [&](const MultipartFormData &file) {
  4589. files.push_back(file);
  4590. return true;
  4591. },
  4592. [&](const char *data, size_t data_length) {
  4593. files.back().content.append(data, data_length);
  4594. return true;
  4595. });
  4596. ASSERT_TRUE(files.size() == 2);
  4597. EXPECT_EQ(files[0].name, "name3");
  4598. EXPECT_EQ(files[0].content, rand1);
  4599. EXPECT_EQ(files[0].filename, "filename3");
  4600. EXPECT_EQ(files[0].content_type, "");
  4601. EXPECT_EQ(files[1].name, "name4");
  4602. EXPECT_EQ(files[1].content, rand2);
  4603. EXPECT_EQ(files[1].filename, "filename4");
  4604. EXPECT_EQ(files[1].content_type, "");
  4605. });
  4606. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  4607. const ContentReader &content_reader) {
  4608. ASSERT_TRUE(req.is_multipart_form_data());
  4609. MultipartFormDataItems files;
  4610. content_reader(
  4611. [&](const MultipartFormData &file) {
  4612. files.push_back(file);
  4613. return true;
  4614. },
  4615. [&](const char *data, size_t data_length) {
  4616. files.back().content.append(data, data_length);
  4617. return true;
  4618. });
  4619. ASSERT_TRUE(files.size() == 4);
  4620. EXPECT_EQ(std::string(files[0].name), "name1");
  4621. EXPECT_EQ(files[0].content, "Testing123");
  4622. EXPECT_EQ(files[0].filename, "filename1");
  4623. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4624. EXPECT_EQ(files[1].name, "name2");
  4625. EXPECT_EQ(files[1].content, "Testing456");
  4626. EXPECT_EQ(files[1].filename, "");
  4627. EXPECT_EQ(files[1].content_type, "");
  4628. EXPECT_EQ(files[2].name, "name3");
  4629. EXPECT_EQ(files[2].content, rand1);
  4630. EXPECT_EQ(files[2].filename, "filename3");
  4631. EXPECT_EQ(files[2].content_type, "");
  4632. EXPECT_EQ(files[3].name, "name4");
  4633. EXPECT_EQ(files[3].content, rand2);
  4634. EXPECT_EQ(files[3].filename, "filename4");
  4635. EXPECT_EQ(files[3].content_type, "");
  4636. });
  4637. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4638. auto se = detail::scope_exit([&] {
  4639. svr.stop();
  4640. t.join();
  4641. ASSERT_FALSE(svr.is_running());
  4642. });
  4643. while (!svr.is_running()) {
  4644. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4645. }
  4646. std::this_thread::sleep_for(std::chrono::seconds(1));
  4647. {
  4648. Client cli("https://localhost:8080");
  4649. cli.enable_server_certificate_verification(false);
  4650. MultipartFormDataItems items{
  4651. {"name1", "Testing123", "filename1", "application/octet-stream"},
  4652. {"name2", "Testing456", "", ""}, // not a file
  4653. };
  4654. {
  4655. auto res = cli.Post("/post-none", {}, {}, {});
  4656. ASSERT_TRUE(res);
  4657. ASSERT_EQ(200, res->status);
  4658. }
  4659. MultipartFormDataProviderItems providers;
  4660. {
  4661. auto res =
  4662. cli.Post("/post-items", {}, items, providers); // empty providers
  4663. ASSERT_TRUE(res);
  4664. ASSERT_EQ(200, res->status);
  4665. }
  4666. providers.push_back({"name3",
  4667. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4668. // test the offset is given correctly at each step
  4669. if (!offset)
  4670. sink.os.write(rand1.data(), 30);
  4671. else if (offset == 30)
  4672. sink.os.write(rand1.data() + 30, 300);
  4673. else if (offset == 330)
  4674. sink.os.write(rand1.data() + 330, 670);
  4675. else if (offset == rand1.size())
  4676. sink.done();
  4677. return true;
  4678. },
  4679. "filename3",
  4680. {}});
  4681. providers.push_back({"name4",
  4682. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4683. // test the offset is given correctly at each step
  4684. if (!offset)
  4685. sink.os.write(rand2.data(), 2000);
  4686. else if (offset == 2000)
  4687. sink.os.write(rand2.data() + 2000, 1);
  4688. else if (offset == 2001)
  4689. sink.os.write(rand2.data() + 2001, 999);
  4690. else if (offset == rand2.size())
  4691. sink.done();
  4692. return true;
  4693. },
  4694. "filename4",
  4695. {}});
  4696. {
  4697. auto res = cli.Post("/post-providers", {}, {}, providers);
  4698. ASSERT_TRUE(res);
  4699. ASSERT_EQ(200, res->status);
  4700. }
  4701. {
  4702. auto res = cli.Post("/post-both", {}, items, providers);
  4703. ASSERT_TRUE(res);
  4704. ASSERT_EQ(200, res->status);
  4705. }
  4706. }
  4707. }
  4708. TEST(MultipartFormDataTest, BadHeader) {
  4709. Server svr;
  4710. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4711. res.set_content("ok", "text/plain");
  4712. });
  4713. thread t = thread([&] { svr.listen(HOST, PORT); });
  4714. auto se = detail::scope_exit([&] {
  4715. svr.stop();
  4716. t.join();
  4717. ASSERT_FALSE(svr.is_running());
  4718. });
  4719. while (!svr.is_running()) {
  4720. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4721. }
  4722. const std::string body =
  4723. "This is the preamble. It is to be ignored, though it\r\n"
  4724. "is a handy place for composition agents to include an\r\n"
  4725. "explanatory note to non-MIME conformant readers.\r\n"
  4726. "\r\n"
  4727. "\r\n"
  4728. "--simple boundary\r\n"
  4729. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4730. ": BAD...\r\n"
  4731. "\r\n"
  4732. "value1\r\n"
  4733. "--simple boundary\r\n"
  4734. "Content-Disposition: form-data; name=\"field2\"; "
  4735. "filename=\"example.txt\"\r\n"
  4736. "\r\n"
  4737. "value2\r\n"
  4738. "--simple boundary--\r\n"
  4739. "This is the epilogue. It is also to be ignored.\r\n";
  4740. std::string content_type =
  4741. R"(multipart/form-data; boundary="simple boundary")";
  4742. Client cli(HOST, PORT);
  4743. auto res = cli.Post("/post", body, content_type.c_str());
  4744. ASSERT_TRUE(res);
  4745. EXPECT_EQ(400, res->status);
  4746. }
  4747. TEST(MultipartFormDataTest, WithPreamble) {
  4748. Server svr;
  4749. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4750. res.set_content("ok", "text/plain");
  4751. });
  4752. thread t = thread([&] { svr.listen(HOST, PORT); });
  4753. auto se = detail::scope_exit([&] {
  4754. svr.stop();
  4755. t.join();
  4756. ASSERT_FALSE(svr.is_running());
  4757. });
  4758. while (!svr.is_running()) {
  4759. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4760. }
  4761. const std::string body =
  4762. "This is the preamble. It is to be ignored, though it\r\n"
  4763. "is a handy place for composition agents to include an\r\n"
  4764. "explanatory note to non-MIME conformant readers.\r\n"
  4765. "\r\n"
  4766. "\r\n"
  4767. "--simple boundary\r\n"
  4768. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4769. "\r\n"
  4770. "value1\r\n"
  4771. "--simple boundary\r\n"
  4772. "Content-Disposition: form-data; name=\"field2\"; "
  4773. "filename=\"example.txt\"\r\n"
  4774. "\r\n"
  4775. "value2\r\n"
  4776. "--simple boundary--\r\n"
  4777. "This is the epilogue. It is also to be ignored.\r\n";
  4778. std::string content_type =
  4779. R"(multipart/form-data; boundary="simple boundary")";
  4780. Client cli(HOST, PORT);
  4781. auto res = cli.Post("/post", body, content_type.c_str());
  4782. ASSERT_TRUE(res);
  4783. EXPECT_EQ(200, res->status);
  4784. }
  4785. TEST(MultipartFormDataTest, PostCustomBoundary) {
  4786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4787. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  4788. const ContentReader &content_reader) {
  4789. if (req.is_multipart_form_data()) {
  4790. MultipartFormDataItems files;
  4791. content_reader(
  4792. [&](const MultipartFormData &file) {
  4793. files.push_back(file);
  4794. return true;
  4795. },
  4796. [&](const char *data, size_t data_length) {
  4797. files.back().content.append(data, data_length);
  4798. return true;
  4799. });
  4800. EXPECT_TRUE(std::string(files[0].name) == "document");
  4801. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4802. EXPECT_TRUE(files[0].filename == "2MB_data");
  4803. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4804. EXPECT_TRUE(files[1].name == "hello");
  4805. EXPECT_TRUE(files[1].content == "world");
  4806. EXPECT_TRUE(files[1].filename == "");
  4807. EXPECT_TRUE(files[1].content_type == "");
  4808. } else {
  4809. std::string body;
  4810. content_reader([&](const char *data, size_t data_length) {
  4811. body.append(data, data_length);
  4812. return true;
  4813. });
  4814. }
  4815. });
  4816. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4817. auto se = detail::scope_exit([&] {
  4818. svr.stop();
  4819. t.join();
  4820. ASSERT_FALSE(svr.is_running());
  4821. });
  4822. while (!svr.is_running()) {
  4823. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4824. }
  4825. std::this_thread::sleep_for(std::chrono::seconds(1));
  4826. {
  4827. std::string data(1024 * 1024 * 2, '.');
  4828. std::stringstream buffer;
  4829. buffer << data;
  4830. Client cli("https://localhost:8080");
  4831. cli.enable_server_certificate_verification(false);
  4832. MultipartFormDataItems items{
  4833. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4834. {"hello", "world", "", ""},
  4835. };
  4836. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  4837. ASSERT_TRUE(res);
  4838. ASSERT_EQ(200, res->status);
  4839. }
  4840. }
  4841. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  4842. std::this_thread::sleep_for(std::chrono::seconds(1));
  4843. std::string data(1024 * 1024 * 2, '&');
  4844. std::stringstream buffer;
  4845. buffer << data;
  4846. Client cli("https://localhost:8080");
  4847. MultipartFormDataItems items{
  4848. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4849. {"hello", "world", "", ""},
  4850. };
  4851. for (const char &c : " \t\r\n") {
  4852. auto res =
  4853. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  4854. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  4855. ASSERT_FALSE(res);
  4856. }
  4857. }
  4858. TEST(MultipartFormDataTest, PutFormData) {
  4859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4860. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  4861. const ContentReader &content_reader) {
  4862. if (req.is_multipart_form_data()) {
  4863. MultipartFormDataItems files;
  4864. content_reader(
  4865. [&](const MultipartFormData &file) {
  4866. files.push_back(file);
  4867. return true;
  4868. },
  4869. [&](const char *data, size_t data_length) {
  4870. files.back().content.append(data, data_length);
  4871. return true;
  4872. });
  4873. EXPECT_TRUE(std::string(files[0].name) == "document");
  4874. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4875. EXPECT_TRUE(files[0].filename == "2MB_data");
  4876. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4877. EXPECT_TRUE(files[1].name == "hello");
  4878. EXPECT_TRUE(files[1].content == "world");
  4879. EXPECT_TRUE(files[1].filename == "");
  4880. EXPECT_TRUE(files[1].content_type == "");
  4881. } else {
  4882. std::string body;
  4883. content_reader([&](const char *data, size_t data_length) {
  4884. body.append(data, data_length);
  4885. return true;
  4886. });
  4887. }
  4888. });
  4889. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4890. auto se = detail::scope_exit([&] {
  4891. svr.stop();
  4892. t.join();
  4893. ASSERT_FALSE(svr.is_running());
  4894. });
  4895. while (!svr.is_running()) {
  4896. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4897. }
  4898. std::this_thread::sleep_for(std::chrono::seconds(1));
  4899. {
  4900. std::string data(1024 * 1024 * 2, '&');
  4901. std::stringstream buffer;
  4902. buffer << data;
  4903. Client cli("https://localhost:8080");
  4904. cli.enable_server_certificate_verification(false);
  4905. MultipartFormDataItems items{
  4906. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4907. {"hello", "world", "", ""},
  4908. };
  4909. auto res = cli.Put("/put", items);
  4910. ASSERT_TRUE(res);
  4911. ASSERT_EQ(200, res->status);
  4912. }
  4913. }
  4914. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  4915. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4916. svr.Put("/put_customboundary",
  4917. [&](const Request &req, const Response & /*res*/,
  4918. const ContentReader &content_reader) {
  4919. if (req.is_multipart_form_data()) {
  4920. MultipartFormDataItems files;
  4921. content_reader(
  4922. [&](const MultipartFormData &file) {
  4923. files.push_back(file);
  4924. return true;
  4925. },
  4926. [&](const char *data, size_t data_length) {
  4927. files.back().content.append(data, data_length);
  4928. return true;
  4929. });
  4930. EXPECT_TRUE(std::string(files[0].name) == "document");
  4931. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4932. EXPECT_TRUE(files[0].filename == "2MB_data");
  4933. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4934. EXPECT_TRUE(files[1].name == "hello");
  4935. EXPECT_TRUE(files[1].content == "world");
  4936. EXPECT_TRUE(files[1].filename == "");
  4937. EXPECT_TRUE(files[1].content_type == "");
  4938. } else {
  4939. std::string body;
  4940. content_reader([&](const char *data, size_t data_length) {
  4941. body.append(data, data_length);
  4942. return true;
  4943. });
  4944. }
  4945. });
  4946. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4947. auto se = detail::scope_exit([&] {
  4948. svr.stop();
  4949. t.join();
  4950. ASSERT_FALSE(svr.is_running());
  4951. });
  4952. while (!svr.is_running()) {
  4953. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4954. }
  4955. std::this_thread::sleep_for(std::chrono::seconds(1));
  4956. {
  4957. std::string data(1024 * 1024 * 2, '&');
  4958. std::stringstream buffer;
  4959. buffer << data;
  4960. Client cli("https://localhost:8080");
  4961. cli.enable_server_certificate_verification(false);
  4962. MultipartFormDataItems items{
  4963. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4964. {"hello", "world", "", ""},
  4965. };
  4966. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  4967. ASSERT_TRUE(res);
  4968. ASSERT_EQ(200, res->status);
  4969. }
  4970. }
  4971. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  4972. std::this_thread::sleep_for(std::chrono::seconds(1));
  4973. std::string data(1024 * 1024 * 2, '&');
  4974. std::stringstream buffer;
  4975. buffer << data;
  4976. Client cli("https://localhost:8080");
  4977. cli.enable_server_certificate_verification(false);
  4978. MultipartFormDataItems items{
  4979. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4980. {"hello", "world", "", ""},
  4981. };
  4982. for (const char &c : " \t\r\n") {
  4983. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  4984. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  4985. ASSERT_FALSE(res);
  4986. }
  4987. }
  4988. #endif
  4989. #ifndef _WIN32
  4990. class UnixSocketTest : public ::testing::Test {
  4991. protected:
  4992. void TearDown() override { std::remove(pathname_.c_str()); }
  4993. void client_GET(const std::string &addr) {
  4994. httplib::Client cli{addr};
  4995. cli.set_address_family(AF_UNIX);
  4996. ASSERT_TRUE(cli.is_valid());
  4997. const auto &result = cli.Get(pattern_);
  4998. ASSERT_TRUE(result) << "error: " << result.error();
  4999. const auto &resp = result.value();
  5000. EXPECT_EQ(resp.status, 200);
  5001. EXPECT_EQ(resp.body, content_);
  5002. }
  5003. const std::string pathname_{"./httplib-server.sock"};
  5004. const std::string pattern_{"/hi"};
  5005. const std::string content_{"Hello World!"};
  5006. };
  5007. TEST_F(UnixSocketTest, pathname) {
  5008. httplib::Server svr;
  5009. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5010. res.set_content(content_, "text/plain");
  5011. });
  5012. std::thread t{[&] {
  5013. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5014. }};
  5015. auto se = detail::scope_exit([&] {
  5016. svr.stop();
  5017. t.join();
  5018. ASSERT_FALSE(svr.is_running());
  5019. });
  5020. while (!svr.is_running()) {
  5021. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  5022. }
  5023. ASSERT_TRUE(svr.is_running());
  5024. client_GET(pathname_);
  5025. }
  5026. #if defined(__linux__) || \
  5027. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  5028. TEST_F(UnixSocketTest, PeerPid) {
  5029. httplib::Server svr;
  5030. std::string remote_port_val;
  5031. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  5032. res.set_content(content_, "text/plain");
  5033. remote_port_val = req.get_header_value("REMOTE_PORT");
  5034. });
  5035. std::thread t{[&] {
  5036. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5037. }};
  5038. auto se = detail::scope_exit([&] {
  5039. svr.stop();
  5040. t.join();
  5041. ASSERT_FALSE(svr.is_running());
  5042. });
  5043. while (!svr.is_running()) {
  5044. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  5045. }
  5046. ASSERT_TRUE(svr.is_running());
  5047. client_GET(pathname_);
  5048. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  5049. }
  5050. #endif
  5051. #ifdef __linux__
  5052. TEST_F(UnixSocketTest, abstract) {
  5053. constexpr char svr_path[]{"\x00httplib-server.sock"};
  5054. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  5055. httplib::Server svr;
  5056. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5057. res.set_content(content_, "text/plain");
  5058. });
  5059. std::thread t{[&] {
  5060. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  5061. }};
  5062. auto se = detail::scope_exit([&] {
  5063. svr.stop();
  5064. t.join();
  5065. ASSERT_FALSE(svr.is_running());
  5066. });
  5067. while (!svr.is_running()) {
  5068. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  5069. }
  5070. ASSERT_TRUE(svr.is_running());
  5071. client_GET(abstract_addr);
  5072. }
  5073. #endif
  5074. TEST(SocketStream, is_writable_UNIX) {
  5075. int fds[2];
  5076. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  5077. const auto asSocketStream = [&](socket_t fd,
  5078. std::function<bool(Stream &)> func) {
  5079. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5080. };
  5081. asSocketStream(fds[0], [&](Stream &s0) {
  5082. EXPECT_EQ(s0.socket(), fds[0]);
  5083. EXPECT_TRUE(s0.is_writable());
  5084. EXPECT_EQ(0, close(fds[1]));
  5085. EXPECT_FALSE(s0.is_writable());
  5086. return true;
  5087. });
  5088. EXPECT_EQ(0, close(fds[0]));
  5089. }
  5090. TEST(SocketStream, is_writable_INET) {
  5091. sockaddr_in addr;
  5092. memset(&addr, 0, sizeof(addr));
  5093. addr.sin_family = AF_INET;
  5094. addr.sin_port = htons(PORT + 1);
  5095. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  5096. int disconnected_svr_sock = -1;
  5097. std::thread svr{[&] {
  5098. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5099. ASSERT_LE(0, s);
  5100. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5101. ASSERT_EQ(0, listen(s, 1));
  5102. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  5103. ASSERT_EQ(0, close(s));
  5104. }};
  5105. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5106. std::thread cli{[&] {
  5107. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5108. ASSERT_LE(0, s);
  5109. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5110. ASSERT_EQ(0, close(s));
  5111. }};
  5112. cli.join();
  5113. svr.join();
  5114. ASSERT_NE(disconnected_svr_sock, -1);
  5115. const auto asSocketStream = [&](socket_t fd,
  5116. std::function<bool(Stream &)> func) {
  5117. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5118. };
  5119. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  5120. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  5121. EXPECT_FALSE(ss.is_writable());
  5122. return true;
  5123. });
  5124. ASSERT_EQ(0, close(disconnected_svr_sock));
  5125. }
  5126. #endif // #ifndef _WIN32
  5127. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  5128. static constexpr unsigned int number_of_task{1000000};
  5129. std::atomic_uint count{0};
  5130. std::unique_ptr<TaskQueue> task_queue{
  5131. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  5132. for (unsigned int i = 0; i < number_of_task; ++i) {
  5133. task_queue->enqueue(
  5134. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  5135. }
  5136. EXPECT_NO_THROW(task_queue->shutdown());
  5137. EXPECT_EQ(number_of_task, count.load());
  5138. }
  5139. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  5140. Server svr;
  5141. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5142. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  5143. });
  5144. svr.Get("/hello", [](const Request &req, Response &res) {
  5145. res.set_content(req.get_param_value("key"), "text/plain");
  5146. });
  5147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5148. auto se = detail::scope_exit([&] {
  5149. svr.stop();
  5150. thread.join();
  5151. ASSERT_FALSE(svr.is_running());
  5152. });
  5153. std::this_thread::sleep_for(std::chrono::seconds(1));
  5154. {
  5155. Client cli(HOST, PORT);
  5156. cli.set_follow_location(true);
  5157. auto res = cli.Get("/");
  5158. ASSERT_TRUE(res);
  5159. EXPECT_EQ(200, res->status);
  5160. EXPECT_EQ("val&key2=val2", res->body);
  5161. }
  5162. }