test.cc 239 KB

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