test.cc 253 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <curl/curl.h>
  6. #endif
  7. #include <gtest/gtest.h>
  8. #include <atomic>
  9. #include <chrono>
  10. #include <fstream>
  11. #include <future>
  12. #include <limits>
  13. #include <memory>
  14. #include <sstream>
  15. #include <stdexcept>
  16. #include <thread>
  17. #include <type_traits>
  18. #include <vector>
  19. #define SERVER_CERT_FILE "./cert.pem"
  20. #define SERVER_CERT2_FILE "./cert2.pem"
  21. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  22. #define CA_CERT_FILE "./ca-bundle.crt"
  23. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  24. #define CLIENT_CA_CERT_DIR "."
  25. #define CLIENT_CERT_FILE "./client.cert.pem"
  26. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  27. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  28. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  29. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  30. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  31. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  32. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  33. using namespace std;
  34. using namespace httplib;
  35. const char *HOST = "localhost";
  36. const int PORT = 1234;
  37. const string LONG_QUERY_VALUE = string(25000, '@');
  38. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  39. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  40. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  41. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  42. const char *key) {
  43. auto it = std::find_if(
  44. files.begin(), files.end(),
  45. [&](const MultipartFormData &file) { return file.name == key; });
  46. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  47. return *it;
  48. #else
  49. if (it != files.end()) { return *it; }
  50. throw std::runtime_error("invalid multipart form data name error");
  51. #endif
  52. }
  53. static void read_file(const std::string &path, std::string &out) {
  54. std::ifstream fs(path, std::ios_base::binary);
  55. if (!fs) throw std::runtime_error("File not found: " + path);
  56. fs.seekg(0, std::ios_base::end);
  57. auto size = fs.tellg();
  58. fs.seekg(0);
  59. out.resize(static_cast<size_t>(size));
  60. fs.read(&out[0], static_cast<std::streamsize>(size));
  61. }
  62. #ifndef _WIN32
  63. class UnixSocketTest : public ::testing::Test {
  64. protected:
  65. void TearDown() override { std::remove(pathname_.c_str()); }
  66. void client_GET(const std::string &addr) {
  67. httplib::Client cli{addr};
  68. cli.set_address_family(AF_UNIX);
  69. ASSERT_TRUE(cli.is_valid());
  70. const auto &result = cli.Get(pattern_);
  71. ASSERT_TRUE(result) << "error: " << result.error();
  72. const auto &resp = result.value();
  73. EXPECT_EQ(resp.status, StatusCode::OK_200);
  74. EXPECT_EQ(resp.body, content_);
  75. }
  76. const std::string pathname_{"./httplib-server.sock"};
  77. const std::string pattern_{"/hi"};
  78. const std::string content_{"Hello World!"};
  79. };
  80. TEST_F(UnixSocketTest, pathname) {
  81. httplib::Server svr;
  82. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  83. res.set_content(content_, "text/plain");
  84. });
  85. std::thread t{[&] {
  86. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  87. }};
  88. auto se = detail::scope_exit([&] {
  89. svr.stop();
  90. t.join();
  91. ASSERT_FALSE(svr.is_running());
  92. });
  93. svr.wait_until_ready();
  94. ASSERT_TRUE(svr.is_running());
  95. client_GET(pathname_);
  96. }
  97. #if defined(__linux__) || \
  98. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  99. TEST_F(UnixSocketTest, PeerPid) {
  100. httplib::Server svr;
  101. std::string remote_port_val;
  102. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  103. res.set_content(content_, "text/plain");
  104. remote_port_val = req.get_header_value("REMOTE_PORT");
  105. });
  106. std::thread t{[&] {
  107. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  108. }};
  109. auto se = detail::scope_exit([&] {
  110. svr.stop();
  111. t.join();
  112. ASSERT_FALSE(svr.is_running());
  113. });
  114. svr.wait_until_ready();
  115. ASSERT_TRUE(svr.is_running());
  116. client_GET(pathname_);
  117. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  118. }
  119. #endif
  120. #ifdef __linux__
  121. TEST_F(UnixSocketTest, abstract) {
  122. constexpr char svr_path[]{"\x00httplib-server.sock"};
  123. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  124. httplib::Server svr;
  125. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  126. res.set_content(content_, "text/plain");
  127. });
  128. std::thread t{[&] {
  129. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  130. }};
  131. auto se = detail::scope_exit([&] {
  132. svr.stop();
  133. t.join();
  134. ASSERT_FALSE(svr.is_running());
  135. });
  136. svr.wait_until_ready();
  137. ASSERT_TRUE(svr.is_running());
  138. client_GET(abstract_addr);
  139. }
  140. #endif
  141. TEST(SocketStream, wait_writable_UNIX) {
  142. int fds[2];
  143. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  144. const auto asSocketStream = [&](socket_t fd,
  145. std::function<bool(Stream &)> func) {
  146. return detail::process_client_socket(
  147. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  148. };
  149. asSocketStream(fds[0], [&](Stream &s0) {
  150. EXPECT_EQ(s0.socket(), fds[0]);
  151. EXPECT_TRUE(s0.wait_writable());
  152. EXPECT_EQ(0, close(fds[1]));
  153. EXPECT_FALSE(s0.wait_writable());
  154. return true;
  155. });
  156. EXPECT_EQ(0, close(fds[0]));
  157. }
  158. TEST(SocketStream, wait_writable_INET) {
  159. sockaddr_in addr;
  160. memset(&addr, 0, sizeof(addr));
  161. addr.sin_family = AF_INET;
  162. addr.sin_port = htons(PORT + 1);
  163. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  164. int disconnected_svr_sock = -1;
  165. std::thread svr{[&] {
  166. const int s = socket(AF_INET, SOCK_STREAM, 0);
  167. ASSERT_LE(0, s);
  168. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  169. ASSERT_EQ(0, listen(s, 1));
  170. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  171. ASSERT_EQ(0, close(s));
  172. }};
  173. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  174. std::thread cli{[&] {
  175. const int s = socket(AF_INET, SOCK_STREAM, 0);
  176. ASSERT_LE(0, s);
  177. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  178. ASSERT_EQ(0, close(s));
  179. }};
  180. cli.join();
  181. svr.join();
  182. ASSERT_NE(disconnected_svr_sock, -1);
  183. const auto asSocketStream = [&](socket_t fd,
  184. std::function<bool(Stream &)> func) {
  185. return detail::process_client_socket(
  186. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  187. };
  188. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  189. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  190. EXPECT_FALSE(ss.wait_writable());
  191. return true;
  192. });
  193. ASSERT_EQ(0, close(disconnected_svr_sock));
  194. }
  195. #endif // #ifndef _WIN32
  196. TEST(ClientTest, MoveConstructible) {
  197. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  198. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  199. }
  200. TEST(ClientTest, MoveAssignable) {
  201. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  202. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  203. }
  204. #ifdef _WIN32
  205. TEST(StartupTest, WSAStartup) {
  206. WSADATA wsaData;
  207. int ret = WSAStartup(0x0002, &wsaData);
  208. ASSERT_EQ(0, ret);
  209. }
  210. #endif
  211. TEST(DecodeURLTest, PercentCharacter) {
  212. EXPECT_EQ(
  213. detail::decode_url(
  214. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  215. false),
  216. u8"descrip=Gastos áéíóúñÑ 6");
  217. }
  218. TEST(DecodeURLTest, PercentCharacterNUL) {
  219. string expected;
  220. expected.push_back('x');
  221. expected.push_back('\0');
  222. expected.push_back('x');
  223. EXPECT_EQ(detail::decode_url("x%00x", false), expected);
  224. }
  225. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  226. string unescapedCharacters = "-_.!~*'()";
  227. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  228. }
  229. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  230. string reservedCharacters = ";,/?:@&=+$";
  231. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  232. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  233. }
  234. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  235. string chineseCharacters = u8"中国語";
  236. string russianCharacters = u8"дом";
  237. string brazilianCharacters = u8"óculos";
  238. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  239. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  240. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  241. "%D0%B4%D0%BE%D0%BC");
  242. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  243. }
  244. TEST(TrimTests, TrimStringTests) {
  245. EXPECT_EQ("abc", detail::trim_copy("abc"));
  246. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  247. EXPECT_TRUE(detail::trim_copy("").empty());
  248. }
  249. TEST(DivideTest, DivideStringTests) {
  250. auto divide = [](const std::string &str, char d) {
  251. std::string lhs;
  252. std::string rhs;
  253. detail::divide(str, d,
  254. [&](const char *lhs_data, std::size_t lhs_size,
  255. const char *rhs_data, std::size_t rhs_size) {
  256. lhs.assign(lhs_data, lhs_size);
  257. rhs.assign(rhs_data, rhs_size);
  258. });
  259. return std::make_pair(std::move(lhs), std::move(rhs));
  260. };
  261. {
  262. const auto res = divide("", '=');
  263. EXPECT_EQ(res.first, "");
  264. EXPECT_EQ(res.second, "");
  265. }
  266. {
  267. const auto res = divide("=", '=');
  268. EXPECT_EQ(res.first, "");
  269. EXPECT_EQ(res.second, "");
  270. }
  271. {
  272. const auto res = divide(" ", '=');
  273. EXPECT_EQ(res.first, " ");
  274. EXPECT_EQ(res.second, "");
  275. }
  276. {
  277. const auto res = divide("a", '=');
  278. EXPECT_EQ(res.first, "a");
  279. EXPECT_EQ(res.second, "");
  280. }
  281. {
  282. const auto res = divide("a=", '=');
  283. EXPECT_EQ(res.first, "a");
  284. EXPECT_EQ(res.second, "");
  285. }
  286. {
  287. const auto res = divide("=b", '=');
  288. EXPECT_EQ(res.first, "");
  289. EXPECT_EQ(res.second, "b");
  290. }
  291. {
  292. const auto res = divide("a=b", '=');
  293. EXPECT_EQ(res.first, "a");
  294. EXPECT_EQ(res.second, "b");
  295. }
  296. {
  297. const auto res = divide("a=b=", '=');
  298. EXPECT_EQ(res.first, "a");
  299. EXPECT_EQ(res.second, "b=");
  300. }
  301. {
  302. const auto res = divide("a=b=c", '=');
  303. EXPECT_EQ(res.first, "a");
  304. EXPECT_EQ(res.second, "b=c");
  305. }
  306. }
  307. TEST(SplitTest, ParseQueryString) {
  308. string s = "key1=val1&key2=val2&key3=val3";
  309. Params dic;
  310. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  311. [&](const char *b, const char *e) {
  312. string key, val;
  313. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  314. if (key.empty()) {
  315. key.assign(b2, e2);
  316. } else {
  317. val.assign(b2, e2);
  318. }
  319. });
  320. dic.emplace(key, val);
  321. });
  322. EXPECT_EQ("val1", dic.find("key1")->second);
  323. EXPECT_EQ("val2", dic.find("key2")->second);
  324. EXPECT_EQ("val3", dic.find("key3")->second);
  325. }
  326. TEST(SplitTest, ParseInvalidQueryTests) {
  327. {
  328. string s = " ";
  329. Params dict;
  330. detail::parse_query_text(s, dict);
  331. EXPECT_TRUE(dict.empty());
  332. }
  333. {
  334. string s = " = =";
  335. Params dict;
  336. detail::parse_query_text(s, dict);
  337. EXPECT_TRUE(dict.empty());
  338. }
  339. }
  340. TEST(ParseQueryTest, ParseQueryString) {
  341. {
  342. std::string s = "key1=val1&key2=val2&key3=val3";
  343. Params dic;
  344. detail::parse_query_text(s, dic);
  345. EXPECT_EQ("val1", dic.find("key1")->second);
  346. EXPECT_EQ("val2", dic.find("key2")->second);
  347. EXPECT_EQ("val3", dic.find("key3")->second);
  348. }
  349. {
  350. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  351. Params dic;
  352. detail::parse_query_text(s, dic);
  353. EXPECT_EQ("", dic.find("key1")->second);
  354. EXPECT_EQ("val1", dic.find("key2")->second);
  355. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  356. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  357. }
  358. }
  359. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  360. Params dic;
  361. EXPECT_EQ(detail::params_to_query_str(dic), "");
  362. dic.emplace("key1", "val1");
  363. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  364. dic.emplace("key2", "val2");
  365. dic.emplace("key3", "val3");
  366. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  367. }
  368. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  369. string content_type = "multipart/form-data; boundary=something";
  370. string boundary;
  371. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  372. EXPECT_TRUE(ret);
  373. EXPECT_EQ(boundary, "something");
  374. }
  375. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  376. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  377. string boundary;
  378. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  379. EXPECT_TRUE(ret);
  380. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  381. }
  382. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  383. string content_type =
  384. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  385. string boundary;
  386. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  387. EXPECT_TRUE(ret);
  388. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  389. }
  390. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  391. string content_type =
  392. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  393. string boundary;
  394. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  395. EXPECT_TRUE(ret);
  396. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  397. }
  398. TEST(GetHeaderValueTest, DefaultValue) {
  399. Headers headers = {{"Dummy", "Dummy"}};
  400. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  401. EXPECT_STREQ("text/plain", val);
  402. }
  403. TEST(GetHeaderValueTest, DefaultValueInt) {
  404. Headers headers = {{"Dummy", "Dummy"}};
  405. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  406. EXPECT_EQ(100ull, val);
  407. }
  408. TEST(GetHeaderValueTest, RegularValue) {
  409. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  410. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  411. EXPECT_STREQ("text/html", val);
  412. }
  413. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  414. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  415. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  416. EXPECT_STREQ("text/html", val);
  417. }
  418. TEST(GetHeaderValueTest, SetContent) {
  419. Response res;
  420. res.set_content("html", "text/html");
  421. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  422. res.set_content("text", "text/plain");
  423. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  424. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  425. }
  426. TEST(GetHeaderValueTest, RegularValueInt) {
  427. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  428. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  429. EXPECT_EQ(100ull, val);
  430. }
  431. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  432. Headers headers = {{"Content-Length", "x"}};
  433. auto is_invalid_value = false;
  434. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  435. is_invalid_value);
  436. EXPECT_EQ(0ull, val);
  437. EXPECT_TRUE(is_invalid_value);
  438. }
  439. TEST(GetHeaderValueTest, Range) {
  440. {
  441. Headers headers = {make_range_header({{1, -1}})};
  442. auto val = detail::get_header_value(headers, "Range", 0, 0);
  443. EXPECT_STREQ("bytes=1-", val);
  444. }
  445. {
  446. Headers headers = {make_range_header({{-1, 1}})};
  447. auto val = detail::get_header_value(headers, "Range", 0, 0);
  448. EXPECT_STREQ("bytes=-1", val);
  449. }
  450. {
  451. Headers headers = {make_range_header({{1, 10}})};
  452. auto val = detail::get_header_value(headers, "Range", 0, 0);
  453. EXPECT_STREQ("bytes=1-10", val);
  454. }
  455. {
  456. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  457. auto val = detail::get_header_value(headers, "Range", 0, 0);
  458. EXPECT_STREQ("bytes=1-10, 100-", val);
  459. }
  460. {
  461. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  462. auto val = detail::get_header_value(headers, "Range", 0, 0);
  463. EXPECT_STREQ("bytes=1-10, 100-200", val);
  464. }
  465. {
  466. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  467. auto val = detail::get_header_value(headers, "Range", 0, 0);
  468. EXPECT_STREQ("bytes=0-0, -1", val);
  469. }
  470. }
  471. TEST(ParseHeaderValueTest, Range) {
  472. {
  473. Ranges ranges;
  474. auto ret = detail::parse_range_header("bytes=1-", ranges);
  475. EXPECT_TRUE(ret);
  476. EXPECT_EQ(1u, ranges.size());
  477. EXPECT_EQ(1u, ranges[0].first);
  478. EXPECT_EQ(-1, ranges[0].second);
  479. }
  480. {
  481. Ranges ranges;
  482. auto ret = detail::parse_range_header("bytes=-1", ranges);
  483. EXPECT_TRUE(ret);
  484. EXPECT_EQ(1u, ranges.size());
  485. EXPECT_EQ(-1, ranges[0].first);
  486. EXPECT_EQ(1u, ranges[0].second);
  487. }
  488. {
  489. Ranges ranges;
  490. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  491. EXPECT_TRUE(ret);
  492. EXPECT_EQ(1u, ranges.size());
  493. EXPECT_EQ(1u, ranges[0].first);
  494. EXPECT_EQ(10u, ranges[0].second);
  495. }
  496. {
  497. Ranges ranges;
  498. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  499. EXPECT_FALSE(ret);
  500. }
  501. {
  502. Ranges ranges;
  503. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  504. EXPECT_TRUE(ret);
  505. EXPECT_EQ(2u, ranges.size());
  506. EXPECT_EQ(1u, ranges[0].first);
  507. EXPECT_EQ(10u, ranges[0].second);
  508. EXPECT_EQ(100u, ranges[1].first);
  509. EXPECT_EQ(-1, ranges[1].second);
  510. }
  511. {
  512. Ranges ranges;
  513. auto ret =
  514. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  515. EXPECT_TRUE(ret);
  516. EXPECT_EQ(3u, ranges.size());
  517. EXPECT_EQ(1u, ranges[0].first);
  518. EXPECT_EQ(10u, ranges[0].second);
  519. EXPECT_EQ(100u, ranges[1].first);
  520. EXPECT_EQ(200u, ranges[1].second);
  521. EXPECT_EQ(300u, ranges[2].first);
  522. EXPECT_EQ(400u, ranges[2].second);
  523. }
  524. {
  525. Ranges ranges;
  526. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  527. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  528. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  529. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  530. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  531. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  532. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  533. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  534. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  535. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  536. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  537. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  538. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  539. EXPECT_TRUE(ranges.empty());
  540. }
  541. }
  542. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  543. Request req;
  544. req.set_header("Accept-Encoding", "gzip");
  545. Response res;
  546. res.set_header("Content-Type", "text/plain");
  547. auto ret = detail::encoding_type(req, res);
  548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  549. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  550. #else
  551. EXPECT_TRUE(ret == detail::EncodingType::None);
  552. #endif
  553. }
  554. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  555. Request req;
  556. req.set_header("Accept-Encoding", "gzip, deflate, br");
  557. Response res;
  558. res.set_header("Content-Type", "text/plain");
  559. auto ret = detail::encoding_type(req, res);
  560. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  561. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  562. #elif CPPHTTPLIB_ZLIB_SUPPORT
  563. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  564. #else
  565. EXPECT_TRUE(ret == detail::EncodingType::None);
  566. #endif
  567. }
  568. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  569. Request req;
  570. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  571. Response res;
  572. res.set_header("Content-Type", "text/plain");
  573. auto ret = detail::encoding_type(req, res);
  574. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  575. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  576. #elif CPPHTTPLIB_ZLIB_SUPPORT
  577. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  578. #else
  579. EXPECT_TRUE(ret == detail::EncodingType::None);
  580. #endif
  581. }
  582. TEST(BufferStreamTest, read) {
  583. detail::BufferStream strm1;
  584. Stream &strm = strm1;
  585. EXPECT_EQ(5, strm.write("hello"));
  586. char buf[512];
  587. EXPECT_EQ(2, strm.read(buf, 2));
  588. EXPECT_EQ('h', buf[0]);
  589. EXPECT_EQ('e', buf[1]);
  590. EXPECT_EQ(2, strm.read(buf, 2));
  591. EXPECT_EQ('l', buf[0]);
  592. EXPECT_EQ('l', buf[1]);
  593. EXPECT_EQ(1, strm.read(buf, 1));
  594. EXPECT_EQ('o', buf[0]);
  595. EXPECT_EQ(0, strm.read(buf, 1));
  596. }
  597. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  598. auto host = "www.httpwatch.com";
  599. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  600. auto port = 443;
  601. SSLClient cli(host, port);
  602. #else
  603. auto port = 80;
  604. Client cli(host, port);
  605. #endif
  606. cli.set_connection_timeout(2);
  607. auto res =
  608. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  609. ASSERT_TRUE(res);
  610. std::string out;
  611. read_file("./image.jpg", out);
  612. EXPECT_EQ(StatusCode::OK_200, res->status);
  613. EXPECT_EQ(out, res->body);
  614. }
  615. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  616. auto host = "www.httpwatch.com";
  617. auto ip = hosted_at(host);
  618. EXPECT_EQ("23.96.13.243", ip);
  619. std::vector<std::string> addrs;
  620. hosted_at(host, addrs);
  621. EXPECT_EQ(1u, addrs.size());
  622. }
  623. #if 0 // It depends on each test environment...
  624. TEST(HostnameToIPConversionTest, YouTube_Online) {
  625. auto host = "www.youtube.com";
  626. std::vector<std::string> addrs;
  627. hosted_at(host, addrs);
  628. EXPECT_EQ(20u, addrs.size());
  629. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  630. EXPECT_TRUE(it != addrs.end());
  631. }
  632. #endif
  633. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  634. auto host = "www.httpwatch.com";
  635. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  636. auto port = 443;
  637. SSLClient cli(host, port);
  638. #else
  639. auto port = 80;
  640. Client cli(host, port);
  641. #endif
  642. cli.set_connection_timeout(2);
  643. std::string body;
  644. auto res =
  645. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  646. [&](const char *data, size_t data_length) {
  647. body.append(data, data_length);
  648. return true;
  649. });
  650. ASSERT_TRUE(res);
  651. std::string out;
  652. read_file("./image.jpg", out);
  653. EXPECT_EQ(StatusCode::OK_200, res->status);
  654. EXPECT_EQ(out, body);
  655. }
  656. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  657. auto host = "www.httpwatch.com";
  658. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  659. auto port = 443;
  660. SSLClient cli(host, port);
  661. #else
  662. auto port = 80;
  663. Client cli(host, port);
  664. #endif
  665. cli.set_connection_timeout(2);
  666. std::string body;
  667. auto res = cli.Get(
  668. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  669. [&](const Response &response) {
  670. EXPECT_EQ(StatusCode::OK_200, response.status);
  671. return true;
  672. },
  673. [&](const char *data, size_t data_length) {
  674. body.append(data, data_length);
  675. return true;
  676. });
  677. ASSERT_TRUE(res);
  678. std::string out;
  679. read_file("./image.jpg", out);
  680. EXPECT_EQ(StatusCode::OK_200, res->status);
  681. EXPECT_EQ(out, body);
  682. }
  683. TEST(RangeTest, FromHTTPBin_Online) {
  684. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  685. auto host = "httpbin.org";
  686. auto path = std::string{"/range/32"};
  687. #else
  688. auto host = "nghttp2.org";
  689. auto path = std::string{"/httpbin/range/32"};
  690. #endif
  691. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  692. auto port = 443;
  693. SSLClient cli(host, port);
  694. #else
  695. auto port = 80;
  696. Client cli(host, port);
  697. #endif
  698. cli.set_connection_timeout(5);
  699. {
  700. auto res = cli.Get(path);
  701. ASSERT_TRUE(res);
  702. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  703. EXPECT_EQ(StatusCode::OK_200, res->status);
  704. }
  705. {
  706. Headers headers = {make_range_header({{1, -1}})};
  707. auto res = cli.Get(path, headers);
  708. ASSERT_TRUE(res);
  709. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  710. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  711. }
  712. {
  713. Headers headers = {make_range_header({{1, 10}})};
  714. auto res = cli.Get(path, headers);
  715. ASSERT_TRUE(res);
  716. EXPECT_EQ("bcdefghijk", res->body);
  717. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  718. }
  719. {
  720. Headers headers = {make_range_header({{0, 31}})};
  721. auto res = cli.Get(path, headers);
  722. ASSERT_TRUE(res);
  723. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  724. EXPECT_EQ(StatusCode::OK_200, res->status);
  725. }
  726. {
  727. Headers headers = {make_range_header({{0, -1}})};
  728. auto res = cli.Get(path, headers);
  729. ASSERT_TRUE(res);
  730. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  731. EXPECT_EQ(StatusCode::OK_200, res->status);
  732. }
  733. {
  734. Headers headers = {make_range_header({{0, 32}})};
  735. auto res = cli.Get(path, headers);
  736. ASSERT_TRUE(res);
  737. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  738. }
  739. }
  740. TEST(ConnectionErrorTest, InvalidHost) {
  741. auto host = "-abcde.com";
  742. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  743. auto port = 443;
  744. SSLClient cli(host, port);
  745. #else
  746. auto port = 80;
  747. Client cli(host, port);
  748. #endif
  749. cli.set_connection_timeout(std::chrono::seconds(2));
  750. auto res = cli.Get("/");
  751. ASSERT_TRUE(!res);
  752. EXPECT_EQ(Error::Connection, res.error());
  753. }
  754. TEST(ConnectionErrorTest, InvalidHost2) {
  755. auto host = "httpbin.org/";
  756. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  757. SSLClient cli(host);
  758. #else
  759. Client cli(host);
  760. #endif
  761. cli.set_connection_timeout(std::chrono::seconds(2));
  762. auto res = cli.Get("/");
  763. ASSERT_TRUE(!res);
  764. EXPECT_EQ(Error::Connection, res.error());
  765. }
  766. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  767. auto host = "httpbin.org/";
  768. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  769. SSLClient cli(host);
  770. #else
  771. Client cli(host);
  772. #endif
  773. cli.set_connection_timeout(std::chrono::seconds(2));
  774. auto res = cli.Get("/");
  775. ASSERT_TRUE(!res);
  776. stringstream s;
  777. s << "error code: " << res.error();
  778. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  779. }
  780. TEST(ConnectionErrorTest, InvalidPort) {
  781. auto host = "localhost";
  782. auto port = 44380;
  783. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  784. SSLClient cli(host, port);
  785. #else
  786. Client cli(host, port);
  787. #endif
  788. cli.set_connection_timeout(std::chrono::seconds(2));
  789. auto res = cli.Get("/");
  790. ASSERT_TRUE(!res);
  791. EXPECT_TRUE(Error::Connection == res.error() ||
  792. Error::ConnectionTimeout == res.error());
  793. }
  794. TEST(ConnectionErrorTest, Timeout_Online) {
  795. auto host = "google.com";
  796. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  797. auto port = 44380;
  798. SSLClient cli(host, port);
  799. #else
  800. auto port = 8080;
  801. Client cli(host, port);
  802. #endif
  803. cli.set_connection_timeout(std::chrono::seconds(2));
  804. // only probe one address type so that the error reason
  805. // correlates to the timed-out IPv4, not the unsupported
  806. // IPv6 connection attempt
  807. cli.set_address_family(AF_INET);
  808. auto res = cli.Get("/");
  809. ASSERT_TRUE(!res);
  810. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  811. }
  812. TEST(CancelTest, NoCancel_Online) {
  813. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  814. auto host = "httpbin.org";
  815. auto path = std::string{"/range/32"};
  816. #else
  817. auto host = "nghttp2.org";
  818. auto path = std::string{"/httpbin/range/32"};
  819. #endif
  820. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  821. auto port = 443;
  822. SSLClient cli(host, port);
  823. #else
  824. auto port = 80;
  825. Client cli(host, port);
  826. #endif
  827. cli.set_connection_timeout(std::chrono::seconds(5));
  828. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  829. ASSERT_TRUE(res);
  830. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  831. EXPECT_EQ(StatusCode::OK_200, res->status);
  832. }
  833. TEST(CancelTest, WithCancelSmallPayload_Online) {
  834. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  835. auto host = "httpbin.org";
  836. auto path = std::string{"/range/32"};
  837. #else
  838. auto host = "nghttp2.org";
  839. auto path = std::string{"/httpbin/range/32"};
  840. #endif
  841. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  842. auto port = 443;
  843. SSLClient cli(host, port);
  844. #else
  845. auto port = 80;
  846. Client cli(host, port);
  847. #endif
  848. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  849. cli.set_connection_timeout(std::chrono::seconds(5));
  850. ASSERT_TRUE(!res);
  851. EXPECT_EQ(Error::Canceled, res.error());
  852. }
  853. TEST(CancelTest, WithCancelLargePayload_Online) {
  854. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  855. auto host = "httpbin.org";
  856. auto path = std::string{"/range/65536"};
  857. #else
  858. auto host = "nghttp2.org";
  859. auto path = std::string{"/httpbin/range/65536"};
  860. #endif
  861. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  862. auto port = 443;
  863. SSLClient cli(host, port);
  864. #else
  865. auto port = 80;
  866. Client cli(host, port);
  867. #endif
  868. cli.set_connection_timeout(std::chrono::seconds(5));
  869. uint32_t count = 0;
  870. auto res =
  871. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  872. ASSERT_TRUE(!res);
  873. EXPECT_EQ(Error::Canceled, res.error());
  874. }
  875. TEST(CancelTest, NoCancelPost) {
  876. Server svr;
  877. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  878. res.set_content("Hello World!", "text/plain");
  879. });
  880. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  881. auto se = detail::scope_exit([&] {
  882. svr.stop();
  883. thread.join();
  884. ASSERT_FALSE(svr.is_running());
  885. });
  886. svr.wait_until_ready();
  887. Client cli(HOST, PORT);
  888. cli.set_connection_timeout(std::chrono::seconds(5));
  889. auto res =
  890. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  891. "application/json", [](uint64_t, uint64_t) { return true; });
  892. ASSERT_TRUE(res);
  893. EXPECT_EQ("Hello World!", res->body);
  894. EXPECT_EQ(StatusCode::OK_200, res->status);
  895. }
  896. TEST(CancelTest, WithCancelSmallPayloadPost) {
  897. Server svr;
  898. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  899. res.set_content("Hello World!", "text/plain");
  900. });
  901. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  902. auto se = detail::scope_exit([&] {
  903. svr.stop();
  904. thread.join();
  905. ASSERT_FALSE(svr.is_running());
  906. });
  907. svr.wait_until_ready();
  908. Client cli(HOST, PORT);
  909. cli.set_connection_timeout(std::chrono::seconds(5));
  910. auto res =
  911. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  912. "application/json", [](uint64_t, uint64_t) { return false; });
  913. ASSERT_TRUE(!res);
  914. EXPECT_EQ(Error::Canceled, res.error());
  915. }
  916. TEST(CancelTest, WithCancelLargePayloadPost) {
  917. Server svr;
  918. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  919. res.set_content(LARGE_DATA, "text/plain");
  920. });
  921. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  922. auto se = detail::scope_exit([&] {
  923. svr.stop();
  924. thread.join();
  925. ASSERT_FALSE(svr.is_running());
  926. });
  927. svr.wait_until_ready();
  928. Client cli(HOST, PORT);
  929. cli.set_connection_timeout(std::chrono::seconds(5));
  930. auto res =
  931. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  932. "application/json", [](uint64_t, uint64_t) { return false; });
  933. ASSERT_TRUE(!res);
  934. EXPECT_EQ(Error::Canceled, res.error());
  935. }
  936. TEST(CancelTest, NoCancelPut) {
  937. Server svr;
  938. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  939. res.set_content("Hello World!", "text/plain");
  940. });
  941. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  942. auto se = detail::scope_exit([&] {
  943. svr.stop();
  944. thread.join();
  945. ASSERT_FALSE(svr.is_running());
  946. });
  947. svr.wait_until_ready();
  948. Client cli(HOST, PORT);
  949. cli.set_connection_timeout(std::chrono::seconds(5));
  950. auto res =
  951. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  952. "application/json", [](uint64_t, uint64_t) { return true; });
  953. ASSERT_TRUE(res);
  954. EXPECT_EQ("Hello World!", res->body);
  955. EXPECT_EQ(StatusCode::OK_200, res->status);
  956. }
  957. TEST(CancelTest, WithCancelSmallPayloadPut) {
  958. Server svr;
  959. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  960. res.set_content("Hello World!", "text/plain");
  961. });
  962. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  963. auto se = detail::scope_exit([&] {
  964. svr.stop();
  965. thread.join();
  966. ASSERT_FALSE(svr.is_running());
  967. });
  968. svr.wait_until_ready();
  969. Client cli(HOST, PORT);
  970. cli.set_connection_timeout(std::chrono::seconds(5));
  971. auto res =
  972. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  973. "application/json", [](uint64_t, uint64_t) { return false; });
  974. ASSERT_TRUE(!res);
  975. EXPECT_EQ(Error::Canceled, res.error());
  976. }
  977. TEST(CancelTest, WithCancelLargePayloadPut) {
  978. Server svr;
  979. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  980. res.set_content(LARGE_DATA, "text/plain");
  981. });
  982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  983. auto se = detail::scope_exit([&] {
  984. svr.stop();
  985. thread.join();
  986. ASSERT_FALSE(svr.is_running());
  987. });
  988. svr.wait_until_ready();
  989. Client cli(HOST, PORT);
  990. cli.set_connection_timeout(std::chrono::seconds(5));
  991. auto res =
  992. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  993. "application/json", [](uint64_t, uint64_t) { return false; });
  994. ASSERT_TRUE(!res);
  995. EXPECT_EQ(Error::Canceled, res.error());
  996. }
  997. TEST(CancelTest, NoCancelPatch) {
  998. Server svr;
  999. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1000. res.set_content("Hello World!", "text/plain");
  1001. });
  1002. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1003. auto se = detail::scope_exit([&] {
  1004. svr.stop();
  1005. thread.join();
  1006. ASSERT_FALSE(svr.is_running());
  1007. });
  1008. svr.wait_until_ready();
  1009. Client cli(HOST, PORT);
  1010. cli.set_connection_timeout(std::chrono::seconds(5));
  1011. auto res =
  1012. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1013. "application/json", [](uint64_t, uint64_t) { return true; });
  1014. ASSERT_TRUE(res);
  1015. EXPECT_EQ("Hello World!", res->body);
  1016. EXPECT_EQ(StatusCode::OK_200, res->status);
  1017. }
  1018. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1019. Server svr;
  1020. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1021. res.set_content("Hello World!", "text/plain");
  1022. });
  1023. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1024. auto se = detail::scope_exit([&] {
  1025. svr.stop();
  1026. thread.join();
  1027. ASSERT_FALSE(svr.is_running());
  1028. });
  1029. svr.wait_until_ready();
  1030. Client cli(HOST, PORT);
  1031. cli.set_connection_timeout(std::chrono::seconds(5));
  1032. auto res =
  1033. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1034. "application/json", [](uint64_t, uint64_t) { return false; });
  1035. ASSERT_TRUE(!res);
  1036. EXPECT_EQ(Error::Canceled, res.error());
  1037. }
  1038. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1039. Server svr;
  1040. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1041. res.set_content(LARGE_DATA, "text/plain");
  1042. });
  1043. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1044. auto se = detail::scope_exit([&] {
  1045. svr.stop();
  1046. thread.join();
  1047. ASSERT_FALSE(svr.is_running());
  1048. });
  1049. svr.wait_until_ready();
  1050. Client cli(HOST, PORT);
  1051. cli.set_connection_timeout(std::chrono::seconds(5));
  1052. auto res =
  1053. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1054. "application/json", [](uint64_t, uint64_t) { return false; });
  1055. ASSERT_TRUE(!res);
  1056. EXPECT_EQ(Error::Canceled, res.error());
  1057. }
  1058. TEST(CancelTest, NoCancelDelete) {
  1059. Server svr;
  1060. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1061. res.set_content("Hello World!", "text/plain");
  1062. });
  1063. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1064. auto se = detail::scope_exit([&] {
  1065. svr.stop();
  1066. thread.join();
  1067. ASSERT_FALSE(svr.is_running());
  1068. });
  1069. svr.wait_until_ready();
  1070. Client cli(HOST, PORT);
  1071. cli.set_connection_timeout(std::chrono::seconds(5));
  1072. auto res =
  1073. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1074. "application/json", [](uint64_t, uint64_t) { return true; });
  1075. ASSERT_TRUE(res);
  1076. EXPECT_EQ("Hello World!", res->body);
  1077. EXPECT_EQ(StatusCode::OK_200, res->status);
  1078. }
  1079. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1080. Server svr;
  1081. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1082. res.set_content("Hello World!", "text/plain");
  1083. });
  1084. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1085. auto se = detail::scope_exit([&] {
  1086. svr.stop();
  1087. thread.join();
  1088. ASSERT_FALSE(svr.is_running());
  1089. });
  1090. svr.wait_until_ready();
  1091. Client cli(HOST, PORT);
  1092. cli.set_connection_timeout(std::chrono::seconds(5));
  1093. auto res =
  1094. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1095. "application/json", [](uint64_t, uint64_t) { return false; });
  1096. ASSERT_TRUE(!res);
  1097. EXPECT_EQ(Error::Canceled, res.error());
  1098. }
  1099. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1100. Server svr;
  1101. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1102. res.set_content(LARGE_DATA, "text/plain");
  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. svr.wait_until_ready();
  1111. Client cli(HOST, PORT);
  1112. cli.set_connection_timeout(std::chrono::seconds(5));
  1113. auto res =
  1114. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1115. "application/json", [](uint64_t, uint64_t) { return false; });
  1116. ASSERT_TRUE(!res);
  1117. EXPECT_EQ(Error::Canceled, res.error());
  1118. }
  1119. static std::string remove_whitespace(const std::string &input) {
  1120. std::string output;
  1121. output.reserve(input.size());
  1122. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1123. [](unsigned char c) { return !std::isspace(c); });
  1124. return output;
  1125. }
  1126. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1127. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1128. auto host = "httpbin.org";
  1129. auto path = std::string{"/basic-auth/hello/world"};
  1130. #else
  1131. auto host = "nghttp2.org";
  1132. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1133. #endif
  1134. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1135. auto port = 443;
  1136. SSLClient cli(host, port);
  1137. #else
  1138. auto port = 80;
  1139. Client cli(host, port);
  1140. #endif
  1141. {
  1142. auto res = cli.Get(path);
  1143. ASSERT_TRUE(res);
  1144. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1145. }
  1146. {
  1147. auto res =
  1148. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1149. ASSERT_TRUE(res);
  1150. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1151. remove_whitespace(res->body));
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. }
  1154. {
  1155. cli.set_basic_auth("hello", "world");
  1156. auto res = cli.Get(path);
  1157. ASSERT_TRUE(res);
  1158. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1159. remove_whitespace(res->body));
  1160. EXPECT_EQ(StatusCode::OK_200, res->status);
  1161. }
  1162. {
  1163. cli.set_basic_auth("hello", "bad");
  1164. auto res = cli.Get(path);
  1165. ASSERT_TRUE(res);
  1166. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1167. }
  1168. {
  1169. cli.set_basic_auth("bad", "world");
  1170. auto res = cli.Get(path);
  1171. ASSERT_TRUE(res);
  1172. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1173. }
  1174. }
  1175. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1176. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1177. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1178. auto host = "httpbin.org";
  1179. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1180. auto paths = std::vector<std::string>{
  1181. "/digest-auth/auth/hello/world/MD5",
  1182. "/digest-auth/auth/hello/world/SHA-256",
  1183. "/digest-auth/auth/hello/world/SHA-512",
  1184. "/digest-auth/auth-int/hello/world/MD5",
  1185. };
  1186. #else
  1187. auto host = "nghttp2.org";
  1188. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1189. auto paths = std::vector<std::string>{
  1190. "/httpbin/digest-auth/auth/hello/world/MD5",
  1191. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1192. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1193. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1194. };
  1195. #endif
  1196. auto port = 443;
  1197. SSLClient cli(host, port);
  1198. {
  1199. auto res = cli.Get(unauth_path);
  1200. ASSERT_TRUE(res);
  1201. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1202. }
  1203. {
  1204. cli.set_digest_auth("hello", "world");
  1205. for (const auto &path : paths) {
  1206. auto res = cli.Get(path.c_str());
  1207. ASSERT_TRUE(res);
  1208. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1209. remove_whitespace(res->body));
  1210. EXPECT_EQ(StatusCode::OK_200, res->status);
  1211. }
  1212. cli.set_digest_auth("hello", "bad");
  1213. for (const auto &path : paths) {
  1214. auto res = cli.Get(path.c_str());
  1215. ASSERT_TRUE(res);
  1216. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1217. }
  1218. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1219. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1220. // cli.set_digest_auth("bad", "world");
  1221. // for (const auto& path : paths) {
  1222. // auto res = cli.Get(path.c_str());
  1223. // ASSERT_TRUE(res);
  1224. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1225. // }
  1226. }
  1227. }
  1228. #endif
  1229. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1230. auto host = "google.com";
  1231. auto another_host = "example.com";
  1232. auto wrong_ip = "0.0.0.0";
  1233. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1234. SSLClient cli(host);
  1235. #else
  1236. Client cli(host);
  1237. #endif
  1238. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1239. auto res = cli.Get("/");
  1240. ASSERT_TRUE(res);
  1241. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1242. }
  1243. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1244. auto host = "google.com";
  1245. auto wrong_ip = "0.0.0.0";
  1246. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1247. SSLClient cli(host);
  1248. #else
  1249. Client cli(host);
  1250. #endif
  1251. cli.set_hostname_addr_map({{host, wrong_ip}});
  1252. auto res = cli.Get("/");
  1253. ASSERT_TRUE(!res);
  1254. EXPECT_EQ(Error::Connection, res.error());
  1255. }
  1256. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1257. auto host = "nghttp2.org";
  1258. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1259. SSLClient cli(host);
  1260. #else
  1261. Client cli(host);
  1262. #endif
  1263. cli.set_follow_location(true);
  1264. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1265. ASSERT_TRUE(res);
  1266. EXPECT_EQ(StatusCode::OK_200, res->status);
  1267. }
  1268. TEST(RedirectTest, Redirect_Online) {
  1269. auto host = "nghttp2.org";
  1270. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1271. SSLClient cli(host);
  1272. #else
  1273. Client cli(host);
  1274. #endif
  1275. cli.set_follow_location(true);
  1276. auto res = cli.Get("/httpbin/redirect/3");
  1277. ASSERT_TRUE(res);
  1278. EXPECT_EQ(StatusCode::OK_200, res->status);
  1279. }
  1280. TEST(RelativeRedirectTest, Redirect_Online) {
  1281. auto host = "nghttp2.org";
  1282. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1283. SSLClient cli(host);
  1284. #else
  1285. Client cli(host);
  1286. #endif
  1287. cli.set_follow_location(true);
  1288. auto res = cli.Get("/httpbin/relative-redirect/3");
  1289. ASSERT_TRUE(res);
  1290. EXPECT_EQ(StatusCode::OK_200, res->status);
  1291. }
  1292. TEST(TooManyRedirectTest, Redirect_Online) {
  1293. auto host = "nghttp2.org";
  1294. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1295. SSLClient cli(host);
  1296. #else
  1297. Client cli(host);
  1298. #endif
  1299. cli.set_follow_location(true);
  1300. auto res = cli.Get("/httpbin/redirect/21");
  1301. ASSERT_TRUE(!res);
  1302. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1303. }
  1304. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1305. TEST(YahooRedirectTest, Redirect_Online) {
  1306. Client cli("yahoo.com");
  1307. auto res = cli.Get("/");
  1308. ASSERT_TRUE(res);
  1309. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1310. cli.set_follow_location(true);
  1311. res = cli.Get("/");
  1312. ASSERT_TRUE(res);
  1313. EXPECT_EQ(StatusCode::OK_200, res->status);
  1314. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1315. }
  1316. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1317. #define REDIR_HOST "httpbingo.org"
  1318. #define REDIR_PATH "/redirect-to"
  1319. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1320. SSLClient cli(REDIR_HOST);
  1321. cli.set_follow_location(true);
  1322. auto res =
  1323. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1324. ASSERT_TRUE(res);
  1325. EXPECT_EQ(StatusCode::OK_200, res->status);
  1326. }
  1327. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1328. SSLClient cli(REDIR_HOST);
  1329. cli.set_follow_location(true);
  1330. Params params;
  1331. params.emplace("url", "http://example.com");
  1332. params.emplace("status_code", "302");
  1333. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1334. ASSERT_TRUE(res);
  1335. EXPECT_EQ(StatusCode::OK_200, res->status);
  1336. }
  1337. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1338. SSLClient cli(REDIR_HOST);
  1339. cli.set_follow_location(true);
  1340. Params params;
  1341. params.emplace("url", "http://example.com");
  1342. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1343. ASSERT_TRUE(res);
  1344. EXPECT_EQ(StatusCode::OK_200, res->status);
  1345. }
  1346. TEST(UrlWithSpace, Redirect_Online) {
  1347. SSLClient cli("edge.forgecdn.net");
  1348. cli.set_follow_location(true);
  1349. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1350. ASSERT_TRUE(res);
  1351. EXPECT_EQ(StatusCode::OK_200, res->status);
  1352. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1353. }
  1354. #endif
  1355. #if !defined(_WIN32) && !defined(_WIN64)
  1356. TEST(ReceiveSignals, Signal) {
  1357. auto setupSignalHandlers = []() {
  1358. struct sigaction act;
  1359. sigemptyset(&act.sa_mask);
  1360. act.sa_flags = SA_SIGINFO;
  1361. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1362. switch (sig) {
  1363. case SIGINT:
  1364. default: break;
  1365. }
  1366. };
  1367. ::sigaction(SIGINT, &act, nullptr);
  1368. };
  1369. Server svr;
  1370. int port = 0;
  1371. auto thread = std::thread([&]() {
  1372. setupSignalHandlers();
  1373. port = svr.bind_to_any_port("localhost");
  1374. svr.listen_after_bind();
  1375. });
  1376. auto se = detail::scope_exit([&] {
  1377. svr.stop();
  1378. thread.join();
  1379. ASSERT_FALSE(svr.is_running());
  1380. });
  1381. svr.wait_until_ready();
  1382. ASSERT_TRUE(svr.is_running());
  1383. pthread_kill(thread.native_handle(), SIGINT);
  1384. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1385. ASSERT_TRUE(svr.is_running());
  1386. }
  1387. #endif
  1388. TEST(RedirectToDifferentPort, Redirect) {
  1389. Server svr1;
  1390. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1391. res.set_content("Hello World!", "text/plain");
  1392. });
  1393. int svr1_port = 0;
  1394. auto thread1 = std::thread([&]() {
  1395. svr1_port = svr1.bind_to_any_port("localhost");
  1396. svr1.listen_after_bind();
  1397. });
  1398. Server svr2;
  1399. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1400. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1401. });
  1402. int svr2_port = 0;
  1403. auto thread2 = std::thread([&]() {
  1404. svr2_port = svr2.bind_to_any_port("localhost");
  1405. svr2.listen_after_bind();
  1406. });
  1407. auto se = detail::scope_exit([&] {
  1408. svr2.stop();
  1409. thread2.join();
  1410. svr1.stop();
  1411. thread1.join();
  1412. ASSERT_FALSE(svr2.is_running());
  1413. ASSERT_FALSE(svr1.is_running());
  1414. });
  1415. svr1.wait_until_ready();
  1416. svr2.wait_until_ready();
  1417. Client cli("localhost", svr2_port);
  1418. cli.set_follow_location(true);
  1419. auto res = cli.Get("/2");
  1420. ASSERT_TRUE(res);
  1421. EXPECT_EQ(StatusCode::OK_200, res->status);
  1422. EXPECT_EQ("Hello World!", res->body);
  1423. }
  1424. TEST(RedirectFromPageWithContent, Redirect) {
  1425. Server svr;
  1426. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1427. res.set_content("___", "text/plain");
  1428. res.set_redirect("/2");
  1429. });
  1430. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1431. res.set_content("Hello World!", "text/plain");
  1432. });
  1433. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1434. auto se = detail::scope_exit([&] {
  1435. svr.stop();
  1436. th.join();
  1437. ASSERT_FALSE(svr.is_running());
  1438. });
  1439. svr.wait_until_ready();
  1440. {
  1441. Client cli("localhost", PORT);
  1442. cli.set_follow_location(true);
  1443. std::string body;
  1444. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1445. body.append(data, data_length);
  1446. return true;
  1447. });
  1448. ASSERT_TRUE(res);
  1449. EXPECT_EQ(StatusCode::OK_200, res->status);
  1450. EXPECT_EQ("Hello World!", body);
  1451. }
  1452. {
  1453. Client cli("localhost", PORT);
  1454. std::string body;
  1455. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1456. body.append(data, data_length);
  1457. return true;
  1458. });
  1459. ASSERT_TRUE(res);
  1460. EXPECT_EQ(StatusCode::Found_302, res->status);
  1461. EXPECT_EQ("___", body);
  1462. }
  1463. }
  1464. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1465. Server svr;
  1466. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1467. res.set_content("___", "text/plain");
  1468. // res.set_redirect("/2");
  1469. res.set_redirect("http://[::1]:1234/2");
  1470. });
  1471. svr.Get("/2", [&](const Request &req, Response &res) {
  1472. auto host_header = req.headers.find("Host");
  1473. ASSERT_TRUE(host_header != req.headers.end());
  1474. EXPECT_EQ("[::1]:1234", host_header->second);
  1475. res.set_content("Hello World!", "text/plain");
  1476. });
  1477. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1478. auto se = detail::scope_exit([&] {
  1479. svr.stop();
  1480. th.join();
  1481. ASSERT_FALSE(svr.is_running());
  1482. });
  1483. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1484. // actually starts anything, so the condition !svr.is_running() will
  1485. // always remain true, and the loop never stops.
  1486. // This basically counts how many milliseconds have passed since the
  1487. // call to svr.listen(), and if after 5 seconds nothing started yet
  1488. // aborts the test.
  1489. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1490. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1491. ASSERT_LT(milliseconds, 5000U);
  1492. }
  1493. {
  1494. Client cli("http://[::1]:1234");
  1495. cli.set_follow_location(true);
  1496. std::string body;
  1497. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1498. body.append(data, data_length);
  1499. return true;
  1500. });
  1501. ASSERT_TRUE(res);
  1502. EXPECT_EQ(StatusCode::OK_200, res->status);
  1503. EXPECT_EQ("Hello World!", body);
  1504. }
  1505. {
  1506. Client cli("http://[::1]:1234");
  1507. std::string body;
  1508. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1509. body.append(data, data_length);
  1510. return true;
  1511. });
  1512. ASSERT_TRUE(res);
  1513. EXPECT_EQ(StatusCode::Found_302, res->status);
  1514. EXPECT_EQ("___", body);
  1515. }
  1516. }
  1517. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1518. Server svr;
  1519. svr.Get("/foo", [](const Request &req, Response &res) {
  1520. auto a = req.params.find("a");
  1521. if (a != req.params.end()) {
  1522. res.set_content((*a).second, "text/plain");
  1523. res.status = StatusCode::OK_200;
  1524. } else {
  1525. res.status = StatusCode::BadRequest_400;
  1526. }
  1527. });
  1528. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1529. auto se = detail::scope_exit([&] {
  1530. svr.stop();
  1531. thread.join();
  1532. ASSERT_FALSE(svr.is_running());
  1533. });
  1534. svr.wait_until_ready();
  1535. {
  1536. Client cli(HOST, PORT);
  1537. cli.set_url_encode(false);
  1538. auto res = cli.Get("/foo?a=explicitly+encoded");
  1539. ASSERT_TRUE(res);
  1540. EXPECT_EQ(StatusCode::OK_200, res->status);
  1541. // This expects it back with a space, as the `+` won't have been
  1542. // url-encoded, and server-side the params get decoded turning `+`
  1543. // into spaces.
  1544. EXPECT_EQ("explicitly encoded", res->body);
  1545. }
  1546. }
  1547. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1548. Server svr;
  1549. svr.Get("/", [](const Request &req, Response &) {
  1550. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1551. });
  1552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1553. auto se = detail::scope_exit([&] {
  1554. svr.stop();
  1555. thread.join();
  1556. ASSERT_FALSE(svr.is_running());
  1557. });
  1558. svr.wait_until_ready();
  1559. {
  1560. Client cli(HOST, PORT);
  1561. cli.set_url_encode(false);
  1562. auto res = cli.Get("/?something=%0A");
  1563. ASSERT_TRUE(res);
  1564. EXPECT_EQ(StatusCode::OK_200, res->status);
  1565. }
  1566. }
  1567. TEST(BindServerTest, DISABLED_BindDualStack) {
  1568. Server svr;
  1569. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1570. res.set_content("Hello World!", "text/plain");
  1571. });
  1572. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1573. auto se = detail::scope_exit([&] {
  1574. svr.stop();
  1575. thread.join();
  1576. ASSERT_FALSE(svr.is_running());
  1577. });
  1578. svr.wait_until_ready();
  1579. {
  1580. Client cli("127.0.0.1", PORT);
  1581. auto res = cli.Get("/1");
  1582. ASSERT_TRUE(res);
  1583. EXPECT_EQ(StatusCode::OK_200, res->status);
  1584. EXPECT_EQ("Hello World!", res->body);
  1585. }
  1586. {
  1587. Client cli("::1", PORT);
  1588. auto res = cli.Get("/1");
  1589. ASSERT_TRUE(res);
  1590. EXPECT_EQ(StatusCode::OK_200, res->status);
  1591. EXPECT_EQ("Hello World!", res->body);
  1592. }
  1593. }
  1594. TEST(BindServerTest, BindAndListenSeparately) {
  1595. Server svr;
  1596. int port = svr.bind_to_any_port("0.0.0.0");
  1597. ASSERT_TRUE(svr.is_valid());
  1598. ASSERT_TRUE(port > 0);
  1599. svr.stop();
  1600. }
  1601. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1602. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1603. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1604. CLIENT_CA_CERT_DIR);
  1605. int port = svr.bind_to_any_port("0.0.0.0");
  1606. ASSERT_TRUE(svr.is_valid());
  1607. ASSERT_TRUE(port > 0);
  1608. svr.stop();
  1609. }
  1610. #endif
  1611. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1612. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1613. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1614. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1615. int port = svr.bind_to_any_port("0.0.0.0");
  1616. ASSERT_TRUE(svr.is_valid());
  1617. ASSERT_TRUE(port > 0);
  1618. svr.stop();
  1619. }
  1620. #endif
  1621. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1622. X509 *readCertificate(const std::string &strFileName) {
  1623. std::ifstream inStream(strFileName);
  1624. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1625. std::istreambuf_iterator<char>());
  1626. if (strCertPEM.empty()) return (nullptr);
  1627. BIO *pbCert = BIO_new(BIO_s_mem());
  1628. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1629. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1630. BIO_free(pbCert);
  1631. return (pCert);
  1632. }
  1633. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1634. std::ifstream inStream(strFileName);
  1635. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1636. std::istreambuf_iterator<char>());
  1637. if (strPrivateKeyPEM.empty()) return (nullptr);
  1638. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1639. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1640. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1641. BIO_free(pbPrivKey);
  1642. return (pPrivateKey);
  1643. }
  1644. TEST(BindServerTest, UpdateCerts) {
  1645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1646. int port = svr.bind_to_any_port("0.0.0.0");
  1647. ASSERT_TRUE(svr.is_valid());
  1648. ASSERT_TRUE(port > 0);
  1649. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1650. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1651. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1652. ASSERT_TRUE(cert != nullptr);
  1653. ASSERT_TRUE(ca_cert != nullptr);
  1654. ASSERT_TRUE(key != nullptr);
  1655. X509_STORE *cert_store = X509_STORE_new();
  1656. X509_STORE_add_cert(cert_store, ca_cert);
  1657. svr.update_certs(cert, key, cert_store);
  1658. ASSERT_TRUE(svr.is_valid());
  1659. svr.stop();
  1660. X509_free(cert);
  1661. X509_free(ca_cert);
  1662. EVP_PKEY_free(key);
  1663. }
  1664. #endif
  1665. TEST(ErrorHandlerTest, ContentLength) {
  1666. Server svr;
  1667. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1668. res.status = StatusCode::OK_200;
  1669. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1670. "text/html"); // <= Content-Length still 13
  1671. });
  1672. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1673. res.set_content("Hello World!\n", "text/plain");
  1674. res.status = 524;
  1675. });
  1676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1677. auto se = detail::scope_exit([&] {
  1678. svr.stop();
  1679. thread.join();
  1680. ASSERT_FALSE(svr.is_running());
  1681. });
  1682. svr.wait_until_ready();
  1683. {
  1684. Client cli(HOST, PORT);
  1685. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1686. ASSERT_TRUE(res);
  1687. EXPECT_EQ(StatusCode::OK_200, res->status);
  1688. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1689. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1690. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1691. }
  1692. }
  1693. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1694. TEST(ExceptionTest, WithoutExceptionHandler) {
  1695. Server svr;
  1696. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  1697. throw std::runtime_error("exception...");
  1698. });
  1699. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  1700. throw std::runtime_error("exception\r\n...");
  1701. });
  1702. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1703. auto se = detail::scope_exit([&] {
  1704. svr.stop();
  1705. listen_thread.join();
  1706. ASSERT_FALSE(svr.is_running());
  1707. });
  1708. svr.wait_until_ready();
  1709. Client cli("localhost", PORT);
  1710. {
  1711. auto res = cli.Get("/exception");
  1712. ASSERT_TRUE(res);
  1713. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1714. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1715. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  1716. }
  1717. {
  1718. auto res = cli.Get("/unknown");
  1719. ASSERT_TRUE(res);
  1720. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1721. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1722. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  1723. }
  1724. }
  1725. TEST(ExceptionTest, WithExceptionHandler) {
  1726. Server svr;
  1727. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1728. std::exception_ptr ep) {
  1729. EXPECT_FALSE(ep == nullptr);
  1730. try {
  1731. std::rethrow_exception(ep);
  1732. } catch (std::exception &e) {
  1733. EXPECT_EQ("abc", std::string(e.what()));
  1734. } catch (...) {}
  1735. res.status = StatusCode::InternalServerError_500;
  1736. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1737. "text/html"); // <= Content-Length still 13 at this point
  1738. });
  1739. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1740. res.set_content("Hello World!\n", "text/plain");
  1741. throw std::runtime_error("abc");
  1742. });
  1743. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1744. auto se = detail::scope_exit([&] {
  1745. svr.stop();
  1746. thread.join();
  1747. ASSERT_FALSE(svr.is_running());
  1748. });
  1749. svr.wait_until_ready();
  1750. for (size_t i = 0; i < 10; i++) {
  1751. Client cli(HOST, PORT);
  1752. for (size_t j = 0; j < 100; j++) {
  1753. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1754. ASSERT_TRUE(res);
  1755. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1756. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1757. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1758. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1759. }
  1760. cli.set_keep_alive(true);
  1761. for (size_t j = 0; j < 100; j++) {
  1762. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1763. ASSERT_TRUE(res);
  1764. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1765. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1766. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1767. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1768. }
  1769. }
  1770. }
  1771. TEST(ExceptionTest, AndErrorHandler) {
  1772. Server svr;
  1773. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1774. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  1775. });
  1776. svr.set_exception_handler(
  1777. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  1778. EXPECT_FALSE(ep == nullptr);
  1779. try {
  1780. std::rethrow_exception(ep);
  1781. } catch (std::exception &e) {
  1782. res.set_content(e.what(), "text/html");
  1783. } catch (...) {}
  1784. res.status = StatusCode::InternalServerError_500;
  1785. });
  1786. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  1787. throw std::runtime_error("EXCEPTION");
  1788. });
  1789. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  1790. res.set_content("ERROR", "text/html");
  1791. res.status = StatusCode::InternalServerError_500;
  1792. });
  1793. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1794. auto se = detail::scope_exit([&] {
  1795. svr.stop();
  1796. thread.join();
  1797. ASSERT_FALSE(svr.is_running());
  1798. });
  1799. svr.wait_until_ready();
  1800. Client cli(HOST, PORT);
  1801. {
  1802. auto res = cli.Get("/exception");
  1803. ASSERT_TRUE(res);
  1804. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1805. EXPECT_EQ("EXCEPTION", res->body);
  1806. }
  1807. {
  1808. auto res = cli.Get("/error");
  1809. ASSERT_TRUE(res);
  1810. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1811. EXPECT_EQ("ERROR", res->body);
  1812. }
  1813. {
  1814. auto res = cli.Get("/invalid");
  1815. ASSERT_TRUE(res);
  1816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1817. EXPECT_EQ("NOT_FOUND", res->body);
  1818. }
  1819. }
  1820. #endif
  1821. TEST(NoContentTest, ContentLength) {
  1822. Server svr;
  1823. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1824. res.status = StatusCode::NoContent_204;
  1825. });
  1826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1827. auto se = detail::scope_exit([&] {
  1828. svr.stop();
  1829. thread.join();
  1830. ASSERT_FALSE(svr.is_running());
  1831. });
  1832. svr.wait_until_ready();
  1833. {
  1834. Client cli(HOST, PORT);
  1835. auto res = cli.Get("/hi");
  1836. ASSERT_TRUE(res);
  1837. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  1838. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1839. }
  1840. }
  1841. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1842. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  1844. ASSERT_TRUE(svr.is_valid());
  1845. #else
  1846. Server svr;
  1847. #endif
  1848. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1849. if (req.path == "/routing_handler") {
  1850. res.set_header("PRE_ROUTING", "on");
  1851. res.set_content("Routing Handler", "text/plain");
  1852. return httplib::Server::HandlerResponse::Handled;
  1853. }
  1854. return httplib::Server::HandlerResponse::Unhandled;
  1855. });
  1856. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1857. res.set_content("Error", "text/html");
  1858. });
  1859. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1860. if (req.path == "/routing_handler") {
  1861. res.set_header("POST_ROUTING", "on");
  1862. }
  1863. });
  1864. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1865. res.set_content("Hello World!\n", "text/plain");
  1866. });
  1867. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1868. auto se = detail::scope_exit([&] {
  1869. svr.stop();
  1870. thread.join();
  1871. ASSERT_FALSE(svr.is_running());
  1872. });
  1873. svr.wait_until_ready();
  1874. {
  1875. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1876. SSLClient cli(HOST, PORT);
  1877. cli.enable_server_certificate_verification(false);
  1878. #else
  1879. Client cli(HOST, PORT);
  1880. #endif
  1881. auto res = cli.Get("/routing_handler");
  1882. ASSERT_TRUE(res);
  1883. EXPECT_EQ(StatusCode::OK_200, res->status);
  1884. EXPECT_EQ("Routing Handler", res->body);
  1885. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1886. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1887. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1888. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1889. }
  1890. {
  1891. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1892. SSLClient cli(HOST, PORT);
  1893. cli.enable_server_certificate_verification(false);
  1894. #else
  1895. Client cli(HOST, PORT);
  1896. #endif
  1897. auto res = cli.Get("/hi");
  1898. ASSERT_TRUE(res);
  1899. EXPECT_EQ(StatusCode::OK_200, res->status);
  1900. EXPECT_EQ("Hello World!\n", res->body);
  1901. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1902. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1903. }
  1904. {
  1905. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1906. SSLClient cli(HOST, PORT);
  1907. cli.enable_server_certificate_verification(false);
  1908. #else
  1909. Client cli(HOST, PORT);
  1910. #endif
  1911. auto res = cli.Get("/aaa");
  1912. ASSERT_TRUE(res);
  1913. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1914. EXPECT_EQ("Error", res->body);
  1915. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1916. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1917. }
  1918. }
  1919. TEST(InvalidFormatTest, StatusCode) {
  1920. Server svr;
  1921. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1922. res.set_content("Hello World!\n", "text/plain");
  1923. res.status = 9999; // Status should be a three-digit code...
  1924. });
  1925. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1926. auto se = detail::scope_exit([&] {
  1927. svr.stop();
  1928. thread.join();
  1929. ASSERT_FALSE(svr.is_running());
  1930. });
  1931. svr.wait_until_ready();
  1932. {
  1933. Client cli(HOST, PORT);
  1934. auto res = cli.Get("/hi");
  1935. ASSERT_FALSE(res);
  1936. }
  1937. }
  1938. TEST(URLFragmentTest, WithFragment) {
  1939. Server svr;
  1940. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1941. EXPECT_TRUE(req.target == "/hi");
  1942. });
  1943. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1944. auto se = detail::scope_exit([&] {
  1945. svr.stop();
  1946. thread.join();
  1947. ASSERT_FALSE(svr.is_running());
  1948. });
  1949. svr.wait_until_ready();
  1950. {
  1951. Client cli(HOST, PORT);
  1952. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1953. EXPECT_TRUE(res);
  1954. EXPECT_EQ(StatusCode::OK_200, res->status);
  1955. res = cli.Get("/hi%23key1=val1=key2=val2");
  1956. EXPECT_TRUE(res);
  1957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1958. }
  1959. }
  1960. TEST(HeaderWriter, SetHeaderWriter) {
  1961. Server svr;
  1962. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  1963. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  1964. return detail::write_headers(strm, hdrs);
  1965. });
  1966. svr.Get("/hi", [](const Request &req, Response &res) {
  1967. auto it = req.headers.find("CustomClientHeader");
  1968. EXPECT_TRUE(it != req.headers.end());
  1969. EXPECT_EQ(it->second, "CustomClientValue");
  1970. res.set_content("Hello World!\n", "text/plain");
  1971. });
  1972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1973. auto se = detail::scope_exit([&] {
  1974. svr.stop();
  1975. thread.join();
  1976. ASSERT_FALSE(svr.is_running());
  1977. });
  1978. svr.wait_until_ready();
  1979. {
  1980. Client cli(HOST, PORT);
  1981. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  1982. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  1983. return detail::write_headers(strm, hdrs);
  1984. });
  1985. auto res = cli.Get("/hi");
  1986. EXPECT_TRUE(res);
  1987. EXPECT_EQ(StatusCode::OK_200, res->status);
  1988. auto it = res->headers.find("CustomServerHeader");
  1989. EXPECT_TRUE(it != res->headers.end());
  1990. EXPECT_EQ(it->second, "CustomServerValue");
  1991. }
  1992. }
  1993. class ServerTest : public ::testing::Test {
  1994. protected:
  1995. ServerTest()
  1996. : cli_(HOST, PORT)
  1997. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1998. ,
  1999. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2000. #endif
  2001. {
  2002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2003. cli_.enable_server_certificate_verification(false);
  2004. #endif
  2005. }
  2006. virtual void SetUp() {
  2007. svr_.set_mount_point("/", "./www");
  2008. svr_.set_mount_point("/mount", "./www2");
  2009. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2010. svr_.Get("/hi",
  2011. [&](const Request & /*req*/, Response &res) {
  2012. res.set_content("Hello World!", "text/plain");
  2013. })
  2014. .Get("/file_content",
  2015. [&](const Request & /*req*/, Response &res) {
  2016. res.set_file_content("./www/dir/test.html");
  2017. })
  2018. .Get("/file_content_with_content_type",
  2019. [&](const Request & /*req*/, Response &res) {
  2020. res.set_file_content("./www/file", "text/plain");
  2021. })
  2022. .Get("/invalid_file_content",
  2023. [&](const Request & /*req*/, Response &res) {
  2024. res.set_file_content("./www/dir/invalid_file_path");
  2025. })
  2026. .Get("/http_response_splitting",
  2027. [&](const Request & /*req*/, Response &res) {
  2028. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2029. EXPECT_EQ(0U, res.headers.size());
  2030. EXPECT_FALSE(res.has_header("a"));
  2031. res.set_header("a", "1\nSet-Cookie: a=1");
  2032. EXPECT_EQ(0U, res.headers.size());
  2033. EXPECT_FALSE(res.has_header("a"));
  2034. res.set_header("a", "1\rSet-Cookie: a=1");
  2035. EXPECT_EQ(0U, res.headers.size());
  2036. EXPECT_FALSE(res.has_header("a"));
  2037. res.set_header("a\r\nb", "0");
  2038. EXPECT_EQ(0U, res.headers.size());
  2039. EXPECT_FALSE(res.has_header("a"));
  2040. res.set_header("a\rb", "0");
  2041. EXPECT_EQ(0U, res.headers.size());
  2042. EXPECT_FALSE(res.has_header("a"));
  2043. res.set_header("a\nb", "0");
  2044. EXPECT_EQ(0U, res.headers.size());
  2045. EXPECT_FALSE(res.has_header("a"));
  2046. res.set_redirect("1\r\nSet-Cookie: a=1");
  2047. EXPECT_EQ(0U, res.headers.size());
  2048. EXPECT_FALSE(res.has_header("Location"));
  2049. })
  2050. .Get("/slow",
  2051. [&](const Request & /*req*/, Response &res) {
  2052. std::this_thread::sleep_for(std::chrono::seconds(2));
  2053. res.set_content("slow", "text/plain");
  2054. })
  2055. #if 0
  2056. .Post("/slowpost",
  2057. [&](const Request & /*req*/, Response &res) {
  2058. std::this_thread::sleep_for(std::chrono::seconds(2));
  2059. res.set_content("slow", "text/plain");
  2060. })
  2061. #endif
  2062. .Get("/remote_addr",
  2063. [&](const Request &req, Response &res) {
  2064. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2065. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2066. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2067. EXPECT_EQ(req.remote_port,
  2068. std::stoi(req.get_header_value("REMOTE_PORT")));
  2069. res.set_content(remote_addr.c_str(), "text/plain");
  2070. })
  2071. .Get("/local_addr",
  2072. [&](const Request &req, Response &res) {
  2073. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2074. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2075. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2076. auto local_port = req.get_header_value("LOCAL_PORT");
  2077. EXPECT_EQ(req.local_addr, local_addr);
  2078. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2079. res.set_content(local_addr.append(":").append(local_port),
  2080. "text/plain");
  2081. })
  2082. .Get("/endwith%",
  2083. [&](const Request & /*req*/, Response &res) {
  2084. res.set_content("Hello World!", "text/plain");
  2085. })
  2086. .Get("/a\\+\\+b",
  2087. [&](const Request &req, Response &res) {
  2088. ASSERT_TRUE(req.has_param("a +b"));
  2089. auto val = req.get_param_value("a +b");
  2090. res.set_content(val, "text/plain");
  2091. })
  2092. .Get("/", [&](const Request & /*req*/,
  2093. Response &res) { res.set_redirect("/hi"); })
  2094. .Post("/1",
  2095. [](const Request & /*req*/, Response &res) {
  2096. res.set_redirect("/2", StatusCode::SeeOther_303);
  2097. })
  2098. .Get("/2",
  2099. [](const Request & /*req*/, Response &res) {
  2100. res.set_content("redirected.", "text/plain");
  2101. res.status = StatusCode::OK_200;
  2102. })
  2103. .Post("/person",
  2104. [&](const Request &req, Response &res) {
  2105. if (req.has_param("name") && req.has_param("note")) {
  2106. persons_[req.get_param_value("name")] =
  2107. req.get_param_value("note");
  2108. } else {
  2109. res.status = StatusCode::BadRequest_400;
  2110. }
  2111. })
  2112. .Put("/person",
  2113. [&](const Request &req, Response &res) {
  2114. if (req.has_param("name") && req.has_param("note")) {
  2115. persons_[req.get_param_value("name")] =
  2116. req.get_param_value("note");
  2117. } else {
  2118. res.status = StatusCode::BadRequest_400;
  2119. }
  2120. })
  2121. .Get("/person/(.*)",
  2122. [&](const Request &req, Response &res) {
  2123. string name = req.matches[1];
  2124. if (persons_.find(name) != persons_.end()) {
  2125. auto note = persons_[name];
  2126. res.set_content(note, "text/plain");
  2127. } else {
  2128. res.status = StatusCode::NotFound_404;
  2129. }
  2130. })
  2131. .Post("/x-www-form-urlencoded-json",
  2132. [&](const Request &req, Response &res) {
  2133. auto json = req.get_param_value("json");
  2134. ASSERT_EQ(JSON_DATA, json);
  2135. res.set_content(json, "appliation/json");
  2136. res.status = StatusCode::OK_200;
  2137. })
  2138. .Get("/streamed-chunked",
  2139. [&](const Request & /*req*/, Response &res) {
  2140. res.set_chunked_content_provider(
  2141. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2142. sink.os << "123";
  2143. sink.os << "456";
  2144. sink.os << "789";
  2145. sink.done();
  2146. return true;
  2147. });
  2148. })
  2149. .Get("/streamed-chunked2",
  2150. [&](const Request & /*req*/, Response &res) {
  2151. auto i = new int(0);
  2152. res.set_chunked_content_provider(
  2153. "text/plain",
  2154. [i](size_t /*offset*/, DataSink &sink) {
  2155. switch (*i) {
  2156. case 0: sink.os << "123"; break;
  2157. case 1: sink.os << "456"; break;
  2158. case 2: sink.os << "789"; break;
  2159. case 3: sink.done(); break;
  2160. }
  2161. (*i)++;
  2162. return true;
  2163. },
  2164. [i](bool success) {
  2165. EXPECT_TRUE(success);
  2166. delete i;
  2167. });
  2168. })
  2169. .Get("/streamed-chunked-with-trailer",
  2170. [&](const Request & /*req*/, Response &res) {
  2171. auto i = new int(0);
  2172. res.set_header("Trailer", "Dummy1, Dummy2");
  2173. res.set_chunked_content_provider(
  2174. "text/plain",
  2175. [i](size_t /*offset*/, DataSink &sink) {
  2176. switch (*i) {
  2177. case 0: sink.os << "123"; break;
  2178. case 1: sink.os << "456"; break;
  2179. case 2: sink.os << "789"; break;
  2180. case 3: {
  2181. sink.done_with_trailer(
  2182. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2183. } break;
  2184. }
  2185. (*i)++;
  2186. return true;
  2187. },
  2188. [i](bool success) {
  2189. EXPECT_TRUE(success);
  2190. delete i;
  2191. });
  2192. })
  2193. .Get("/streamed",
  2194. [&](const Request & /*req*/, Response &res) {
  2195. res.set_content_provider(
  2196. 6, "text/plain",
  2197. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2198. sink.os << (offset < 3 ? "a" : "b");
  2199. return true;
  2200. });
  2201. })
  2202. .Get("/streamed-with-range",
  2203. [&](const Request &req, Response &res) {
  2204. auto data = new std::string("abcdefg");
  2205. res.set_content_provider(
  2206. data->size(), "text/plain",
  2207. [data](size_t offset, size_t length, DataSink &sink) {
  2208. size_t DATA_CHUNK_SIZE = 4;
  2209. const auto &d = *data;
  2210. auto out_len =
  2211. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2212. auto ret =
  2213. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2214. EXPECT_TRUE(ret);
  2215. return true;
  2216. },
  2217. [data, &req](bool success) {
  2218. EXPECT_EQ(success, !req.has_param("error"));
  2219. delete data;
  2220. });
  2221. })
  2222. .Get("/streamed-cancel",
  2223. [&](const Request & /*req*/, Response &res) {
  2224. res.set_content_provider(
  2225. size_t(-1), "text/plain",
  2226. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2227. sink.os << "data_chunk";
  2228. return true;
  2229. });
  2230. })
  2231. .Get("/regex-with-delimiter",
  2232. [&](const Request &req, Response & /*res*/) {
  2233. ASSERT_TRUE(req.has_param("key"));
  2234. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2235. })
  2236. .Get("/with-range",
  2237. [&](const Request & /*req*/, Response &res) {
  2238. res.set_content("abcdefg", "text/plain");
  2239. })
  2240. .Get("/with-range-customized-response",
  2241. [&](const Request & /*req*/, Response &res) {
  2242. res.status = StatusCode::BadRequest_400;
  2243. res.set_content(JSON_DATA, "application/json");
  2244. })
  2245. .Post("/chunked",
  2246. [&](const Request &req, Response & /*res*/) {
  2247. EXPECT_EQ(req.body, "dechunked post body");
  2248. })
  2249. .Post("/large-chunked",
  2250. [&](const Request &req, Response & /*res*/) {
  2251. std::string expected(6 * 30 * 1024u, 'a');
  2252. EXPECT_EQ(req.body, expected);
  2253. })
  2254. .Post("/multipart",
  2255. [&](const Request &req, Response & /*res*/) {
  2256. EXPECT_EQ(6u, req.files.size());
  2257. ASSERT_TRUE(!req.has_file("???"));
  2258. ASSERT_TRUE(req.body.empty());
  2259. {
  2260. const auto &file = req.get_file_value("text1");
  2261. EXPECT_TRUE(file.filename.empty());
  2262. EXPECT_EQ("text default", file.content);
  2263. }
  2264. {
  2265. const auto &file = req.get_file_value("text2");
  2266. EXPECT_TRUE(file.filename.empty());
  2267. EXPECT_EQ("aωb", file.content);
  2268. }
  2269. {
  2270. const auto &file = req.get_file_value("file1");
  2271. EXPECT_EQ("hello.txt", file.filename);
  2272. EXPECT_EQ("text/plain", file.content_type);
  2273. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2274. }
  2275. {
  2276. const auto &file = req.get_file_value("file3");
  2277. EXPECT_TRUE(file.filename.empty());
  2278. EXPECT_EQ("application/octet-stream", file.content_type);
  2279. EXPECT_EQ(0u, file.content.size());
  2280. }
  2281. {
  2282. const auto &file = req.get_file_value("file4");
  2283. EXPECT_TRUE(file.filename.empty());
  2284. EXPECT_EQ(0u, file.content.size());
  2285. EXPECT_EQ("application/json tmp-string", file.content_type);
  2286. }
  2287. })
  2288. .Post("/multipart/multi_file_values",
  2289. [&](const Request &req, Response & /*res*/) {
  2290. EXPECT_EQ(5u, req.files.size());
  2291. ASSERT_TRUE(!req.has_file("???"));
  2292. ASSERT_TRUE(req.body.empty());
  2293. {
  2294. const auto &text_value = req.get_file_values("text");
  2295. EXPECT_EQ(1u, text_value.size());
  2296. auto &text = text_value[0];
  2297. EXPECT_TRUE(text.filename.empty());
  2298. EXPECT_EQ("default text", text.content);
  2299. }
  2300. {
  2301. const auto &text1_values = req.get_file_values("multi_text1");
  2302. EXPECT_EQ(2u, text1_values.size());
  2303. EXPECT_EQ("aaaaa", text1_values[0].content);
  2304. EXPECT_EQ("bbbbb", text1_values[1].content);
  2305. }
  2306. {
  2307. const auto &file1_values = req.get_file_values("multi_file1");
  2308. EXPECT_EQ(2u, file1_values.size());
  2309. auto file1 = file1_values[0];
  2310. EXPECT_EQ(file1.filename, "hello.txt");
  2311. EXPECT_EQ(file1.content_type, "text/plain");
  2312. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2313. auto file2 = file1_values[1];
  2314. EXPECT_EQ(file2.filename, "world.json");
  2315. EXPECT_EQ(file2.content_type, "application/json");
  2316. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2317. }
  2318. })
  2319. .Post("/empty",
  2320. [&](const Request &req, Response &res) {
  2321. EXPECT_EQ(req.body, "");
  2322. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2323. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2324. res.set_content("empty", "text/plain");
  2325. })
  2326. .Post("/empty-no-content-type",
  2327. [&](const Request &req, Response &res) {
  2328. EXPECT_EQ(req.body, "");
  2329. EXPECT_FALSE(req.has_header("Content-Type"));
  2330. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2331. res.set_content("empty-no-content-type", "text/plain");
  2332. })
  2333. .Post("/path-only",
  2334. [&](const Request &req, Response &res) {
  2335. EXPECT_EQ(req.body, "");
  2336. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2337. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2338. res.set_content("path-only", "text/plain");
  2339. })
  2340. .Post("/path-headers-only",
  2341. [&](const Request &req, Response &res) {
  2342. EXPECT_EQ(req.body, "");
  2343. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2344. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2345. EXPECT_EQ("world", req.get_header_value("hello"));
  2346. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2347. res.set_content("path-headers-only", "text/plain");
  2348. })
  2349. .Post("/post-large",
  2350. [&](const Request &req, Response &res) {
  2351. EXPECT_EQ(req.body, LARGE_DATA);
  2352. res.set_content(req.body, "text/plain");
  2353. })
  2354. .Put("/empty-no-content-type",
  2355. [&](const Request &req, Response &res) {
  2356. EXPECT_EQ(req.body, "");
  2357. EXPECT_FALSE(req.has_header("Content-Type"));
  2358. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2359. res.set_content("empty-no-content-type", "text/plain");
  2360. })
  2361. .Put("/put",
  2362. [&](const Request &req, Response &res) {
  2363. EXPECT_EQ(req.body, "PUT");
  2364. res.set_content(req.body, "text/plain");
  2365. })
  2366. .Put("/put-large",
  2367. [&](const Request &req, Response &res) {
  2368. EXPECT_EQ(req.body, LARGE_DATA);
  2369. res.set_content(req.body, "text/plain");
  2370. })
  2371. .Patch("/patch",
  2372. [&](const Request &req, Response &res) {
  2373. EXPECT_EQ(req.body, "PATCH");
  2374. res.set_content(req.body, "text/plain");
  2375. })
  2376. .Delete("/delete",
  2377. [&](const Request & /*req*/, Response &res) {
  2378. res.set_content("DELETE", "text/plain");
  2379. })
  2380. .Delete("/delete-body",
  2381. [&](const Request &req, Response &res) {
  2382. EXPECT_EQ(req.body, "content");
  2383. res.set_content(req.body, "text/plain");
  2384. })
  2385. .Options(R"(\*)",
  2386. [&](const Request & /*req*/, Response &res) {
  2387. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2388. })
  2389. .Get("/request-target",
  2390. [&](const Request &req, Response & /*res*/) {
  2391. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2392. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2393. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2394. })
  2395. .Get("/long-query-value",
  2396. [&](const Request &req, Response & /*res*/) {
  2397. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2398. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2399. })
  2400. .Get("/array-param",
  2401. [&](const Request &req, Response & /*res*/) {
  2402. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2403. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2404. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2405. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2406. })
  2407. .Post("/validate-no-multiple-headers",
  2408. [&](const Request &req, Response & /*res*/) {
  2409. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2410. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2411. })
  2412. .Post("/content_receiver",
  2413. [&](const Request &req, Response &res,
  2414. const ContentReader &content_reader) {
  2415. if (req.is_multipart_form_data()) {
  2416. MultipartFormDataItems files;
  2417. content_reader(
  2418. [&](const MultipartFormData &file) {
  2419. files.push_back(file);
  2420. return true;
  2421. },
  2422. [&](const char *data, size_t data_length) {
  2423. files.back().content.append(data, data_length);
  2424. return true;
  2425. });
  2426. EXPECT_EQ(5u, files.size());
  2427. {
  2428. const auto &file = get_file_value(files, "text1");
  2429. EXPECT_TRUE(file.filename.empty());
  2430. EXPECT_EQ("text default", file.content);
  2431. }
  2432. {
  2433. const auto &file = get_file_value(files, "text2");
  2434. EXPECT_TRUE(file.filename.empty());
  2435. EXPECT_EQ("aωb", file.content);
  2436. }
  2437. {
  2438. const auto &file = get_file_value(files, "file1");
  2439. EXPECT_EQ("hello.txt", file.filename);
  2440. EXPECT_EQ("text/plain", file.content_type);
  2441. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2442. }
  2443. {
  2444. const auto &file = get_file_value(files, "file3");
  2445. EXPECT_TRUE(file.filename.empty());
  2446. EXPECT_EQ("application/octet-stream", file.content_type);
  2447. EXPECT_EQ(0u, file.content.size());
  2448. }
  2449. } else {
  2450. std::string body;
  2451. content_reader([&](const char *data, size_t data_length) {
  2452. EXPECT_EQ(7U, data_length);
  2453. body.append(data, data_length);
  2454. return true;
  2455. });
  2456. EXPECT_EQ(body, "content");
  2457. res.set_content(body, "text/plain");
  2458. }
  2459. })
  2460. .Put("/content_receiver",
  2461. [&](const Request & /*req*/, Response &res,
  2462. const ContentReader &content_reader) {
  2463. std::string body;
  2464. content_reader([&](const char *data, size_t data_length) {
  2465. body.append(data, data_length);
  2466. return true;
  2467. });
  2468. EXPECT_EQ(body, "content");
  2469. res.set_content(body, "text/plain");
  2470. })
  2471. .Patch("/content_receiver",
  2472. [&](const Request & /*req*/, Response &res,
  2473. const ContentReader &content_reader) {
  2474. std::string body;
  2475. content_reader([&](const char *data, size_t data_length) {
  2476. body.append(data, data_length);
  2477. return true;
  2478. });
  2479. EXPECT_EQ(body, "content");
  2480. res.set_content(body, "text/plain");
  2481. })
  2482. .Post("/query-string-and-body",
  2483. [&](const Request &req, Response & /*res*/) {
  2484. ASSERT_TRUE(req.has_param("key"));
  2485. EXPECT_EQ(req.get_param_value("key"), "value");
  2486. EXPECT_EQ(req.body, "content");
  2487. })
  2488. .Get("/last-request",
  2489. [&](const Request &req, Response & /*res*/) {
  2490. EXPECT_EQ("close", req.get_header_value("Connection"));
  2491. })
  2492. .Get(R"(/redirect/(\d+))",
  2493. [&](const Request &req, Response &res) {
  2494. auto num = std::stoi(req.matches[1]) + 1;
  2495. std::string url = "/redirect/" + std::to_string(num);
  2496. res.set_redirect(url);
  2497. })
  2498. .Post("/binary",
  2499. [&](const Request &req, Response &res) {
  2500. EXPECT_EQ(4U, req.body.size());
  2501. EXPECT_EQ("application/octet-stream",
  2502. req.get_header_value("Content-Type"));
  2503. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2504. res.set_content(req.body, "application/octet-stream");
  2505. })
  2506. .Put("/binary",
  2507. [&](const Request &req, Response &res) {
  2508. EXPECT_EQ(4U, req.body.size());
  2509. EXPECT_EQ("application/octet-stream",
  2510. req.get_header_value("Content-Type"));
  2511. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2512. res.set_content(req.body, "application/octet-stream");
  2513. })
  2514. .Patch("/binary",
  2515. [&](const Request &req, Response &res) {
  2516. EXPECT_EQ(4U, req.body.size());
  2517. EXPECT_EQ("application/octet-stream",
  2518. req.get_header_value("Content-Type"));
  2519. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2520. res.set_content(req.body, "application/octet-stream");
  2521. })
  2522. .Delete("/binary",
  2523. [&](const Request &req, Response &res) {
  2524. EXPECT_EQ(4U, req.body.size());
  2525. EXPECT_EQ("application/octet-stream",
  2526. req.get_header_value("Content-Type"));
  2527. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2528. res.set_content(req.body, "application/octet-stream");
  2529. })
  2530. .Get("/issue1772",
  2531. [&](const Request & /*req*/, Response &res) {
  2532. res.status = 401;
  2533. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2534. })
  2535. .Delete("/issue609",
  2536. [](const httplib::Request &, httplib::Response &res,
  2537. const httplib::ContentReader &) {
  2538. res.set_content("ok", "text/plain");
  2539. })
  2540. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  2541. .Get("/compress",
  2542. [&](const Request & /*req*/, Response &res) {
  2543. res.set_content(
  2544. "12345678901234567890123456789012345678901234567890123456789"
  2545. "01234567890123456789012345678901234567890",
  2546. "text/plain");
  2547. })
  2548. .Get("/nocompress",
  2549. [&](const Request & /*req*/, Response &res) {
  2550. res.set_content(
  2551. "12345678901234567890123456789012345678901234567890123456789"
  2552. "01234567890123456789012345678901234567890",
  2553. "application/octet-stream");
  2554. })
  2555. .Post("/compress-multipart",
  2556. [&](const Request &req, Response & /*res*/) {
  2557. EXPECT_EQ(2u, req.files.size());
  2558. ASSERT_TRUE(!req.has_file("???"));
  2559. {
  2560. const auto &file = req.get_file_value("key1");
  2561. EXPECT_TRUE(file.filename.empty());
  2562. EXPECT_EQ("test", file.content);
  2563. }
  2564. {
  2565. const auto &file = req.get_file_value("key2");
  2566. EXPECT_TRUE(file.filename.empty());
  2567. EXPECT_EQ("--abcdefg123", file.content);
  2568. }
  2569. })
  2570. #endif
  2571. ;
  2572. persons_["john"] = "programmer";
  2573. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2574. svr_.wait_until_ready();
  2575. }
  2576. virtual void TearDown() {
  2577. svr_.stop();
  2578. if (!request_threads_.empty()) {
  2579. std::this_thread::sleep_for(std::chrono::seconds(1));
  2580. for (auto &t : request_threads_) {
  2581. t.join();
  2582. }
  2583. }
  2584. t_.join();
  2585. }
  2586. map<string, string> persons_;
  2587. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2588. SSLClient cli_;
  2589. SSLServer svr_;
  2590. #else
  2591. Client cli_;
  2592. Server svr_;
  2593. #endif
  2594. thread t_;
  2595. std::vector<thread> request_threads_;
  2596. };
  2597. TEST_F(ServerTest, GetMethod200) {
  2598. auto res = cli_.Get("/hi");
  2599. ASSERT_TRUE(res);
  2600. EXPECT_EQ("HTTP/1.1", res->version);
  2601. EXPECT_EQ(StatusCode::OK_200, res->status);
  2602. EXPECT_EQ("OK", res->reason);
  2603. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2604. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2605. EXPECT_EQ("Hello World!", res->body);
  2606. }
  2607. TEST_F(ServerTest, GetEmptyFile) {
  2608. auto res = cli_.Get("/empty_file");
  2609. ASSERT_TRUE(res);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2612. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  2613. EXPECT_EQ("", res->body);
  2614. }
  2615. TEST_F(ServerTest, GetFileContent) {
  2616. auto res = cli_.Get("/file_content");
  2617. ASSERT_TRUE(res);
  2618. EXPECT_EQ(StatusCode::OK_200, res->status);
  2619. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2620. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2621. EXPECT_EQ("test.html", res->body);
  2622. }
  2623. TEST_F(ServerTest, GetFileContentWithRange) {
  2624. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  2625. ASSERT_TRUE(res);
  2626. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2627. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2628. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  2629. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  2630. EXPECT_EQ("est", res->body);
  2631. }
  2632. TEST_F(ServerTest, GetFileContentWithContentType) {
  2633. auto res = cli_.Get("/file_content_with_content_type");
  2634. ASSERT_TRUE(res);
  2635. EXPECT_EQ(StatusCode::OK_200, res->status);
  2636. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2637. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2638. EXPECT_EQ("file\n", res->body);
  2639. }
  2640. TEST_F(ServerTest, GetInvalidFileContent) {
  2641. auto res = cli_.Get("/invalid_file_content");
  2642. ASSERT_TRUE(res);
  2643. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2644. }
  2645. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2646. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2647. ASSERT_TRUE(res);
  2648. EXPECT_EQ("HTTP/1.1", res->version);
  2649. EXPECT_EQ(StatusCode::OK_200, res->status);
  2650. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2651. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2652. EXPECT_EQ("Hello World!", res->body);
  2653. }
  2654. TEST_F(ServerTest, GetMethod302) {
  2655. auto res = cli_.Get("/");
  2656. ASSERT_TRUE(res);
  2657. EXPECT_EQ(StatusCode::Found_302, res->status);
  2658. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2659. }
  2660. TEST_F(ServerTest, GetMethod302Redirect) {
  2661. cli_.set_follow_location(true);
  2662. auto res = cli_.Get("/");
  2663. ASSERT_TRUE(res);
  2664. EXPECT_EQ(StatusCode::OK_200, res->status);
  2665. EXPECT_EQ("Hello World!", res->body);
  2666. EXPECT_EQ("/hi", res->location);
  2667. }
  2668. TEST_F(ServerTest, GetMethod404) {
  2669. auto res = cli_.Get("/invalid");
  2670. ASSERT_TRUE(res);
  2671. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2672. }
  2673. TEST_F(ServerTest, HeadMethod200) {
  2674. auto res = cli_.Head("/hi");
  2675. ASSERT_TRUE(res);
  2676. EXPECT_EQ(StatusCode::OK_200, res->status);
  2677. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2678. EXPECT_TRUE(res->body.empty());
  2679. }
  2680. TEST_F(ServerTest, HeadMethod200Static) {
  2681. auto res = cli_.Head("/mount/dir/index.html");
  2682. ASSERT_TRUE(res);
  2683. EXPECT_EQ(StatusCode::OK_200, res->status);
  2684. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2685. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2686. EXPECT_TRUE(res->body.empty());
  2687. }
  2688. TEST_F(ServerTest, HeadMethod404) {
  2689. auto res = cli_.Head("/invalid");
  2690. ASSERT_TRUE(res);
  2691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2692. EXPECT_TRUE(res->body.empty());
  2693. }
  2694. TEST_F(ServerTest, GetMethodPersonJohn) {
  2695. auto res = cli_.Get("/person/john");
  2696. ASSERT_TRUE(res);
  2697. EXPECT_EQ(StatusCode::OK_200, res->status);
  2698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2699. EXPECT_EQ("programmer", res->body);
  2700. }
  2701. TEST_F(ServerTest, PostMethod1) {
  2702. auto res = cli_.Get("/person/john1");
  2703. ASSERT_TRUE(res);
  2704. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2705. res = cli_.Post("/person", "name=john1&note=coder",
  2706. "application/x-www-form-urlencoded");
  2707. ASSERT_TRUE(res);
  2708. ASSERT_EQ(StatusCode::OK_200, res->status);
  2709. res = cli_.Get("/person/john1");
  2710. ASSERT_TRUE(res);
  2711. ASSERT_EQ(StatusCode::OK_200, res->status);
  2712. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2713. ASSERT_EQ("coder", res->body);
  2714. }
  2715. TEST_F(ServerTest, PostMethod2) {
  2716. auto res = cli_.Get("/person/john2");
  2717. ASSERT_TRUE(res);
  2718. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2719. Params params;
  2720. params.emplace("name", "john2");
  2721. params.emplace("note", "coder");
  2722. res = cli_.Post("/person", params);
  2723. ASSERT_TRUE(res);
  2724. ASSERT_EQ(StatusCode::OK_200, res->status);
  2725. res = cli_.Get("/person/john2");
  2726. ASSERT_TRUE(res);
  2727. ASSERT_EQ(StatusCode::OK_200, res->status);
  2728. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2729. ASSERT_EQ("coder", res->body);
  2730. }
  2731. TEST_F(ServerTest, PutMethod3) {
  2732. auto res = cli_.Get("/person/john3");
  2733. ASSERT_TRUE(res);
  2734. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2735. Params params;
  2736. params.emplace("name", "john3");
  2737. params.emplace("note", "coder");
  2738. res = cli_.Put("/person", params);
  2739. ASSERT_TRUE(res);
  2740. ASSERT_EQ(StatusCode::OK_200, res->status);
  2741. res = cli_.Get("/person/john3");
  2742. ASSERT_TRUE(res);
  2743. ASSERT_EQ(StatusCode::OK_200, res->status);
  2744. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2745. ASSERT_EQ("coder", res->body);
  2746. }
  2747. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2748. Params params;
  2749. params.emplace("json", JSON_DATA);
  2750. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2751. ASSERT_TRUE(res);
  2752. ASSERT_EQ(StatusCode::OK_200, res->status);
  2753. ASSERT_EQ(JSON_DATA, res->body);
  2754. }
  2755. TEST_F(ServerTest, PostEmptyContent) {
  2756. auto res = cli_.Post("/empty", "", "text/plain");
  2757. ASSERT_TRUE(res);
  2758. ASSERT_EQ(StatusCode::OK_200, res->status);
  2759. ASSERT_EQ("empty", res->body);
  2760. }
  2761. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2762. auto res = cli_.Post("/empty-no-content-type");
  2763. ASSERT_TRUE(res);
  2764. ASSERT_EQ(StatusCode::OK_200, res->status);
  2765. ASSERT_EQ("empty-no-content-type", res->body);
  2766. }
  2767. TEST_F(ServerTest, PostPathOnly) {
  2768. auto res = cli_.Post("/path-only");
  2769. ASSERT_TRUE(res);
  2770. ASSERT_EQ(StatusCode::OK_200, res->status);
  2771. ASSERT_EQ("path-only", res->body);
  2772. }
  2773. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2774. auto res = cli_.Post("/path-headers-only",
  2775. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2776. ASSERT_TRUE(res);
  2777. ASSERT_EQ(StatusCode::OK_200, res->status);
  2778. ASSERT_EQ("path-headers-only", res->body);
  2779. }
  2780. TEST_F(ServerTest, PostLarge) {
  2781. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2782. ASSERT_TRUE(res);
  2783. ASSERT_EQ(StatusCode::OK_200, res->status);
  2784. EXPECT_EQ(LARGE_DATA, res->body);
  2785. }
  2786. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2787. auto res = cli_.Put("/empty-no-content-type");
  2788. ASSERT_TRUE(res);
  2789. ASSERT_EQ(StatusCode::OK_200, res->status);
  2790. ASSERT_EQ("empty-no-content-type", res->body);
  2791. }
  2792. TEST_F(ServerTest, GetMethodDir) {
  2793. auto res = cli_.Get("/dir/");
  2794. ASSERT_TRUE(res);
  2795. EXPECT_EQ(StatusCode::OK_200, res->status);
  2796. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2797. auto body = R"(<html>
  2798. <head>
  2799. </head>
  2800. <body>
  2801. <a href="/dir/test.html">Test</a>
  2802. <a href="/hi">hi</a>
  2803. </body>
  2804. </html>
  2805. )";
  2806. EXPECT_EQ(body, res->body);
  2807. }
  2808. TEST_F(ServerTest, GetMethodDirTest) {
  2809. auto res = cli_.Get("/dir/test.html");
  2810. ASSERT_TRUE(res);
  2811. EXPECT_EQ(StatusCode::OK_200, res->status);
  2812. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2813. EXPECT_EQ("test.html", res->body);
  2814. }
  2815. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2816. auto res = cli_.Get("/dir/../dir/test.html");
  2817. ASSERT_TRUE(res);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2820. EXPECT_EQ("test.html", res->body);
  2821. }
  2822. TEST_F(ServerTest, GetMethodInvalidPath) {
  2823. auto res = cli_.Get("/dir/../test.html");
  2824. ASSERT_TRUE(res);
  2825. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2826. }
  2827. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2828. auto res = cli_.Get("/../www/dir/test.html");
  2829. ASSERT_TRUE(res);
  2830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2831. }
  2832. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2833. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2834. ASSERT_TRUE(res);
  2835. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2836. }
  2837. TEST_F(ServerTest, GetMethodDirMountTest) {
  2838. auto res = cli_.Get("/mount/dir/test.html");
  2839. ASSERT_TRUE(res);
  2840. EXPECT_EQ(StatusCode::OK_200, res->status);
  2841. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2842. EXPECT_EQ("test.html", res->body);
  2843. }
  2844. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2845. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2846. ASSERT_TRUE(res);
  2847. EXPECT_EQ(StatusCode::OK_200, res->status);
  2848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2849. EXPECT_EQ("test.html", res->body);
  2850. }
  2851. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2852. auto res = cli_.Get("/mount/dir/../test.html");
  2853. ASSERT_TRUE(res);
  2854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2855. }
  2856. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  2857. auto res = cli_.Get("/mount/dir/test.html%00.js");
  2858. ASSERT_TRUE(res);
  2859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2860. }
  2861. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2862. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2863. ASSERT_TRUE(res);
  2864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2865. }
  2866. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2867. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2868. ASSERT_TRUE(res);
  2869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2870. }
  2871. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  2872. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  2873. ASSERT_TRUE(res);
  2874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2875. }
  2876. TEST_F(ServerTest, PostMethod303) {
  2877. auto res = cli_.Post("/1", "body", "text/plain");
  2878. ASSERT_TRUE(res);
  2879. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  2880. EXPECT_EQ("/2", res->get_header_value("Location"));
  2881. }
  2882. TEST_F(ServerTest, PostMethod303Redirect) {
  2883. cli_.set_follow_location(true);
  2884. auto res = cli_.Post("/1", "body", "text/plain");
  2885. ASSERT_TRUE(res);
  2886. EXPECT_EQ(StatusCode::OK_200, res->status);
  2887. EXPECT_EQ("redirected.", res->body);
  2888. EXPECT_EQ("/2", res->location);
  2889. }
  2890. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2891. auto res = cli_.Get("/dir/test.abcde");
  2892. ASSERT_TRUE(res);
  2893. EXPECT_EQ(StatusCode::OK_200, res->status);
  2894. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2895. EXPECT_EQ("abcde", res->body);
  2896. }
  2897. TEST_F(ServerTest, StaticFileRange) {
  2898. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2899. ASSERT_TRUE(res);
  2900. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2901. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2902. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2903. EXPECT_EQ(true, res->has_header("Content-Range"));
  2904. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2905. EXPECT_EQ(std::string("cd"), res->body);
  2906. }
  2907. TEST_F(ServerTest, StaticFileRanges) {
  2908. auto res =
  2909. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2910. ASSERT_TRUE(res);
  2911. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2912. EXPECT_TRUE(
  2913. res->get_header_value("Content-Type")
  2914. .find(
  2915. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2916. 0);
  2917. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  2918. }
  2919. TEST_F(ServerTest, StaticFileRangeHead) {
  2920. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2921. ASSERT_TRUE(res);
  2922. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2923. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2924. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2925. EXPECT_EQ(true, res->has_header("Content-Range"));
  2926. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2927. }
  2928. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2929. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2930. ASSERT_TRUE(res);
  2931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2932. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2933. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2934. EXPECT_EQ(true, res->has_header("Content-Range"));
  2935. EXPECT_EQ("bytes 1048571-1048575/1048576",
  2936. res->get_header_value("Content-Range"));
  2937. EXPECT_EQ("LAST\n", res->body);
  2938. }
  2939. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  2940. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  2941. ASSERT_TRUE(res);
  2942. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2944. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  2945. EXPECT_EQ(true, res->has_header("Content-Range"));
  2946. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  2947. }
  2948. TEST_F(ServerTest, StaticFileBigFile) {
  2949. auto res = cli_.Get("/dir/1MB.txt");
  2950. ASSERT_TRUE(res);
  2951. EXPECT_EQ(StatusCode::OK_200, res->status);
  2952. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2953. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  2954. }
  2955. TEST_F(ServerTest, InvalidBaseDirMount) {
  2956. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2957. }
  2958. TEST_F(ServerTest, Binary) {
  2959. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2960. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2961. "application/octet-stream");
  2962. ASSERT_TRUE(res);
  2963. ASSERT_EQ(StatusCode::OK_200, res->status);
  2964. ASSERT_EQ(4U, res->body.size());
  2965. res = cli_.Put("/binary", binary.data(), binary.size(),
  2966. "application/octet-stream");
  2967. ASSERT_TRUE(res);
  2968. ASSERT_EQ(StatusCode::OK_200, res->status);
  2969. ASSERT_EQ(4U, res->body.size());
  2970. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2971. "application/octet-stream");
  2972. ASSERT_TRUE(res);
  2973. ASSERT_EQ(StatusCode::OK_200, res->status);
  2974. ASSERT_EQ(4U, res->body.size());
  2975. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2976. "application/octet-stream");
  2977. ASSERT_TRUE(res);
  2978. ASSERT_EQ(StatusCode::OK_200, res->status);
  2979. ASSERT_EQ(4U, res->body.size());
  2980. }
  2981. TEST_F(ServerTest, BinaryString) {
  2982. auto binary = std::string("\x00\x01\x02\x03", 4);
  2983. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2984. ASSERT_TRUE(res);
  2985. ASSERT_EQ(StatusCode::OK_200, res->status);
  2986. ASSERT_EQ(4U, res->body.size());
  2987. res = cli_.Put("/binary", binary, "application/octet-stream");
  2988. ASSERT_TRUE(res);
  2989. ASSERT_EQ(StatusCode::OK_200, res->status);
  2990. ASSERT_EQ(4U, res->body.size());
  2991. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2992. ASSERT_TRUE(res);
  2993. ASSERT_EQ(StatusCode::OK_200, res->status);
  2994. ASSERT_EQ(4U, res->body.size());
  2995. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2996. ASSERT_TRUE(res);
  2997. ASSERT_EQ(StatusCode::OK_200, res->status);
  2998. ASSERT_EQ(4U, res->body.size());
  2999. }
  3000. TEST_F(ServerTest, EmptyRequest) {
  3001. auto res = cli_.Get("");
  3002. ASSERT_TRUE(!res);
  3003. EXPECT_EQ(Error::Connection, res.error());
  3004. }
  3005. TEST_F(ServerTest, LongRequest) {
  3006. std::string request;
  3007. for (size_t i = 0; i < 545; i++) {
  3008. request += "/TooLongRequest";
  3009. }
  3010. request += "OK";
  3011. auto res = cli_.Get(request.c_str());
  3012. ASSERT_TRUE(res);
  3013. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3014. }
  3015. TEST_F(ServerTest, TooLongRequest) {
  3016. std::string request;
  3017. for (size_t i = 0; i < 546; i++) {
  3018. request += "/TooLongRequest";
  3019. }
  3020. request += "_NG";
  3021. auto res = cli_.Get(request.c_str());
  3022. ASSERT_TRUE(res);
  3023. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3024. }
  3025. TEST_F(ServerTest, AlmostTooLongRequest) {
  3026. // test for #2046 - URI length check shouldn't include other content on req
  3027. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3028. // leading /, space, HTTP/1.1)
  3029. std::string request =
  3030. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3031. auto res = cli_.Get(request.c_str());
  3032. ASSERT_TRUE(res);
  3033. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3034. }
  3035. TEST_F(ServerTest, LongHeader) {
  3036. Request req;
  3037. req.method = "GET";
  3038. req.path = "/hi";
  3039. std::string host_and_port;
  3040. host_and_port += HOST;
  3041. host_and_port += ":";
  3042. host_and_port += std::to_string(PORT);
  3043. req.headers.emplace("Host", host_and_port.c_str());
  3044. req.headers.emplace("Accept", "*/*");
  3045. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3046. req.headers.emplace(
  3047. "Header-Name",
  3048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3076. "@@@@@@@@@@@@@@@@");
  3077. auto res = std::make_shared<Response>();
  3078. auto error = Error::Success;
  3079. auto ret = cli_.send(req, *res, error);
  3080. ASSERT_TRUE(ret);
  3081. EXPECT_EQ(StatusCode::OK_200, res->status);
  3082. }
  3083. TEST_F(ServerTest, LongQueryValue) {
  3084. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3085. ASSERT_TRUE(res);
  3086. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3087. }
  3088. TEST_F(ServerTest, TooLongHeader) {
  3089. Request req;
  3090. req.method = "GET";
  3091. req.path = "/hi";
  3092. std::string host_and_port;
  3093. host_and_port += HOST;
  3094. host_and_port += ":";
  3095. host_and_port += std::to_string(PORT);
  3096. req.headers.emplace("Host", host_and_port.c_str());
  3097. req.headers.emplace("Accept", "*/*");
  3098. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3099. req.headers.emplace(
  3100. "Header-Name",
  3101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3114. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3115. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3116. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3117. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3118. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3119. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3120. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3129. "@@@@@@@@@@@@@@@@@");
  3130. auto res = std::make_shared<Response>();
  3131. auto error = Error::Success;
  3132. auto ret = cli_.send(req, *res, error);
  3133. ASSERT_TRUE(ret);
  3134. EXPECT_EQ(StatusCode::OK_200, res->status);
  3135. }
  3136. TEST_F(ServerTest, PercentEncoding) {
  3137. auto res = cli_.Get("/e%6edwith%");
  3138. ASSERT_TRUE(res);
  3139. EXPECT_EQ(StatusCode::OK_200, res->status);
  3140. }
  3141. TEST_F(ServerTest, PercentEncodingUnicode) {
  3142. auto res = cli_.Get("/e%u006edwith%");
  3143. ASSERT_TRUE(res);
  3144. EXPECT_EQ(StatusCode::OK_200, res->status);
  3145. }
  3146. TEST_F(ServerTest, InvalidPercentEncoding) {
  3147. auto res = cli_.Get("/%endwith%");
  3148. ASSERT_TRUE(res);
  3149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3150. }
  3151. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3152. auto res = cli_.Get("/%uendwith%");
  3153. ASSERT_TRUE(res);
  3154. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3155. }
  3156. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3157. auto res = cli_.Get("/hello?aaa=bbb%");
  3158. ASSERT_TRUE(res);
  3159. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3160. }
  3161. TEST_F(ServerTest, PlusSignEncoding) {
  3162. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3163. ASSERT_TRUE(res);
  3164. EXPECT_EQ(StatusCode::OK_200, res->status);
  3165. EXPECT_EQ("a +b", res->body);
  3166. }
  3167. TEST_F(ServerTest, MultipartFormData) {
  3168. MultipartFormDataItems items = {
  3169. {"text1", "text default", "", ""},
  3170. {"text2", "aωb", "", ""},
  3171. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3172. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3173. {"file3", "", "", "application/octet-stream"},
  3174. {"file4", "", "", " application/json tmp-string "}};
  3175. auto res = cli_.Post("/multipart", items);
  3176. ASSERT_TRUE(res);
  3177. EXPECT_EQ(StatusCode::OK_200, res->status);
  3178. }
  3179. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3180. MultipartFormDataItems items = {
  3181. {"text", "default text", "", ""},
  3182. {"multi_text1", "aaaaa", "", ""},
  3183. {"multi_text1", "bbbbb", "", ""},
  3184. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3185. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3186. "application/json"},
  3187. };
  3188. auto res = cli_.Post("/multipart/multi_file_values", items);
  3189. ASSERT_TRUE(res);
  3190. EXPECT_EQ(StatusCode::OK_200, res->status);
  3191. }
  3192. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3193. auto res = cli_.Get("/hi");
  3194. ASSERT_TRUE(res);
  3195. EXPECT_EQ(StatusCode::OK_200, res->status);
  3196. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3197. EXPECT_EQ("Hello World!", res->body);
  3198. }
  3199. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3200. Request req;
  3201. req.method = "POST";
  3202. req.path = "/chunked";
  3203. std::string host_and_port;
  3204. host_and_port += HOST;
  3205. host_and_port += ":";
  3206. host_and_port += std::to_string(PORT);
  3207. req.headers.emplace("Host", host_and_port.c_str());
  3208. req.headers.emplace("Accept", "*/*");
  3209. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3210. req.headers.emplace("Content-Type", "text/plain");
  3211. req.headers.emplace("Content-Length", "0");
  3212. req.headers.emplace(
  3213. "Transfer-Encoding",
  3214. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3215. // Client does not chunk, so make a chunked body manually.
  3216. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3217. auto res = std::make_shared<Response>();
  3218. auto error = Error::Success;
  3219. auto ret = cli_.send(req, *res, error);
  3220. ASSERT_TRUE(ret);
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. }
  3223. TEST_F(ServerTest, GetStreamed2) {
  3224. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3225. ASSERT_TRUE(res);
  3226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3227. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3228. EXPECT_EQ(true, res->has_header("Content-Range"));
  3229. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3230. EXPECT_EQ(std::string("ab"), res->body);
  3231. }
  3232. TEST_F(ServerTest, GetStreamed) {
  3233. auto res = cli_.Get("/streamed");
  3234. ASSERT_TRUE(res);
  3235. EXPECT_EQ(StatusCode::OK_200, res->status);
  3236. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3237. EXPECT_EQ(std::string("aaabbb"), res->body);
  3238. }
  3239. TEST_F(ServerTest, GetStreamedWithRange1) {
  3240. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3241. ASSERT_TRUE(res);
  3242. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3243. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3244. EXPECT_EQ(true, res->has_header("Content-Range"));
  3245. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3246. EXPECT_EQ(std::string("def"), res->body);
  3247. }
  3248. TEST_F(ServerTest, GetStreamedWithRange2) {
  3249. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3250. ASSERT_TRUE(res);
  3251. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3252. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3253. EXPECT_EQ(true, res->has_header("Content-Range"));
  3254. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3255. EXPECT_EQ(std::string("bcdefg"), res->body);
  3256. }
  3257. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3258. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3259. ASSERT_TRUE(res);
  3260. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3261. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3262. EXPECT_EQ(true, res->has_header("Content-Range"));
  3263. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3264. EXPECT_EQ(std::string("efg"), res->body);
  3265. }
  3266. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3267. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3268. ASSERT_TRUE(res);
  3269. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3270. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3271. EXPECT_EQ(false, res->has_header("Content-Range"));
  3272. EXPECT_EQ(0U, res->body.size());
  3273. }
  3274. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3275. auto res = cli_.Get("/streamed-with-range",
  3276. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3277. "92233720368547758079223372036854775807"}});
  3278. ASSERT_TRUE(res);
  3279. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3280. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3281. EXPECT_EQ(false, res->has_header("Content-Range"));
  3282. EXPECT_EQ(0U, res->body.size());
  3283. }
  3284. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3285. auto res = cli_.Get(
  3286. "/with-range",
  3287. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3288. {"Accept-Encoding", ""}});
  3289. ASSERT_TRUE(res);
  3290. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3291. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3292. EXPECT_EQ(true, res->has_header("Content-Range"));
  3293. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3294. EXPECT_EQ(std::string("abcdefg"), res->body);
  3295. }
  3296. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3297. auto res = cli_.Get("/with-range", {
  3298. {"Range", "bytes=0-"},
  3299. {"Accept-Encoding", ""},
  3300. });
  3301. ASSERT_TRUE(res);
  3302. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3303. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3304. EXPECT_EQ(true, res->has_header("Content-Range"));
  3305. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3306. EXPECT_EQ(std::string("abcdefg"), res->body);
  3307. }
  3308. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3309. auto res =
  3310. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3311. ASSERT_TRUE(res);
  3312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3313. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3314. EXPECT_EQ(false, res->has_header("Content-Range"));
  3315. EXPECT_EQ(267U, res->body.size());
  3316. }
  3317. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3318. Ranges ranges;
  3319. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3320. ranges.emplace_back(0, -1);
  3321. }
  3322. auto res =
  3323. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3324. ASSERT_TRUE(res);
  3325. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3326. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3327. EXPECT_EQ(false, res->has_header("Content-Range"));
  3328. EXPECT_EQ(0U, res->body.size());
  3329. }
  3330. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3331. auto res = cli_.Get("/streamed-with-range?error",
  3332. {{make_range_header({{0, -1}, {0, -1}})}});
  3333. ASSERT_TRUE(res);
  3334. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3335. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3336. EXPECT_EQ(false, res->has_header("Content-Range"));
  3337. EXPECT_EQ(0U, res->body.size());
  3338. }
  3339. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3340. auto res = cli_.Get("/streamed-with-range?error",
  3341. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3342. ASSERT_TRUE(res);
  3343. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3344. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3345. EXPECT_EQ(false, res->has_header("Content-Range"));
  3346. EXPECT_EQ(0U, res->body.size());
  3347. }
  3348. TEST_F(ServerTest, GetStreamedEndless) {
  3349. uint64_t offset = 0;
  3350. auto res = cli_.Get("/streamed-cancel",
  3351. [&](const char * /*data*/, uint64_t data_length) {
  3352. if (offset < 100) {
  3353. offset += data_length;
  3354. return true;
  3355. }
  3356. return false;
  3357. });
  3358. ASSERT_TRUE(!res);
  3359. EXPECT_EQ(Error::Canceled, res.error());
  3360. }
  3361. TEST_F(ServerTest, ClientStop) {
  3362. std::atomic_size_t count{4};
  3363. std::vector<std::thread> threads;
  3364. for (auto i = count.load(); i != 0; --i) {
  3365. threads.emplace_back([&]() {
  3366. auto res = cli_.Get("/streamed-cancel",
  3367. [&](const char *, uint64_t) { return true; });
  3368. --count;
  3369. ASSERT_TRUE(!res);
  3370. EXPECT_TRUE(res.error() == Error::Canceled ||
  3371. res.error() == Error::Read || res.error() == Error::Write);
  3372. });
  3373. }
  3374. std::this_thread::sleep_for(std::chrono::seconds(2));
  3375. while (count != 0) {
  3376. cli_.stop();
  3377. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3378. }
  3379. for (auto &t : threads) {
  3380. t.join();
  3381. }
  3382. }
  3383. TEST_F(ServerTest, GetWithRange1) {
  3384. auto res = cli_.Get("/with-range", {
  3385. make_range_header({{3, 5}}),
  3386. {"Accept-Encoding", ""},
  3387. });
  3388. ASSERT_TRUE(res);
  3389. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3390. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3391. EXPECT_EQ(true, res->has_header("Content-Range"));
  3392. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3393. EXPECT_EQ(std::string("def"), res->body);
  3394. }
  3395. TEST_F(ServerTest, GetWithRange2) {
  3396. auto res = cli_.Get("/with-range", {
  3397. make_range_header({{1, -1}}),
  3398. {"Accept-Encoding", ""},
  3399. });
  3400. ASSERT_TRUE(res);
  3401. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3402. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3403. EXPECT_EQ(true, res->has_header("Content-Range"));
  3404. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3405. EXPECT_EQ(std::string("bcdefg"), res->body);
  3406. }
  3407. TEST_F(ServerTest, GetWithRange3) {
  3408. auto res = cli_.Get("/with-range", {
  3409. make_range_header({{0, 0}}),
  3410. {"Accept-Encoding", ""},
  3411. });
  3412. ASSERT_TRUE(res);
  3413. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3414. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3415. EXPECT_EQ(true, res->has_header("Content-Range"));
  3416. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3417. EXPECT_EQ(std::string("a"), res->body);
  3418. }
  3419. TEST_F(ServerTest, GetWithRange4) {
  3420. auto res = cli_.Get("/with-range", {
  3421. make_range_header({{-1, 2}}),
  3422. {"Accept-Encoding", ""},
  3423. });
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3426. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3427. EXPECT_EQ(true, res->has_header("Content-Range"));
  3428. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3429. EXPECT_EQ(std::string("fg"), res->body);
  3430. }
  3431. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3432. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3433. ASSERT_TRUE(res);
  3434. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3435. }
  3436. TEST_F(ServerTest, GetWithRangeMultipart) {
  3437. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3438. ASSERT_TRUE(res);
  3439. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3440. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3441. EXPECT_EQ(false, res->has_header("Content-Range"));
  3442. EXPECT_EQ(267U, res->body.size());
  3443. }
  3444. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3445. auto res =
  3446. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3447. ASSERT_TRUE(res);
  3448. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3449. }
  3450. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3451. auto res = cli_.Get("/with-range-customized-response",
  3452. {{make_range_header({{1, 2}})}});
  3453. ASSERT_TRUE(res);
  3454. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3455. EXPECT_EQ(true, res->has_header("Content-Length"));
  3456. EXPECT_EQ(false, res->has_header("Content-Range"));
  3457. EXPECT_EQ(JSON_DATA, res->body);
  3458. }
  3459. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3460. auto res = cli_.Get("/with-range-customized-response",
  3461. {{make_range_header({{1, 2}, {4, 5}})}});
  3462. ASSERT_TRUE(res);
  3463. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3464. EXPECT_EQ(true, res->has_header("Content-Length"));
  3465. EXPECT_EQ(false, res->has_header("Content-Range"));
  3466. EXPECT_EQ(JSON_DATA, res->body);
  3467. }
  3468. TEST_F(ServerTest, Issue1772) {
  3469. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3470. ASSERT_TRUE(res);
  3471. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3472. }
  3473. TEST_F(ServerTest, Issue609) {
  3474. auto res = cli_.Delete("/issue609");
  3475. ASSERT_TRUE(res);
  3476. EXPECT_EQ(StatusCode::OK_200, res->status);
  3477. EXPECT_EQ(std::string("ok"), res->body);
  3478. }
  3479. TEST_F(ServerTest, GetStreamedChunked) {
  3480. auto res = cli_.Get("/streamed-chunked");
  3481. ASSERT_TRUE(res);
  3482. EXPECT_EQ(StatusCode::OK_200, res->status);
  3483. EXPECT_EQ(std::string("123456789"), res->body);
  3484. }
  3485. TEST_F(ServerTest, GetStreamedChunked2) {
  3486. auto res = cli_.Get("/streamed-chunked2");
  3487. ASSERT_TRUE(res);
  3488. EXPECT_EQ(StatusCode::OK_200, res->status);
  3489. EXPECT_EQ(std::string("123456789"), res->body);
  3490. }
  3491. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3492. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3493. ASSERT_TRUE(res);
  3494. EXPECT_EQ(StatusCode::OK_200, res->status);
  3495. EXPECT_EQ(std::string("123456789"), res->body);
  3496. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3497. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3498. }
  3499. TEST_F(ServerTest, LargeChunkedPost) {
  3500. Request req;
  3501. req.method = "POST";
  3502. req.path = "/large-chunked";
  3503. std::string host_and_port;
  3504. host_and_port += HOST;
  3505. host_and_port += ":";
  3506. host_and_port += std::to_string(PORT);
  3507. req.headers.emplace("Host", host_and_port.c_str());
  3508. req.headers.emplace("Accept", "*/*");
  3509. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3510. req.headers.emplace("Content-Type", "text/plain");
  3511. req.headers.emplace("Content-Length", "0");
  3512. req.headers.emplace("Transfer-Encoding", "chunked");
  3513. std::string long_string(30 * 1024u, 'a');
  3514. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3515. // Attempt to make a large enough post to exceed OS buffers, to test that
  3516. // the server handles short reads if the full chunk data isn't available.
  3517. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3518. auto res = std::make_shared<Response>();
  3519. auto error = Error::Success;
  3520. auto ret = cli_.send(req, *res, error);
  3521. ASSERT_TRUE(ret);
  3522. EXPECT_EQ(StatusCode::OK_200, res->status);
  3523. }
  3524. TEST_F(ServerTest, GetMethodRemoteAddr) {
  3525. auto res = cli_.Get("/remote_addr");
  3526. ASSERT_TRUE(res);
  3527. EXPECT_EQ(StatusCode::OK_200, res->status);
  3528. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3529. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  3530. }
  3531. TEST_F(ServerTest, GetMethodLocalAddr) {
  3532. auto res = cli_.Get("/local_addr");
  3533. ASSERT_TRUE(res);
  3534. EXPECT_EQ(StatusCode::OK_200, res->status);
  3535. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3536. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  3537. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  3538. }
  3539. TEST_F(ServerTest, HTTPResponseSplitting) {
  3540. auto res = cli_.Get("/http_response_splitting");
  3541. ASSERT_TRUE(res);
  3542. EXPECT_EQ(StatusCode::OK_200, res->status);
  3543. }
  3544. TEST_F(ServerTest, SlowRequest) {
  3545. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3546. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3547. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3548. }
  3549. #if 0
  3550. TEST_F(ServerTest, SlowPost) {
  3551. char buffer[64 * 1024];
  3552. memset(buffer, 0x42, sizeof(buffer));
  3553. auto res = cli_.Post(
  3554. "/slowpost", 64 * 1024 * 1024,
  3555. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3556. auto ret = sink.write(buffer, sizeof(buffer));
  3557. EXPECT_TRUE(ret);
  3558. return true;
  3559. },
  3560. "text/plain");
  3561. ASSERT_TRUE(res);
  3562. EXPECT_EQ(StatusCode::OK_200, res->status);
  3563. }
  3564. TEST_F(ServerTest, SlowPostFail) {
  3565. char buffer[64 * 1024];
  3566. memset(buffer, 0x42, sizeof(buffer));
  3567. cli_.set_write_timeout(std::chrono::seconds(0));
  3568. auto res = cli_.Post(
  3569. "/slowpost", 64 * 1024 * 1024,
  3570. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3571. sink.write(buffer, sizeof(buffer));
  3572. return true;
  3573. },
  3574. "text/plain");
  3575. ASSERT_TRUE(!res);
  3576. EXPECT_EQ(Error::Write, res.error());
  3577. }
  3578. #endif
  3579. TEST_F(ServerTest, Put) {
  3580. auto res = cli_.Put("/put", "PUT", "text/plain");
  3581. ASSERT_TRUE(res);
  3582. EXPECT_EQ(StatusCode::OK_200, res->status);
  3583. EXPECT_EQ("PUT", res->body);
  3584. }
  3585. TEST_F(ServerTest, PutWithContentProvider) {
  3586. auto res = cli_.Put(
  3587. "/put", 3,
  3588. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3589. sink.os << "PUT";
  3590. return true;
  3591. },
  3592. "text/plain");
  3593. ASSERT_TRUE(res);
  3594. EXPECT_EQ(StatusCode::OK_200, res->status);
  3595. EXPECT_EQ("PUT", res->body);
  3596. }
  3597. TEST_F(ServerTest, PostWithContentProviderAbort) {
  3598. auto res = cli_.Post(
  3599. "/post", 42,
  3600. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3601. return false;
  3602. },
  3603. "text/plain");
  3604. ASSERT_TRUE(!res);
  3605. EXPECT_EQ(Error::Canceled, res.error());
  3606. }
  3607. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  3608. auto res = cli_.Put(
  3609. "/put",
  3610. [](size_t /*offset*/, DataSink &sink) {
  3611. sink.os << "PUT";
  3612. sink.done();
  3613. return true;
  3614. },
  3615. "text/plain");
  3616. ASSERT_TRUE(res);
  3617. EXPECT_EQ(StatusCode::OK_200, res->status);
  3618. EXPECT_EQ("PUT", res->body);
  3619. }
  3620. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  3621. auto res = cli_.Post(
  3622. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3623. "text/plain");
  3624. ASSERT_TRUE(!res);
  3625. EXPECT_EQ(Error::Canceled, res.error());
  3626. }
  3627. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3628. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  3629. cli_.set_compress(true);
  3630. auto res = cli_.Put(
  3631. "/put", 3,
  3632. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3633. sink.os << "PUT";
  3634. return true;
  3635. },
  3636. "text/plain");
  3637. ASSERT_TRUE(res);
  3638. EXPECT_EQ(StatusCode::OK_200, res->status);
  3639. EXPECT_EQ("PUT", res->body);
  3640. }
  3641. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  3642. cli_.set_compress(true);
  3643. auto res = cli_.Post(
  3644. "/post", 42,
  3645. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3646. return false;
  3647. },
  3648. "text/plain");
  3649. ASSERT_TRUE(!res);
  3650. EXPECT_EQ(Error::Canceled, res.error());
  3651. }
  3652. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  3653. cli_.set_compress(true);
  3654. auto res = cli_.Put(
  3655. "/put",
  3656. [](size_t /*offset*/, DataSink &sink) {
  3657. sink.os << "PUT";
  3658. sink.done();
  3659. return true;
  3660. },
  3661. "text/plain");
  3662. ASSERT_TRUE(res);
  3663. EXPECT_EQ(StatusCode::OK_200, res->status);
  3664. EXPECT_EQ("PUT", res->body);
  3665. }
  3666. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  3667. cli_.set_compress(true);
  3668. auto res = cli_.Post(
  3669. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3670. "text/plain");
  3671. ASSERT_TRUE(!res);
  3672. EXPECT_EQ(Error::Canceled, res.error());
  3673. }
  3674. TEST_F(ServerTest, PutLargeFileWithGzip) {
  3675. cli_.set_compress(true);
  3676. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  3677. ASSERT_TRUE(res);
  3678. EXPECT_EQ(StatusCode::OK_200, res->status);
  3679. EXPECT_EQ(LARGE_DATA, res->body);
  3680. }
  3681. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  3682. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3683. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  3684. Client cli(s.c_str());
  3685. cli.enable_server_certificate_verification(false);
  3686. #else
  3687. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  3688. Client cli(s.c_str());
  3689. #endif
  3690. cli.set_compress(true);
  3691. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  3692. ASSERT_TRUE(res);
  3693. EXPECT_EQ(StatusCode::OK_200, res->status);
  3694. EXPECT_EQ(LARGE_DATA, res->body);
  3695. // The compressed size should be less than a 10th of the original. May vary
  3696. // depending on the zlib library.
  3697. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  3698. static_cast<uint64_t>(10 * 1024 * 1024));
  3699. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  3700. }
  3701. TEST_F(ServerTest, PutContentWithDeflate) {
  3702. cli_.set_compress(false);
  3703. Headers headers;
  3704. headers.emplace("Content-Encoding", "deflate");
  3705. // PUT in deflate format:
  3706. auto res = cli_.Put("/put", headers,
  3707. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  3708. ASSERT_TRUE(res);
  3709. EXPECT_EQ(StatusCode::OK_200, res->status);
  3710. EXPECT_EQ("PUT", res->body);
  3711. }
  3712. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  3713. Headers headers;
  3714. headers.emplace("Accept-Encoding", "gzip, deflate");
  3715. auto res = cli_.Get("/streamed-chunked", headers);
  3716. ASSERT_TRUE(res);
  3717. EXPECT_EQ(StatusCode::OK_200, res->status);
  3718. EXPECT_EQ(std::string("123456789"), res->body);
  3719. }
  3720. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  3721. Headers headers;
  3722. headers.emplace("Accept-Encoding", "gzip, deflate");
  3723. auto res = cli_.Get("/streamed-chunked2", headers);
  3724. ASSERT_TRUE(res);
  3725. EXPECT_EQ(StatusCode::OK_200, res->status);
  3726. EXPECT_EQ(std::string("123456789"), res->body);
  3727. }
  3728. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  3729. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. }
  3733. TEST(GzipDecompressor, ChunkedDecompression) {
  3734. std::string data;
  3735. for (size_t i = 0; i < 32 * 1024; ++i) {
  3736. data.push_back(static_cast<char>('a' + i % 26));
  3737. }
  3738. std::string compressed_data;
  3739. {
  3740. httplib::detail::gzip_compressor compressor;
  3741. bool result = compressor.compress(
  3742. data.data(), data.size(),
  3743. /*last=*/true,
  3744. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  3745. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  3746. compressed_data_size);
  3747. return true;
  3748. });
  3749. ASSERT_TRUE(result);
  3750. }
  3751. std::string decompressed_data;
  3752. {
  3753. httplib::detail::gzip_decompressor decompressor;
  3754. // Chunk size is chosen specifically to have a decompressed chunk size equal
  3755. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  3756. size_t chunk_size = 130;
  3757. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  3758. chunk_begin += chunk_size) {
  3759. size_t current_chunk_size =
  3760. std::min(compressed_data.size() - chunk_begin, chunk_size);
  3761. bool result = decompressor.decompress(
  3762. compressed_data.data() + chunk_begin, current_chunk_size,
  3763. [&](const char *decompressed_data_chunk,
  3764. size_t decompressed_data_chunk_size) {
  3765. decompressed_data.insert(decompressed_data.size(),
  3766. decompressed_data_chunk,
  3767. decompressed_data_chunk_size);
  3768. return true;
  3769. });
  3770. ASSERT_TRUE(result);
  3771. }
  3772. }
  3773. ASSERT_EQ(data, decompressed_data);
  3774. }
  3775. TEST(GzipDecompressor, DeflateDecompression) {
  3776. std::string original_text = "Raw deflate without gzip";
  3777. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3778. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3779. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3780. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  3781. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3782. std::string decompressed_data;
  3783. {
  3784. httplib::detail::gzip_decompressor decompressor;
  3785. bool result = decompressor.decompress(
  3786. compressed_data.data(), compressed_data.size(),
  3787. [&](const char *decompressed_data_chunk,
  3788. size_t decompressed_data_chunk_size) {
  3789. decompressed_data.insert(decompressed_data.size(),
  3790. decompressed_data_chunk,
  3791. decompressed_data_chunk_size);
  3792. return true;
  3793. });
  3794. ASSERT_TRUE(result);
  3795. }
  3796. ASSERT_EQ(original_text, decompressed_data);
  3797. }
  3798. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  3799. std::string original_text = "Raw deflate without gzip";
  3800. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3801. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3802. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3803. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  3804. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  3805. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3806. std::string decompressed_data;
  3807. {
  3808. httplib::detail::gzip_decompressor decompressor;
  3809. bool result = decompressor.decompress(
  3810. compressed_data.data(), compressed_data.size(),
  3811. [&](const char *decompressed_data_chunk,
  3812. size_t decompressed_data_chunk_size) {
  3813. decompressed_data.insert(decompressed_data.size(),
  3814. decompressed_data_chunk,
  3815. decompressed_data_chunk_size);
  3816. return true;
  3817. });
  3818. ASSERT_TRUE(result);
  3819. }
  3820. ASSERT_EQ(original_text, decompressed_data);
  3821. }
  3822. #ifdef _WIN32
  3823. TEST(GzipDecompressor, LargeRandomData) {
  3824. // prepare large random data that is difficult to be compressed and is
  3825. // expected to have large size even when compressed
  3826. std::random_device seed_gen;
  3827. std::mt19937 random(seed_gen());
  3828. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  3829. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  3830. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  3831. std::generate(data.begin(), data.end(), [&]() { return random(); });
  3832. // compress data over 4GiB
  3833. std::string compressed_data;
  3834. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  3835. httplib::detail::gzip_compressor compressor;
  3836. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  3837. data.size() * sizeof(std::uint32_t), true,
  3838. [&](const char *data, size_t size) {
  3839. compressed_data.insert(
  3840. compressed_data.size(), data, size);
  3841. return true;
  3842. });
  3843. ASSERT_TRUE(result);
  3844. // FIXME: compressed data size is expected to be greater than 4GiB,
  3845. // but there is no guarantee
  3846. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  3847. // decompress data over 4GiB
  3848. std::string decompressed_data;
  3849. decompressed_data.reserve(data_size);
  3850. httplib::detail::gzip_decompressor decompressor;
  3851. result = decompressor.decompress(
  3852. compressed_data.data(), compressed_data.size(),
  3853. [&](const char *data, size_t size) {
  3854. decompressed_data.insert(decompressed_data.size(), data, size);
  3855. return true;
  3856. });
  3857. ASSERT_TRUE(result);
  3858. // compare
  3859. ASSERT_EQ(data_size, decompressed_data.size());
  3860. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  3861. 0);
  3862. }
  3863. #endif
  3864. #endif
  3865. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3866. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3867. Headers headers;
  3868. headers.emplace("Accept-Encoding", "br");
  3869. auto res = cli_.Get("/streamed-chunked", headers);
  3870. ASSERT_TRUE(res);
  3871. EXPECT_EQ(StatusCode::OK_200, res->status);
  3872. EXPECT_EQ(std::string("123456789"), res->body);
  3873. }
  3874. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3875. Headers headers;
  3876. headers.emplace("Accept-Encoding", "br");
  3877. auto res = cli_.Get("/streamed-chunked2", headers);
  3878. ASSERT_TRUE(res);
  3879. EXPECT_EQ(StatusCode::OK_200, res->status);
  3880. EXPECT_EQ(std::string("123456789"), res->body);
  3881. }
  3882. #endif
  3883. TEST_F(ServerTest, Patch) {
  3884. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::OK_200, res->status);
  3887. EXPECT_EQ("PATCH", res->body);
  3888. }
  3889. TEST_F(ServerTest, Delete) {
  3890. auto res = cli_.Delete("/delete");
  3891. ASSERT_TRUE(res);
  3892. EXPECT_EQ(StatusCode::OK_200, res->status);
  3893. EXPECT_EQ("DELETE", res->body);
  3894. }
  3895. TEST_F(ServerTest, DeleteContentReceiver) {
  3896. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::OK_200, res->status);
  3899. EXPECT_EQ("content", res->body);
  3900. }
  3901. TEST_F(ServerTest, Options) {
  3902. auto res = cli_.Options("*");
  3903. ASSERT_TRUE(res);
  3904. EXPECT_EQ(StatusCode::OK_200, res->status);
  3905. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3906. EXPECT_TRUE(res->body.empty());
  3907. }
  3908. TEST_F(ServerTest, URL) {
  3909. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3910. ASSERT_TRUE(res);
  3911. EXPECT_EQ(StatusCode::OK_200, res->status);
  3912. }
  3913. TEST_F(ServerTest, ArrayParam) {
  3914. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3915. ASSERT_TRUE(res);
  3916. EXPECT_EQ(StatusCode::OK_200, res->status);
  3917. }
  3918. TEST_F(ServerTest, NoMultipleHeaders) {
  3919. Headers headers = {{"Content-Length", "5"}};
  3920. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3921. "text/plain");
  3922. ASSERT_TRUE(res);
  3923. EXPECT_EQ(StatusCode::OK_200, res->status);
  3924. }
  3925. TEST_F(ServerTest, PostContentReceiver) {
  3926. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3927. ASSERT_TRUE(res);
  3928. ASSERT_EQ(StatusCode::OK_200, res->status);
  3929. ASSERT_EQ("content", res->body);
  3930. }
  3931. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3932. MultipartFormDataItems items = {
  3933. {"text1", "text default", "", ""},
  3934. {"text2", "aωb", "", ""},
  3935. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3936. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3937. {"file3", "", "", "application/octet-stream"},
  3938. };
  3939. auto res = cli_.Post("/content_receiver", items);
  3940. ASSERT_TRUE(res);
  3941. EXPECT_EQ(StatusCode::OK_200, res->status);
  3942. }
  3943. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3944. MultipartFormDataItems items = {
  3945. {"text1", "text default", "", ""},
  3946. {"text2", "aωb", "", ""},
  3947. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3948. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3949. {"file3", "", "", "application/octet-stream"},
  3950. };
  3951. auto boundary = std::string("+++++");
  3952. std::string body;
  3953. for (const auto &item : items) {
  3954. body += "--" + boundary + "\r\n";
  3955. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3956. if (!item.filename.empty()) {
  3957. body += "; filename=\"" + item.filename + "\"";
  3958. }
  3959. body += "\r\n";
  3960. if (!item.content_type.empty()) {
  3961. body += "Content-Type: " + item.content_type + "\r\n";
  3962. }
  3963. body += "\r\n";
  3964. body += item.content + "\r\n";
  3965. }
  3966. body += "--" + boundary + "--\r\n";
  3967. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3968. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3969. ASSERT_TRUE(res);
  3970. EXPECT_EQ(StatusCode::OK_200, res->status);
  3971. }
  3972. TEST_F(ServerTest, PostContentReceiverGzip) {
  3973. cli_.set_compress(true);
  3974. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3975. ASSERT_TRUE(res);
  3976. ASSERT_EQ(StatusCode::OK_200, res->status);
  3977. ASSERT_EQ("content", res->body);
  3978. }
  3979. TEST_F(ServerTest, PutContentReceiver) {
  3980. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3981. ASSERT_TRUE(res);
  3982. ASSERT_EQ(StatusCode::OK_200, res->status);
  3983. ASSERT_EQ("content", res->body);
  3984. }
  3985. TEST_F(ServerTest, PatchContentReceiver) {
  3986. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3987. ASSERT_TRUE(res);
  3988. ASSERT_EQ(StatusCode::OK_200, res->status);
  3989. ASSERT_EQ("content", res->body);
  3990. }
  3991. TEST_F(ServerTest, PostQueryStringAndBody) {
  3992. auto res =
  3993. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3994. ASSERT_TRUE(res);
  3995. ASSERT_EQ(StatusCode::OK_200, res->status);
  3996. }
  3997. TEST_F(ServerTest, HTTP2Magic) {
  3998. Request req;
  3999. req.method = "PRI";
  4000. req.path = "*";
  4001. req.body = "SM";
  4002. auto res = std::make_shared<Response>();
  4003. auto error = Error::Success;
  4004. auto ret = cli_.send(req, *res, error);
  4005. ASSERT_TRUE(ret);
  4006. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4007. }
  4008. TEST_F(ServerTest, KeepAlive) {
  4009. auto res = cli_.Get("/hi");
  4010. ASSERT_TRUE(res);
  4011. EXPECT_EQ(StatusCode::OK_200, res->status);
  4012. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4013. EXPECT_EQ("Hello World!", res->body);
  4014. res = cli_.Get("/hi");
  4015. ASSERT_TRUE(res);
  4016. EXPECT_EQ(StatusCode::OK_200, res->status);
  4017. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4018. EXPECT_EQ("Hello World!", res->body);
  4019. res = cli_.Get("/hi");
  4020. ASSERT_TRUE(res);
  4021. EXPECT_EQ(StatusCode::OK_200, res->status);
  4022. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4023. EXPECT_EQ("Hello World!", res->body);
  4024. res = cli_.Get("/not-exist");
  4025. ASSERT_TRUE(res);
  4026. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4027. res = cli_.Post("/empty", "", "text/plain");
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::OK_200, res->status);
  4030. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4031. EXPECT_EQ("empty", res->body);
  4032. EXPECT_EQ("close", res->get_header_value("Connection"));
  4033. res = cli_.Post(
  4034. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4035. "text/plain");
  4036. ASSERT_TRUE(res);
  4037. EXPECT_EQ(StatusCode::OK_200, res->status);
  4038. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4039. EXPECT_EQ("empty", res->body);
  4040. cli_.set_keep_alive(false);
  4041. res = cli_.Get("/last-request");
  4042. ASSERT_TRUE(res);
  4043. EXPECT_EQ(StatusCode::OK_200, res->status);
  4044. EXPECT_EQ("close", res->get_header_value("Connection"));
  4045. }
  4046. TEST_F(ServerTest, TooManyRedirect) {
  4047. cli_.set_follow_location(true);
  4048. auto res = cli_.Get("/redirect/0");
  4049. ASSERT_TRUE(!res);
  4050. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4051. }
  4052. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4053. TEST_F(ServerTest, Gzip) {
  4054. Headers headers;
  4055. headers.emplace("Accept-Encoding", "gzip, deflate");
  4056. auto res = cli_.Get("/compress", headers);
  4057. ASSERT_TRUE(res);
  4058. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4059. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4060. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4061. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4062. "7890123456789012345678901234567890",
  4063. res->body);
  4064. EXPECT_EQ(StatusCode::OK_200, res->status);
  4065. }
  4066. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4067. Headers headers;
  4068. headers.emplace("Accept-Encoding", "");
  4069. auto res = cli_.Get("/compress", headers);
  4070. ASSERT_TRUE(res);
  4071. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4072. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4073. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4074. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4075. "7890123456789012345678901234567890",
  4076. res->body);
  4077. EXPECT_EQ(StatusCode::OK_200, res->status);
  4078. }
  4079. TEST_F(ServerTest, GzipWithContentReceiver) {
  4080. Headers headers;
  4081. headers.emplace("Accept-Encoding", "gzip, deflate");
  4082. std::string body;
  4083. auto res = cli_.Get("/compress", headers,
  4084. [&](const char *data, uint64_t data_length) {
  4085. EXPECT_EQ(100U, data_length);
  4086. body.append(data, data_length);
  4087. return true;
  4088. });
  4089. ASSERT_TRUE(res);
  4090. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4091. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4092. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4093. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4094. "7890123456789012345678901234567890",
  4095. body);
  4096. EXPECT_EQ(StatusCode::OK_200, res->status);
  4097. }
  4098. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4099. Headers headers;
  4100. headers.emplace("Accept-Encoding", "gzip, deflate");
  4101. cli_.set_decompress(false);
  4102. auto res = cli_.Get("/compress", headers);
  4103. ASSERT_TRUE(res);
  4104. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4105. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4106. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4107. EXPECT_EQ(33U, res->body.size());
  4108. EXPECT_EQ(StatusCode::OK_200, res->status);
  4109. }
  4110. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4111. Headers headers;
  4112. headers.emplace("Accept-Encoding", "");
  4113. std::string body;
  4114. auto res = cli_.Get("/compress", headers,
  4115. [&](const char *data, uint64_t data_length) {
  4116. EXPECT_EQ(100U, data_length);
  4117. body.append(data, data_length);
  4118. return true;
  4119. });
  4120. ASSERT_TRUE(res);
  4121. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4122. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4123. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4124. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4125. "7890123456789012345678901234567890",
  4126. body);
  4127. EXPECT_EQ(StatusCode::OK_200, res->status);
  4128. }
  4129. TEST_F(ServerTest, NoGzip) {
  4130. Headers headers;
  4131. headers.emplace("Accept-Encoding", "gzip, deflate");
  4132. auto res = cli_.Get("/nocompress", headers);
  4133. ASSERT_TRUE(res);
  4134. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4135. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4136. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4137. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4138. "7890123456789012345678901234567890",
  4139. res->body);
  4140. EXPECT_EQ(StatusCode::OK_200, res->status);
  4141. }
  4142. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4143. Headers headers;
  4144. headers.emplace("Accept-Encoding", "gzip, deflate");
  4145. std::string body;
  4146. auto res = cli_.Get("/nocompress", headers,
  4147. [&](const char *data, uint64_t data_length) {
  4148. EXPECT_EQ(100U, data_length);
  4149. body.append(data, data_length);
  4150. return true;
  4151. });
  4152. ASSERT_TRUE(res);
  4153. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4154. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4155. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4156. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4157. "7890123456789012345678901234567890",
  4158. body);
  4159. EXPECT_EQ(StatusCode::OK_200, res->status);
  4160. }
  4161. TEST_F(ServerTest, MultipartFormDataGzip) {
  4162. MultipartFormDataItems items = {
  4163. {"key1", "test", "", ""},
  4164. {"key2", "--abcdefg123", "", ""},
  4165. };
  4166. cli_.set_compress(true);
  4167. auto res = cli_.Post("/compress-multipart", items);
  4168. ASSERT_TRUE(res);
  4169. EXPECT_EQ(StatusCode::OK_200, res->status);
  4170. }
  4171. #endif
  4172. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4173. TEST_F(ServerTest, Brotli) {
  4174. Headers headers;
  4175. headers.emplace("Accept-Encoding", "br");
  4176. auto res = cli_.Get("/compress", headers);
  4177. ASSERT_TRUE(res);
  4178. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4179. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4180. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4181. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4182. "7890123456789012345678901234567890",
  4183. res->body);
  4184. EXPECT_EQ(StatusCode::OK_200, res->status);
  4185. }
  4186. #endif
  4187. // Sends a raw request to a server listening at HOST:PORT.
  4188. static bool send_request(time_t read_timeout_sec, const std::string &req,
  4189. std::string *resp = nullptr) {
  4190. auto error = Error::Success;
  4191. auto client_sock = detail::create_client_socket(
  4192. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4193. /*connection_timeout_sec=*/5, 0,
  4194. /*read_timeout_sec=*/5, 0,
  4195. /*write_timeout_sec=*/5, 0, std::string(), error);
  4196. if (client_sock == INVALID_SOCKET) { return false; }
  4197. auto ret = detail::process_client_socket(
  4198. client_sock, read_timeout_sec, 0, 0, 0, 0,
  4199. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  4200. if (req.size() !=
  4201. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  4202. return false;
  4203. }
  4204. char buf[512];
  4205. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  4206. while (line_reader.getline()) {
  4207. if (resp) { *resp += line_reader.ptr(); }
  4208. }
  4209. return true;
  4210. });
  4211. detail::close_socket(client_sock);
  4212. return ret;
  4213. }
  4214. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  4215. Server svr;
  4216. std::string header_value;
  4217. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  4218. header_value = req.get_header_value("foo");
  4219. res.set_content("ok", "text/plain");
  4220. });
  4221. thread t = thread([&] { svr.listen(HOST, PORT); });
  4222. auto se = detail::scope_exit([&] {
  4223. svr.stop();
  4224. t.join();
  4225. ASSERT_FALSE(svr.is_running());
  4226. });
  4227. svr.wait_until_ready();
  4228. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  4229. // like characters are not treated the same - use vertical tab and escape.
  4230. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  4231. "foo: \t \v bar \x1B\t \r\n"
  4232. "Connection: close\r\n"
  4233. "\r\n";
  4234. std::string res;
  4235. ASSERT_TRUE(send_request(5, req, &res));
  4236. EXPECT_EQ(header_value, "");
  4237. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  4238. }
  4239. // Sends a raw request and verifies that there isn't a crash or exception.
  4240. static void test_raw_request(const std::string &req,
  4241. std::string *out = nullptr) {
  4242. Server svr;
  4243. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4244. res.set_content("ok", "text/plain");
  4245. });
  4246. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4247. res.set_content("ok", "text/plain");
  4248. });
  4249. svr.Get("/header_field_value_check",
  4250. [&](const Request & /*req*/, Response &res) {
  4251. res.set_content("ok", "text/plain");
  4252. });
  4253. // Server read timeout must be longer than the client read timeout for the
  4254. // bug to reproduce, probably to force the server to process a request
  4255. // without a trailing blank line.
  4256. const time_t client_read_timeout_sec = 1;
  4257. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4258. bool listen_thread_ok = false;
  4259. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4260. auto se = detail::scope_exit([&] {
  4261. svr.stop();
  4262. t.join();
  4263. ASSERT_FALSE(svr.is_running());
  4264. EXPECT_TRUE(listen_thread_ok);
  4265. });
  4266. svr.wait_until_ready();
  4267. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4268. }
  4269. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4270. // A certain header line causes an exception if the header property is parsed
  4271. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4272. test_raw_request(
  4273. "GET /hi HTTP/1.1\r\n"
  4274. " : "
  4275. " "
  4276. " ");
  4277. }
  4278. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4279. // A certain header line causes an exception if the header property *name* is
  4280. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4281. // greedy matcher and requires backtracking when there are a lot of ":"
  4282. // characters.
  4283. // This occurs with libc++ but not libstdc++.
  4284. test_raw_request(
  4285. "GET /hi HTTP/1.1\r\n"
  4286. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4287. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4288. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4289. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4290. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4291. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4292. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4293. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4294. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4295. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4296. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4297. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4298. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4299. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4300. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4301. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4302. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4303. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4304. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4305. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4306. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4307. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4308. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4309. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4310. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4311. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4312. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  4313. "&&&%%%");
  4314. }
  4315. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  4316. // Make sure this doesn't crash the server.
  4317. // In a previous version of the header line regex, the "\r" rendered the line
  4318. // unparsable and the regex engine repeatedly backtracked, trying to look for
  4319. // a new position where the leading white space ended and the field value
  4320. // began.
  4321. // The crash occurs with libc++ but not libstdc++.
  4322. test_raw_request("GET /hi HTTP/1.1\r\n"
  4323. "a:" +
  4324. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  4325. "\r\n"
  4326. "\r\n");
  4327. }
  4328. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  4329. std::string out;
  4330. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4331. "Content-Type: text/plain\r\n"
  4332. "Transfer-Encoding: chunked\r\n"
  4333. "\r\n"
  4334. "nothex\r\n",
  4335. &out);
  4336. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4337. }
  4338. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  4339. std::string out;
  4340. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4341. "Content-Type: text/plain\r\n"
  4342. "Transfer-Encoding: chunked\r\n"
  4343. "\r\n"
  4344. "3\r\n"
  4345. "xyz\r\n"
  4346. "NaN\r\n",
  4347. &out);
  4348. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4349. }
  4350. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  4351. std::string out;
  4352. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4353. "Content-Type: text/plain\r\n"
  4354. "Transfer-Encoding: chunked\r\n"
  4355. "\r\n"
  4356. // Length is too large for 64 bits.
  4357. "1ffffffffffffffff\r\n"
  4358. "xyz\r\n",
  4359. &out);
  4360. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4361. }
  4362. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  4363. test_raw_request("GET /hi HTTP/1.1\r\n"
  4364. "Content-Type: text/plain\r\n\r");
  4365. }
  4366. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  4367. std::string out;
  4368. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  4369. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4370. }
  4371. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  4372. std::string out;
  4373. std::string request(
  4374. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  4375. test_raw_request(request, &out);
  4376. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4377. }
  4378. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  4379. std::string out;
  4380. std::string request(
  4381. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  4382. test_raw_request(request, &out);
  4383. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4384. }
  4385. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  4386. std::string out;
  4387. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  4388. "Test: \r\n\r\n",
  4389. &out);
  4390. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  4391. }
  4392. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  4393. Server svr;
  4394. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  4395. res.set_header("Cache-Control", "no-cache");
  4396. res.set_chunked_content_provider(
  4397. "text/event-stream", [](size_t offset, DataSink &sink) {
  4398. std::string s = "data:";
  4399. s += std::to_string(offset);
  4400. s += "\n\n";
  4401. auto ret = sink.write(s.data(), s.size());
  4402. EXPECT_TRUE(ret);
  4403. std::this_thread::sleep_for(std::chrono::seconds(1));
  4404. return true;
  4405. });
  4406. });
  4407. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4408. svr.wait_until_ready();
  4409. Client client(HOST, PORT);
  4410. const Headers headers = {{"Accept", "text/event-stream"}};
  4411. auto get_thread = std::thread([&client, &headers]() {
  4412. auto res = client.Get(
  4413. "/events", headers,
  4414. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  4415. });
  4416. auto se = detail::scope_exit([&] {
  4417. svr.stop();
  4418. get_thread.join();
  4419. listen_thread.join();
  4420. ASSERT_FALSE(svr.is_running());
  4421. });
  4422. // Give GET time to get a few messages.
  4423. std::this_thread::sleep_for(std::chrono::seconds(2));
  4424. }
  4425. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  4426. httplib::Server svr;
  4427. svr.Post("/hi",
  4428. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4429. res.status = StatusCode::OK_200;
  4430. });
  4431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4432. svr.wait_until_ready();
  4433. Client cli(HOST, PORT);
  4434. auto res = cli.Post("/hi", "data", "text/plain");
  4435. ASSERT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::OK_200, res->status);
  4437. svr.stop();
  4438. thread.join();
  4439. ASSERT_FALSE(svr.is_running());
  4440. res = cli.Post("/hi", "data", "text/plain");
  4441. ASSERT_FALSE(res);
  4442. }
  4443. TEST(ServerStopTest, ListenFailure) {
  4444. Server svr;
  4445. auto t = thread([&]() {
  4446. auto ret = svr.listen("????", PORT);
  4447. EXPECT_FALSE(ret);
  4448. });
  4449. svr.wait_until_ready();
  4450. svr.stop();
  4451. t.join();
  4452. }
  4453. TEST(ServerStopTest, Decommision) {
  4454. Server svr;
  4455. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  4456. for (int i = 0; i < 4; i++) {
  4457. auto is_even = !(i % 2);
  4458. std::thread t{[&] {
  4459. try {
  4460. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4461. if (is_even) {
  4462. throw std::runtime_error("Some thing that happens to go wrong.");
  4463. }
  4464. svr.listen(HOST, PORT);
  4465. } catch (...) { svr.decommission(); }
  4466. }};
  4467. svr.wait_until_ready();
  4468. // Server is up
  4469. {
  4470. Client cli(HOST, PORT);
  4471. auto res = cli.Get("/hi");
  4472. if (is_even) {
  4473. EXPECT_FALSE(res);
  4474. } else {
  4475. EXPECT_TRUE(res);
  4476. EXPECT_EQ("hi...", res->body);
  4477. }
  4478. }
  4479. svr.stop();
  4480. t.join();
  4481. // Server is down...
  4482. {
  4483. Client cli(HOST, PORT);
  4484. auto res = cli.Get("/hi");
  4485. EXPECT_FALSE(res);
  4486. }
  4487. }
  4488. }
  4489. TEST(StreamingTest, NoContentLengthStreaming) {
  4490. Server svr;
  4491. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  4492. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  4493. if (offset < 6) {
  4494. sink.os << (offset < 3 ? "a" : "b");
  4495. } else {
  4496. sink.done();
  4497. }
  4498. return true;
  4499. });
  4500. });
  4501. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4502. auto listen_se = detail::scope_exit([&] {
  4503. svr.stop();
  4504. listen_thread.join();
  4505. ASSERT_FALSE(svr.is_running());
  4506. });
  4507. svr.wait_until_ready();
  4508. Client client(HOST, PORT);
  4509. auto get_thread = std::thread([&client]() {
  4510. std::string s;
  4511. auto res =
  4512. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  4513. s += std::string(data, len);
  4514. return true;
  4515. });
  4516. EXPECT_EQ("aaabbb", s);
  4517. });
  4518. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  4519. // Give GET time to get a few messages.
  4520. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4521. }
  4522. TEST(MountTest, Unmount) {
  4523. Server svr;
  4524. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4525. auto se = detail::scope_exit([&] {
  4526. svr.stop();
  4527. listen_thread.join();
  4528. ASSERT_FALSE(svr.is_running());
  4529. });
  4530. svr.wait_until_ready();
  4531. Client cli("localhost", PORT);
  4532. svr.set_mount_point("/mount2", "./www2");
  4533. auto res = cli.Get("/");
  4534. ASSERT_TRUE(res);
  4535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4536. res = cli.Get("/mount2/dir/test.html");
  4537. ASSERT_TRUE(res);
  4538. EXPECT_EQ(StatusCode::OK_200, res->status);
  4539. svr.set_mount_point("/", "./www");
  4540. res = cli.Get("/dir/");
  4541. ASSERT_TRUE(res);
  4542. EXPECT_EQ(StatusCode::OK_200, res->status);
  4543. svr.remove_mount_point("/");
  4544. res = cli.Get("/dir/");
  4545. ASSERT_TRUE(res);
  4546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4547. svr.remove_mount_point("/mount2");
  4548. res = cli.Get("/mount2/dir/test.html");
  4549. ASSERT_TRUE(res);
  4550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4551. }
  4552. TEST(MountTest, Redicect) {
  4553. Server svr;
  4554. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4555. auto se = detail::scope_exit([&] {
  4556. svr.stop();
  4557. listen_thread.join();
  4558. ASSERT_FALSE(svr.is_running());
  4559. });
  4560. svr.set_mount_point("/", "./www");
  4561. svr.wait_until_ready();
  4562. Client cli("localhost", PORT);
  4563. auto res = cli.Get("/dir/");
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. res = cli.Get("/dir");
  4567. ASSERT_TRUE(res);
  4568. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  4569. res = cli.Get("/file");
  4570. ASSERT_TRUE(res);
  4571. EXPECT_EQ(StatusCode::OK_200, res->status);
  4572. res = cli.Get("/file/");
  4573. ASSERT_TRUE(res);
  4574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4575. cli.set_follow_location(true);
  4576. res = cli.Get("/dir");
  4577. ASSERT_TRUE(res);
  4578. EXPECT_EQ(StatusCode::OK_200, res->status);
  4579. }
  4580. TEST(MountTest, MultibytesPathName) {
  4581. Server svr;
  4582. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4583. auto se = detail::scope_exit([&] {
  4584. svr.stop();
  4585. listen_thread.join();
  4586. ASSERT_FALSE(svr.is_running());
  4587. });
  4588. svr.set_mount_point("/", "./www");
  4589. svr.wait_until_ready();
  4590. Client cli("localhost", PORT);
  4591. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  4592. ASSERT_TRUE(res);
  4593. EXPECT_EQ(StatusCode::OK_200, res->status);
  4594. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  4595. }
  4596. TEST(KeepAliveTest, ReadTimeout) {
  4597. Server svr;
  4598. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4599. std::this_thread::sleep_for(std::chrono::seconds(2));
  4600. res.set_content("a", "text/plain");
  4601. });
  4602. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4603. res.set_content("b", "text/plain");
  4604. });
  4605. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4606. auto se = detail::scope_exit([&] {
  4607. svr.stop();
  4608. listen_thread.join();
  4609. ASSERT_FALSE(svr.is_running());
  4610. });
  4611. svr.wait_until_ready();
  4612. Client cli("localhost", PORT);
  4613. cli.set_keep_alive(true);
  4614. cli.set_read_timeout(std::chrono::seconds(1));
  4615. auto resa = cli.Get("/a");
  4616. ASSERT_FALSE(resa);
  4617. EXPECT_EQ(Error::Read, resa.error());
  4618. auto resb = cli.Get("/b");
  4619. ASSERT_TRUE(resb);
  4620. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4621. EXPECT_EQ("b", resb->body);
  4622. }
  4623. TEST(KeepAliveTest, Issue1041) {
  4624. Server svr;
  4625. svr.set_keep_alive_timeout(3);
  4626. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4627. res.set_content("Hello World!", "text/plain");
  4628. });
  4629. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4630. auto se = detail::scope_exit([&] {
  4631. svr.stop();
  4632. listen_thread.join();
  4633. ASSERT_FALSE(svr.is_running());
  4634. });
  4635. svr.wait_until_ready();
  4636. Client cli(HOST, PORT);
  4637. cli.set_keep_alive(true);
  4638. auto result = cli.Get("/hi");
  4639. ASSERT_TRUE(result);
  4640. EXPECT_EQ(StatusCode::OK_200, result->status);
  4641. std::this_thread::sleep_for(std::chrono::seconds(5));
  4642. result = cli.Get("/hi");
  4643. ASSERT_TRUE(result);
  4644. EXPECT_EQ(StatusCode::OK_200, result->status);
  4645. }
  4646. TEST(KeepAliveTest, Issue1959) {
  4647. Server svr;
  4648. svr.set_keep_alive_timeout(5);
  4649. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4650. res.set_content("a", "text/plain");
  4651. });
  4652. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4653. auto se = detail::scope_exit([&] {
  4654. if (!svr.is_running()) return;
  4655. svr.stop();
  4656. listen_thread.join();
  4657. ASSERT_FALSE(svr.is_running());
  4658. });
  4659. svr.wait_until_ready();
  4660. Client cli("localhost", PORT);
  4661. cli.set_keep_alive(true);
  4662. using namespace std::chrono;
  4663. auto start = steady_clock::now();
  4664. cli.Get("/a");
  4665. svr.stop();
  4666. listen_thread.join();
  4667. auto end = steady_clock::now();
  4668. auto elapsed = duration_cast<milliseconds>(end - start).count();
  4669. EXPECT_LT(elapsed, 5000);
  4670. }
  4671. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4672. TEST(KeepAliveTest, SSLClientReconnection) {
  4673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4674. ASSERT_TRUE(svr.is_valid());
  4675. svr.set_keep_alive_timeout(1);
  4676. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4677. res.set_content("Hello World!", "text/plain");
  4678. });
  4679. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4680. auto se = detail::scope_exit([&] {
  4681. svr.stop();
  4682. listen_thread.join();
  4683. ASSERT_FALSE(svr.is_running());
  4684. });
  4685. svr.wait_until_ready();
  4686. SSLClient cli(HOST, PORT);
  4687. cli.enable_server_certificate_verification(false);
  4688. cli.set_keep_alive(true);
  4689. auto result = cli.Get("/hi");
  4690. ASSERT_TRUE(result);
  4691. EXPECT_EQ(StatusCode::OK_200, result->status);
  4692. result = cli.Get("/hi");
  4693. ASSERT_TRUE(result);
  4694. EXPECT_EQ(StatusCode::OK_200, result->status);
  4695. std::this_thread::sleep_for(std::chrono::seconds(2));
  4696. // Recoonect
  4697. result = cli.Get("/hi");
  4698. ASSERT_TRUE(result);
  4699. EXPECT_EQ(StatusCode::OK_200, result->status);
  4700. result = cli.Get("/hi");
  4701. ASSERT_TRUE(result);
  4702. EXPECT_EQ(StatusCode::OK_200, result->status);
  4703. }
  4704. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  4705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4706. ASSERT_TRUE(svr.is_valid());
  4707. svr.set_keep_alive_timeout(1);
  4708. std::string content = "reconnect";
  4709. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  4710. res.set_content("Hello World!", "text/plain");
  4711. });
  4712. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4713. auto se = detail::scope_exit([&] {
  4714. svr.stop();
  4715. listen_thread.join();
  4716. ASSERT_FALSE(svr.is_running());
  4717. });
  4718. svr.wait_until_ready();
  4719. SSLClient cli(HOST, PORT);
  4720. cli.enable_server_certificate_verification(false);
  4721. cli.set_keep_alive(true);
  4722. auto result = cli.Post(
  4723. "/hi", content.size(),
  4724. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4725. sink.write(content.c_str(), content.size());
  4726. return true;
  4727. },
  4728. "text/plain");
  4729. ASSERT_TRUE(result);
  4730. EXPECT_EQ(200, result->status);
  4731. std::this_thread::sleep_for(std::chrono::seconds(2));
  4732. // Recoonect
  4733. result = cli.Post(
  4734. "/hi", content.size(),
  4735. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4736. sink.write(content.c_str(), content.size());
  4737. return true;
  4738. },
  4739. "text/plain");
  4740. ASSERT_TRUE(result);
  4741. EXPECT_EQ(200, result->status);
  4742. result = cli.Post(
  4743. "/hi", content.size(),
  4744. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4745. sink.write(content.c_str(), content.size());
  4746. return true;
  4747. },
  4748. "text/plain");
  4749. ASSERT_TRUE(result);
  4750. EXPECT_EQ(200, result->status);
  4751. }
  4752. #endif
  4753. TEST(ClientProblemDetectionTest, ContentProvider) {
  4754. Server svr;
  4755. size_t content_length = 1024 * 1024;
  4756. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4757. res.set_content_provider(
  4758. content_length, "text/plain",
  4759. [&](size_t offset, size_t length, DataSink &sink) {
  4760. auto out_len = std::min(length, static_cast<size_t>(1024));
  4761. std::string out(out_len, '@');
  4762. sink.write(out.data(), out_len);
  4763. return offset < 4096;
  4764. },
  4765. [](bool success) { ASSERT_FALSE(success); });
  4766. });
  4767. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  4768. res.set_content_provider(
  4769. 0, "text/plain",
  4770. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  4771. EXPECT_TRUE(false);
  4772. return true;
  4773. },
  4774. [](bool success) { ASSERT_FALSE(success); });
  4775. });
  4776. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4777. auto se = detail::scope_exit([&] {
  4778. svr.stop();
  4779. listen_thread.join();
  4780. ASSERT_FALSE(svr.is_running());
  4781. });
  4782. svr.wait_until_ready();
  4783. Client cli("localhost", PORT);
  4784. {
  4785. auto res = cli.Get("/hi", [&](const char * /*data*/,
  4786. size_t /*data_length*/) { return false; });
  4787. ASSERT_FALSE(res);
  4788. }
  4789. {
  4790. auto res = cli.Get("/empty", [&](const char * /*data*/,
  4791. size_t /*data_length*/) { return false; });
  4792. ASSERT_TRUE(res);
  4793. }
  4794. }
  4795. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  4796. Server svr;
  4797. svr.set_error_handler([](Request const &, Response &res) -> void {
  4798. res.set_chunked_content_provider(
  4799. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4800. sink.os << "hello";
  4801. sink.os << "world";
  4802. sink.done();
  4803. return true;
  4804. });
  4805. });
  4806. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4807. auto se = detail::scope_exit([&] {
  4808. svr.stop();
  4809. listen_thread.join();
  4810. ASSERT_FALSE(svr.is_running());
  4811. });
  4812. svr.wait_until_ready();
  4813. Client cli("localhost", PORT);
  4814. auto res = cli.Get("/");
  4815. ASSERT_TRUE(res);
  4816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4817. EXPECT_EQ("helloworld", res->body);
  4818. }
  4819. TEST(LongPollingTest, ClientCloseDetection) {
  4820. Server svr;
  4821. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  4822. res.set_chunked_content_provider(
  4823. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4824. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  4825. sink.os << "hello";
  4826. auto count = 10;
  4827. while (count > 0 && sink.is_writable()) {
  4828. this_thread::sleep_for(chrono::milliseconds(10));
  4829. count--;
  4830. }
  4831. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  4832. return true;
  4833. });
  4834. });
  4835. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4836. auto se = detail::scope_exit([&] {
  4837. svr.stop();
  4838. listen_thread.join();
  4839. ASSERT_FALSE(svr.is_running());
  4840. });
  4841. svr.wait_until_ready();
  4842. Client cli("localhost", PORT);
  4843. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  4844. EXPECT_EQ("hello", string(data, data_length));
  4845. return false; // close the socket immediately.
  4846. });
  4847. ASSERT_FALSE(res);
  4848. }
  4849. TEST(GetWithParametersTest, GetWithParameters) {
  4850. Server svr;
  4851. svr.Get("/", [&](const Request &req, Response &) {
  4852. EXPECT_EQ("world", req.get_param_value("hello"));
  4853. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4854. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4855. });
  4856. svr.Get("/params", [&](const Request &req, Response &) {
  4857. EXPECT_EQ("world", req.get_param_value("hello"));
  4858. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4859. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4860. });
  4861. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  4862. EXPECT_EQ("resource-id", req.matches[1]);
  4863. EXPECT_EQ("foo", req.get_param_value("param1"));
  4864. EXPECT_EQ("bar", req.get_param_value("param2"));
  4865. });
  4866. svr.Get("/users/:id", [&](const Request &req, Response &) {
  4867. EXPECT_EQ("user-id", req.path_params.at("id"));
  4868. EXPECT_EQ("foo", req.get_param_value("param1"));
  4869. EXPECT_EQ("bar", req.get_param_value("param2"));
  4870. });
  4871. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4872. auto se = detail::scope_exit([&] {
  4873. svr.stop();
  4874. listen_thread.join();
  4875. ASSERT_FALSE(svr.is_running());
  4876. });
  4877. svr.wait_until_ready();
  4878. {
  4879. Client cli(HOST, PORT);
  4880. Params params;
  4881. params.emplace("hello", "world");
  4882. params.emplace("hello2", "world2");
  4883. params.emplace("hello3", "world3");
  4884. auto res = cli.Get("/", params, Headers{});
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. }
  4888. {
  4889. Client cli(HOST, PORT);
  4890. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  4891. ASSERT_TRUE(res);
  4892. EXPECT_EQ(StatusCode::OK_200, res->status);
  4893. }
  4894. {
  4895. Client cli(HOST, PORT);
  4896. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  4897. ASSERT_TRUE(res);
  4898. EXPECT_EQ(StatusCode::OK_200, res->status);
  4899. }
  4900. {
  4901. Client cli(HOST, PORT);
  4902. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  4903. ASSERT_TRUE(res);
  4904. EXPECT_EQ(StatusCode::OK_200, res->status);
  4905. }
  4906. }
  4907. TEST(GetWithParametersTest, GetWithParameters2) {
  4908. Server svr;
  4909. svr.Get("/", [&](const Request &req, Response &res) {
  4910. auto text = req.get_param_value("hello");
  4911. res.set_content(text, "text/plain");
  4912. });
  4913. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4914. auto se = detail::scope_exit([&] {
  4915. svr.stop();
  4916. listen_thread.join();
  4917. ASSERT_FALSE(svr.is_running());
  4918. });
  4919. svr.wait_until_ready();
  4920. Client cli("localhost", PORT);
  4921. Params params;
  4922. params.emplace("hello", "world");
  4923. std::string body;
  4924. auto res = cli.Get("/", params, Headers{},
  4925. [&](const char *data, size_t data_length) {
  4926. body.append(data, data_length);
  4927. return true;
  4928. });
  4929. ASSERT_TRUE(res);
  4930. EXPECT_EQ(StatusCode::OK_200, res->status);
  4931. EXPECT_EQ("world", body);
  4932. }
  4933. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  4934. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4935. auto host = "httpbin.org";
  4936. auto path = std::string{"/range/32"};
  4937. #else
  4938. auto host = "nghttp2.org";
  4939. auto path = std::string{"/httpbin/range/32"};
  4940. #endif
  4941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4942. SSLClient cli(host);
  4943. #else
  4944. Client cli(host);
  4945. #endif
  4946. cli.set_default_headers({make_range_header({{1, 10}})});
  4947. cli.set_connection_timeout(5);
  4948. {
  4949. auto res = cli.Get(path);
  4950. ASSERT_TRUE(res);
  4951. EXPECT_EQ("bcdefghijk", res->body);
  4952. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4953. }
  4954. {
  4955. auto res = cli.Get(path);
  4956. ASSERT_TRUE(res);
  4957. EXPECT_EQ("bcdefghijk", res->body);
  4958. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4959. }
  4960. }
  4961. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  4962. Server svr;
  4963. svr.set_default_headers({{"Hello", "World"}});
  4964. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4965. res.set_content("ok", "text/plain");
  4966. });
  4967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4968. auto se = detail::scope_exit([&] {
  4969. svr.stop();
  4970. listen_thread.join();
  4971. ASSERT_FALSE(svr.is_running());
  4972. });
  4973. svr.wait_until_ready();
  4974. Client cli("localhost", PORT);
  4975. auto res = cli.Get("/");
  4976. ASSERT_TRUE(res);
  4977. EXPECT_EQ(StatusCode::OK_200, res->status);
  4978. EXPECT_EQ("ok", res->body);
  4979. EXPECT_EQ("World", res->get_header_value("Hello"));
  4980. }
  4981. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4982. TEST(KeepAliveTest, ReadTimeoutSSL) {
  4983. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4984. ASSERT_TRUE(svr.is_valid());
  4985. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4986. std::this_thread::sleep_for(std::chrono::seconds(2));
  4987. res.set_content("a", "text/plain");
  4988. });
  4989. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4990. res.set_content("b", "text/plain");
  4991. });
  4992. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4993. auto se = detail::scope_exit([&] {
  4994. svr.stop();
  4995. listen_thread.join();
  4996. ASSERT_FALSE(svr.is_running());
  4997. });
  4998. svr.wait_until_ready();
  4999. SSLClient cli("localhost", PORT);
  5000. cli.enable_server_certificate_verification(false);
  5001. cli.set_keep_alive(true);
  5002. cli.set_read_timeout(std::chrono::seconds(1));
  5003. auto resa = cli.Get("/a");
  5004. ASSERT_TRUE(!resa);
  5005. EXPECT_EQ(Error::Read, resa.error());
  5006. auto resb = cli.Get("/b");
  5007. ASSERT_TRUE(resb);
  5008. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5009. EXPECT_EQ("b", resb->body);
  5010. }
  5011. #endif
  5012. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  5013. protected:
  5014. ServerTestWithAI_PASSIVE()
  5015. : cli_(HOST, PORT)
  5016. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5017. ,
  5018. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5019. #endif
  5020. {
  5021. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5022. cli_.enable_server_certificate_verification(false);
  5023. #endif
  5024. }
  5025. virtual void SetUp() {
  5026. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5027. res.set_content("Hello World!", "text/plain");
  5028. });
  5029. t_ = thread(
  5030. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  5031. svr_.wait_until_ready();
  5032. }
  5033. virtual void TearDown() {
  5034. svr_.stop();
  5035. t_.join();
  5036. }
  5037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5038. SSLClient cli_;
  5039. SSLServer svr_;
  5040. #else
  5041. Client cli_;
  5042. Server svr_;
  5043. #endif
  5044. thread t_;
  5045. };
  5046. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  5047. auto res = cli_.Get("/hi");
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ(StatusCode::OK_200, res->status);
  5050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5051. EXPECT_EQ("Hello World!", res->body);
  5052. }
  5053. class ServerUpDownTest : public ::testing::Test {
  5054. protected:
  5055. ServerUpDownTest() : cli_(HOST, PORT) {}
  5056. virtual void SetUp() {
  5057. t_ = thread([&]() {
  5058. svr_.bind_to_any_port(HOST);
  5059. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5060. ASSERT_TRUE(svr_.listen_after_bind());
  5061. });
  5062. svr_.wait_until_ready();
  5063. }
  5064. virtual void TearDown() {
  5065. svr_.stop();
  5066. t_.join();
  5067. }
  5068. Client cli_;
  5069. Server svr_;
  5070. thread t_;
  5071. };
  5072. TEST_F(ServerUpDownTest, QuickStartStop) {
  5073. // Should not crash, especially when run with
  5074. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  5075. }
  5076. class PayloadMaxLengthTest : public ::testing::Test {
  5077. protected:
  5078. PayloadMaxLengthTest()
  5079. : cli_(HOST, PORT)
  5080. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5081. ,
  5082. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5083. #endif
  5084. {
  5085. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5086. cli_.enable_server_certificate_verification(false);
  5087. #endif
  5088. }
  5089. virtual void SetUp() {
  5090. svr_.set_payload_max_length(8);
  5091. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  5092. res.set_content("test", "text/plain");
  5093. });
  5094. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5095. svr_.wait_until_ready();
  5096. }
  5097. virtual void TearDown() {
  5098. svr_.stop();
  5099. t_.join();
  5100. }
  5101. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5102. SSLClient cli_;
  5103. SSLServer svr_;
  5104. #else
  5105. Client cli_;
  5106. Server svr_;
  5107. #endif
  5108. thread t_;
  5109. };
  5110. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  5111. auto res = cli_.Post("/test", "123456789", "text/plain");
  5112. ASSERT_TRUE(res);
  5113. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5114. res = cli_.Post("/test", "12345678", "text/plain");
  5115. ASSERT_TRUE(res);
  5116. EXPECT_EQ(StatusCode::OK_200, res->status);
  5117. }
  5118. TEST(HostAndPortPropertiesTest, NoSSL) {
  5119. httplib::Client cli("www.google.com", 1234);
  5120. ASSERT_EQ("www.google.com", cli.host());
  5121. ASSERT_EQ(1234, cli.port());
  5122. }
  5123. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  5124. httplib::Client cli("www.google.com:1234");
  5125. ASSERT_EQ("www.google.com", cli.host());
  5126. ASSERT_EQ(1234, cli.port());
  5127. }
  5128. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5129. TEST(HostAndPortPropertiesTest, SSL) {
  5130. httplib::SSLClient cli("www.google.com");
  5131. ASSERT_EQ("www.google.com", cli.host());
  5132. ASSERT_EQ(443, cli.port());
  5133. }
  5134. #endif
  5135. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5136. TEST(SSLClientTest, UpdateCAStore) {
  5137. httplib::SSLClient httplib_client("www.google.com");
  5138. auto ca_store_1 = X509_STORE_new();
  5139. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  5140. nullptr);
  5141. httplib_client.set_ca_cert_store(ca_store_1);
  5142. auto ca_store_2 = X509_STORE_new();
  5143. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  5144. nullptr);
  5145. httplib_client.set_ca_cert_store(ca_store_2);
  5146. }
  5147. TEST(SSLClientTest, ServerNameIndication_Online) {
  5148. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5149. auto host = "httpbin.org";
  5150. auto path = std::string{"/get"};
  5151. #else
  5152. auto host = "nghttp2.org";
  5153. auto path = std::string{"/httpbin/get"};
  5154. #endif
  5155. SSLClient cli(host, 443);
  5156. auto res = cli.Get(path);
  5157. ASSERT_TRUE(res);
  5158. ASSERT_EQ(StatusCode::OK_200, res->status);
  5159. }
  5160. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  5161. Client cli("https://google.com");
  5162. auto res = cli.Get("/");
  5163. ASSERT_TRUE(res);
  5164. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5165. }
  5166. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  5167. SSLClient cli("google.com");
  5168. cli.enable_server_certificate_verification(true);
  5169. cli.set_ca_cert_path("hello");
  5170. auto res = cli.Get("/");
  5171. ASSERT_TRUE(!res);
  5172. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  5173. }
  5174. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  5175. SSLClient cli("google.com");
  5176. cli.set_ca_cert_path(CA_CERT_FILE);
  5177. auto res = cli.Get("/");
  5178. ASSERT_TRUE(res);
  5179. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5180. }
  5181. TEST(SSLClientTest, ServerCertificateVerification4) {
  5182. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5183. ASSERT_TRUE(svr.is_valid());
  5184. svr.Get("/test", [&](const Request &, Response &res) {
  5185. res.set_content("test", "text/plain");
  5186. svr.stop();
  5187. ASSERT_TRUE(true);
  5188. });
  5189. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5190. auto se = detail::scope_exit([&] {
  5191. t.join();
  5192. ASSERT_FALSE(svr.is_running());
  5193. });
  5194. svr.wait_until_ready();
  5195. SSLClient cli("127.0.0.1", PORT);
  5196. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5197. cli.enable_server_certificate_verification(true);
  5198. cli.set_connection_timeout(30);
  5199. auto res = cli.Get("/test");
  5200. ASSERT_TRUE(res);
  5201. ASSERT_EQ(StatusCode::OK_200, res->status);
  5202. }
  5203. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  5204. std::string cert;
  5205. read_file(CA_CERT_FILE, cert);
  5206. SSLClient cli("google.com");
  5207. cli.load_ca_cert_store(cert.data(), cert.size());
  5208. const auto res = cli.Get("/");
  5209. ASSERT_TRUE(res);
  5210. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5211. }
  5212. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  5213. // clang-format off
  5214. static constexpr char cert[] =
  5215. "GlobalSign Root CA\n"
  5216. "==================\n"
  5217. "-----BEGIN CERTIFICATE-----\n"
  5218. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  5219. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  5220. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  5221. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  5222. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  5223. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  5224. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  5225. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  5226. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  5227. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  5228. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  5229. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  5230. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  5231. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  5232. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  5233. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  5234. "-----END CERTIFICATE-----\n";
  5235. // clang-format on
  5236. SSLClient cli("google.com");
  5237. cli.load_ca_cert_store(cert, sizeof(cert));
  5238. const auto res = cli.Get("/");
  5239. ASSERT_TRUE(res);
  5240. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5241. }
  5242. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  5243. SSLClient cli("www.youtube.com");
  5244. cli.set_ca_cert_path(CA_CERT_FILE);
  5245. cli.enable_server_certificate_verification(true);
  5246. cli.set_follow_location(true);
  5247. auto res = cli.Get("/");
  5248. ASSERT_TRUE(res);
  5249. ASSERT_EQ(StatusCode::OK_200, res->status);
  5250. }
  5251. TEST(SSLClientTest, Issue2004_Online) {
  5252. Client client("https://google.com");
  5253. client.set_follow_location(true);
  5254. auto res = client.Get("/");
  5255. ASSERT_TRUE(res);
  5256. ASSERT_EQ(StatusCode::OK_200, res->status);
  5257. auto body = res->body;
  5258. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  5259. }
  5260. #if 0
  5261. TEST(SSLClientTest, SetInterfaceWithINET6) {
  5262. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  5263. ASSERT_TRUE(cli != nullptr);
  5264. cli->set_address_family(AF_INET6);
  5265. cli->set_interface("en0");
  5266. auto res = cli->Get("/get");
  5267. ASSERT_TRUE(res);
  5268. ASSERT_EQ(StatusCode::OK_200, res->status);
  5269. }
  5270. #endif
  5271. void ClientCertPresent(
  5272. const std::string &client_cert_file,
  5273. const std::string &client_private_key_file,
  5274. const std::string &client_encrypted_private_key_pass = std::string()) {
  5275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5276. CLIENT_CA_CERT_DIR);
  5277. ASSERT_TRUE(svr.is_valid());
  5278. svr.Get("/test", [&](const Request &req, Response &res) {
  5279. res.set_content("test", "text/plain");
  5280. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5281. ASSERT_TRUE(peer_cert != nullptr);
  5282. auto subject_name = X509_get_subject_name(peer_cert);
  5283. ASSERT_TRUE(subject_name != nullptr);
  5284. std::string common_name;
  5285. {
  5286. char name[BUFSIZ];
  5287. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5288. name, sizeof(name));
  5289. common_name.assign(name, static_cast<size_t>(name_len));
  5290. }
  5291. EXPECT_EQ("Common Name", common_name);
  5292. X509_free(peer_cert);
  5293. });
  5294. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5295. auto se = detail::scope_exit([&] {
  5296. svr.stop();
  5297. t.join();
  5298. ASSERT_FALSE(svr.is_running());
  5299. });
  5300. svr.wait_until_ready();
  5301. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  5302. client_encrypted_private_key_pass);
  5303. cli.enable_server_certificate_verification(false);
  5304. cli.set_connection_timeout(30);
  5305. auto res = cli.Get("/test");
  5306. ASSERT_TRUE(res);
  5307. ASSERT_EQ(StatusCode::OK_200, res->status);
  5308. }
  5309. TEST(SSLClientServerTest, ClientCertPresent) {
  5310. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5311. }
  5312. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  5313. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5314. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5315. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5316. }
  5317. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  5318. void MemoryClientCertPresent(
  5319. const std::string &client_cert_file,
  5320. const std::string &client_private_key_file,
  5321. const std::string &client_encrypted_private_key_pass = std::string()) {
  5322. auto f = fopen(SERVER_CERT_FILE, "r+");
  5323. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5324. fclose(f);
  5325. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  5326. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  5327. fclose(f);
  5328. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  5329. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5330. auto client_ca_cert_store = X509_STORE_new();
  5331. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  5332. X509_free(client_cert);
  5333. fclose(f);
  5334. f = fopen(client_cert_file.c_str(), "r+");
  5335. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5336. fclose(f);
  5337. f = fopen(client_private_key_file.c_str(), "r+");
  5338. auto client_private_key = PEM_read_PrivateKey(
  5339. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  5340. fclose(f);
  5341. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  5342. ASSERT_TRUE(svr.is_valid());
  5343. svr.Get("/test", [&](const Request &req, Response &res) {
  5344. res.set_content("test", "text/plain");
  5345. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5346. ASSERT_TRUE(peer_cert != nullptr);
  5347. auto subject_name = X509_get_subject_name(peer_cert);
  5348. ASSERT_TRUE(subject_name != nullptr);
  5349. std::string common_name;
  5350. {
  5351. char name[BUFSIZ];
  5352. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5353. name, sizeof(name));
  5354. common_name.assign(name, static_cast<size_t>(name_len));
  5355. }
  5356. EXPECT_EQ("Common Name", common_name);
  5357. X509_free(peer_cert);
  5358. });
  5359. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5360. auto se = detail::scope_exit([&] {
  5361. svr.stop();
  5362. t.join();
  5363. ASSERT_FALSE(svr.is_running());
  5364. });
  5365. svr.wait_until_ready();
  5366. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  5367. client_encrypted_private_key_pass);
  5368. cli.enable_server_certificate_verification(false);
  5369. cli.set_connection_timeout(30);
  5370. auto res = cli.Get("/test");
  5371. ASSERT_TRUE(res);
  5372. ASSERT_EQ(StatusCode::OK_200, res->status);
  5373. X509_free(server_cert);
  5374. EVP_PKEY_free(server_private_key);
  5375. X509_free(client_cert);
  5376. EVP_PKEY_free(client_private_key);
  5377. }
  5378. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  5379. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5380. }
  5381. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  5382. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5383. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5384. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5385. }
  5386. #endif
  5387. TEST(SSLClientServerTest, ClientCertMissing) {
  5388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5389. CLIENT_CA_CERT_DIR);
  5390. ASSERT_TRUE(svr.is_valid());
  5391. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  5392. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5393. auto se = detail::scope_exit([&] {
  5394. svr.stop();
  5395. t.join();
  5396. ASSERT_FALSE(svr.is_running());
  5397. });
  5398. svr.wait_until_ready();
  5399. SSLClient cli(HOST, PORT);
  5400. auto res = cli.Get("/test");
  5401. cli.set_connection_timeout(30);
  5402. ASSERT_TRUE(!res);
  5403. EXPECT_EQ(Error::SSLServerVerification, res.error());
  5404. }
  5405. TEST(SSLClientServerTest, TrustDirOptional) {
  5406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5407. ASSERT_TRUE(svr.is_valid());
  5408. svr.Get("/test", [&](const Request &, Response &res) {
  5409. res.set_content("test", "text/plain");
  5410. });
  5411. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5412. auto se = detail::scope_exit([&] {
  5413. svr.stop();
  5414. t.join();
  5415. ASSERT_FALSE(svr.is_running());
  5416. });
  5417. svr.wait_until_ready();
  5418. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5419. cli.enable_server_certificate_verification(false);
  5420. cli.set_connection_timeout(30);
  5421. auto res = cli.Get("/test");
  5422. ASSERT_TRUE(res);
  5423. ASSERT_EQ(StatusCode::OK_200, res->status);
  5424. }
  5425. TEST(SSLClientServerTest, SSLConnectTimeout) {
  5426. class NoListenSSLServer : public SSLServer {
  5427. public:
  5428. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  5429. const char *client_ca_cert_file_path,
  5430. const char *client_ca_cert_dir_path = nullptr)
  5431. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  5432. client_ca_cert_dir_path),
  5433. stop_(false) {}
  5434. std::atomic_bool stop_;
  5435. private:
  5436. bool process_and_close_socket(socket_t /*sock*/) override {
  5437. // Don't create SSL context
  5438. while (!stop_.load()) {
  5439. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5440. }
  5441. return true;
  5442. }
  5443. };
  5444. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  5445. CLIENT_CA_CERT_FILE);
  5446. ASSERT_TRUE(svr.is_valid());
  5447. svr.Get("/test", [&](const Request &, Response &res) {
  5448. res.set_content("test", "text/plain");
  5449. });
  5450. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5451. auto se = detail::scope_exit([&] {
  5452. svr.stop_ = true;
  5453. svr.stop();
  5454. t.join();
  5455. ASSERT_FALSE(svr.is_running());
  5456. });
  5457. svr.wait_until_ready();
  5458. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5459. cli.enable_server_certificate_verification(false);
  5460. cli.set_connection_timeout(1);
  5461. auto res = cli.Get("/test");
  5462. ASSERT_TRUE(!res);
  5463. EXPECT_EQ(Error::SSLConnection, res.error());
  5464. }
  5465. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  5466. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  5467. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  5468. SSL_CTX_set_options(&ssl_ctx,
  5469. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  5470. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  5471. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  5472. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  5473. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  5474. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  5475. "ECDHE-DSS-AES128-SHA256:"
  5476. "ECDHE-RSA-AES256-SHA256:"
  5477. "ECDHE-DSS-AES256-SHA256:";
  5478. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  5479. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  5480. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  5481. SSL_FILETYPE_PEM) != 1) {
  5482. return false;
  5483. }
  5484. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  5485. CLIENT_CA_CERT_DIR);
  5486. SSL_CTX_set_verify(
  5487. &ssl_ctx,
  5488. SSL_VERIFY_PEER |
  5489. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  5490. nullptr);
  5491. return true;
  5492. };
  5493. SSLServer svr(setup_ssl_ctx_callback);
  5494. ASSERT_TRUE(svr.is_valid());
  5495. svr.Get("/test", [&](const Request &req, Response &res) {
  5496. res.set_content("test", "text/plain");
  5497. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5498. ASSERT_TRUE(peer_cert != nullptr);
  5499. auto subject_name = X509_get_subject_name(peer_cert);
  5500. ASSERT_TRUE(subject_name != nullptr);
  5501. std::string common_name;
  5502. {
  5503. char name[BUFSIZ];
  5504. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5505. name, sizeof(name));
  5506. common_name.assign(name, static_cast<size_t>(name_len));
  5507. }
  5508. EXPECT_EQ("Common Name", common_name);
  5509. X509_free(peer_cert);
  5510. });
  5511. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5512. auto se = detail::scope_exit([&] {
  5513. svr.stop();
  5514. t.join();
  5515. ASSERT_FALSE(svr.is_running());
  5516. });
  5517. svr.wait_until_ready();
  5518. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5519. cli.enable_server_certificate_verification(false);
  5520. cli.set_connection_timeout(30);
  5521. auto res = cli.Get("/test");
  5522. ASSERT_TRUE(res);
  5523. ASSERT_EQ(StatusCode::OK_200, res->status);
  5524. }
  5525. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  5526. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  5527. // prepare large data
  5528. std::random_device seed_gen;
  5529. std::mt19937 random(seed_gen());
  5530. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  5531. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  5532. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  5533. // server
  5534. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5535. ASSERT_TRUE(svr.is_valid());
  5536. svr.Post("/binary", [&](const Request &req, Response &res) {
  5537. EXPECT_EQ(large_size_byte, req.body.size());
  5538. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  5539. res.set_content(req.body, "application/octet-stream");
  5540. });
  5541. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5542. auto se = detail::scope_exit([&] {
  5543. svr.stop();
  5544. listen_thread.join();
  5545. ASSERT_FALSE(svr.is_running());
  5546. });
  5547. svr.wait_until_ready();
  5548. // client POST
  5549. SSLClient cli("localhost", PORT);
  5550. cli.enable_server_certificate_verification(false);
  5551. cli.set_read_timeout(std::chrono::seconds(100));
  5552. cli.set_write_timeout(std::chrono::seconds(100));
  5553. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  5554. large_size_byte, "application/octet-stream");
  5555. // compare
  5556. EXPECT_EQ(StatusCode::OK_200, res->status);
  5557. EXPECT_EQ(large_size_byte, res->body.size());
  5558. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  5559. }
  5560. #endif
  5561. #ifdef _WIN32
  5562. TEST(CleanupTest, WSACleanup) {
  5563. int ret = WSACleanup();
  5564. ASSERT_EQ(0, ret);
  5565. }
  5566. #endif
  5567. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  5568. TEST(NoSSLSupport, SimpleInterface) {
  5569. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  5570. }
  5571. #endif
  5572. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5573. TEST(InvalidScheme, SimpleInterface) {
  5574. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  5575. }
  5576. #endif
  5577. TEST(NoScheme, SimpleInterface) {
  5578. Client cli("yahoo.com:80");
  5579. ASSERT_TRUE(cli.is_valid());
  5580. }
  5581. TEST(SendAPI, SimpleInterface_Online) {
  5582. Client cli("http://yahoo.com");
  5583. Request req;
  5584. req.method = "GET";
  5585. req.path = "/";
  5586. auto res = cli.send(req);
  5587. ASSERT_TRUE(res);
  5588. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5589. }
  5590. TEST(SendAPI, WithParamsInRequest) {
  5591. Server svr;
  5592. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  5593. EXPECT_TRUE(req.has_param("test"));
  5594. EXPECT_EQ("test_value", req.get_param_value("test"));
  5595. });
  5596. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  5597. auto se = detail::scope_exit([&] {
  5598. svr.stop();
  5599. t.join();
  5600. ASSERT_FALSE(svr.is_running());
  5601. });
  5602. svr.wait_until_ready();
  5603. Client cli(HOST, PORT);
  5604. {
  5605. Request req;
  5606. req.method = "GET";
  5607. req.path = "/";
  5608. req.params.emplace("test", "test_value");
  5609. auto res = cli.send(req);
  5610. ASSERT_TRUE(res);
  5611. }
  5612. {
  5613. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  5614. ASSERT_TRUE(res);
  5615. }
  5616. }
  5617. TEST(ClientImplMethods, GetSocketTest) {
  5618. httplib::Server svr;
  5619. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5620. res.status = StatusCode::OK_200;
  5621. });
  5622. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  5623. auto se = detail::scope_exit([&] {
  5624. svr.stop();
  5625. thread.join();
  5626. ASSERT_FALSE(svr.is_running());
  5627. });
  5628. svr.wait_until_ready();
  5629. {
  5630. httplib::Client cli("http://127.0.0.1:3333");
  5631. cli.set_keep_alive(true);
  5632. // Use the behavior of cpp-httplib of opening the connection
  5633. // only when the first request happens. If that changes,
  5634. // this test would be obsolete.
  5635. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  5636. // This also implicitly tests the server. But other tests would fail much
  5637. // earlier than this one to be considered.
  5638. auto res = cli.Get("/");
  5639. ASSERT_TRUE(res);
  5640. EXPECT_EQ(StatusCode::OK_200, res->status);
  5641. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  5642. }
  5643. }
  5644. // Disabled due to out-of-memory problem on GitHub Actions
  5645. #ifdef _WIN64
  5646. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  5647. // allocate content size larger than 2GB in memory
  5648. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  5649. char *content = (char *)malloc(content_size);
  5650. ASSERT_TRUE(content);
  5651. Server svr;
  5652. svr.Get("/foo",
  5653. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  5654. res.set_content(content, content_size, "application/octet-stream");
  5655. });
  5656. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5657. auto se = detail::scope_exit([&] {
  5658. svr.stop();
  5659. listen_thread.join();
  5660. if (content) free(content);
  5661. ASSERT_FALSE(svr.is_running());
  5662. });
  5663. svr.wait_until_ready();
  5664. Client cli(HOST, PORT);
  5665. auto res = cli.Get("/foo");
  5666. ASSERT_TRUE(res);
  5667. EXPECT_EQ(StatusCode::OK_200, res->status);
  5668. EXPECT_EQ(content_size, res->body.length());
  5669. }
  5670. #endif
  5671. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5672. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  5673. Client cli("http://yahoo.com");
  5674. auto res = cli.Get("/");
  5675. ASSERT_TRUE(res);
  5676. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5677. cli.set_follow_location(true);
  5678. res = cli.Get("/");
  5679. ASSERT_TRUE(res);
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5682. }
  5683. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  5684. Client cli("https://yahoo.com");
  5685. auto res = cli.Get("/");
  5686. ASSERT_TRUE(res);
  5687. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5688. cli.set_follow_location(true);
  5689. res = cli.Get("/");
  5690. ASSERT_TRUE(res);
  5691. EXPECT_EQ(StatusCode::OK_200, res->status);
  5692. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5693. }
  5694. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  5695. Client cli("https://yahoo.com");
  5696. auto res = cli.Get("/");
  5697. ASSERT_TRUE(res);
  5698. ASSERT_FALSE(!res);
  5699. ASSERT_TRUE(res);
  5700. ASSERT_FALSE(res == nullptr);
  5701. ASSERT_TRUE(res != nullptr);
  5702. EXPECT_EQ(Error::Success, res.error());
  5703. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  5704. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  5705. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5706. cli.set_follow_location(true);
  5707. res = cli.Get("/");
  5708. ASSERT_TRUE(res);
  5709. EXPECT_EQ(Error::Success, res.error());
  5710. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  5711. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  5712. EXPECT_EQ(StatusCode::OK_200, res->status);
  5713. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5714. }
  5715. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5716. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  5717. Client cli("https://cdnjs.cloudflare.com");
  5718. auto res =
  5719. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  5720. ASSERT_TRUE(res);
  5721. EXPECT_EQ(StatusCode::OK_200, res->status);
  5722. EXPECT_EQ(287630U, res->body.size());
  5723. EXPECT_EQ("application/javascript; charset=utf-8",
  5724. res->get_header_value("Content-Type"));
  5725. }
  5726. #endif
  5727. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  5728. #undef REDIR_HOST // Silence compiler warning
  5729. #define REDIR_HOST "https://httpbingo.org"
  5730. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  5731. Client cli(REDIR_HOST);
  5732. cli.set_follow_location(true);
  5733. auto res =
  5734. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  5735. ASSERT_TRUE(res);
  5736. EXPECT_EQ(StatusCode::OK_200, res->status);
  5737. }
  5738. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  5739. Client cli(REDIR_HOST);
  5740. cli.set_follow_location(true);
  5741. Params params;
  5742. params.emplace("url", "http://example.com");
  5743. params.emplace("status_code", "302");
  5744. auto res = cli.Get(REDIR_PATH, params, Headers{});
  5745. ASSERT_TRUE(res);
  5746. EXPECT_EQ(StatusCode::OK_200, res->status);
  5747. }
  5748. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  5749. Client cli(REDIR_HOST);
  5750. cli.set_follow_location(true);
  5751. Params params;
  5752. params.emplace("url", "http://example.com");
  5753. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  5754. ASSERT_TRUE(res);
  5755. EXPECT_EQ(StatusCode::OK_200, res->status);
  5756. }
  5757. TEST(HttpToHttpsRedirectTest, CertFile) {
  5758. Server svr;
  5759. ASSERT_TRUE(svr.is_valid());
  5760. svr.Get("/index", [&](const Request &, Response &res) {
  5761. res.set_redirect("https://127.0.0.1:1235/index");
  5762. svr.stop();
  5763. });
  5764. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5765. ASSERT_TRUE(ssl_svr.is_valid());
  5766. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  5767. res.set_content("test", "text/plain");
  5768. ssl_svr.stop();
  5769. });
  5770. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5771. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  5772. auto se = detail::scope_exit([&] {
  5773. t2.join();
  5774. t.join();
  5775. ASSERT_FALSE(svr.is_running());
  5776. });
  5777. svr.wait_until_ready();
  5778. ssl_svr.wait_until_ready();
  5779. Client cli("127.0.0.1", PORT);
  5780. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5781. cli.enable_server_certificate_verification(true);
  5782. cli.set_follow_location(true);
  5783. cli.set_connection_timeout(30);
  5784. auto res = cli.Get("/index");
  5785. ASSERT_TRUE(res);
  5786. ASSERT_EQ(StatusCode::OK_200, res->status);
  5787. }
  5788. TEST(MultipartFormDataTest, LargeData) {
  5789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5790. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5791. const ContentReader &content_reader) {
  5792. if (req.is_multipart_form_data()) {
  5793. MultipartFormDataItems files;
  5794. content_reader(
  5795. [&](const MultipartFormData &file) {
  5796. files.push_back(file);
  5797. return true;
  5798. },
  5799. [&](const char *data, size_t data_length) {
  5800. files.back().content.append(data, data_length);
  5801. return true;
  5802. });
  5803. EXPECT_TRUE(std::string(files[0].name) == "document");
  5804. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5805. EXPECT_TRUE(files[0].filename == "2MB_data");
  5806. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5807. EXPECT_TRUE(files[1].name == "hello");
  5808. EXPECT_TRUE(files[1].content == "world");
  5809. EXPECT_TRUE(files[1].filename == "");
  5810. EXPECT_TRUE(files[1].content_type == "");
  5811. } else {
  5812. std::string body;
  5813. content_reader([&](const char *data, size_t data_length) {
  5814. body.append(data, data_length);
  5815. return true;
  5816. });
  5817. }
  5818. });
  5819. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5820. auto se = detail::scope_exit([&] {
  5821. svr.stop();
  5822. t.join();
  5823. ASSERT_FALSE(svr.is_running());
  5824. });
  5825. svr.wait_until_ready();
  5826. {
  5827. std::string data(1024 * 1024 * 2, '.');
  5828. std::stringstream buffer;
  5829. buffer << data;
  5830. Client cli("https://localhost:8080");
  5831. cli.enable_server_certificate_verification(false);
  5832. MultipartFormDataItems items{
  5833. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5834. {"hello", "world", "", ""},
  5835. };
  5836. auto res = cli.Post("/post", items);
  5837. ASSERT_TRUE(res);
  5838. ASSERT_EQ(StatusCode::OK_200, res->status);
  5839. }
  5840. }
  5841. TEST(MultipartFormDataTest, DataProviderItems) {
  5842. std::random_device seed_gen;
  5843. std::mt19937 random(seed_gen());
  5844. std::string rand1;
  5845. rand1.resize(1000);
  5846. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  5847. std::string rand2;
  5848. rand2.resize(3000);
  5849. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  5850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5851. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  5852. const ContentReader &content_reader) {
  5853. ASSERT_FALSE(req.is_multipart_form_data());
  5854. std::string body;
  5855. content_reader([&](const char *data, size_t data_length) {
  5856. body.append(data, data_length);
  5857. return true;
  5858. });
  5859. EXPECT_EQ(body, "");
  5860. });
  5861. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  5862. const ContentReader &content_reader) {
  5863. ASSERT_TRUE(req.is_multipart_form_data());
  5864. MultipartFormDataItems files;
  5865. content_reader(
  5866. [&](const MultipartFormData &file) {
  5867. files.push_back(file);
  5868. return true;
  5869. },
  5870. [&](const char *data, size_t data_length) {
  5871. files.back().content.append(data, data_length);
  5872. return true;
  5873. });
  5874. ASSERT_TRUE(files.size() == 2);
  5875. EXPECT_EQ(std::string(files[0].name), "name1");
  5876. EXPECT_EQ(files[0].content, "Testing123");
  5877. EXPECT_EQ(files[0].filename, "filename1");
  5878. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5879. EXPECT_EQ(files[1].name, "name2");
  5880. EXPECT_EQ(files[1].content, "Testing456");
  5881. EXPECT_EQ(files[1].filename, "");
  5882. EXPECT_EQ(files[1].content_type, "");
  5883. });
  5884. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  5885. const ContentReader &content_reader) {
  5886. ASSERT_TRUE(req.is_multipart_form_data());
  5887. MultipartFormDataItems files;
  5888. content_reader(
  5889. [&](const MultipartFormData &file) {
  5890. files.push_back(file);
  5891. return true;
  5892. },
  5893. [&](const char *data, size_t data_length) {
  5894. files.back().content.append(data, data_length);
  5895. return true;
  5896. });
  5897. ASSERT_TRUE(files.size() == 2);
  5898. EXPECT_EQ(files[0].name, "name3");
  5899. EXPECT_EQ(files[0].content, rand1);
  5900. EXPECT_EQ(files[0].filename, "filename3");
  5901. EXPECT_EQ(files[0].content_type, "");
  5902. EXPECT_EQ(files[1].name, "name4");
  5903. EXPECT_EQ(files[1].content, rand2);
  5904. EXPECT_EQ(files[1].filename, "filename4");
  5905. EXPECT_EQ(files[1].content_type, "");
  5906. });
  5907. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  5908. const ContentReader &content_reader) {
  5909. ASSERT_TRUE(req.is_multipart_form_data());
  5910. MultipartFormDataItems files;
  5911. content_reader(
  5912. [&](const MultipartFormData &file) {
  5913. files.push_back(file);
  5914. return true;
  5915. },
  5916. [&](const char *data, size_t data_length) {
  5917. files.back().content.append(data, data_length);
  5918. return true;
  5919. });
  5920. ASSERT_TRUE(files.size() == 4);
  5921. EXPECT_EQ(std::string(files[0].name), "name1");
  5922. EXPECT_EQ(files[0].content, "Testing123");
  5923. EXPECT_EQ(files[0].filename, "filename1");
  5924. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5925. EXPECT_EQ(files[1].name, "name2");
  5926. EXPECT_EQ(files[1].content, "Testing456");
  5927. EXPECT_EQ(files[1].filename, "");
  5928. EXPECT_EQ(files[1].content_type, "");
  5929. EXPECT_EQ(files[2].name, "name3");
  5930. EXPECT_EQ(files[2].content, rand1);
  5931. EXPECT_EQ(files[2].filename, "filename3");
  5932. EXPECT_EQ(files[2].content_type, "");
  5933. EXPECT_EQ(files[3].name, "name4");
  5934. EXPECT_EQ(files[3].content, rand2);
  5935. EXPECT_EQ(files[3].filename, "filename4");
  5936. EXPECT_EQ(files[3].content_type, "");
  5937. });
  5938. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5939. auto se = detail::scope_exit([&] {
  5940. svr.stop();
  5941. t.join();
  5942. ASSERT_FALSE(svr.is_running());
  5943. });
  5944. svr.wait_until_ready();
  5945. {
  5946. Client cli("https://localhost:8080");
  5947. cli.enable_server_certificate_verification(false);
  5948. MultipartFormDataItems items{
  5949. {"name1", "Testing123", "filename1", "application/octet-stream"},
  5950. {"name2", "Testing456", "", ""}, // not a file
  5951. };
  5952. {
  5953. auto res = cli.Post("/post-none", {}, {}, {});
  5954. ASSERT_TRUE(res);
  5955. ASSERT_EQ(StatusCode::OK_200, res->status);
  5956. }
  5957. MultipartFormDataProviderItems providers;
  5958. {
  5959. auto res =
  5960. cli.Post("/post-items", {}, items, providers); // empty providers
  5961. ASSERT_TRUE(res);
  5962. ASSERT_EQ(StatusCode::OK_200, res->status);
  5963. }
  5964. providers.push_back({"name3",
  5965. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5966. // test the offset is given correctly at each step
  5967. if (!offset)
  5968. sink.os.write(rand1.data(), 30);
  5969. else if (offset == 30)
  5970. sink.os.write(rand1.data() + 30, 300);
  5971. else if (offset == 330)
  5972. sink.os.write(rand1.data() + 330, 670);
  5973. else if (offset == rand1.size())
  5974. sink.done();
  5975. return true;
  5976. },
  5977. "filename3",
  5978. {}});
  5979. providers.push_back({"name4",
  5980. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5981. // test the offset is given correctly at each step
  5982. if (!offset)
  5983. sink.os.write(rand2.data(), 2000);
  5984. else if (offset == 2000)
  5985. sink.os.write(rand2.data() + 2000, 1);
  5986. else if (offset == 2001)
  5987. sink.os.write(rand2.data() + 2001, 999);
  5988. else if (offset == rand2.size())
  5989. sink.done();
  5990. return true;
  5991. },
  5992. "filename4",
  5993. {}});
  5994. {
  5995. auto res = cli.Post("/post-providers", {}, {}, providers);
  5996. ASSERT_TRUE(res);
  5997. ASSERT_EQ(StatusCode::OK_200, res->status);
  5998. }
  5999. {
  6000. auto res = cli.Post("/post-both", {}, items, providers);
  6001. ASSERT_TRUE(res);
  6002. ASSERT_EQ(StatusCode::OK_200, res->status);
  6003. }
  6004. }
  6005. }
  6006. TEST(MultipartFormDataTest, BadHeader) {
  6007. Server svr;
  6008. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6009. res.set_content("ok", "text/plain");
  6010. });
  6011. thread t = thread([&] { svr.listen(HOST, PORT); });
  6012. auto se = detail::scope_exit([&] {
  6013. svr.stop();
  6014. t.join();
  6015. ASSERT_FALSE(svr.is_running());
  6016. });
  6017. svr.wait_until_ready();
  6018. const std::string body =
  6019. "This is the preamble. It is to be ignored, though it\r\n"
  6020. "is a handy place for composition agents to include an\r\n"
  6021. "explanatory note to non-MIME conformant readers.\r\n"
  6022. "\r\n"
  6023. "\r\n"
  6024. "--simple boundary\r\n"
  6025. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6026. ": BAD...\r\n"
  6027. "\r\n"
  6028. "value1\r\n"
  6029. "--simple boundary\r\n"
  6030. "Content-Disposition: form-data; name=\"field2\"; "
  6031. "filename=\"example.txt\"\r\n"
  6032. "\r\n"
  6033. "value2\r\n"
  6034. "--simple boundary--\r\n"
  6035. "This is the epilogue. It is also to be ignored.\r\n";
  6036. std::string content_type =
  6037. R"(multipart/form-data; boundary="simple boundary")";
  6038. Client cli(HOST, PORT);
  6039. auto res = cli.Post("/post", body, content_type.c_str());
  6040. ASSERT_TRUE(res);
  6041. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6042. }
  6043. TEST(MultipartFormDataTest, WithPreamble) {
  6044. Server svr;
  6045. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6046. res.set_content("ok", "text/plain");
  6047. });
  6048. thread t = thread([&] { svr.listen(HOST, PORT); });
  6049. auto se = detail::scope_exit([&] {
  6050. svr.stop();
  6051. t.join();
  6052. ASSERT_FALSE(svr.is_running());
  6053. });
  6054. svr.wait_until_ready();
  6055. const std::string body =
  6056. "This is the preamble. It is to be ignored, though it\r\n"
  6057. "is a handy place for composition agents to include an\r\n"
  6058. "explanatory note to non-MIME conformant readers.\r\n"
  6059. "\r\n"
  6060. "\r\n"
  6061. "--simple boundary\r\n"
  6062. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6063. "\r\n"
  6064. "value1\r\n"
  6065. "--simple boundary\r\n"
  6066. "Content-Disposition: form-data; name=\"field2\"; "
  6067. "filename=\"example.txt\"\r\n"
  6068. "\r\n"
  6069. "value2\r\n"
  6070. "--simple boundary--\r\n"
  6071. "This is the epilogue. It is also to be ignored.\r\n";
  6072. std::string content_type =
  6073. R"(multipart/form-data; boundary="simple boundary")";
  6074. Client cli(HOST, PORT);
  6075. auto res = cli.Post("/post", body, content_type.c_str());
  6076. ASSERT_TRUE(res);
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. }
  6079. TEST(MultipartFormDataTest, PostCustomBoundary) {
  6080. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6081. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  6082. const ContentReader &content_reader) {
  6083. if (req.is_multipart_form_data()) {
  6084. MultipartFormDataItems files;
  6085. content_reader(
  6086. [&](const MultipartFormData &file) {
  6087. files.push_back(file);
  6088. return true;
  6089. },
  6090. [&](const char *data, size_t data_length) {
  6091. files.back().content.append(data, data_length);
  6092. return true;
  6093. });
  6094. EXPECT_TRUE(std::string(files[0].name) == "document");
  6095. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6096. EXPECT_TRUE(files[0].filename == "2MB_data");
  6097. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6098. EXPECT_TRUE(files[1].name == "hello");
  6099. EXPECT_TRUE(files[1].content == "world");
  6100. EXPECT_TRUE(files[1].filename == "");
  6101. EXPECT_TRUE(files[1].content_type == "");
  6102. } else {
  6103. std::string body;
  6104. content_reader([&](const char *data, size_t data_length) {
  6105. body.append(data, data_length);
  6106. return true;
  6107. });
  6108. }
  6109. });
  6110. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6111. auto se = detail::scope_exit([&] {
  6112. svr.stop();
  6113. t.join();
  6114. ASSERT_FALSE(svr.is_running());
  6115. });
  6116. svr.wait_until_ready();
  6117. {
  6118. std::string data(1024 * 1024 * 2, '.');
  6119. std::stringstream buffer;
  6120. buffer << data;
  6121. Client cli("https://localhost:8080");
  6122. cli.enable_server_certificate_verification(false);
  6123. MultipartFormDataItems items{
  6124. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6125. {"hello", "world", "", ""},
  6126. };
  6127. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  6128. ASSERT_TRUE(res);
  6129. ASSERT_EQ(StatusCode::OK_200, res->status);
  6130. }
  6131. }
  6132. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  6133. std::string data(1024 * 1024 * 2, '&');
  6134. std::stringstream buffer;
  6135. buffer << data;
  6136. Client cli("https://localhost:8080");
  6137. MultipartFormDataItems items{
  6138. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6139. {"hello", "world", "", ""},
  6140. };
  6141. for (const char &c : " \t\r\n") {
  6142. auto res =
  6143. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  6144. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6145. ASSERT_FALSE(res);
  6146. }
  6147. }
  6148. TEST(MultipartFormDataTest, PutFormData) {
  6149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6150. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  6151. const ContentReader &content_reader) {
  6152. if (req.is_multipart_form_data()) {
  6153. MultipartFormDataItems files;
  6154. content_reader(
  6155. [&](const MultipartFormData &file) {
  6156. files.push_back(file);
  6157. return true;
  6158. },
  6159. [&](const char *data, size_t data_length) {
  6160. files.back().content.append(data, data_length);
  6161. return true;
  6162. });
  6163. EXPECT_TRUE(std::string(files[0].name) == "document");
  6164. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6165. EXPECT_TRUE(files[0].filename == "2MB_data");
  6166. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6167. EXPECT_TRUE(files[1].name == "hello");
  6168. EXPECT_TRUE(files[1].content == "world");
  6169. EXPECT_TRUE(files[1].filename == "");
  6170. EXPECT_TRUE(files[1].content_type == "");
  6171. } else {
  6172. std::string body;
  6173. content_reader([&](const char *data, size_t data_length) {
  6174. body.append(data, data_length);
  6175. return true;
  6176. });
  6177. }
  6178. });
  6179. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6180. auto se = detail::scope_exit([&] {
  6181. svr.stop();
  6182. t.join();
  6183. ASSERT_FALSE(svr.is_running());
  6184. });
  6185. svr.wait_until_ready();
  6186. {
  6187. std::string data(1024 * 1024 * 2, '&');
  6188. std::stringstream buffer;
  6189. buffer << data;
  6190. Client cli("https://localhost:8080");
  6191. cli.enable_server_certificate_verification(false);
  6192. MultipartFormDataItems items{
  6193. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6194. {"hello", "world", "", ""},
  6195. };
  6196. auto res = cli.Put("/put", items);
  6197. ASSERT_TRUE(res);
  6198. ASSERT_EQ(StatusCode::OK_200, res->status);
  6199. }
  6200. }
  6201. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  6202. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6203. svr.Put("/put_customboundary",
  6204. [&](const Request &req, const Response & /*res*/,
  6205. const ContentReader &content_reader) {
  6206. if (req.is_multipart_form_data()) {
  6207. MultipartFormDataItems files;
  6208. content_reader(
  6209. [&](const MultipartFormData &file) {
  6210. files.push_back(file);
  6211. return true;
  6212. },
  6213. [&](const char *data, size_t data_length) {
  6214. files.back().content.append(data, data_length);
  6215. return true;
  6216. });
  6217. EXPECT_TRUE(std::string(files[0].name) == "document");
  6218. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6219. EXPECT_TRUE(files[0].filename == "2MB_data");
  6220. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6221. EXPECT_TRUE(files[1].name == "hello");
  6222. EXPECT_TRUE(files[1].content == "world");
  6223. EXPECT_TRUE(files[1].filename == "");
  6224. EXPECT_TRUE(files[1].content_type == "");
  6225. } else {
  6226. std::string body;
  6227. content_reader([&](const char *data, size_t data_length) {
  6228. body.append(data, data_length);
  6229. return true;
  6230. });
  6231. }
  6232. });
  6233. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6234. auto se = detail::scope_exit([&] {
  6235. svr.stop();
  6236. t.join();
  6237. ASSERT_FALSE(svr.is_running());
  6238. });
  6239. svr.wait_until_ready();
  6240. {
  6241. std::string data(1024 * 1024 * 2, '&');
  6242. std::stringstream buffer;
  6243. buffer << data;
  6244. Client cli("https://localhost:8080");
  6245. cli.enable_server_certificate_verification(false);
  6246. MultipartFormDataItems items{
  6247. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6248. {"hello", "world", "", ""},
  6249. };
  6250. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  6251. ASSERT_TRUE(res);
  6252. ASSERT_EQ(StatusCode::OK_200, res->status);
  6253. }
  6254. }
  6255. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  6256. std::string data(1024 * 1024 * 2, '&');
  6257. std::stringstream buffer;
  6258. buffer << data;
  6259. Client cli("https://localhost:8080");
  6260. cli.enable_server_certificate_verification(false);
  6261. MultipartFormDataItems items{
  6262. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6263. {"hello", "world", "", ""},
  6264. };
  6265. for (const char &c : " \t\r\n") {
  6266. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  6267. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6268. ASSERT_FALSE(res);
  6269. }
  6270. }
  6271. TEST(MultipartFormDataTest, AlternateFilename) {
  6272. auto handled = false;
  6273. Server svr;
  6274. svr.Post("/test", [&](const Request &req, Response &res) {
  6275. ASSERT_EQ(3u, req.files.size());
  6276. auto it = req.files.begin();
  6277. ASSERT_EQ("file1", it->second.name);
  6278. ASSERT_EQ("A.txt", it->second.filename);
  6279. ASSERT_EQ("text/plain", it->second.content_type);
  6280. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  6281. ++it;
  6282. ASSERT_EQ("file2", it->second.name);
  6283. ASSERT_EQ("a.html", it->second.filename);
  6284. ASSERT_EQ("text/html", it->second.content_type);
  6285. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  6286. it->second.content);
  6287. ++it;
  6288. ASSERT_EQ("text", it->second.name);
  6289. ASSERT_EQ("", it->second.filename);
  6290. ASSERT_EQ("", it->second.content_type);
  6291. ASSERT_EQ("text default", it->second.content);
  6292. res.set_content("ok", "text/plain");
  6293. handled = true;
  6294. });
  6295. thread t = thread([&] { svr.listen(HOST, PORT); });
  6296. auto se = detail::scope_exit([&] {
  6297. svr.stop();
  6298. t.join();
  6299. ASSERT_FALSE(svr.is_running());
  6300. ASSERT_TRUE(handled);
  6301. });
  6302. svr.wait_until_ready();
  6303. auto req = "POST /test HTTP/1.1\r\n"
  6304. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6305. "Content-Length: 399\r\n"
  6306. "\r\n"
  6307. "----------\r\n"
  6308. "Content-Disposition: form-data; name=\"text\"\r\n"
  6309. "\r\n"
  6310. "text default\r\n"
  6311. "----------\r\n"
  6312. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  6313. "filename=\"a.txt\"; name=\"file1\"\r\n"
  6314. "Content-Type: text/plain\r\n"
  6315. "\r\n"
  6316. "Content of a.txt.\r\n"
  6317. "\r\n"
  6318. "----------\r\n"
  6319. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  6320. "\"a.html\"\r\n"
  6321. "Content-Type: text/html\r\n"
  6322. "\r\n"
  6323. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  6324. "\r\n"
  6325. "------------\r\n";
  6326. ASSERT_TRUE(send_request(1, req));
  6327. }
  6328. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  6329. auto handled = false;
  6330. Server svr;
  6331. svr.Post("/test", [&](const Request &req, Response &) {
  6332. ASSERT_EQ(2u, req.files.size());
  6333. auto it = req.files.begin();
  6334. ASSERT_EQ("text1", it->second.name);
  6335. ASSERT_EQ("text1", it->second.content);
  6336. ++it;
  6337. ASSERT_EQ("text2", it->second.name);
  6338. ASSERT_EQ("text2", it->second.content);
  6339. handled = true;
  6340. });
  6341. thread t = thread([&] { svr.listen(HOST, PORT); });
  6342. auto se = detail::scope_exit([&] {
  6343. svr.stop();
  6344. t.join();
  6345. ASSERT_FALSE(svr.is_running());
  6346. ASSERT_TRUE(handled);
  6347. });
  6348. svr.wait_until_ready();
  6349. auto req = "POST /test HTTP/1.1\r\n"
  6350. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6351. "Content-Length: 146\r\n"
  6352. "\r\n----------\r\n"
  6353. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6354. "\r\n"
  6355. "text1"
  6356. "\r\n----------\r\n"
  6357. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6358. "\r\n"
  6359. "text2"
  6360. "\r\n------------";
  6361. std::string response;
  6362. ASSERT_TRUE(send_request(1, req, &response));
  6363. ASSERT_EQ("200", response.substr(9, 3));
  6364. }
  6365. TEST(MultipartFormDataTest, ContentLength) {
  6366. auto handled = false;
  6367. Server svr;
  6368. svr.Post("/test", [&](const Request &req, Response &) {
  6369. ASSERT_EQ(2u, req.files.size());
  6370. auto it = req.files.begin();
  6371. ASSERT_EQ("text1", it->second.name);
  6372. ASSERT_EQ("text1", it->second.content);
  6373. ++it;
  6374. ASSERT_EQ("text2", it->second.name);
  6375. ASSERT_EQ("text2", it->second.content);
  6376. handled = true;
  6377. });
  6378. thread t = thread([&] { svr.listen(HOST, PORT); });
  6379. auto se = detail::scope_exit([&] {
  6380. svr.stop();
  6381. t.join();
  6382. ASSERT_FALSE(svr.is_running());
  6383. ASSERT_TRUE(handled);
  6384. });
  6385. svr.wait_until_ready();
  6386. auto req = "POST /test HTTP/1.1\r\n"
  6387. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6388. "Content-Length: 167\r\n"
  6389. "\r\n----------\r\n"
  6390. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6391. "Content-Length: 5\r\n"
  6392. "\r\n"
  6393. "text1"
  6394. "\r\n----------\r\n"
  6395. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6396. "\r\n"
  6397. "text2"
  6398. "\r\n------------\r\n";
  6399. std::string response;
  6400. ASSERT_TRUE(send_request(1, req, &response));
  6401. ASSERT_EQ("200", response.substr(9, 3));
  6402. }
  6403. #endif
  6404. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  6405. static constexpr unsigned int number_of_tasks{1000000};
  6406. std::atomic_uint count{0};
  6407. std::unique_ptr<TaskQueue> task_queue{
  6408. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  6409. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6410. auto queued = task_queue->enqueue(
  6411. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  6412. EXPECT_TRUE(queued);
  6413. }
  6414. EXPECT_NO_THROW(task_queue->shutdown());
  6415. EXPECT_EQ(number_of_tasks, count.load());
  6416. }
  6417. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  6418. static constexpr unsigned int number_of_tasks{1000000};
  6419. static constexpr unsigned int qlimit{2};
  6420. unsigned int queued_count{0};
  6421. std::atomic_uint count{0};
  6422. std::unique_ptr<TaskQueue> task_queue{
  6423. new ThreadPool{/*num_threads=*/1, qlimit}};
  6424. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6425. if (task_queue->enqueue(
  6426. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  6427. queued_count++;
  6428. }
  6429. }
  6430. EXPECT_NO_THROW(task_queue->shutdown());
  6431. EXPECT_EQ(queued_count, count.load());
  6432. EXPECT_TRUE(queued_count <= number_of_tasks);
  6433. EXPECT_TRUE(queued_count >= qlimit);
  6434. }
  6435. TEST(TaskQueueTest, MaxQueuedRequests) {
  6436. static constexpr unsigned int qlimit{3};
  6437. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  6438. std::condition_variable sem_cv;
  6439. std::mutex sem_mtx;
  6440. int credits = 0;
  6441. bool queued;
  6442. /* Fill up the queue with tasks that will block until we give them credits to
  6443. * complete. */
  6444. for (unsigned int n = 0; n <= qlimit;) {
  6445. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  6446. std::unique_lock<std::mutex> lock(sem_mtx);
  6447. while (credits <= 0) {
  6448. sem_cv.wait(lock);
  6449. }
  6450. /* Consume the credit and signal the test code if they are all gone. */
  6451. if (--credits == 0) { sem_cv.notify_one(); }
  6452. });
  6453. if (n < qlimit) {
  6454. /* The first qlimit enqueues must succeed. */
  6455. EXPECT_TRUE(queued);
  6456. } else {
  6457. /* The last one will succeed only when the worker thread
  6458. * starts and dequeues the first blocking task. Although
  6459. * not necessary for the correctness of this test, we sleep for
  6460. * a short while to avoid busy waiting. */
  6461. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6462. }
  6463. if (queued) { n++; }
  6464. }
  6465. /* Further enqueues must fail since the queue is full. */
  6466. for (auto i = 0; i < 4; i++) {
  6467. queued = task_queue->enqueue([] {});
  6468. EXPECT_FALSE(queued);
  6469. }
  6470. /* Give the credits to allow the previous tasks to complete. */
  6471. {
  6472. std::unique_lock<std::mutex> lock(sem_mtx);
  6473. credits += qlimit + 1;
  6474. }
  6475. sem_cv.notify_all();
  6476. /* Wait for all the credits to be consumed. */
  6477. {
  6478. std::unique_lock<std::mutex> lock(sem_mtx);
  6479. while (credits > 0) {
  6480. sem_cv.wait(lock);
  6481. }
  6482. }
  6483. /* Check that we are able again to enqueue at least qlimit tasks. */
  6484. for (unsigned int i = 0; i < qlimit; i++) {
  6485. queued = task_queue->enqueue([] {});
  6486. EXPECT_TRUE(queued);
  6487. }
  6488. EXPECT_NO_THROW(task_queue->shutdown());
  6489. }
  6490. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  6491. Server svr;
  6492. svr.Get("/", [](const Request & /*req*/, Response &res) {
  6493. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  6494. });
  6495. svr.Get("/hello", [](const Request &req, Response &res) {
  6496. res.set_content(req.get_param_value("key"), "text/plain");
  6497. });
  6498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6499. auto se = detail::scope_exit([&] {
  6500. svr.stop();
  6501. thread.join();
  6502. ASSERT_FALSE(svr.is_running());
  6503. });
  6504. svr.wait_until_ready();
  6505. {
  6506. Client cli(HOST, PORT);
  6507. cli.set_follow_location(true);
  6508. auto res = cli.Get("/");
  6509. ASSERT_TRUE(res);
  6510. EXPECT_EQ(StatusCode::OK_200, res->status);
  6511. EXPECT_EQ("val&key2=val2", res->body);
  6512. }
  6513. }
  6514. TEST(VulnerabilityTest, CRLFInjection) {
  6515. Server svr;
  6516. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  6517. res.set_content("Hello 1", "text/plain");
  6518. });
  6519. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  6520. res.set_content("Hello 2", "text/plain");
  6521. });
  6522. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  6523. res.set_content("Hello 3", "text/plain");
  6524. });
  6525. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  6526. res.set_content("Hello 4", "text/plain");
  6527. });
  6528. svr.set_logger([](const Request &req, const Response & /*res*/) {
  6529. for (const auto &x : req.headers) {
  6530. auto key = x.first;
  6531. EXPECT_STRNE("evil", key.c_str());
  6532. }
  6533. });
  6534. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6535. auto se = detail::scope_exit([&] {
  6536. svr.stop();
  6537. thread.join();
  6538. ASSERT_FALSE(svr.is_running());
  6539. });
  6540. svr.wait_until_ready();
  6541. {
  6542. Client cli(HOST, PORT);
  6543. cli.Post("/test1", "A=B",
  6544. "application/x-www-form-urlencoded\r\nevil: hello1");
  6545. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  6546. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  6547. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  6548. }
  6549. }
  6550. TEST(PathParamsTest, StaticMatch) {
  6551. const auto pattern = "/users/all";
  6552. detail::PathParamsMatcher matcher(pattern);
  6553. Request request;
  6554. request.path = "/users/all";
  6555. ASSERT_TRUE(matcher.match(request));
  6556. std::unordered_map<std::string, std::string> expected_params = {};
  6557. EXPECT_EQ(request.path_params, expected_params);
  6558. }
  6559. TEST(PathParamsTest, StaticMismatch) {
  6560. const auto pattern = "/users/all";
  6561. detail::PathParamsMatcher matcher(pattern);
  6562. Request request;
  6563. request.path = "/users/1";
  6564. ASSERT_FALSE(matcher.match(request));
  6565. }
  6566. TEST(PathParamsTest, SingleParamInTheMiddle) {
  6567. const auto pattern = "/users/:id/subscriptions";
  6568. detail::PathParamsMatcher matcher(pattern);
  6569. Request request;
  6570. request.path = "/users/42/subscriptions";
  6571. ASSERT_TRUE(matcher.match(request));
  6572. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6573. EXPECT_EQ(request.path_params, expected_params);
  6574. }
  6575. TEST(PathParamsTest, SingleParamInTheEnd) {
  6576. const auto pattern = "/users/:id";
  6577. detail::PathParamsMatcher matcher(pattern);
  6578. Request request;
  6579. request.path = "/users/24";
  6580. ASSERT_TRUE(matcher.match(request));
  6581. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  6582. EXPECT_EQ(request.path_params, expected_params);
  6583. }
  6584. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  6585. const auto pattern = "/users/:id/";
  6586. detail::PathParamsMatcher matcher(pattern);
  6587. Request request;
  6588. request.path = "/users/42/";
  6589. ASSERT_TRUE(matcher.match(request));
  6590. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6591. EXPECT_EQ(request.path_params, expected_params);
  6592. }
  6593. TEST(PathParamsTest, EmptyParam) {
  6594. const auto pattern = "/users/:id/";
  6595. detail::PathParamsMatcher matcher(pattern);
  6596. Request request;
  6597. request.path = "/users//";
  6598. ASSERT_TRUE(matcher.match(request));
  6599. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  6600. EXPECT_EQ(request.path_params, expected_params);
  6601. }
  6602. TEST(PathParamsTest, FragmentMismatch) {
  6603. const auto pattern = "/users/:id/";
  6604. detail::PathParamsMatcher matcher(pattern);
  6605. Request request;
  6606. request.path = "/admins/24/";
  6607. ASSERT_FALSE(matcher.match(request));
  6608. }
  6609. TEST(PathParamsTest, ExtraFragments) {
  6610. const auto pattern = "/users/:id";
  6611. detail::PathParamsMatcher matcher(pattern);
  6612. Request request;
  6613. request.path = "/users/42/subscriptions";
  6614. ASSERT_FALSE(matcher.match(request));
  6615. }
  6616. TEST(PathParamsTest, MissingTrailingParam) {
  6617. const auto pattern = "/users/:id";
  6618. detail::PathParamsMatcher matcher(pattern);
  6619. Request request;
  6620. request.path = "/users";
  6621. ASSERT_FALSE(matcher.match(request));
  6622. }
  6623. TEST(PathParamsTest, MissingParamInTheMiddle) {
  6624. const auto pattern = "/users/:id/subscriptions";
  6625. detail::PathParamsMatcher matcher(pattern);
  6626. Request request;
  6627. request.path = "/users/subscriptions";
  6628. ASSERT_FALSE(matcher.match(request));
  6629. }
  6630. TEST(PathParamsTest, MultipleParams) {
  6631. const auto pattern = "/users/:userid/subscriptions/:subid";
  6632. detail::PathParamsMatcher matcher(pattern);
  6633. Request request;
  6634. request.path = "/users/42/subscriptions/2";
  6635. ASSERT_TRUE(matcher.match(request));
  6636. std::unordered_map<std::string, std::string> expected_params = {
  6637. {"userid", "42"}, {"subid", "2"}};
  6638. EXPECT_EQ(request.path_params, expected_params);
  6639. }
  6640. TEST(PathParamsTest, SequenceOfParams) {
  6641. const auto pattern = "/values/:x/:y/:z";
  6642. detail::PathParamsMatcher matcher(pattern);
  6643. Request request;
  6644. request.path = "/values/1/2/3";
  6645. ASSERT_TRUE(matcher.match(request));
  6646. std::unordered_map<std::string, std::string> expected_params = {
  6647. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  6648. EXPECT_EQ(request.path_params, expected_params);
  6649. }
  6650. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  6651. const auto pattern = "/prefix:suffix";
  6652. detail::PathParamsMatcher matcher(pattern);
  6653. Request request;
  6654. request.path = "/prefix:suffix";
  6655. ASSERT_TRUE(matcher.match(request));
  6656. const std::unordered_map<std::string, std::string> expected_params = {};
  6657. EXPECT_EQ(request.path_params, expected_params);
  6658. }
  6659. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  6660. // If ipv6 regex working, regex match codepath is taken.
  6661. // else port will default to 80 in Client impl
  6662. int clientImplMagicPort = 80;
  6663. int port = 4321;
  6664. // above ports must be different to avoid false negative
  6665. EXPECT_NE(clientImplMagicPort, port);
  6666. std::string ipV6TestURL = "http://[ff06::c3]";
  6667. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  6668. CLIENT_PRIVATE_KEY_FILE);
  6669. EXPECT_EQ(cli.port(), port);
  6670. }
  6671. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  6672. auto file_path = "./www/dir/index.html";
  6673. auto dir_path = "./www/dir";
  6674. detail::FileStat stat_file(file_path);
  6675. EXPECT_TRUE(stat_file.is_file());
  6676. EXPECT_FALSE(stat_file.is_dir());
  6677. detail::FileStat stat_dir(dir_path);
  6678. EXPECT_FALSE(stat_dir.is_file());
  6679. EXPECT_TRUE(stat_dir.is_dir());
  6680. }
  6681. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  6682. Server svr;
  6683. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  6684. EXPECT_EQ(res.status, 400);
  6685. });
  6686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6687. auto se = detail::scope_exit([&] {
  6688. svr.stop();
  6689. thread.join();
  6690. ASSERT_FALSE(svr.is_running());
  6691. });
  6692. svr.wait_until_ready();
  6693. Client cli(HOST, PORT);
  6694. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  6695. }
  6696. TEST(InvalidHeaderCharsTest, is_field_name) {
  6697. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  6698. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  6699. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  6700. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  6701. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  6702. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  6703. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  6704. EXPECT_FALSE(detail::fields::is_field_name(""));
  6705. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  6706. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  6707. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  6708. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  6709. }
  6710. TEST(InvalidHeaderCharsTest, is_field_value) {
  6711. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  6712. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  6713. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  6714. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  6715. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  6716. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  6717. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  6718. EXPECT_TRUE(detail::fields::is_field_value(""));
  6719. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  6720. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  6721. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  6722. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  6723. EXPECT_TRUE(detail::fields::is_field_value("0"));
  6724. }
  6725. TEST(InvalidHeaderCharsTest, OnServer) {
  6726. Server svr;
  6727. svr.Get("/test_name", [&](const Request &req, Response &res) {
  6728. std::string header = "Not Set";
  6729. if (req.has_param("header")) { header = req.get_param_value("header"); }
  6730. res.set_header(header, "value");
  6731. res.set_content("Page Content Page Content", "text/plain");
  6732. });
  6733. svr.Get("/test_value", [&](const Request &req, Response &res) {
  6734. std::string header = "Not Set";
  6735. if (req.has_param("header")) { header = req.get_param_value("header"); }
  6736. res.set_header("X-Test", header);
  6737. res.set_content("Page Content Page Content", "text/plain");
  6738. });
  6739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6740. auto se = detail::scope_exit([&] {
  6741. svr.stop();
  6742. thread.join();
  6743. ASSERT_FALSE(svr.is_running());
  6744. });
  6745. svr.wait_until_ready();
  6746. Client cli(HOST, PORT);
  6747. {
  6748. auto res = cli.Get(
  6749. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  6750. ASSERT_TRUE(res);
  6751. EXPECT_EQ("Page Content Page Content", res->body);
  6752. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  6753. }
  6754. {
  6755. auto res = cli.Get(
  6756. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  6757. ASSERT_TRUE(res);
  6758. EXPECT_EQ("Page Content Page Content", res->body);
  6759. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  6760. }
  6761. }
  6762. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  6763. auto handled = false;
  6764. Server svr;
  6765. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  6766. thread t = thread([&] { svr.listen(HOST, PORT); });
  6767. auto se = detail::scope_exit([&] {
  6768. svr.stop();
  6769. t.join();
  6770. ASSERT_FALSE(svr.is_running());
  6771. ASSERT_FALSE(handled);
  6772. });
  6773. svr.wait_until_ready();
  6774. auto req = "POST /test HTTP/1.1\r\n"
  6775. "Content-Length: x\r\n"
  6776. "\r\n";
  6777. std::string response;
  6778. ASSERT_TRUE(send_request(1, req, &response));
  6779. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  6780. response.substr(0, response.find("\r\n")));
  6781. }
  6782. #ifndef _WIN32
  6783. TEST(Expect100ContinueTest, ServerClosesConnection) {
  6784. static constexpr char reject[] = "Unauthorized";
  6785. static constexpr char accept[] = "Upload accepted";
  6786. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  6787. Server svr;
  6788. svr.set_expect_100_continue_handler(
  6789. [](const Request & /*req*/, Response &res) {
  6790. res.status = StatusCode::Unauthorized_401;
  6791. res.set_content(reject, "text/plain");
  6792. return res.status;
  6793. });
  6794. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  6795. res.set_content(accept, "text/plain");
  6796. });
  6797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6798. auto se = detail::scope_exit([&] {
  6799. svr.stop();
  6800. thread.join();
  6801. ASSERT_FALSE(svr.is_running());
  6802. });
  6803. svr.wait_until_ready();
  6804. {
  6805. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  6806. curl_easy_init(), &curl_easy_cleanup};
  6807. ASSERT_NE(curl, nullptr);
  6808. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  6809. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  6810. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  6811. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  6812. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  6813. &curl_slist_free_all};
  6814. ASSERT_NE(list, nullptr);
  6815. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  6816. struct read_data {
  6817. size_t read_size;
  6818. size_t total_size;
  6819. } data = {0, total_size};
  6820. using read_callback_t =
  6821. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  6822. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  6823. void *userdata) -> size_t {
  6824. read_data *data = (read_data *)userdata;
  6825. if (!userdata || data->read_size >= data->total_size) { return 0; }
  6826. std::fill_n(ptr, size * nmemb, 'A');
  6827. data->read_size += size * nmemb;
  6828. return size * nmemb;
  6829. };
  6830. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  6831. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  6832. std::vector<char> buffer;
  6833. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  6834. using write_callback_t =
  6835. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  6836. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  6837. void *userdata) -> size_t {
  6838. std::vector<char> *buffer = (std::vector<char> *)userdata;
  6839. buffer->reserve(buffer->size() + size * nmemb + 1);
  6840. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  6841. return size * nmemb;
  6842. };
  6843. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  6844. {
  6845. const auto res = curl_easy_perform(curl.get());
  6846. ASSERT_EQ(res, CURLE_OK);
  6847. }
  6848. {
  6849. auto response_code = long{};
  6850. const auto res =
  6851. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  6852. ASSERT_EQ(res, CURLE_OK);
  6853. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  6854. }
  6855. {
  6856. auto dl = curl_off_t{};
  6857. const auto res =
  6858. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  6859. ASSERT_EQ(res, CURLE_OK);
  6860. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  6861. }
  6862. {
  6863. buffer.push_back('\0');
  6864. ASSERT_STRCASEEQ(buffer.data(), reject);
  6865. }
  6866. }
  6867. }
  6868. #endif
  6869. template <typename S, typename C>
  6870. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  6871. svr.Get("/stream", [&](const Request &, Response &res) {
  6872. auto data = new std::string("01234567890123456789");
  6873. res.set_content_provider(
  6874. data->size(), "text/plain",
  6875. [&, data](size_t offset, size_t length, DataSink &sink) {
  6876. const size_t DATA_CHUNK_SIZE = 4;
  6877. const auto &d = *data;
  6878. std::this_thread::sleep_for(std::chrono::seconds(1));
  6879. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  6880. return true;
  6881. },
  6882. [data](bool success) {
  6883. EXPECT_FALSE(success);
  6884. delete data;
  6885. });
  6886. });
  6887. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  6888. auto i = new size_t(0);
  6889. res.set_content_provider(
  6890. "text/plain",
  6891. [i](size_t, DataSink &sink) {
  6892. if (*i < 5) {
  6893. std::this_thread::sleep_for(std::chrono::seconds(1));
  6894. sink.write("abcd", 4);
  6895. (*i)++;
  6896. } else {
  6897. sink.done();
  6898. }
  6899. return true;
  6900. },
  6901. [i](bool success) {
  6902. EXPECT_FALSE(success);
  6903. delete i;
  6904. });
  6905. });
  6906. svr.Get("/chunked", [&](const Request &, Response &res) {
  6907. auto i = new size_t(0);
  6908. res.set_chunked_content_provider(
  6909. "text/plain",
  6910. [i](size_t, DataSink &sink) {
  6911. if (*i < 5) {
  6912. std::this_thread::sleep_for(std::chrono::seconds(1));
  6913. sink.os << "abcd";
  6914. (*i)++;
  6915. } else {
  6916. sink.done();
  6917. }
  6918. return true;
  6919. },
  6920. [i](bool success) {
  6921. EXPECT_FALSE(success);
  6922. delete i;
  6923. });
  6924. });
  6925. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6926. auto se = detail::scope_exit([&] {
  6927. svr.stop();
  6928. listen_thread.join();
  6929. ASSERT_FALSE(svr.is_running());
  6930. });
  6931. svr.wait_until_ready();
  6932. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  6933. {
  6934. auto start = std::chrono::steady_clock::now();
  6935. auto res = cli.Get("/stream");
  6936. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  6937. std::chrono::steady_clock::now() - start)
  6938. .count();
  6939. ASSERT_FALSE(res);
  6940. EXPECT_EQ(Error::Read, res.error());
  6941. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  6942. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  6943. }
  6944. {
  6945. auto start = std::chrono::steady_clock::now();
  6946. auto res = cli.Get("/stream_without_length");
  6947. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  6948. std::chrono::steady_clock::now() - start)
  6949. .count();
  6950. ASSERT_FALSE(res);
  6951. EXPECT_EQ(Error::Read, res.error());
  6952. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  6953. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  6954. }
  6955. {
  6956. auto start = std::chrono::steady_clock::now();
  6957. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  6958. EXPECT_EQ("abcd", string(data, data_length));
  6959. return true;
  6960. });
  6961. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  6962. std::chrono::steady_clock::now() - start)
  6963. .count();
  6964. ASSERT_FALSE(res);
  6965. EXPECT_EQ(Error::Read, res.error());
  6966. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  6967. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  6968. }
  6969. }
  6970. TEST(MaxTimeoutTest, ContentStream) {
  6971. time_t timeout = 2000;
  6972. time_t threshold = 200;
  6973. Server svr;
  6974. Client cli("localhost", PORT);
  6975. max_timeout_test(svr, cli, timeout, threshold);
  6976. }
  6977. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6978. TEST(MaxTimeoutTest, ContentStreamSSL) {
  6979. time_t timeout = 2000;
  6980. time_t threshold = 500; // SSL_shutdown is slow on some operating systems.
  6981. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6982. SSLClient cli("localhost", PORT);
  6983. cli.enable_server_certificate_verification(false);
  6984. max_timeout_test(svr, cli, timeout, threshold);
  6985. }
  6986. #endif
  6987. class EventDispatcher {
  6988. public:
  6989. EventDispatcher() {}
  6990. void wait_event(DataSink *sink) {
  6991. unique_lock<mutex> lk(m_);
  6992. int id = id_;
  6993. cv_.wait(lk, [&] { return cid_ == id; });
  6994. sink->write(message_.data(), message_.size());
  6995. }
  6996. void send_event(const string &message) {
  6997. lock_guard<mutex> lk(m_);
  6998. cid_ = id_++;
  6999. message_ = message;
  7000. cv_.notify_all();
  7001. }
  7002. private:
  7003. mutex m_;
  7004. condition_variable cv_;
  7005. atomic_int id_{0};
  7006. atomic_int cid_{-1};
  7007. string message_;
  7008. };
  7009. TEST(ClientInThreadTest, Issue2068) {
  7010. EventDispatcher ed;
  7011. Server svr;
  7012. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  7013. res.set_chunked_content_provider("text/event-stream",
  7014. [&](size_t /*offset*/, DataSink &sink) {
  7015. ed.wait_event(&sink);
  7016. return true;
  7017. });
  7018. });
  7019. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7020. svr.wait_until_ready();
  7021. thread event_thread([&] {
  7022. int id = 0;
  7023. while (svr.is_running()) {
  7024. this_thread::sleep_for(chrono::milliseconds(500));
  7025. std::stringstream ss;
  7026. ss << "data: " << id << "\n\n";
  7027. ed.send_event(ss.str());
  7028. id++;
  7029. }
  7030. });
  7031. auto se = detail::scope_exit([&] {
  7032. svr.stop();
  7033. listen_thread.join();
  7034. event_thread.join();
  7035. ASSERT_FALSE(svr.is_running());
  7036. });
  7037. {
  7038. auto client = detail::make_unique<Client>(HOST, PORT);
  7039. client->set_read_timeout(std::chrono::minutes(10));
  7040. std::atomic<bool> stop{false};
  7041. std::thread t([&] {
  7042. client->Get("/event1",
  7043. [&](const char *, size_t) -> bool { return !stop; });
  7044. });
  7045. std::this_thread::sleep_for(std::chrono::seconds(2));
  7046. stop = true;
  7047. client->stop();
  7048. client.reset();
  7049. t.join();
  7050. }
  7051. }