test.cc 186 KB

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