test.cc 174 KB

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