test.cc 182 KB

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