test.cc 245 KB

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