test.cc 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831
  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("/empty",
  1473. [&](const Request &req, Response &res) {
  1474. EXPECT_EQ(req.body, "");
  1475. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1476. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1477. res.set_content("empty", "text/plain");
  1478. })
  1479. .Post("/empty-no-content-type",
  1480. [&](const Request &req, Response &res) {
  1481. EXPECT_EQ(req.body, "");
  1482. EXPECT_FALSE(req.has_header("Content-Type"));
  1483. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1484. res.set_content("empty-no-content-type", "text/plain");
  1485. })
  1486. .Post("/path-only",
  1487. [&](const Request &req, Response &res) {
  1488. EXPECT_EQ(req.body, "");
  1489. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1490. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1491. res.set_content("path-only", "text/plain");
  1492. })
  1493. .Post("/path-headers-only",
  1494. [&](const Request &req, Response &res) {
  1495. EXPECT_EQ(req.body, "");
  1496. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1497. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1498. EXPECT_EQ("world", req.get_header_value("hello"));
  1499. EXPECT_EQ("world2", req.get_header_value("hello2"));
  1500. res.set_content("path-headers-only", "text/plain");
  1501. })
  1502. .Post("/post-large",
  1503. [&](const Request &req, Response &res) {
  1504. EXPECT_EQ(req.body, LARGE_DATA);
  1505. res.set_content(req.body, "text/plain");
  1506. })
  1507. .Put("/empty-no-content-type",
  1508. [&](const Request &req, Response &res) {
  1509. EXPECT_EQ(req.body, "");
  1510. EXPECT_FALSE(req.has_header("Content-Type"));
  1511. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1512. res.set_content("empty-no-content-type", "text/plain");
  1513. })
  1514. .Put("/put",
  1515. [&](const Request &req, Response &res) {
  1516. EXPECT_EQ(req.body, "PUT");
  1517. res.set_content(req.body, "text/plain");
  1518. })
  1519. .Put("/put-large",
  1520. [&](const Request &req, Response &res) {
  1521. EXPECT_EQ(req.body, LARGE_DATA);
  1522. res.set_content(req.body, "text/plain");
  1523. })
  1524. .Patch("/patch",
  1525. [&](const Request &req, Response &res) {
  1526. EXPECT_EQ(req.body, "PATCH");
  1527. res.set_content(req.body, "text/plain");
  1528. })
  1529. .Delete("/delete",
  1530. [&](const Request & /*req*/, Response &res) {
  1531. res.set_content("DELETE", "text/plain");
  1532. })
  1533. .Delete("/delete-body",
  1534. [&](const Request &req, Response &res) {
  1535. EXPECT_EQ(req.body, "content");
  1536. res.set_content(req.body, "text/plain");
  1537. })
  1538. .Options(R"(\*)",
  1539. [&](const Request & /*req*/, Response &res) {
  1540. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1541. })
  1542. .Get("/request-target",
  1543. [&](const Request &req, Response & /*res*/) {
  1544. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1545. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1546. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1547. })
  1548. .Get("/long-query-value",
  1549. [&](const Request &req, Response & /*res*/) {
  1550. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1551. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1552. })
  1553. .Get("/array-param",
  1554. [&](const Request &req, Response & /*res*/) {
  1555. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1556. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1557. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1558. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1559. })
  1560. .Post("/validate-no-multiple-headers",
  1561. [&](const Request &req, Response & /*res*/) {
  1562. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1563. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1564. })
  1565. .Post("/content_receiver",
  1566. [&](const Request &req, Response &res,
  1567. const ContentReader &content_reader) {
  1568. if (req.is_multipart_form_data()) {
  1569. MultipartFormDataItems files;
  1570. content_reader(
  1571. [&](const MultipartFormData &file) {
  1572. files.push_back(file);
  1573. return true;
  1574. },
  1575. [&](const char *data, size_t data_length) {
  1576. files.back().content.append(data, data_length);
  1577. return true;
  1578. });
  1579. EXPECT_EQ(5u, files.size());
  1580. {
  1581. const auto &file = get_file_value(files, "text1");
  1582. EXPECT_TRUE(file.filename.empty());
  1583. EXPECT_EQ("text default", file.content);
  1584. }
  1585. {
  1586. const auto &file = get_file_value(files, "text2");
  1587. EXPECT_TRUE(file.filename.empty());
  1588. EXPECT_EQ("aωb", file.content);
  1589. }
  1590. {
  1591. const auto &file = get_file_value(files, "file1");
  1592. EXPECT_EQ("hello.txt", file.filename);
  1593. EXPECT_EQ("text/plain", file.content_type);
  1594. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1595. }
  1596. {
  1597. const auto &file = get_file_value(files, "file3");
  1598. EXPECT_TRUE(file.filename.empty());
  1599. EXPECT_EQ("application/octet-stream", file.content_type);
  1600. EXPECT_EQ(0u, file.content.size());
  1601. }
  1602. } else {
  1603. std::string body;
  1604. content_reader([&](const char *data, size_t data_length) {
  1605. EXPECT_EQ(7U, data_length);
  1606. body.append(data, data_length);
  1607. return true;
  1608. });
  1609. EXPECT_EQ(body, "content");
  1610. res.set_content(body, "text/plain");
  1611. }
  1612. })
  1613. .Put("/content_receiver",
  1614. [&](const Request & /*req*/, Response &res,
  1615. const ContentReader &content_reader) {
  1616. std::string body;
  1617. content_reader([&](const char *data, size_t data_length) {
  1618. body.append(data, data_length);
  1619. return true;
  1620. });
  1621. EXPECT_EQ(body, "content");
  1622. res.set_content(body, "text/plain");
  1623. })
  1624. .Patch("/content_receiver",
  1625. [&](const Request & /*req*/, Response &res,
  1626. const ContentReader &content_reader) {
  1627. std::string body;
  1628. content_reader([&](const char *data, size_t data_length) {
  1629. body.append(data, data_length);
  1630. return true;
  1631. });
  1632. EXPECT_EQ(body, "content");
  1633. res.set_content(body, "text/plain");
  1634. })
  1635. .Post("/query-string-and-body",
  1636. [&](const Request &req, Response & /*res*/) {
  1637. ASSERT_TRUE(req.has_param("key"));
  1638. EXPECT_EQ(req.get_param_value("key"), "value");
  1639. EXPECT_EQ(req.body, "content");
  1640. })
  1641. .Get("/last-request",
  1642. [&](const Request &req, Response & /*res*/) {
  1643. EXPECT_EQ("close", req.get_header_value("Connection"));
  1644. })
  1645. .Get(R"(/redirect/(\d+))",
  1646. [&](const Request &req, Response &res) {
  1647. auto num = std::stoi(req.matches[1]) + 1;
  1648. std::string url = "/redirect/" + std::to_string(num);
  1649. res.set_redirect(url);
  1650. })
  1651. .Post("/binary",
  1652. [&](const Request &req, Response &res) {
  1653. EXPECT_EQ(4U, req.body.size());
  1654. EXPECT_EQ("application/octet-stream",
  1655. req.get_header_value("Content-Type"));
  1656. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1657. res.set_content(req.body, "application/octet-stream");
  1658. })
  1659. .Put("/binary",
  1660. [&](const Request &req, Response &res) {
  1661. EXPECT_EQ(4U, req.body.size());
  1662. EXPECT_EQ("application/octet-stream",
  1663. req.get_header_value("Content-Type"));
  1664. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1665. res.set_content(req.body, "application/octet-stream");
  1666. })
  1667. .Patch("/binary",
  1668. [&](const Request &req, Response &res) {
  1669. EXPECT_EQ(4U, req.body.size());
  1670. EXPECT_EQ("application/octet-stream",
  1671. req.get_header_value("Content-Type"));
  1672. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1673. res.set_content(req.body, "application/octet-stream");
  1674. })
  1675. .Delete("/binary",
  1676. [&](const Request &req, Response &res) {
  1677. EXPECT_EQ(4U, req.body.size());
  1678. EXPECT_EQ("application/octet-stream",
  1679. req.get_header_value("Content-Type"));
  1680. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1681. res.set_content(req.body, "application/octet-stream");
  1682. })
  1683. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1684. .Get("/compress",
  1685. [&](const Request & /*req*/, Response &res) {
  1686. res.set_content(
  1687. "12345678901234567890123456789012345678901234567890123456789"
  1688. "01234567890123456789012345678901234567890",
  1689. "text/plain");
  1690. })
  1691. .Get("/nocompress",
  1692. [&](const Request & /*req*/, Response &res) {
  1693. res.set_content(
  1694. "12345678901234567890123456789012345678901234567890123456789"
  1695. "01234567890123456789012345678901234567890",
  1696. "application/octet-stream");
  1697. })
  1698. .Post("/compress-multipart",
  1699. [&](const Request &req, Response & /*res*/) {
  1700. EXPECT_EQ(2u, req.files.size());
  1701. ASSERT_TRUE(!req.has_file("???"));
  1702. {
  1703. const auto &file = req.get_file_value("key1");
  1704. EXPECT_TRUE(file.filename.empty());
  1705. EXPECT_EQ("test", file.content);
  1706. }
  1707. {
  1708. const auto &file = req.get_file_value("key2");
  1709. EXPECT_TRUE(file.filename.empty());
  1710. EXPECT_EQ("--abcdefg123", file.content);
  1711. }
  1712. })
  1713. #endif
  1714. ;
  1715. persons_["john"] = "programmer";
  1716. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1717. while (!svr_.is_running()) {
  1718. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1719. }
  1720. }
  1721. virtual void TearDown() {
  1722. svr_.stop();
  1723. if (!request_threads_.empty()) {
  1724. std::this_thread::sleep_for(std::chrono::seconds(1));
  1725. for (auto &t : request_threads_) {
  1726. t.join();
  1727. }
  1728. }
  1729. t_.join();
  1730. }
  1731. map<string, string> persons_;
  1732. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1733. SSLClient cli_;
  1734. SSLServer svr_;
  1735. #else
  1736. Client cli_;
  1737. Server svr_;
  1738. #endif
  1739. thread t_;
  1740. std::vector<thread> request_threads_;
  1741. };
  1742. TEST_F(ServerTest, GetMethod200) {
  1743. auto res = cli_.Get("/hi");
  1744. ASSERT_TRUE(res);
  1745. EXPECT_EQ("HTTP/1.1", res->version);
  1746. EXPECT_EQ(200, res->status);
  1747. EXPECT_EQ("OK", res->reason);
  1748. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1749. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1750. EXPECT_EQ("Hello World!", res->body);
  1751. }
  1752. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1753. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1754. ASSERT_TRUE(res);
  1755. EXPECT_EQ("HTTP/1.1", res->version);
  1756. EXPECT_EQ(200, res->status);
  1757. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1758. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1759. EXPECT_EQ("Hello World!", res->body);
  1760. }
  1761. TEST_F(ServerTest, GetMethod302) {
  1762. auto res = cli_.Get("/");
  1763. ASSERT_TRUE(res);
  1764. EXPECT_EQ(302, res->status);
  1765. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1766. }
  1767. TEST_F(ServerTest, GetMethod302Redirect) {
  1768. cli_.set_follow_location(true);
  1769. auto res = cli_.Get("/");
  1770. ASSERT_TRUE(res);
  1771. EXPECT_EQ(200, res->status);
  1772. EXPECT_EQ("Hello World!", res->body);
  1773. EXPECT_EQ("/hi", res->location);
  1774. }
  1775. TEST_F(ServerTest, GetMethod404) {
  1776. auto res = cli_.Get("/invalid");
  1777. ASSERT_TRUE(res);
  1778. EXPECT_EQ(404, res->status);
  1779. }
  1780. TEST_F(ServerTest, HeadMethod200) {
  1781. auto res = cli_.Head("/hi");
  1782. ASSERT_TRUE(res);
  1783. EXPECT_EQ(200, res->status);
  1784. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1785. EXPECT_TRUE(res->body.empty());
  1786. }
  1787. TEST_F(ServerTest, HeadMethod200Static) {
  1788. auto res = cli_.Head("/mount/dir/index.html");
  1789. ASSERT_TRUE(res);
  1790. EXPECT_EQ(200, res->status);
  1791. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1792. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1793. EXPECT_TRUE(res->body.empty());
  1794. }
  1795. TEST_F(ServerTest, HeadMethod404) {
  1796. auto res = cli_.Head("/invalid");
  1797. ASSERT_TRUE(res);
  1798. EXPECT_EQ(404, res->status);
  1799. EXPECT_TRUE(res->body.empty());
  1800. }
  1801. TEST_F(ServerTest, GetMethodPersonJohn) {
  1802. auto res = cli_.Get("/person/john");
  1803. ASSERT_TRUE(res);
  1804. EXPECT_EQ(200, res->status);
  1805. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1806. EXPECT_EQ("programmer", res->body);
  1807. }
  1808. TEST_F(ServerTest, PostMethod1) {
  1809. auto res = cli_.Get("/person/john1");
  1810. ASSERT_TRUE(res);
  1811. ASSERT_EQ(404, res->status);
  1812. res = cli_.Post("/person", "name=john1&note=coder",
  1813. "application/x-www-form-urlencoded");
  1814. ASSERT_TRUE(res);
  1815. ASSERT_EQ(200, res->status);
  1816. res = cli_.Get("/person/john1");
  1817. ASSERT_TRUE(res);
  1818. ASSERT_EQ(200, res->status);
  1819. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1820. ASSERT_EQ("coder", res->body);
  1821. }
  1822. TEST_F(ServerTest, PostMethod2) {
  1823. auto res = cli_.Get("/person/john2");
  1824. ASSERT_TRUE(res);
  1825. ASSERT_EQ(404, res->status);
  1826. Params params;
  1827. params.emplace("name", "john2");
  1828. params.emplace("note", "coder");
  1829. res = cli_.Post("/person", params);
  1830. ASSERT_TRUE(res);
  1831. ASSERT_EQ(200, res->status);
  1832. res = cli_.Get("/person/john2");
  1833. ASSERT_TRUE(res);
  1834. ASSERT_EQ(200, res->status);
  1835. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1836. ASSERT_EQ("coder", res->body);
  1837. }
  1838. TEST_F(ServerTest, PutMethod3) {
  1839. auto res = cli_.Get("/person/john3");
  1840. ASSERT_TRUE(res);
  1841. ASSERT_EQ(404, res->status);
  1842. Params params;
  1843. params.emplace("name", "john3");
  1844. params.emplace("note", "coder");
  1845. res = cli_.Put("/person", params);
  1846. ASSERT_TRUE(res);
  1847. ASSERT_EQ(200, res->status);
  1848. res = cli_.Get("/person/john3");
  1849. ASSERT_TRUE(res);
  1850. ASSERT_EQ(200, res->status);
  1851. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1852. ASSERT_EQ("coder", res->body);
  1853. }
  1854. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1855. Params params;
  1856. params.emplace("json", JSON_DATA);
  1857. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1858. ASSERT_TRUE(res);
  1859. ASSERT_EQ(200, res->status);
  1860. ASSERT_EQ(JSON_DATA, res->body);
  1861. }
  1862. TEST_F(ServerTest, PostEmptyContent) {
  1863. auto res = cli_.Post("/empty", "", "text/plain");
  1864. ASSERT_TRUE(res);
  1865. ASSERT_EQ(200, res->status);
  1866. ASSERT_EQ("empty", res->body);
  1867. }
  1868. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1869. auto res = cli_.Post("/empty-no-content-type");
  1870. ASSERT_TRUE(res);
  1871. ASSERT_EQ(200, res->status);
  1872. ASSERT_EQ("empty-no-content-type", res->body);
  1873. }
  1874. TEST_F(ServerTest, PostPathOnly) {
  1875. auto res = cli_.Post("/path-only");
  1876. ASSERT_TRUE(res);
  1877. ASSERT_EQ(200, res->status);
  1878. ASSERT_EQ("path-only", res->body);
  1879. }
  1880. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  1881. auto res = cli_.Post("/path-headers-only",
  1882. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  1883. ASSERT_TRUE(res);
  1884. ASSERT_EQ(200, res->status);
  1885. ASSERT_EQ("path-headers-only", res->body);
  1886. }
  1887. TEST_F(ServerTest, PostLarge) {
  1888. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  1889. ASSERT_TRUE(res);
  1890. ASSERT_EQ(200, res->status);
  1891. EXPECT_EQ(LARGE_DATA, res->body);
  1892. }
  1893. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  1894. auto res = cli_.Put("/empty-no-content-type");
  1895. ASSERT_TRUE(res);
  1896. ASSERT_EQ(200, res->status);
  1897. ASSERT_EQ("empty-no-content-type", res->body);
  1898. }
  1899. TEST_F(ServerTest, GetMethodDir) {
  1900. auto res = cli_.Get("/dir/");
  1901. ASSERT_TRUE(res);
  1902. EXPECT_EQ(200, res->status);
  1903. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1904. auto body = R"(<html>
  1905. <head>
  1906. </head>
  1907. <body>
  1908. <a href="/dir/test.html">Test</a>
  1909. <a href="/hi">hi</a>
  1910. </body>
  1911. </html>
  1912. )";
  1913. EXPECT_EQ(body, res->body);
  1914. }
  1915. TEST_F(ServerTest, GetMethodDirTest) {
  1916. auto res = cli_.Get("/dir/test.html");
  1917. ASSERT_TRUE(res);
  1918. EXPECT_EQ(200, res->status);
  1919. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1920. EXPECT_EQ("test.html", res->body);
  1921. }
  1922. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1923. auto res = cli_.Get("/dir/../dir/test.html");
  1924. ASSERT_TRUE(res);
  1925. EXPECT_EQ(200, res->status);
  1926. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1927. EXPECT_EQ("test.html", res->body);
  1928. }
  1929. TEST_F(ServerTest, GetMethodInvalidPath) {
  1930. auto res = cli_.Get("/dir/../test.html");
  1931. ASSERT_TRUE(res);
  1932. EXPECT_EQ(404, res->status);
  1933. }
  1934. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1935. auto res = cli_.Get("/../www/dir/test.html");
  1936. ASSERT_TRUE(res);
  1937. EXPECT_EQ(404, res->status);
  1938. }
  1939. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1940. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1941. ASSERT_TRUE(res);
  1942. EXPECT_EQ(404, res->status);
  1943. }
  1944. TEST_F(ServerTest, GetMethodDirMountTest) {
  1945. auto res = cli_.Get("/mount/dir/test.html");
  1946. ASSERT_TRUE(res);
  1947. EXPECT_EQ(200, res->status);
  1948. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1949. EXPECT_EQ("test.html", res->body);
  1950. }
  1951. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1952. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1953. ASSERT_TRUE(res);
  1954. EXPECT_EQ(200, res->status);
  1955. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1956. EXPECT_EQ("test.html", res->body);
  1957. }
  1958. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1959. auto res = cli_.Get("/mount/dir/../test.html");
  1960. ASSERT_TRUE(res);
  1961. EXPECT_EQ(404, res->status);
  1962. }
  1963. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1964. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1965. ASSERT_TRUE(res);
  1966. EXPECT_EQ(404, res->status);
  1967. }
  1968. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1969. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(404, res->status);
  1972. }
  1973. TEST_F(ServerTest, PostMethod303) {
  1974. auto res = cli_.Post("/1", "body", "text/plain");
  1975. ASSERT_TRUE(res);
  1976. EXPECT_EQ(303, res->status);
  1977. EXPECT_EQ("/2", res->get_header_value("Location"));
  1978. }
  1979. TEST_F(ServerTest, PostMethod303Redirect) {
  1980. cli_.set_follow_location(true);
  1981. auto res = cli_.Post("/1", "body", "text/plain");
  1982. ASSERT_TRUE(res);
  1983. EXPECT_EQ(200, res->status);
  1984. EXPECT_EQ("redirected.", res->body);
  1985. EXPECT_EQ("/2", res->location);
  1986. }
  1987. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1988. auto res = cli_.Get("/dir/test.abcde");
  1989. ASSERT_TRUE(res);
  1990. EXPECT_EQ(200, res->status);
  1991. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1992. EXPECT_EQ("abcde", res->body);
  1993. }
  1994. TEST_F(ServerTest, StaticFileRange) {
  1995. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  1996. ASSERT_TRUE(res);
  1997. EXPECT_EQ(206, res->status);
  1998. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1999. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2000. EXPECT_EQ(true, res->has_header("Content-Range"));
  2001. EXPECT_EQ(std::string("cd"), res->body);
  2002. }
  2003. TEST_F(ServerTest, InvalidBaseDirMount) {
  2004. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2005. }
  2006. TEST_F(ServerTest, Binary) {
  2007. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2008. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2009. "application/octet-stream");
  2010. ASSERT_TRUE(res);
  2011. ASSERT_EQ(200, res->status);
  2012. ASSERT_EQ(4U, res->body.size());
  2013. res = cli_.Put("/binary", binary.data(), binary.size(),
  2014. "application/octet-stream");
  2015. ASSERT_TRUE(res);
  2016. ASSERT_EQ(200, res->status);
  2017. ASSERT_EQ(4U, res->body.size());
  2018. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2019. "application/octet-stream");
  2020. ASSERT_TRUE(res);
  2021. ASSERT_EQ(200, res->status);
  2022. ASSERT_EQ(4U, res->body.size());
  2023. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2024. "application/octet-stream");
  2025. ASSERT_TRUE(res);
  2026. ASSERT_EQ(200, res->status);
  2027. ASSERT_EQ(4U, res->body.size());
  2028. }
  2029. TEST_F(ServerTest, BinaryString) {
  2030. auto binary = std::string("\x00\x01\x02\x03", 4);
  2031. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2032. ASSERT_TRUE(res);
  2033. ASSERT_EQ(200, res->status);
  2034. ASSERT_EQ(4U, res->body.size());
  2035. res = cli_.Put("/binary", binary, "application/octet-stream");
  2036. ASSERT_TRUE(res);
  2037. ASSERT_EQ(200, res->status);
  2038. ASSERT_EQ(4U, res->body.size());
  2039. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2040. ASSERT_TRUE(res);
  2041. ASSERT_EQ(200, res->status);
  2042. ASSERT_EQ(4U, res->body.size());
  2043. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2044. ASSERT_TRUE(res);
  2045. ASSERT_EQ(200, res->status);
  2046. ASSERT_EQ(4U, res->body.size());
  2047. }
  2048. TEST_F(ServerTest, EmptyRequest) {
  2049. auto res = cli_.Get("");
  2050. ASSERT_TRUE(!res);
  2051. EXPECT_EQ(Error::Connection, res.error());
  2052. }
  2053. TEST_F(ServerTest, LongRequest) {
  2054. std::string request;
  2055. for (size_t i = 0; i < 545; i++) {
  2056. request += "/TooLongRequest";
  2057. }
  2058. request += "OK";
  2059. auto res = cli_.Get(request.c_str());
  2060. ASSERT_TRUE(res);
  2061. EXPECT_EQ(404, res->status);
  2062. }
  2063. TEST_F(ServerTest, TooLongRequest) {
  2064. std::string request;
  2065. for (size_t i = 0; i < 545; i++) {
  2066. request += "/TooLongRequest";
  2067. }
  2068. request += "_NG";
  2069. auto res = cli_.Get(request.c_str());
  2070. ASSERT_TRUE(res);
  2071. EXPECT_EQ(414, res->status);
  2072. }
  2073. TEST_F(ServerTest, LongHeader) {
  2074. Request req;
  2075. req.method = "GET";
  2076. req.path = "/hi";
  2077. std::string host_and_port;
  2078. host_and_port += HOST;
  2079. host_and_port += ":";
  2080. host_and_port += std::to_string(PORT);
  2081. req.headers.emplace("Host", host_and_port.c_str());
  2082. req.headers.emplace("Accept", "*/*");
  2083. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2084. req.headers.emplace(
  2085. "Header-Name",
  2086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2114. "@@@@@@@@@@@@@@@@");
  2115. auto res = std::make_shared<Response>();
  2116. auto error = Error::Success;
  2117. auto ret = cli_.send(req, *res, error);
  2118. ASSERT_TRUE(ret);
  2119. EXPECT_EQ(200, res->status);
  2120. }
  2121. TEST_F(ServerTest, LongQueryValue) {
  2122. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2123. ASSERT_TRUE(res);
  2124. EXPECT_EQ(414, res->status);
  2125. }
  2126. TEST_F(ServerTest, TooLongHeader) {
  2127. Request req;
  2128. req.method = "GET";
  2129. req.path = "/hi";
  2130. std::string host_and_port;
  2131. host_and_port += HOST;
  2132. host_and_port += ":";
  2133. host_and_port += std::to_string(PORT);
  2134. req.headers.emplace("Host", host_and_port.c_str());
  2135. req.headers.emplace("Accept", "*/*");
  2136. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2137. req.headers.emplace(
  2138. "Header-Name",
  2139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2167. "@@@@@@@@@@@@@@@@@");
  2168. auto res = std::make_shared<Response>();
  2169. auto error = Error::Success;
  2170. auto ret = cli_.send(req, *res, error);
  2171. ASSERT_TRUE(ret);
  2172. EXPECT_EQ(200, res->status);
  2173. }
  2174. TEST_F(ServerTest, PercentEncoding) {
  2175. auto res = cli_.Get("/e%6edwith%");
  2176. ASSERT_TRUE(res);
  2177. EXPECT_EQ(200, res->status);
  2178. }
  2179. TEST_F(ServerTest, PercentEncodingUnicode) {
  2180. auto res = cli_.Get("/e%u006edwith%");
  2181. ASSERT_TRUE(res);
  2182. EXPECT_EQ(200, res->status);
  2183. }
  2184. TEST_F(ServerTest, InvalidPercentEncoding) {
  2185. auto res = cli_.Get("/%endwith%");
  2186. ASSERT_TRUE(res);
  2187. EXPECT_EQ(404, res->status);
  2188. }
  2189. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2190. auto res = cli_.Get("/%uendwith%");
  2191. ASSERT_TRUE(res);
  2192. EXPECT_EQ(404, res->status);
  2193. }
  2194. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2195. auto res = cli_.Get("/hello?aaa=bbb%");
  2196. ASSERT_TRUE(res);
  2197. EXPECT_EQ(404, res->status);
  2198. }
  2199. TEST_F(ServerTest, PlusSignEncoding) {
  2200. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(200, res->status);
  2203. EXPECT_EQ("a +b", res->body);
  2204. }
  2205. TEST_F(ServerTest, MultipartFormData) {
  2206. MultipartFormDataItems items = {
  2207. {"text1", "text default", "", ""},
  2208. {"text2", "aωb", "", ""},
  2209. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2210. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2211. {"file3", "", "", "application/octet-stream"},
  2212. {"file4", "", "", " application/json tmp-string "}};
  2213. auto res = cli_.Post("/multipart", items);
  2214. ASSERT_TRUE(res);
  2215. EXPECT_EQ(200, res->status);
  2216. }
  2217. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2218. auto res = cli_.Get("/hi");
  2219. ASSERT_TRUE(res);
  2220. EXPECT_EQ(200, res->status);
  2221. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2222. EXPECT_EQ("Hello World!", res->body);
  2223. }
  2224. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2225. Request req;
  2226. req.method = "POST";
  2227. req.path = "/chunked";
  2228. std::string host_and_port;
  2229. host_and_port += HOST;
  2230. host_and_port += ":";
  2231. host_and_port += std::to_string(PORT);
  2232. req.headers.emplace("Host", host_and_port.c_str());
  2233. req.headers.emplace("Accept", "*/*");
  2234. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2235. req.headers.emplace("Content-Type", "text/plain");
  2236. req.headers.emplace("Content-Length", "0");
  2237. req.headers.emplace(
  2238. "Transfer-Encoding",
  2239. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2240. // Client does not chunk, so make a chunked body manually.
  2241. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2242. auto res = std::make_shared<Response>();
  2243. auto error = Error::Success;
  2244. auto ret = cli_.send(req, *res, error);
  2245. ASSERT_TRUE(ret);
  2246. EXPECT_EQ(200, res->status);
  2247. }
  2248. TEST_F(ServerTest, GetStreamed2) {
  2249. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2250. ASSERT_TRUE(res);
  2251. EXPECT_EQ(206, res->status);
  2252. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2253. EXPECT_EQ(std::string("ab"), res->body);
  2254. }
  2255. TEST_F(ServerTest, GetStreamed) {
  2256. auto res = cli_.Get("/streamed");
  2257. ASSERT_TRUE(res);
  2258. EXPECT_EQ(200, res->status);
  2259. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2260. EXPECT_EQ(std::string("aaabbb"), res->body);
  2261. }
  2262. TEST_F(ServerTest, GetStreamedWithRange1) {
  2263. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2264. ASSERT_TRUE(res);
  2265. EXPECT_EQ(206, res->status);
  2266. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2267. EXPECT_EQ(true, res->has_header("Content-Range"));
  2268. EXPECT_EQ(std::string("def"), res->body);
  2269. }
  2270. TEST_F(ServerTest, GetStreamedWithRange2) {
  2271. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2272. ASSERT_TRUE(res);
  2273. EXPECT_EQ(206, res->status);
  2274. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2275. EXPECT_EQ(true, res->has_header("Content-Range"));
  2276. EXPECT_EQ(std::string("bcdefg"), res->body);
  2277. }
  2278. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2279. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2280. ASSERT_TRUE(res);
  2281. EXPECT_EQ(206, res->status);
  2282. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2283. EXPECT_EQ(true, res->has_header("Content-Range"));
  2284. EXPECT_EQ(std::string("efg"), res->body);
  2285. }
  2286. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2287. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2288. ASSERT_TRUE(res);
  2289. EXPECT_EQ(206, res->status);
  2290. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2291. EXPECT_EQ(true, res->has_header("Content-Range"));
  2292. EXPECT_EQ(std::string("abcdefg"), res->body);
  2293. }
  2294. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2295. auto res = cli_.Get("/streamed-with-range",
  2296. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2297. "92233720368547758079223372036854775807"}});
  2298. ASSERT_TRUE(res);
  2299. EXPECT_EQ(416, res->status);
  2300. }
  2301. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2302. auto res =
  2303. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2304. EXPECT_EQ(206, res->status);
  2305. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2306. EXPECT_EQ(true, res->has_header("Content-Range"));
  2307. EXPECT_EQ(std::string("abcdefg"), res->body);
  2308. }
  2309. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2310. auto res =
  2311. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2312. ASSERT_TRUE(res);
  2313. EXPECT_EQ(206, res->status);
  2314. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2315. EXPECT_EQ(false, res->has_header("Content-Range"));
  2316. EXPECT_EQ(269U, res->body.size());
  2317. }
  2318. TEST_F(ServerTest, GetStreamedEndless) {
  2319. uint64_t offset = 0;
  2320. auto res = cli_.Get("/streamed-cancel",
  2321. [&](const char * /*data*/, uint64_t data_length) {
  2322. if (offset < 100) {
  2323. offset += data_length;
  2324. return true;
  2325. }
  2326. return false;
  2327. });
  2328. ASSERT_TRUE(!res);
  2329. EXPECT_EQ(Error::Canceled, res.error());
  2330. }
  2331. TEST_F(ServerTest, ClientStop) {
  2332. std::vector<std::thread> threads;
  2333. for (auto i = 0; i < 3; i++) {
  2334. threads.emplace_back(thread([&]() {
  2335. auto res = cli_.Get("/streamed-cancel",
  2336. [&](const char *, uint64_t) { return true; });
  2337. ASSERT_TRUE(!res);
  2338. EXPECT_TRUE(res.error() == Error::Canceled ||
  2339. res.error() == Error::Read || res.error() == Error::Write);
  2340. }));
  2341. }
  2342. std::this_thread::sleep_for(std::chrono::seconds(2));
  2343. while (cli_.is_socket_open()) {
  2344. cli_.stop();
  2345. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2346. }
  2347. for (auto &t : threads) {
  2348. t.join();
  2349. }
  2350. }
  2351. TEST_F(ServerTest, GetWithRange1) {
  2352. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2353. ASSERT_TRUE(res);
  2354. EXPECT_EQ(206, res->status);
  2355. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2356. EXPECT_EQ(true, res->has_header("Content-Range"));
  2357. EXPECT_EQ(std::string("def"), res->body);
  2358. }
  2359. TEST_F(ServerTest, GetWithRange2) {
  2360. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2361. ASSERT_TRUE(res);
  2362. EXPECT_EQ(206, res->status);
  2363. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2364. EXPECT_EQ(true, res->has_header("Content-Range"));
  2365. EXPECT_EQ(std::string("bcdefg"), res->body);
  2366. }
  2367. TEST_F(ServerTest, GetWithRange3) {
  2368. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2369. ASSERT_TRUE(res);
  2370. EXPECT_EQ(206, res->status);
  2371. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2372. EXPECT_EQ(true, res->has_header("Content-Range"));
  2373. EXPECT_EQ(std::string("a"), res->body);
  2374. }
  2375. TEST_F(ServerTest, GetWithRange4) {
  2376. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2377. ASSERT_TRUE(res);
  2378. EXPECT_EQ(206, res->status);
  2379. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2380. EXPECT_EQ(true, res->has_header("Content-Range"));
  2381. EXPECT_EQ(std::string("fg"), res->body);
  2382. }
  2383. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2384. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2385. ASSERT_TRUE(res);
  2386. EXPECT_EQ(416, res->status);
  2387. }
  2388. TEST_F(ServerTest, GetWithRangeMultipart) {
  2389. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ(206, res->status);
  2392. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2393. EXPECT_EQ(false, res->has_header("Content-Range"));
  2394. EXPECT_EQ(269U, res->body.size());
  2395. }
  2396. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2397. auto res =
  2398. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2399. ASSERT_TRUE(res);
  2400. EXPECT_EQ(416, res->status);
  2401. }
  2402. TEST_F(ServerTest, GetStreamedChunked) {
  2403. auto res = cli_.Get("/streamed-chunked");
  2404. ASSERT_TRUE(res);
  2405. EXPECT_EQ(200, res->status);
  2406. EXPECT_EQ(std::string("123456789"), res->body);
  2407. }
  2408. TEST_F(ServerTest, GetStreamedChunked2) {
  2409. auto res = cli_.Get("/streamed-chunked2");
  2410. ASSERT_TRUE(res);
  2411. EXPECT_EQ(200, res->status);
  2412. EXPECT_EQ(std::string("123456789"), res->body);
  2413. }
  2414. TEST_F(ServerTest, LargeChunkedPost) {
  2415. Request req;
  2416. req.method = "POST";
  2417. req.path = "/large-chunked";
  2418. std::string host_and_port;
  2419. host_and_port += HOST;
  2420. host_and_port += ":";
  2421. host_and_port += std::to_string(PORT);
  2422. req.headers.emplace("Host", host_and_port.c_str());
  2423. req.headers.emplace("Accept", "*/*");
  2424. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2425. req.headers.emplace("Content-Type", "text/plain");
  2426. req.headers.emplace("Content-Length", "0");
  2427. req.headers.emplace("Transfer-Encoding", "chunked");
  2428. std::string long_string(30 * 1024u, 'a');
  2429. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2430. // Attempt to make a large enough post to exceed OS buffers, to test that
  2431. // the server handles short reads if the full chunk data isn't available.
  2432. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2433. auto res = std::make_shared<Response>();
  2434. auto error = Error::Success;
  2435. auto ret = cli_.send(req, *res, error);
  2436. ASSERT_TRUE(ret);
  2437. EXPECT_EQ(200, res->status);
  2438. }
  2439. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2440. auto res = cli_.Get("/remote_addr");
  2441. ASSERT_TRUE(res);
  2442. EXPECT_EQ(200, res->status);
  2443. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2444. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2445. }
  2446. TEST_F(ServerTest, GetMethodLocalAddr) {
  2447. auto res = cli_.Get("/local_addr");
  2448. ASSERT_TRUE(res);
  2449. EXPECT_EQ(200, res->status);
  2450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2451. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  2452. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  2453. }
  2454. TEST_F(ServerTest, HTTPResponseSplitting) {
  2455. auto res = cli_.Get("/http_response_splitting");
  2456. ASSERT_TRUE(res);
  2457. EXPECT_EQ(200, res->status);
  2458. }
  2459. TEST_F(ServerTest, SlowRequest) {
  2460. request_threads_.push_back(
  2461. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2462. request_threads_.push_back(
  2463. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2464. request_threads_.push_back(
  2465. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2466. }
  2467. #if 0
  2468. TEST_F(ServerTest, SlowPost) {
  2469. char buffer[64 * 1024];
  2470. memset(buffer, 0x42, sizeof(buffer));
  2471. auto res = cli_.Post(
  2472. "/slowpost", 64 * 1024 * 1024,
  2473. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2474. auto ret = sink.write(buffer, sizeof(buffer));
  2475. EXPECT_TRUE(ret);
  2476. return true;
  2477. },
  2478. "text/plain");
  2479. ASSERT_TRUE(res);
  2480. EXPECT_EQ(200, res->status);
  2481. }
  2482. TEST_F(ServerTest, SlowPostFail) {
  2483. char buffer[64 * 1024];
  2484. memset(buffer, 0x42, sizeof(buffer));
  2485. cli_.set_write_timeout(std::chrono::seconds(0));
  2486. auto res = cli_.Post(
  2487. "/slowpost", 64 * 1024 * 1024,
  2488. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2489. sink.write(buffer, sizeof(buffer));
  2490. return true;
  2491. },
  2492. "text/plain");
  2493. ASSERT_TRUE(!res);
  2494. EXPECT_EQ(Error::Write, res.error());
  2495. }
  2496. #endif
  2497. TEST_F(ServerTest, Put) {
  2498. auto res = cli_.Put("/put", "PUT", "text/plain");
  2499. ASSERT_TRUE(res);
  2500. EXPECT_EQ(200, res->status);
  2501. EXPECT_EQ("PUT", res->body);
  2502. }
  2503. TEST_F(ServerTest, PutWithContentProvider) {
  2504. auto res = cli_.Put(
  2505. "/put", 3,
  2506. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2507. sink.os << "PUT";
  2508. return true;
  2509. },
  2510. "text/plain");
  2511. ASSERT_TRUE(res);
  2512. EXPECT_EQ(200, res->status);
  2513. EXPECT_EQ("PUT", res->body);
  2514. }
  2515. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2516. auto res = cli_.Post(
  2517. "/post", 42,
  2518. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2519. return false;
  2520. },
  2521. "text/plain");
  2522. ASSERT_TRUE(!res);
  2523. EXPECT_EQ(Error::Canceled, res.error());
  2524. }
  2525. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2526. auto res = cli_.Put(
  2527. "/put",
  2528. [](size_t /*offset*/, DataSink &sink) {
  2529. sink.os << "PUT";
  2530. sink.done();
  2531. return true;
  2532. },
  2533. "text/plain");
  2534. ASSERT_TRUE(res);
  2535. EXPECT_EQ(200, res->status);
  2536. EXPECT_EQ("PUT", res->body);
  2537. }
  2538. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2539. auto res = cli_.Post(
  2540. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2541. "text/plain");
  2542. ASSERT_TRUE(!res);
  2543. EXPECT_EQ(Error::Canceled, res.error());
  2544. }
  2545. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2546. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2547. cli_.set_compress(true);
  2548. auto res = cli_.Put(
  2549. "/put", 3,
  2550. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2551. sink.os << "PUT";
  2552. return true;
  2553. },
  2554. "text/plain");
  2555. ASSERT_TRUE(res);
  2556. EXPECT_EQ(200, res->status);
  2557. EXPECT_EQ("PUT", res->body);
  2558. }
  2559. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2560. cli_.set_compress(true);
  2561. auto res = cli_.Post(
  2562. "/post", 42,
  2563. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2564. return false;
  2565. },
  2566. "text/plain");
  2567. ASSERT_TRUE(!res);
  2568. EXPECT_EQ(Error::Canceled, res.error());
  2569. }
  2570. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2571. cli_.set_compress(true);
  2572. auto res = cli_.Put(
  2573. "/put",
  2574. [](size_t /*offset*/, DataSink &sink) {
  2575. sink.os << "PUT";
  2576. sink.done();
  2577. return true;
  2578. },
  2579. "text/plain");
  2580. ASSERT_TRUE(res);
  2581. EXPECT_EQ(200, res->status);
  2582. EXPECT_EQ("PUT", res->body);
  2583. }
  2584. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2585. cli_.set_compress(true);
  2586. auto res = cli_.Post(
  2587. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2588. "text/plain");
  2589. ASSERT_TRUE(!res);
  2590. EXPECT_EQ(Error::Canceled, res.error());
  2591. }
  2592. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2593. cli_.set_compress(true);
  2594. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2595. ASSERT_TRUE(res);
  2596. EXPECT_EQ(200, res->status);
  2597. EXPECT_EQ(LARGE_DATA, res->body);
  2598. }
  2599. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2600. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2601. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2602. Client cli(s.c_str());
  2603. cli.enable_server_certificate_verification(false);
  2604. #else
  2605. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2606. Client cli(s.c_str());
  2607. #endif
  2608. cli.set_compress(true);
  2609. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2610. ASSERT_TRUE(res);
  2611. EXPECT_EQ(200, res->status);
  2612. EXPECT_EQ(LARGE_DATA, res->body);
  2613. EXPECT_EQ(101942u, res.get_request_header_value<uint64_t>("Content-Length"));
  2614. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2615. }
  2616. TEST_F(ServerTest, PutContentWithDeflate) {
  2617. cli_.set_compress(false);
  2618. Headers headers;
  2619. headers.emplace("Content-Encoding", "deflate");
  2620. // PUT in deflate format:
  2621. auto res = cli_.Put("/put", headers,
  2622. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2623. ASSERT_TRUE(res);
  2624. EXPECT_EQ(200, res->status);
  2625. EXPECT_EQ("PUT", res->body);
  2626. }
  2627. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2628. Headers headers;
  2629. headers.emplace("Accept-Encoding", "gzip, deflate");
  2630. auto res = cli_.Get("/streamed-chunked", headers);
  2631. ASSERT_TRUE(res);
  2632. EXPECT_EQ(200, res->status);
  2633. EXPECT_EQ(std::string("123456789"), res->body);
  2634. }
  2635. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2636. Headers headers;
  2637. headers.emplace("Accept-Encoding", "gzip, deflate");
  2638. auto res = cli_.Get("/streamed-chunked2", headers);
  2639. ASSERT_TRUE(res);
  2640. EXPECT_EQ(200, res->status);
  2641. EXPECT_EQ(std::string("123456789"), res->body);
  2642. }
  2643. TEST(GzipDecompressor, ChunkedDecompression) {
  2644. std::string data;
  2645. for (size_t i = 0; i < 32 * 1024; ++i) {
  2646. data.push_back(static_cast<char>('a' + i % 26));
  2647. }
  2648. std::string compressed_data;
  2649. {
  2650. httplib::detail::gzip_compressor compressor;
  2651. bool result = compressor.compress(
  2652. data.data(), data.size(),
  2653. /*last=*/true,
  2654. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  2655. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  2656. compressed_data_size);
  2657. return true;
  2658. });
  2659. ASSERT_TRUE(result);
  2660. }
  2661. std::string decompressed_data;
  2662. {
  2663. httplib::detail::gzip_decompressor decompressor;
  2664. // Chunk size is chosen specificaly to have a decompressed chunk size equal
  2665. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2666. size_t chunk_size = 130;
  2667. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2668. chunk_begin += chunk_size) {
  2669. size_t current_chunk_size =
  2670. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2671. bool result = decompressor.decompress(
  2672. compressed_data.data() + chunk_begin, current_chunk_size,
  2673. [&](const char *decompressed_data_chunk,
  2674. size_t decompressed_data_chunk_size) {
  2675. decompressed_data.insert(decompressed_data.size(),
  2676. decompressed_data_chunk,
  2677. decompressed_data_chunk_size);
  2678. return true;
  2679. });
  2680. ASSERT_TRUE(result);
  2681. }
  2682. }
  2683. ASSERT_EQ(data, decompressed_data);
  2684. }
  2685. #ifdef _WIN32
  2686. TEST(GzipDecompressor, LargeRandomData) {
  2687. // prepare large random data that is difficult to be compressed and is
  2688. // expected to have large size even when compressed
  2689. std::random_device seed_gen;
  2690. std::mt19937 random(seed_gen());
  2691. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2692. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2693. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2694. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2695. // compress data over 4GiB
  2696. std::string compressed_data;
  2697. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2698. httplib::detail::gzip_compressor compressor;
  2699. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2700. data.size() * sizeof(std::uint32_t), true,
  2701. [&](const char *data, size_t size) {
  2702. compressed_data.insert(
  2703. compressed_data.size(), data, size);
  2704. return true;
  2705. });
  2706. ASSERT_TRUE(result);
  2707. // FIXME: compressed data size is expected to be greater than 4GiB,
  2708. // but there is no guarantee
  2709. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2710. // decompress data over 4GiB
  2711. std::string decompressed_data;
  2712. decompressed_data.reserve(data_size);
  2713. httplib::detail::gzip_decompressor decompressor;
  2714. result = decompressor.decompress(
  2715. compressed_data.data(), compressed_data.size(),
  2716. [&](const char *data, size_t size) {
  2717. decompressed_data.insert(decompressed_data.size(), data, size);
  2718. return true;
  2719. });
  2720. ASSERT_TRUE(result);
  2721. // compare
  2722. ASSERT_EQ(data_size, decompressed_data.size());
  2723. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2724. 0);
  2725. }
  2726. #endif
  2727. #endif
  2728. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2729. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2730. Headers headers;
  2731. headers.emplace("Accept-Encoding", "br");
  2732. auto res = cli_.Get("/streamed-chunked", headers);
  2733. ASSERT_TRUE(res);
  2734. EXPECT_EQ(200, res->status);
  2735. EXPECT_EQ(std::string("123456789"), res->body);
  2736. }
  2737. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2738. Headers headers;
  2739. headers.emplace("Accept-Encoding", "br");
  2740. auto res = cli_.Get("/streamed-chunked2", headers);
  2741. ASSERT_TRUE(res);
  2742. EXPECT_EQ(200, res->status);
  2743. EXPECT_EQ(std::string("123456789"), res->body);
  2744. }
  2745. #endif
  2746. TEST_F(ServerTest, Patch) {
  2747. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2748. ASSERT_TRUE(res);
  2749. EXPECT_EQ(200, res->status);
  2750. EXPECT_EQ("PATCH", res->body);
  2751. }
  2752. TEST_F(ServerTest, Delete) {
  2753. auto res = cli_.Delete("/delete");
  2754. ASSERT_TRUE(res);
  2755. EXPECT_EQ(200, res->status);
  2756. EXPECT_EQ("DELETE", res->body);
  2757. }
  2758. TEST_F(ServerTest, DeleteContentReceiver) {
  2759. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2760. ASSERT_TRUE(res);
  2761. EXPECT_EQ(200, res->status);
  2762. EXPECT_EQ("content", res->body);
  2763. }
  2764. TEST_F(ServerTest, Options) {
  2765. auto res = cli_.Options("*");
  2766. ASSERT_TRUE(res);
  2767. EXPECT_EQ(200, res->status);
  2768. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2769. EXPECT_TRUE(res->body.empty());
  2770. }
  2771. TEST_F(ServerTest, URL) {
  2772. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2773. ASSERT_TRUE(res);
  2774. EXPECT_EQ(200, res->status);
  2775. }
  2776. TEST_F(ServerTest, ArrayParam) {
  2777. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2778. ASSERT_TRUE(res);
  2779. EXPECT_EQ(200, res->status);
  2780. }
  2781. TEST_F(ServerTest, NoMultipleHeaders) {
  2782. Headers headers = {{"Content-Length", "5"}};
  2783. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2784. "text/plain");
  2785. ASSERT_TRUE(res);
  2786. EXPECT_EQ(200, res->status);
  2787. }
  2788. TEST_F(ServerTest, PostContentReceiver) {
  2789. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2790. ASSERT_TRUE(res);
  2791. ASSERT_EQ(200, res->status);
  2792. ASSERT_EQ("content", res->body);
  2793. }
  2794. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  2795. MultipartFormDataItems items = {
  2796. {"text1", "text default", "", ""},
  2797. {"text2", "aωb", "", ""},
  2798. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2799. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2800. {"file3", "", "", "application/octet-stream"},
  2801. };
  2802. auto res = cli_.Post("/content_receiver", items);
  2803. ASSERT_TRUE(res);
  2804. EXPECT_EQ(200, res->status);
  2805. }
  2806. TEST_F(ServerTest, PostMulitpartPlusBoundary) {
  2807. MultipartFormDataItems items = {
  2808. {"text1", "text default", "", ""},
  2809. {"text2", "aωb", "", ""},
  2810. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2811. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2812. {"file3", "", "", "application/octet-stream"},
  2813. };
  2814. auto boundary = std::string("+++++");
  2815. std::string body;
  2816. for (const auto &item : items) {
  2817. body += "--" + boundary + "\r\n";
  2818. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2819. if (!item.filename.empty()) {
  2820. body += "; filename=\"" + item.filename + "\"";
  2821. }
  2822. body += "\r\n";
  2823. if (!item.content_type.empty()) {
  2824. body += "Content-Type: " + item.content_type + "\r\n";
  2825. }
  2826. body += "\r\n";
  2827. body += item.content + "\r\n";
  2828. }
  2829. body += "--" + boundary + "--\r\n";
  2830. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2831. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2832. ASSERT_TRUE(res);
  2833. EXPECT_EQ(200, res->status);
  2834. }
  2835. TEST_F(ServerTest, PostContentReceiverGzip) {
  2836. cli_.set_compress(true);
  2837. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2838. ASSERT_TRUE(res);
  2839. ASSERT_EQ(200, res->status);
  2840. ASSERT_EQ("content", res->body);
  2841. }
  2842. TEST_F(ServerTest, PutContentReceiver) {
  2843. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2844. ASSERT_TRUE(res);
  2845. ASSERT_EQ(200, res->status);
  2846. ASSERT_EQ("content", res->body);
  2847. }
  2848. TEST_F(ServerTest, PatchContentReceiver) {
  2849. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2850. ASSERT_TRUE(res);
  2851. ASSERT_EQ(200, res->status);
  2852. ASSERT_EQ("content", res->body);
  2853. }
  2854. TEST_F(ServerTest, PostQueryStringAndBody) {
  2855. auto res =
  2856. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2857. ASSERT_TRUE(res);
  2858. ASSERT_EQ(200, res->status);
  2859. }
  2860. TEST_F(ServerTest, HTTP2Magic) {
  2861. Request req;
  2862. req.method = "PRI";
  2863. req.path = "*";
  2864. req.body = "SM";
  2865. auto res = std::make_shared<Response>();
  2866. auto error = Error::Success;
  2867. auto ret = cli_.send(req, *res, error);
  2868. ASSERT_TRUE(ret);
  2869. EXPECT_EQ(400, res->status);
  2870. }
  2871. TEST_F(ServerTest, KeepAlive) {
  2872. auto res = cli_.Get("/hi");
  2873. ASSERT_TRUE(res);
  2874. EXPECT_EQ(200, res->status);
  2875. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2876. EXPECT_EQ("Hello World!", res->body);
  2877. res = cli_.Get("/hi");
  2878. ASSERT_TRUE(res);
  2879. EXPECT_EQ(200, res->status);
  2880. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2881. EXPECT_EQ("Hello World!", res->body);
  2882. res = cli_.Get("/hi");
  2883. ASSERT_TRUE(res);
  2884. EXPECT_EQ(200, res->status);
  2885. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2886. EXPECT_EQ("Hello World!", res->body);
  2887. res = cli_.Get("/not-exist");
  2888. ASSERT_TRUE(res);
  2889. EXPECT_EQ(404, res->status);
  2890. res = cli_.Post("/empty", "", "text/plain");
  2891. ASSERT_TRUE(res);
  2892. EXPECT_EQ(200, res->status);
  2893. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2894. EXPECT_EQ("empty", res->body);
  2895. EXPECT_EQ("close", res->get_header_value("Connection"));
  2896. res = cli_.Post(
  2897. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  2898. "text/plain");
  2899. ASSERT_TRUE(res);
  2900. EXPECT_EQ(200, res->status);
  2901. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2902. EXPECT_EQ("empty", res->body);
  2903. cli_.set_keep_alive(false);
  2904. res = cli_.Get("/last-request");
  2905. ASSERT_TRUE(res);
  2906. EXPECT_EQ(200, res->status);
  2907. EXPECT_EQ("close", res->get_header_value("Connection"));
  2908. }
  2909. TEST_F(ServerTest, TooManyRedirect) {
  2910. cli_.set_follow_location(true);
  2911. auto res = cli_.Get("/redirect/0");
  2912. ASSERT_TRUE(!res);
  2913. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2914. }
  2915. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2916. TEST_F(ServerTest, Gzip) {
  2917. Headers headers;
  2918. headers.emplace("Accept-Encoding", "gzip, deflate");
  2919. auto res = cli_.Get("/compress", headers);
  2920. ASSERT_TRUE(res);
  2921. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2922. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2923. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2924. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2925. "7890123456789012345678901234567890",
  2926. res->body);
  2927. EXPECT_EQ(200, res->status);
  2928. }
  2929. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  2930. auto res = cli_.Get("/compress");
  2931. ASSERT_TRUE(res);
  2932. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2933. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2934. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2935. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2936. "7890123456789012345678901234567890",
  2937. res->body);
  2938. EXPECT_EQ(200, res->status);
  2939. }
  2940. TEST_F(ServerTest, GzipWithContentReceiver) {
  2941. Headers headers;
  2942. headers.emplace("Accept-Encoding", "gzip, deflate");
  2943. std::string body;
  2944. auto res = cli_.Get("/compress", headers,
  2945. [&](const char *data, uint64_t data_length) {
  2946. EXPECT_EQ(100U, data_length);
  2947. body.append(data, data_length);
  2948. return true;
  2949. });
  2950. ASSERT_TRUE(res);
  2951. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2952. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2953. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2954. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2955. "7890123456789012345678901234567890",
  2956. body);
  2957. EXPECT_EQ(200, res->status);
  2958. }
  2959. TEST_F(ServerTest, GzipWithoutDecompressing) {
  2960. Headers headers;
  2961. headers.emplace("Accept-Encoding", "gzip, deflate");
  2962. cli_.set_decompress(false);
  2963. auto res = cli_.Get("/compress", headers);
  2964. ASSERT_TRUE(res);
  2965. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2966. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2967. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2968. EXPECT_EQ(33U, res->body.size());
  2969. EXPECT_EQ(200, res->status);
  2970. }
  2971. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  2972. std::string body;
  2973. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  2974. EXPECT_EQ(100U, data_length);
  2975. body.append(data, data_length);
  2976. return true;
  2977. });
  2978. ASSERT_TRUE(res);
  2979. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2980. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2981. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2982. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2983. "7890123456789012345678901234567890",
  2984. body);
  2985. EXPECT_EQ(200, res->status);
  2986. }
  2987. TEST_F(ServerTest, NoGzip) {
  2988. Headers headers;
  2989. headers.emplace("Accept-Encoding", "gzip, deflate");
  2990. auto res = cli_.Get("/nocompress", headers);
  2991. ASSERT_TRUE(res);
  2992. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2993. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2994. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2996. "7890123456789012345678901234567890",
  2997. res->body);
  2998. EXPECT_EQ(200, res->status);
  2999. }
  3000. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3001. Headers headers;
  3002. headers.emplace("Accept-Encoding", "gzip, deflate");
  3003. std::string body;
  3004. auto res = cli_.Get("/nocompress", headers,
  3005. [&](const char *data, uint64_t data_length) {
  3006. EXPECT_EQ(100U, data_length);
  3007. body.append(data, data_length);
  3008. return true;
  3009. });
  3010. ASSERT_TRUE(res);
  3011. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3012. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3013. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3014. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3015. "7890123456789012345678901234567890",
  3016. body);
  3017. EXPECT_EQ(200, res->status);
  3018. }
  3019. TEST_F(ServerTest, MultipartFormDataGzip) {
  3020. MultipartFormDataItems items = {
  3021. {"key1", "test", "", ""},
  3022. {"key2", "--abcdefg123", "", ""},
  3023. };
  3024. cli_.set_compress(true);
  3025. auto res = cli_.Post("/compress-multipart", items);
  3026. ASSERT_TRUE(res);
  3027. EXPECT_EQ(200, res->status);
  3028. }
  3029. #endif
  3030. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3031. TEST_F(ServerTest, Brotli) {
  3032. Headers headers;
  3033. headers.emplace("Accept-Encoding", "br");
  3034. auto res = cli_.Get("/compress", headers);
  3035. ASSERT_TRUE(res);
  3036. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3037. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3038. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3039. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3040. "7890123456789012345678901234567890",
  3041. res->body);
  3042. EXPECT_EQ(200, res->status);
  3043. }
  3044. #endif
  3045. // Sends a raw request to a server listening at HOST:PORT.
  3046. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3047. std::string *resp = nullptr) {
  3048. auto error = Error::Success;
  3049. auto client_sock = detail::create_client_socket(
  3050. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  3051. /*connection_timeout_sec=*/5, 0,
  3052. /*read_timeout_sec=*/5, 0,
  3053. /*write_timeout_sec=*/5, 0, std::string(), error);
  3054. if (client_sock == INVALID_SOCKET) { return false; }
  3055. auto ret = detail::process_client_socket(
  3056. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3057. if (req.size() !=
  3058. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3059. return false;
  3060. }
  3061. char buf[512];
  3062. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3063. while (line_reader.getline()) {
  3064. if (resp) { *resp += line_reader.ptr(); }
  3065. }
  3066. return true;
  3067. });
  3068. detail::close_socket(client_sock);
  3069. return ret;
  3070. }
  3071. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3072. Server svr;
  3073. std::string header_value;
  3074. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3075. header_value = req.get_header_value("foo");
  3076. res.set_content("ok", "text/plain");
  3077. });
  3078. thread t = thread([&] { svr.listen(HOST, PORT); });
  3079. while (!svr.is_running()) {
  3080. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3081. }
  3082. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3083. // like characters are not treated the same - use vertical tab and escape.
  3084. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3085. "foo: \t \v bar \x1B\t \r\n"
  3086. "Connection: close\r\n"
  3087. "\r\n";
  3088. ASSERT_TRUE(send_request(5, req));
  3089. svr.stop();
  3090. t.join();
  3091. EXPECT_EQ(header_value, "\v bar \x1B");
  3092. }
  3093. // Sends a raw request and verifies that there isn't a crash or exception.
  3094. static void test_raw_request(const std::string &req,
  3095. std::string *out = nullptr) {
  3096. Server svr;
  3097. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3098. res.set_content("ok", "text/plain");
  3099. });
  3100. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  3101. res.set_content("ok", "text/plain");
  3102. });
  3103. // Server read timeout must be longer than the client read timeout for the
  3104. // bug to reproduce, probably to force the server to process a request
  3105. // without a trailing blank line.
  3106. const time_t client_read_timeout_sec = 1;
  3107. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3108. bool listen_thread_ok = false;
  3109. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3110. while (!svr.is_running()) {
  3111. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3112. }
  3113. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3114. svr.stop();
  3115. t.join();
  3116. EXPECT_TRUE(listen_thread_ok);
  3117. }
  3118. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3119. // A certain header line causes an exception if the header property is parsed
  3120. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3121. test_raw_request(
  3122. "GET /hi HTTP/1.1\r\n"
  3123. " : "
  3124. " "
  3125. " ");
  3126. }
  3127. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3128. // A certain header line causes an exception if the header property *name* is
  3129. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3130. // greedy matcher and requires backtracking when there are a lot of ":"
  3131. // characters.
  3132. // This occurs with libc++ but not libstdc++.
  3133. test_raw_request(
  3134. "GET /hi HTTP/1.1\r\n"
  3135. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3136. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3137. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3138. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3139. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3140. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3141. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3142. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3143. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3144. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3145. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3146. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3147. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3148. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3149. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3150. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3151. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3152. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3153. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3154. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3155. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3156. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3157. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3158. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3159. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3160. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3161. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3162. "&&&%%%");
  3163. }
  3164. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  3165. // Make sure this doesn't crash the server.
  3166. // In a previous version of the header line regex, the "\r" rendered the line
  3167. // unparseable and the regex engine repeatedly backtracked, trying to look for
  3168. // a new position where the leading white space ended and the field value
  3169. // began.
  3170. // The crash occurs with libc++ but not libstdc++.
  3171. test_raw_request("GET /hi HTTP/1.1\r\n"
  3172. "a:" +
  3173. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3174. "\r\n"
  3175. "\r\n");
  3176. }
  3177. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3178. std::string out;
  3179. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3180. "Content-Type: text/plain\r\n"
  3181. "Transfer-Encoding: chunked\r\n"
  3182. "\r\n"
  3183. "nothex\r\n",
  3184. &out);
  3185. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3186. }
  3187. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3188. std::string out;
  3189. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3190. "Content-Type: text/plain\r\n"
  3191. "Transfer-Encoding: chunked\r\n"
  3192. "\r\n"
  3193. "3\r\n"
  3194. "xyz\r\n"
  3195. "NaN\r\n",
  3196. &out);
  3197. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3198. }
  3199. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3200. std::string out;
  3201. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3202. "Content-Type: text/plain\r\n"
  3203. "Transfer-Encoding: chunked\r\n"
  3204. "\r\n"
  3205. // Length is too large for 64 bits.
  3206. "1ffffffffffffffff\r\n"
  3207. "xyz\r\n",
  3208. &out);
  3209. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3210. }
  3211. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3212. test_raw_request("GET /hi HTTP/1.1\r\n"
  3213. "Content-Type: text/plain\r\n\r");
  3214. }
  3215. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3216. std::string out;
  3217. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3218. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3219. }
  3220. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3221. Server svr;
  3222. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3223. res.set_header("Cache-Control", "no-cache");
  3224. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  3225. DataSink &sink) {
  3226. char buffer[27];
  3227. auto size = static_cast<size_t>(sprintf(buffer, "data:%zd\n\n", offset));
  3228. auto ret = sink.write(buffer, size);
  3229. EXPECT_TRUE(ret);
  3230. std::this_thread::sleep_for(std::chrono::seconds(1));
  3231. return true;
  3232. });
  3233. });
  3234. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3235. while (!svr.is_running()) {
  3236. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3237. }
  3238. Client client(HOST, PORT);
  3239. const Headers headers = {{"Accept", "text/event-stream"}};
  3240. auto get_thread = std::thread([&client, &headers]() {
  3241. auto res = client.Get(
  3242. "/events", headers,
  3243. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3244. });
  3245. // Give GET time to get a few messages.
  3246. std::this_thread::sleep_for(std::chrono::seconds(2));
  3247. svr.stop();
  3248. listen_thread.join();
  3249. get_thread.join();
  3250. ASSERT_FALSE(svr.is_running());
  3251. }
  3252. TEST(StreamingTest, NoContentLengthStreaming) {
  3253. Server svr;
  3254. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3255. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3256. if (offset < 6) {
  3257. sink.os << (offset < 3 ? "a" : "b");
  3258. } else {
  3259. sink.done();
  3260. }
  3261. return true;
  3262. });
  3263. });
  3264. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3265. while (!svr.is_running()) {
  3266. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3267. }
  3268. Client client(HOST, PORT);
  3269. auto get_thread = std::thread([&client]() {
  3270. std::string s;
  3271. auto res =
  3272. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3273. s += std::string(data, len);
  3274. return true;
  3275. });
  3276. EXPECT_EQ("aaabbb", s);
  3277. });
  3278. // Give GET time to get a few messages.
  3279. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3280. svr.stop();
  3281. listen_thread.join();
  3282. get_thread.join();
  3283. ASSERT_FALSE(svr.is_running());
  3284. }
  3285. TEST(MountTest, Unmount) {
  3286. Server svr;
  3287. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3288. while (!svr.is_running()) {
  3289. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3290. }
  3291. // Give GET time to get a few messages.
  3292. std::this_thread::sleep_for(std::chrono::seconds(1));
  3293. Client cli("localhost", PORT);
  3294. svr.set_mount_point("/mount2", "./www2");
  3295. auto res = cli.Get("/");
  3296. ASSERT_TRUE(res);
  3297. EXPECT_EQ(404, res->status);
  3298. res = cli.Get("/mount2/dir/test.html");
  3299. ASSERT_TRUE(res);
  3300. EXPECT_EQ(200, res->status);
  3301. svr.set_mount_point("/", "./www");
  3302. res = cli.Get("/dir/");
  3303. ASSERT_TRUE(res);
  3304. EXPECT_EQ(200, res->status);
  3305. svr.remove_mount_point("/");
  3306. res = cli.Get("/dir/");
  3307. ASSERT_TRUE(res);
  3308. EXPECT_EQ(404, res->status);
  3309. svr.remove_mount_point("/mount2");
  3310. res = cli.Get("/mount2/dir/test.html");
  3311. ASSERT_TRUE(res);
  3312. EXPECT_EQ(404, res->status);
  3313. svr.stop();
  3314. listen_thread.join();
  3315. ASSERT_FALSE(svr.is_running());
  3316. }
  3317. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3318. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3319. Server svr;
  3320. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3321. throw std::runtime_error("exception...");
  3322. });
  3323. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3324. throw std::runtime_error("exception\r\n...");
  3325. });
  3326. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3327. while (!svr.is_running()) {
  3328. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3329. }
  3330. // Give GET time to get a few messages.
  3331. std::this_thread::sleep_for(std::chrono::seconds(1));
  3332. Client cli("localhost", PORT);
  3333. {
  3334. auto res = cli.Get("/exception");
  3335. ASSERT_TRUE(res);
  3336. EXPECT_EQ(500, res->status);
  3337. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3338. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3339. }
  3340. {
  3341. auto res = cli.Get("/unknown");
  3342. ASSERT_TRUE(res);
  3343. EXPECT_EQ(500, res->status);
  3344. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3345. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  3346. }
  3347. svr.stop();
  3348. listen_thread.join();
  3349. ASSERT_FALSE(svr.is_running());
  3350. }
  3351. #endif
  3352. TEST(KeepAliveTest, ReadTimeout) {
  3353. Server svr;
  3354. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3355. std::this_thread::sleep_for(std::chrono::seconds(2));
  3356. res.set_content("a", "text/plain");
  3357. });
  3358. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3359. res.set_content("b", "text/plain");
  3360. });
  3361. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3362. while (!svr.is_running()) {
  3363. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3364. }
  3365. // Give GET time to get a few messages.
  3366. std::this_thread::sleep_for(std::chrono::seconds(1));
  3367. Client cli("localhost", PORT);
  3368. cli.set_keep_alive(true);
  3369. cli.set_read_timeout(std::chrono::seconds(1));
  3370. auto resa = cli.Get("/a");
  3371. ASSERT_TRUE(!resa);
  3372. EXPECT_EQ(Error::Read, resa.error());
  3373. auto resb = cli.Get("/b");
  3374. ASSERT_TRUE(resb);
  3375. EXPECT_EQ(200, resb->status);
  3376. EXPECT_EQ("b", resb->body);
  3377. svr.stop();
  3378. listen_thread.join();
  3379. ASSERT_FALSE(svr.is_running());
  3380. }
  3381. TEST(KeepAliveTest, Issue1041) {
  3382. const auto resourcePath = "/hi";
  3383. Server svr;
  3384. svr.set_keep_alive_timeout(3);
  3385. svr.Get(resourcePath, [](const httplib::Request &, httplib::Response &res) {
  3386. res.set_content("Hello World!", "text/plain");
  3387. });
  3388. auto a2 = std::async(std::launch::async, [&svr] { svr.listen(HOST, PORT); });
  3389. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3390. Client cli(HOST, PORT);
  3391. cli.set_keep_alive(true);
  3392. auto result = cli.Get(resourcePath);
  3393. ASSERT_TRUE(result);
  3394. EXPECT_EQ(200, result->status);
  3395. std::this_thread::sleep_for(std::chrono::seconds(5));
  3396. result = cli.Get(resourcePath);
  3397. ASSERT_TRUE(result);
  3398. EXPECT_EQ(200, result->status);
  3399. svr.stop();
  3400. a2.wait();
  3401. }
  3402. TEST(ClientProblemDetectionTest, ContentProvider) {
  3403. Server svr;
  3404. size_t content_length = 1024 * 1024;
  3405. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3406. res.set_content_provider(
  3407. content_length, "text/plain",
  3408. [&](size_t offset, size_t length, DataSink &sink) {
  3409. auto out_len = std::min(length, static_cast<size_t>(1024));
  3410. std::string out(out_len, '@');
  3411. sink.write(out.data(), out_len);
  3412. return offset < 4096;
  3413. },
  3414. [](bool success) { ASSERT_FALSE(success); });
  3415. });
  3416. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3417. while (!svr.is_running()) {
  3418. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3419. }
  3420. // Give GET time to get a few messages.
  3421. std::this_thread::sleep_for(std::chrono::seconds(1));
  3422. Client cli("localhost", PORT);
  3423. auto res = cli.Get("/hi", [&](const char * /*data*/, size_t /*data_length*/) {
  3424. return false;
  3425. });
  3426. ASSERT_FALSE(res);
  3427. svr.stop();
  3428. listen_thread.join();
  3429. ASSERT_FALSE(svr.is_running());
  3430. }
  3431. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3432. Server svr;
  3433. svr.set_error_handler([](Request const &, Response &res) -> void {
  3434. res.set_chunked_content_provider(
  3435. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3436. sink.os << "hello";
  3437. sink.os << "world";
  3438. sink.done();
  3439. return true;
  3440. });
  3441. });
  3442. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3443. while (!svr.is_running()) {
  3444. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3445. }
  3446. // Give GET time to get a few messages.
  3447. std::this_thread::sleep_for(std::chrono::seconds(1));
  3448. Client cli("localhost", PORT);
  3449. auto res = cli.Get("/");
  3450. ASSERT_TRUE(res);
  3451. EXPECT_EQ(404, res->status);
  3452. EXPECT_EQ("helloworld", res->body);
  3453. svr.stop();
  3454. listen_thread.join();
  3455. ASSERT_FALSE(svr.is_running());
  3456. }
  3457. TEST(GetWithParametersTest, GetWithParameters) {
  3458. Server svr;
  3459. svr.Get("/", [&](const Request &req, Response &) {
  3460. EXPECT_EQ("world", req.get_param_value("hello"));
  3461. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3462. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3463. });
  3464. svr.Get("/params", [&](const Request &req, Response &) {
  3465. EXPECT_EQ("world", req.get_param_value("hello"));
  3466. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3467. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3468. });
  3469. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3470. EXPECT_EQ("resource-id", req.matches[1]);
  3471. EXPECT_EQ("foo", req.get_param_value("param1"));
  3472. EXPECT_EQ("bar", req.get_param_value("param2"));
  3473. });
  3474. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3475. while (!svr.is_running()) {
  3476. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3477. }
  3478. std::this_thread::sleep_for(std::chrono::seconds(1));
  3479. {
  3480. Client cli(HOST, PORT);
  3481. Params params;
  3482. params.emplace("hello", "world");
  3483. params.emplace("hello2", "world2");
  3484. params.emplace("hello3", "world3");
  3485. auto res = cli.Get("/", params, Headers{});
  3486. ASSERT_TRUE(res);
  3487. EXPECT_EQ(200, res->status);
  3488. }
  3489. {
  3490. Client cli(HOST, PORT);
  3491. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3492. ASSERT_TRUE(res);
  3493. EXPECT_EQ(200, res->status);
  3494. }
  3495. {
  3496. Client cli(HOST, PORT);
  3497. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3498. ASSERT_TRUE(res);
  3499. EXPECT_EQ(200, res->status);
  3500. }
  3501. svr.stop();
  3502. listen_thread.join();
  3503. ASSERT_FALSE(svr.is_running());
  3504. }
  3505. TEST(GetWithParametersTest, GetWithParameters2) {
  3506. Server svr;
  3507. svr.Get("/", [&](const Request &req, Response &res) {
  3508. auto text = req.get_param_value("hello");
  3509. res.set_content(text, "text/plain");
  3510. });
  3511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3512. while (!svr.is_running()) {
  3513. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3514. }
  3515. std::this_thread::sleep_for(std::chrono::seconds(1));
  3516. Client cli("localhost", PORT);
  3517. Params params;
  3518. params.emplace("hello", "world");
  3519. std::string body;
  3520. auto res = cli.Get("/", params, Headers{},
  3521. [&](const char *data, size_t data_length) {
  3522. body.append(data, data_length);
  3523. return true;
  3524. });
  3525. ASSERT_TRUE(res);
  3526. EXPECT_EQ(200, res->status);
  3527. EXPECT_EQ("world", body);
  3528. svr.stop();
  3529. listen_thread.join();
  3530. ASSERT_FALSE(svr.is_running());
  3531. }
  3532. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3533. Client cli("httpbin.org");
  3534. cli.set_default_headers({make_range_header({{1, 10}})});
  3535. cli.set_connection_timeout(5);
  3536. {
  3537. auto res = cli.Get("/range/32");
  3538. ASSERT_TRUE(res);
  3539. EXPECT_EQ("bcdefghijk", res->body);
  3540. EXPECT_EQ(206, res->status);
  3541. }
  3542. {
  3543. auto res = cli.Get("/range/32");
  3544. ASSERT_TRUE(res);
  3545. EXPECT_EQ("bcdefghijk", res->body);
  3546. EXPECT_EQ(206, res->status);
  3547. }
  3548. }
  3549. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3550. Server svr;
  3551. svr.set_default_headers({{"Hello", "World"}});
  3552. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3553. res.set_content("ok", "text/plain");
  3554. });
  3555. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3556. while (!svr.is_running()) {
  3557. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3558. }
  3559. std::this_thread::sleep_for(std::chrono::seconds(1));
  3560. Client cli("localhost", PORT);
  3561. auto res = cli.Get("/");
  3562. ASSERT_TRUE(res);
  3563. EXPECT_EQ(200, res->status);
  3564. EXPECT_EQ("ok", res->body);
  3565. EXPECT_EQ("World", res->get_header_value("Hello"));
  3566. svr.stop();
  3567. listen_thread.join();
  3568. ASSERT_FALSE(svr.is_running());
  3569. }
  3570. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3571. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3573. ASSERT_TRUE(svr.is_valid());
  3574. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3575. std::this_thread::sleep_for(std::chrono::seconds(2));
  3576. res.set_content("a", "text/plain");
  3577. });
  3578. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3579. res.set_content("b", "text/plain");
  3580. });
  3581. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3582. while (!svr.is_running()) {
  3583. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3584. }
  3585. // Give GET time to get a few messages.
  3586. std::this_thread::sleep_for(std::chrono::seconds(1));
  3587. SSLClient cli("localhost", PORT);
  3588. cli.enable_server_certificate_verification(false);
  3589. cli.set_keep_alive(true);
  3590. cli.set_read_timeout(std::chrono::seconds(1));
  3591. auto resa = cli.Get("/a");
  3592. ASSERT_TRUE(!resa);
  3593. EXPECT_EQ(Error::Read, resa.error());
  3594. auto resb = cli.Get("/b");
  3595. ASSERT_TRUE(resb);
  3596. EXPECT_EQ(200, resb->status);
  3597. EXPECT_EQ("b", resb->body);
  3598. svr.stop();
  3599. listen_thread.join();
  3600. ASSERT_FALSE(svr.is_running());
  3601. }
  3602. #endif
  3603. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3604. protected:
  3605. ServerTestWithAI_PASSIVE()
  3606. : cli_(HOST, PORT)
  3607. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3608. ,
  3609. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3610. #endif
  3611. {
  3612. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3613. cli_.enable_server_certificate_verification(false);
  3614. #endif
  3615. }
  3616. virtual void SetUp() {
  3617. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3618. res.set_content("Hello World!", "text/plain");
  3619. });
  3620. t_ = thread(
  3621. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  3622. while (!svr_.is_running()) {
  3623. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3624. }
  3625. }
  3626. virtual void TearDown() {
  3627. svr_.stop();
  3628. t_.join();
  3629. }
  3630. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3631. SSLClient cli_;
  3632. SSLServer svr_;
  3633. #else
  3634. Client cli_;
  3635. Server svr_;
  3636. #endif
  3637. thread t_;
  3638. };
  3639. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3640. auto res = cli_.Get("/hi");
  3641. ASSERT_TRUE(res);
  3642. EXPECT_EQ(200, res->status);
  3643. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3644. EXPECT_EQ("Hello World!", res->body);
  3645. }
  3646. class ServerUpDownTest : public ::testing::Test {
  3647. protected:
  3648. ServerUpDownTest() : cli_(HOST, PORT) {}
  3649. virtual void SetUp() {
  3650. t_ = thread([&]() {
  3651. svr_.bind_to_any_port(HOST);
  3652. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3653. ASSERT_TRUE(svr_.listen_after_bind());
  3654. });
  3655. while (!svr_.is_running()) {
  3656. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3657. }
  3658. }
  3659. virtual void TearDown() {
  3660. svr_.stop();
  3661. t_.join();
  3662. }
  3663. Client cli_;
  3664. Server svr_;
  3665. thread t_;
  3666. };
  3667. TEST_F(ServerUpDownTest, QuickStartStop) {
  3668. // Should not crash, especially when run with
  3669. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3670. }
  3671. class PayloadMaxLengthTest : public ::testing::Test {
  3672. protected:
  3673. PayloadMaxLengthTest()
  3674. : cli_(HOST, PORT)
  3675. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3676. ,
  3677. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3678. #endif
  3679. {
  3680. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3681. cli_.enable_server_certificate_verification(false);
  3682. #endif
  3683. }
  3684. virtual void SetUp() {
  3685. svr_.set_payload_max_length(8);
  3686. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  3687. res.set_content("test", "text/plain");
  3688. });
  3689. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3690. while (!svr_.is_running()) {
  3691. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3692. }
  3693. }
  3694. virtual void TearDown() {
  3695. svr_.stop();
  3696. t_.join();
  3697. }
  3698. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3699. SSLClient cli_;
  3700. SSLServer svr_;
  3701. #else
  3702. Client cli_;
  3703. Server svr_;
  3704. #endif
  3705. thread t_;
  3706. };
  3707. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  3708. auto res = cli_.Post("/test", "123456789", "text/plain");
  3709. ASSERT_TRUE(res);
  3710. EXPECT_EQ(413, res->status);
  3711. res = cli_.Post("/test", "12345678", "text/plain");
  3712. ASSERT_TRUE(res);
  3713. EXPECT_EQ(200, res->status);
  3714. }
  3715. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3716. TEST(SSLClientTest, UpdateCAStore) {
  3717. httplib::SSLClient httplib_client("www.google.com");
  3718. auto ca_store_1 = X509_STORE_new();
  3719. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  3720. nullptr);
  3721. httplib_client.set_ca_cert_store(ca_store_1);
  3722. auto ca_store_2 = X509_STORE_new();
  3723. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  3724. nullptr);
  3725. httplib_client.set_ca_cert_store(ca_store_2);
  3726. }
  3727. TEST(SSLClientTest, ServerNameIndication_Online) {
  3728. SSLClient cli("httpbin.org", 443);
  3729. auto res = cli.Get("/get");
  3730. ASSERT_TRUE(res);
  3731. ASSERT_EQ(200, res->status);
  3732. }
  3733. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  3734. SSLClient cli("google.com");
  3735. auto res = cli.Get("/");
  3736. ASSERT_TRUE(res);
  3737. ASSERT_EQ(301, res->status);
  3738. }
  3739. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  3740. SSLClient cli("google.com");
  3741. cli.enable_server_certificate_verification(true);
  3742. cli.set_ca_cert_path("hello");
  3743. auto res = cli.Get("/");
  3744. ASSERT_TRUE(!res);
  3745. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  3746. }
  3747. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  3748. SSLClient cli("google.com");
  3749. cli.set_ca_cert_path(CA_CERT_FILE);
  3750. auto res = cli.Get("/");
  3751. ASSERT_TRUE(res);
  3752. ASSERT_EQ(301, res->status);
  3753. }
  3754. TEST(SSLClientTest, ServerCertificateVerification4) {
  3755. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3756. ASSERT_TRUE(svr.is_valid());
  3757. svr.Get("/test", [&](const Request &, Response &res) {
  3758. res.set_content("test", "text/plain");
  3759. svr.stop();
  3760. ASSERT_TRUE(true);
  3761. });
  3762. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3763. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3764. SSLClient cli("127.0.0.1", PORT);
  3765. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3766. cli.enable_server_certificate_verification(true);
  3767. cli.set_connection_timeout(30);
  3768. auto res = cli.Get("/test");
  3769. ASSERT_TRUE(res);
  3770. ASSERT_EQ(200, res->status);
  3771. t.join();
  3772. }
  3773. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  3774. SSLClient cli("www.youtube.com");
  3775. cli.set_ca_cert_path(CA_CERT_FILE);
  3776. cli.enable_server_certificate_verification(true);
  3777. cli.set_follow_location(true);
  3778. auto res = cli.Get("/");
  3779. ASSERT_TRUE(res);
  3780. ASSERT_EQ(200, res->status);
  3781. }
  3782. #if 0
  3783. TEST(SSLClientTest, SetInterfaceWithINET6) {
  3784. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  3785. ASSERT_TRUE(cli != nullptr);
  3786. cli->set_address_family(AF_INET6);
  3787. cli->set_interface("en0");
  3788. auto res = cli->Get("/get");
  3789. ASSERT_TRUE(res);
  3790. ASSERT_EQ(200, res->status);
  3791. }
  3792. #endif
  3793. TEST(SSLClientServerTest, ClientCertPresent) {
  3794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3795. CLIENT_CA_CERT_DIR);
  3796. ASSERT_TRUE(svr.is_valid());
  3797. svr.Get("/test", [&](const Request &req, Response &res) {
  3798. res.set_content("test", "text/plain");
  3799. svr.stop();
  3800. ASSERT_TRUE(true);
  3801. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3802. ASSERT_TRUE(peer_cert != nullptr);
  3803. auto subject_name = X509_get_subject_name(peer_cert);
  3804. ASSERT_TRUE(subject_name != nullptr);
  3805. std::string common_name;
  3806. {
  3807. char name[BUFSIZ];
  3808. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3809. name, sizeof(name));
  3810. common_name.assign(name, static_cast<size_t>(name_len));
  3811. }
  3812. EXPECT_EQ("Common Name", common_name);
  3813. X509_free(peer_cert);
  3814. });
  3815. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3816. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3817. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3818. cli.enable_server_certificate_verification(false);
  3819. cli.set_connection_timeout(30);
  3820. auto res = cli.Get("/test");
  3821. ASSERT_TRUE(res);
  3822. ASSERT_EQ(200, res->status);
  3823. t.join();
  3824. }
  3825. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  3826. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  3827. X509 *server_cert;
  3828. EVP_PKEY *server_private_key;
  3829. X509_STORE *client_ca_cert_store;
  3830. X509 *client_cert;
  3831. EVP_PKEY *client_private_key;
  3832. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  3833. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3834. fclose(f);
  3835. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  3836. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3837. fclose(f);
  3838. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  3839. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3840. client_ca_cert_store = X509_STORE_new();
  3841. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  3842. X509_free(client_cert);
  3843. fclose(f);
  3844. f = fopen(CLIENT_CERT_FILE, "r+");
  3845. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3846. fclose(f);
  3847. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  3848. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3849. fclose(f);
  3850. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  3851. ASSERT_TRUE(svr.is_valid());
  3852. svr.Get("/test", [&](const Request &req, Response &res) {
  3853. res.set_content("test", "text/plain");
  3854. svr.stop();
  3855. ASSERT_TRUE(true);
  3856. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3857. ASSERT_TRUE(peer_cert != nullptr);
  3858. auto subject_name = X509_get_subject_name(peer_cert);
  3859. ASSERT_TRUE(subject_name != nullptr);
  3860. std::string common_name;
  3861. {
  3862. char name[BUFSIZ];
  3863. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3864. name, sizeof(name));
  3865. common_name.assign(name, static_cast<size_t>(name_len));
  3866. }
  3867. EXPECT_EQ("Common Name", common_name);
  3868. X509_free(peer_cert);
  3869. });
  3870. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3871. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3872. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  3873. cli.enable_server_certificate_verification(false);
  3874. cli.set_connection_timeout(30);
  3875. auto res = cli.Get("/test");
  3876. ASSERT_TRUE(res);
  3877. ASSERT_EQ(200, res->status);
  3878. X509_free(server_cert);
  3879. EVP_PKEY_free(server_private_key);
  3880. X509_free(client_cert);
  3881. EVP_PKEY_free(client_private_key);
  3882. t.join();
  3883. }
  3884. #endif
  3885. TEST(SSLClientServerTest, ClientCertMissing) {
  3886. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3887. CLIENT_CA_CERT_DIR);
  3888. ASSERT_TRUE(svr.is_valid());
  3889. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  3890. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3891. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3892. SSLClient cli(HOST, PORT);
  3893. auto res = cli.Get("/test");
  3894. cli.set_connection_timeout(30);
  3895. ASSERT_TRUE(!res);
  3896. EXPECT_EQ(Error::SSLServerVerification, res.error());
  3897. svr.stop();
  3898. t.join();
  3899. }
  3900. TEST(SSLClientServerTest, TrustDirOptional) {
  3901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3902. ASSERT_TRUE(svr.is_valid());
  3903. svr.Get("/test", [&](const Request &, Response &res) {
  3904. res.set_content("test", "text/plain");
  3905. svr.stop();
  3906. });
  3907. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3908. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3909. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3910. cli.enable_server_certificate_verification(false);
  3911. cli.set_connection_timeout(30);
  3912. auto res = cli.Get("/test");
  3913. ASSERT_TRUE(res);
  3914. ASSERT_EQ(200, res->status);
  3915. t.join();
  3916. }
  3917. TEST(SSLClientServerTest, SSLConnectTimeout) {
  3918. class NoListenSSLServer : public SSLServer {
  3919. public:
  3920. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  3921. const char *client_ca_cert_file_path,
  3922. const char *client_ca_cert_dir_path = nullptr)
  3923. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  3924. client_ca_cert_dir_path),
  3925. stop_(false) {}
  3926. bool stop_;
  3927. private:
  3928. bool process_and_close_socket(socket_t /*sock*/) override {
  3929. // Don't create SSL context
  3930. while (!stop_) {
  3931. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3932. }
  3933. return true;
  3934. }
  3935. };
  3936. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  3937. CLIENT_CA_CERT_FILE);
  3938. ASSERT_TRUE(svr.is_valid());
  3939. svr.Get("/test", [&](const Request &, Response &res) {
  3940. res.set_content("test", "text/plain");
  3941. });
  3942. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3943. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3944. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3945. cli.enable_server_certificate_verification(false);
  3946. cli.set_connection_timeout(1);
  3947. auto res = cli.Get("/test");
  3948. ASSERT_TRUE(!res);
  3949. EXPECT_EQ(Error::SSLConnection, res.error());
  3950. svr.stop_ = true;
  3951. svr.stop();
  3952. t.join();
  3953. }
  3954. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  3955. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  3956. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  3957. SSL_CTX_set_options(&ssl_ctx,
  3958. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  3959. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  3960. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  3961. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  3962. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  3963. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  3964. "ECDHE-DSS-AES128-SHA256:"
  3965. "ECDHE-RSA-AES256-SHA256:"
  3966. "ECDHE-DSS-AES256-SHA256:";
  3967. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  3968. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  3969. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  3970. SSL_FILETYPE_PEM) != 1) {
  3971. return false;
  3972. }
  3973. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  3974. CLIENT_CA_CERT_DIR);
  3975. SSL_CTX_set_verify(
  3976. &ssl_ctx,
  3977. SSL_VERIFY_PEER |
  3978. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  3979. nullptr);
  3980. return true;
  3981. };
  3982. SSLServer svr(setup_ssl_ctx_callback);
  3983. ASSERT_TRUE(svr.is_valid());
  3984. svr.Get("/test", [&](const Request &req, Response &res) {
  3985. res.set_content("test", "text/plain");
  3986. svr.stop();
  3987. ASSERT_TRUE(true);
  3988. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3989. ASSERT_TRUE(peer_cert != nullptr);
  3990. auto subject_name = X509_get_subject_name(peer_cert);
  3991. ASSERT_TRUE(subject_name != nullptr);
  3992. std::string common_name;
  3993. {
  3994. char name[BUFSIZ];
  3995. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3996. name, sizeof(name));
  3997. common_name.assign(name, static_cast<size_t>(name_len));
  3998. }
  3999. EXPECT_EQ("Common Name", common_name);
  4000. X509_free(peer_cert);
  4001. });
  4002. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4003. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4004. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4005. cli.enable_server_certificate_verification(false);
  4006. cli.set_connection_timeout(30);
  4007. auto res = cli.Get("/test");
  4008. ASSERT_TRUE(res);
  4009. ASSERT_EQ(200, res->status);
  4010. t.join();
  4011. }
  4012. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  4013. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  4014. // prepare large data
  4015. std::random_device seed_gen;
  4016. std::mt19937 random(seed_gen());
  4017. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  4018. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  4019. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  4020. // server
  4021. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4022. ASSERT_TRUE(svr.is_valid());
  4023. svr.Post("/binary", [&](const Request &req, Response &res) {
  4024. EXPECT_EQ(large_size_byte, req.body.size());
  4025. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  4026. res.set_content(req.body, "application/octet-stream");
  4027. });
  4028. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4029. while (!svr.is_running()) {
  4030. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4031. }
  4032. // client POST
  4033. SSLClient cli("localhost", PORT);
  4034. cli.enable_server_certificate_verification(false);
  4035. cli.set_read_timeout(std::chrono::seconds(100));
  4036. cli.set_write_timeout(std::chrono::seconds(100));
  4037. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  4038. large_size_byte, "application/octet-stream");
  4039. // compare
  4040. EXPECT_EQ(200, res->status);
  4041. EXPECT_EQ(large_size_byte, res->body.size());
  4042. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  4043. // cleanup
  4044. svr.stop();
  4045. listen_thread.join();
  4046. ASSERT_FALSE(svr.is_running());
  4047. }
  4048. #endif
  4049. #ifdef _WIN32
  4050. TEST(CleanupTest, WSACleanup) {
  4051. int ret = WSACleanup();
  4052. ASSERT_EQ(0, ret);
  4053. }
  4054. #endif
  4055. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  4056. TEST(NoSSLSupport, SimpleInterface) {
  4057. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  4058. }
  4059. #endif
  4060. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4061. TEST(InvalidScheme, SimpleInterface) {
  4062. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  4063. }
  4064. #endif
  4065. TEST(NoScheme, SimpleInterface) {
  4066. Client cli("yahoo.com:80");
  4067. ASSERT_TRUE(cli.is_valid());
  4068. }
  4069. TEST(SendAPI, SimpleInterface_Online) {
  4070. Client cli("http://yahoo.com");
  4071. Request req;
  4072. req.method = "GET";
  4073. req.path = "/";
  4074. auto res = cli.send(req);
  4075. ASSERT_TRUE(res);
  4076. EXPECT_EQ(301, res->status);
  4077. }
  4078. TEST(ClientImplMethods, GetSocketTest) {
  4079. httplib::Server svr;
  4080. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4081. res.status = 200;
  4082. });
  4083. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  4084. while (!svr.is_running()) {
  4085. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  4086. }
  4087. {
  4088. httplib::Client cli("http://127.0.0.1:3333");
  4089. cli.set_keep_alive(true);
  4090. // Use the behavior of cpp-httplib of opening the connection
  4091. // only when the first request happens. If that changes,
  4092. // this test would be obsolete.
  4093. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  4094. // This also implicitly tests the server. But other tests would fail much
  4095. // earlier than this one to be considered.
  4096. auto res = cli.Get("/");
  4097. ASSERT_TRUE(res);
  4098. EXPECT_EQ(200, res->status);
  4099. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  4100. }
  4101. svr.stop();
  4102. thread.join();
  4103. ASSERT_FALSE(svr.is_running());
  4104. }
  4105. // Disabled due to out-of-memory problem on GitHub Actions
  4106. #ifdef _WIN64
  4107. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  4108. // allocate content size larger than 2GB in memory
  4109. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  4110. char *content = (char *)malloc(content_size);
  4111. ASSERT_TRUE(content);
  4112. Server svr;
  4113. svr.Get("/foo", [=](const httplib::Request &req, httplib::Response &resp) {
  4114. resp.set_content(content, content_size, "application/octet-stream");
  4115. });
  4116. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4117. while (!svr.is_running()) {
  4118. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4119. }
  4120. // Give GET time to get a few messages.
  4121. std::this_thread::sleep_for(std::chrono::seconds(1));
  4122. Client cli(HOST, PORT);
  4123. auto res = cli.Get("/foo");
  4124. ASSERT_TRUE(res);
  4125. EXPECT_EQ(200, res->status);
  4126. EXPECT_EQ(content_size, res->body.length());
  4127. free(content);
  4128. svr.stop();
  4129. listen_thread.join();
  4130. ASSERT_FALSE(svr.is_running());
  4131. }
  4132. #endif
  4133. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4134. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  4135. Client cli("http://yahoo.com");
  4136. auto res = cli.Get("/");
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(301, res->status);
  4139. cli.set_follow_location(true);
  4140. res = cli.Get("/");
  4141. ASSERT_TRUE(res);
  4142. EXPECT_EQ(200, res->status);
  4143. EXPECT_EQ("https://yahoo.com/", res->location);
  4144. }
  4145. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  4146. Client cli("https://yahoo.com");
  4147. auto res = cli.Get("/");
  4148. ASSERT_TRUE(res);
  4149. EXPECT_EQ(301, res->status);
  4150. cli.set_follow_location(true);
  4151. res = cli.Get("/");
  4152. ASSERT_TRUE(res);
  4153. EXPECT_EQ(200, res->status);
  4154. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4155. }
  4156. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  4157. Client cli("https://yahoo.com");
  4158. auto res = cli.Get("/");
  4159. ASSERT_TRUE(res);
  4160. ASSERT_FALSE(!res);
  4161. ASSERT_TRUE(res);
  4162. ASSERT_FALSE(res == nullptr);
  4163. ASSERT_TRUE(res != nullptr);
  4164. EXPECT_EQ(Error::Success, res.error());
  4165. EXPECT_EQ(301, res.value().status);
  4166. EXPECT_EQ(301, (*res).status);
  4167. EXPECT_EQ(301, res->status);
  4168. cli.set_follow_location(true);
  4169. res = cli.Get("/");
  4170. ASSERT_TRUE(res);
  4171. EXPECT_EQ(Error::Success, res.error());
  4172. EXPECT_EQ(200, res.value().status);
  4173. EXPECT_EQ(200, (*res).status);
  4174. EXPECT_EQ(200, res->status);
  4175. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4176. }
  4177. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4178. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  4179. Client cli("https://cdnjs.cloudflare.com");
  4180. auto res =
  4181. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  4182. ASSERT_TRUE(res);
  4183. EXPECT_EQ(200, res->status);
  4184. EXPECT_EQ(287630U, res->body.size());
  4185. EXPECT_EQ("application/javascript; charset=utf-8",
  4186. res->get_header_value("Content-Type"));
  4187. }
  4188. #endif
  4189. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  4190. Client cli("https://nghttp2.org");
  4191. cli.set_follow_location(true);
  4192. auto res =
  4193. cli.Get("/httpbin/"
  4194. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  4195. ASSERT_TRUE(res);
  4196. EXPECT_EQ(200, res->status);
  4197. }
  4198. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  4199. Client cli("https://nghttp2.org");
  4200. cli.set_follow_location(true);
  4201. Params params;
  4202. params.emplace("url", "http://www.google.com");
  4203. params.emplace("status_code", "302");
  4204. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  4205. ASSERT_TRUE(res);
  4206. EXPECT_EQ(200, res->status);
  4207. }
  4208. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4209. Client cli("https://nghttp2.org");
  4210. cli.set_follow_location(true);
  4211. Params params;
  4212. params.emplace("url", "http://www.google.com");
  4213. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4214. ASSERT_TRUE(res);
  4215. EXPECT_EQ(200, res->status);
  4216. }
  4217. TEST(HttpToHttpsRedirectTest, CertFile) {
  4218. Server svr;
  4219. ASSERT_TRUE(svr.is_valid());
  4220. svr.Get("/index", [&](const Request &, Response &res) {
  4221. res.set_redirect("https://127.0.0.1:1235/index");
  4222. svr.stop();
  4223. });
  4224. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4225. ASSERT_TRUE(ssl_svr.is_valid());
  4226. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4227. res.set_content("test", "text/plain");
  4228. ssl_svr.stop();
  4229. });
  4230. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4231. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4232. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4233. Client cli("127.0.0.1", PORT);
  4234. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4235. cli.enable_server_certificate_verification(true);
  4236. cli.set_follow_location(true);
  4237. cli.set_connection_timeout(30);
  4238. auto res = cli.Get("/index");
  4239. ASSERT_TRUE(res);
  4240. ASSERT_EQ(200, res->status);
  4241. t.join();
  4242. t2.join();
  4243. }
  4244. TEST(MultipartFormDataTest, LargeData) {
  4245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4246. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4247. const ContentReader &content_reader) {
  4248. if (req.is_multipart_form_data()) {
  4249. MultipartFormDataItems files;
  4250. content_reader(
  4251. [&](const MultipartFormData &file) {
  4252. files.push_back(file);
  4253. return true;
  4254. },
  4255. [&](const char *data, size_t data_length) {
  4256. files.back().content.append(data, data_length);
  4257. return true;
  4258. });
  4259. EXPECT_TRUE(std::string(files[0].name) == "document");
  4260. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4261. EXPECT_TRUE(files[0].filename == "2MB_data");
  4262. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4263. EXPECT_TRUE(files[1].name == "hello");
  4264. EXPECT_TRUE(files[1].content == "world");
  4265. EXPECT_TRUE(files[1].filename == "");
  4266. EXPECT_TRUE(files[1].content_type == "");
  4267. } else {
  4268. std::string body;
  4269. content_reader([&](const char *data, size_t data_length) {
  4270. body.append(data, data_length);
  4271. return true;
  4272. });
  4273. }
  4274. });
  4275. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4276. while (!svr.is_running()) {
  4277. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4278. }
  4279. std::this_thread::sleep_for(std::chrono::seconds(1));
  4280. {
  4281. std::string data(1024 * 1024 * 2, '.');
  4282. std::stringstream buffer;
  4283. buffer << data;
  4284. Client cli("https://localhost:8080");
  4285. cli.enable_server_certificate_verification(false);
  4286. MultipartFormDataItems items{
  4287. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4288. {"hello", "world", "", ""},
  4289. };
  4290. auto res = cli.Post("/post", items);
  4291. ASSERT_TRUE(res);
  4292. ASSERT_EQ(200, res->status);
  4293. }
  4294. svr.stop();
  4295. t.join();
  4296. }
  4297. TEST(MultipartFormDataTest, DataProviderItems) {
  4298. std::random_device seed_gen;
  4299. std::mt19937 random(seed_gen());
  4300. std::string rand1;
  4301. rand1.resize(1000);
  4302. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  4303. std::string rand2;
  4304. rand2.resize(3000);
  4305. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  4306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4307. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  4308. const ContentReader &content_reader) {
  4309. ASSERT_FALSE(req.is_multipart_form_data());
  4310. std::string body;
  4311. content_reader([&](const char *data, size_t data_length) {
  4312. body.append(data, data_length);
  4313. return true;
  4314. });
  4315. EXPECT_EQ(body, "");
  4316. });
  4317. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  4318. const ContentReader &content_reader) {
  4319. ASSERT_TRUE(req.is_multipart_form_data());
  4320. MultipartFormDataItems files;
  4321. content_reader(
  4322. [&](const MultipartFormData &file) {
  4323. files.push_back(file);
  4324. return true;
  4325. },
  4326. [&](const char *data, size_t data_length) {
  4327. files.back().content.append(data, data_length);
  4328. return true;
  4329. });
  4330. ASSERT_TRUE(files.size() == 2);
  4331. EXPECT_EQ(std::string(files[0].name), "name1");
  4332. EXPECT_EQ(files[0].content, "Testing123");
  4333. EXPECT_EQ(files[0].filename, "filename1");
  4334. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4335. EXPECT_EQ(files[1].name, "name2");
  4336. EXPECT_EQ(files[1].content, "Testing456");
  4337. EXPECT_EQ(files[1].filename, "");
  4338. EXPECT_EQ(files[1].content_type, "");
  4339. });
  4340. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  4341. const ContentReader &content_reader) {
  4342. ASSERT_TRUE(req.is_multipart_form_data());
  4343. MultipartFormDataItems files;
  4344. content_reader(
  4345. [&](const MultipartFormData &file) {
  4346. files.push_back(file);
  4347. return true;
  4348. },
  4349. [&](const char *data, size_t data_length) {
  4350. files.back().content.append(data, data_length);
  4351. return true;
  4352. });
  4353. ASSERT_TRUE(files.size() == 2);
  4354. EXPECT_EQ(files[0].name, "name3");
  4355. EXPECT_EQ(files[0].content, rand1);
  4356. EXPECT_EQ(files[0].filename, "filename3");
  4357. EXPECT_EQ(files[0].content_type, "");
  4358. EXPECT_EQ(files[1].name, "name4");
  4359. EXPECT_EQ(files[1].content, rand2);
  4360. EXPECT_EQ(files[1].filename, "filename4");
  4361. EXPECT_EQ(files[1].content_type, "");
  4362. });
  4363. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  4364. const ContentReader &content_reader) {
  4365. ASSERT_TRUE(req.is_multipart_form_data());
  4366. MultipartFormDataItems files;
  4367. content_reader(
  4368. [&](const MultipartFormData &file) {
  4369. files.push_back(file);
  4370. return true;
  4371. },
  4372. [&](const char *data, size_t data_length) {
  4373. files.back().content.append(data, data_length);
  4374. return true;
  4375. });
  4376. ASSERT_TRUE(files.size() == 4);
  4377. EXPECT_EQ(std::string(files[0].name), "name1");
  4378. EXPECT_EQ(files[0].content, "Testing123");
  4379. EXPECT_EQ(files[0].filename, "filename1");
  4380. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4381. EXPECT_EQ(files[1].name, "name2");
  4382. EXPECT_EQ(files[1].content, "Testing456");
  4383. EXPECT_EQ(files[1].filename, "");
  4384. EXPECT_EQ(files[1].content_type, "");
  4385. EXPECT_EQ(files[2].name, "name3");
  4386. EXPECT_EQ(files[2].content, rand1);
  4387. EXPECT_EQ(files[2].filename, "filename3");
  4388. EXPECT_EQ(files[2].content_type, "");
  4389. EXPECT_EQ(files[3].name, "name4");
  4390. EXPECT_EQ(files[3].content, rand2);
  4391. EXPECT_EQ(files[3].filename, "filename4");
  4392. EXPECT_EQ(files[3].content_type, "");
  4393. });
  4394. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4395. while (!svr.is_running()) {
  4396. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4397. }
  4398. std::this_thread::sleep_for(std::chrono::seconds(1));
  4399. {
  4400. Client cli("https://localhost:8080");
  4401. cli.enable_server_certificate_verification(false);
  4402. MultipartFormDataItems items{
  4403. {"name1", "Testing123", "filename1", "application/octet-stream"},
  4404. {"name2", "Testing456", "", ""}, // not a file
  4405. };
  4406. {
  4407. auto res = cli.Post("/post-none", {}, {}, {});
  4408. ASSERT_TRUE(res);
  4409. ASSERT_EQ(200, res->status);
  4410. }
  4411. MultipartFormDataProviderItems providers;
  4412. {
  4413. auto res =
  4414. cli.Post("/post-items", {}, items, providers); // empty providers
  4415. ASSERT_TRUE(res);
  4416. ASSERT_EQ(200, res->status);
  4417. }
  4418. providers.push_back({"name3",
  4419. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4420. // test the offset is given correctly at each step
  4421. if (!offset)
  4422. sink.os.write(rand1.data(), 30);
  4423. else if (offset == 30)
  4424. sink.os.write(rand1.data() + 30, 300);
  4425. else if (offset == 330)
  4426. sink.os.write(rand1.data() + 330, 670);
  4427. else if (offset == rand1.size())
  4428. sink.done();
  4429. return true;
  4430. },
  4431. "filename3",
  4432. {}});
  4433. providers.push_back({"name4",
  4434. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4435. // test the offset is given correctly at each step
  4436. if (!offset)
  4437. sink.os.write(rand2.data(), 2000);
  4438. else if (offset == 2000)
  4439. sink.os.write(rand2.data() + 2000, 1);
  4440. else if (offset == 2001)
  4441. sink.os.write(rand2.data() + 2001, 999);
  4442. else if (offset == rand2.size())
  4443. sink.done();
  4444. return true;
  4445. },
  4446. "filename4",
  4447. {}});
  4448. {
  4449. auto res = cli.Post("/post-providers", {}, {}, providers);
  4450. ASSERT_TRUE(res);
  4451. ASSERT_EQ(200, res->status);
  4452. }
  4453. {
  4454. auto res = cli.Post("/post-both", {}, items, providers);
  4455. ASSERT_TRUE(res);
  4456. ASSERT_EQ(200, res->status);
  4457. }
  4458. }
  4459. svr.stop();
  4460. t.join();
  4461. }
  4462. TEST(MultipartFormDataTest, BadHeader) {
  4463. Server svr;
  4464. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4465. res.set_content("ok", "text/plain");
  4466. });
  4467. thread t = thread([&] { svr.listen(HOST, PORT); });
  4468. while (!svr.is_running()) {
  4469. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4470. }
  4471. const std::string body =
  4472. "This is the preamble. It is to be ignored, though it\r\n"
  4473. "is a handy place for composition agents to include an\r\n"
  4474. "explanatory note to non-MIME conformant readers.\r\n"
  4475. "\r\n"
  4476. "\r\n"
  4477. "--simple boundary\r\n"
  4478. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4479. ": BAD...\r\n"
  4480. "\r\n"
  4481. "value1\r\n"
  4482. "--simple boundary\r\n"
  4483. "Content-Disposition: form-data; name=\"field2\"; "
  4484. "filename=\"example.txt\"\r\n"
  4485. "\r\n"
  4486. "value2\r\n"
  4487. "--simple boundary--\r\n"
  4488. "This is the epilogue. It is also to be ignored.\r\n";
  4489. std::string content_type =
  4490. R"(multipart/form-data; boundary="simple boundary")";
  4491. Client cli(HOST, PORT);
  4492. auto res = cli.Post("/post", body, content_type.c_str());
  4493. ASSERT_TRUE(res);
  4494. EXPECT_EQ(400, res->status);
  4495. svr.stop();
  4496. t.join();
  4497. }
  4498. TEST(MultipartFormDataTest, WithPreamble) {
  4499. Server svr;
  4500. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4501. res.set_content("ok", "text/plain");
  4502. });
  4503. thread t = thread([&] { svr.listen(HOST, PORT); });
  4504. while (!svr.is_running()) {
  4505. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4506. }
  4507. const std::string body =
  4508. "This is the preamble. It is to be ignored, though it\r\n"
  4509. "is a handy place for composition agents to include an\r\n"
  4510. "explanatory note to non-MIME conformant readers.\r\n"
  4511. "\r\n"
  4512. "\r\n"
  4513. "--simple boundary\r\n"
  4514. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4515. "\r\n"
  4516. "value1\r\n"
  4517. "--simple boundary\r\n"
  4518. "Content-Disposition: form-data; name=\"field2\"; "
  4519. "filename=\"example.txt\"\r\n"
  4520. "\r\n"
  4521. "value2\r\n"
  4522. "--simple boundary--\r\n"
  4523. "This is the epilogue. It is also to be ignored.\r\n";
  4524. std::string content_type =
  4525. R"(multipart/form-data; boundary="simple boundary")";
  4526. Client cli(HOST, PORT);
  4527. auto res = cli.Post("/post", body, content_type.c_str());
  4528. ASSERT_TRUE(res);
  4529. EXPECT_EQ(200, res->status);
  4530. svr.stop();
  4531. t.join();
  4532. }
  4533. TEST(MultipartFormDataTest, PostCustomBoundary) {
  4534. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4535. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  4536. const ContentReader &content_reader) {
  4537. if (req.is_multipart_form_data()) {
  4538. MultipartFormDataItems files;
  4539. content_reader(
  4540. [&](const MultipartFormData &file) {
  4541. files.push_back(file);
  4542. return true;
  4543. },
  4544. [&](const char *data, size_t data_length) {
  4545. files.back().content.append(data, data_length);
  4546. return true;
  4547. });
  4548. EXPECT_TRUE(std::string(files[0].name) == "document");
  4549. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4550. EXPECT_TRUE(files[0].filename == "2MB_data");
  4551. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4552. EXPECT_TRUE(files[1].name == "hello");
  4553. EXPECT_TRUE(files[1].content == "world");
  4554. EXPECT_TRUE(files[1].filename == "");
  4555. EXPECT_TRUE(files[1].content_type == "");
  4556. } else {
  4557. std::string body;
  4558. content_reader([&](const char *data, size_t data_length) {
  4559. body.append(data, data_length);
  4560. return true;
  4561. });
  4562. }
  4563. });
  4564. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4565. while (!svr.is_running()) {
  4566. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4567. }
  4568. std::this_thread::sleep_for(std::chrono::seconds(1));
  4569. {
  4570. std::string data(1024 * 1024 * 2, '.');
  4571. std::stringstream buffer;
  4572. buffer << data;
  4573. Client cli("https://localhost:8080");
  4574. cli.enable_server_certificate_verification(false);
  4575. MultipartFormDataItems items{
  4576. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4577. {"hello", "world", "", ""},
  4578. };
  4579. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  4580. ASSERT_TRUE(res);
  4581. ASSERT_EQ(200, res->status);
  4582. }
  4583. svr.stop();
  4584. t.join();
  4585. }
  4586. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  4587. std::this_thread::sleep_for(std::chrono::seconds(1));
  4588. std::string data(1024 * 1024 * 2, '&');
  4589. std::stringstream buffer;
  4590. buffer << data;
  4591. Client cli("https://localhost:8080");
  4592. MultipartFormDataItems items{
  4593. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4594. {"hello", "world", "", ""},
  4595. };
  4596. for (const char &c : " \t\r\n") {
  4597. auto res =
  4598. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  4599. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  4600. ASSERT_FALSE(res);
  4601. }
  4602. }
  4603. TEST(MultipartFormDataTest, PutFormData) {
  4604. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4605. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  4606. const ContentReader &content_reader) {
  4607. if (req.is_multipart_form_data()) {
  4608. MultipartFormDataItems files;
  4609. content_reader(
  4610. [&](const MultipartFormData &file) {
  4611. files.push_back(file);
  4612. return true;
  4613. },
  4614. [&](const char *data, size_t data_length) {
  4615. files.back().content.append(data, data_length);
  4616. return true;
  4617. });
  4618. EXPECT_TRUE(std::string(files[0].name) == "document");
  4619. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4620. EXPECT_TRUE(files[0].filename == "2MB_data");
  4621. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4622. EXPECT_TRUE(files[1].name == "hello");
  4623. EXPECT_TRUE(files[1].content == "world");
  4624. EXPECT_TRUE(files[1].filename == "");
  4625. EXPECT_TRUE(files[1].content_type == "");
  4626. } else {
  4627. std::string body;
  4628. content_reader([&](const char *data, size_t data_length) {
  4629. body.append(data, data_length);
  4630. return true;
  4631. });
  4632. }
  4633. });
  4634. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4635. while (!svr.is_running()) {
  4636. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4637. }
  4638. std::this_thread::sleep_for(std::chrono::seconds(1));
  4639. {
  4640. std::string data(1024 * 1024 * 2, '&');
  4641. std::stringstream buffer;
  4642. buffer << data;
  4643. Client cli("https://localhost:8080");
  4644. cli.enable_server_certificate_verification(false);
  4645. MultipartFormDataItems items{
  4646. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4647. {"hello", "world", "", ""},
  4648. };
  4649. auto res = cli.Put("/put", items);
  4650. ASSERT_TRUE(res);
  4651. ASSERT_EQ(200, res->status);
  4652. }
  4653. svr.stop();
  4654. t.join();
  4655. }
  4656. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  4657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4658. svr.Put("/put_customboundary",
  4659. [&](const Request &req, const Response & /*res*/,
  4660. const ContentReader &content_reader) {
  4661. if (req.is_multipart_form_data()) {
  4662. MultipartFormDataItems files;
  4663. content_reader(
  4664. [&](const MultipartFormData &file) {
  4665. files.push_back(file);
  4666. return true;
  4667. },
  4668. [&](const char *data, size_t data_length) {
  4669. files.back().content.append(data, data_length);
  4670. return true;
  4671. });
  4672. EXPECT_TRUE(std::string(files[0].name) == "document");
  4673. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4674. EXPECT_TRUE(files[0].filename == "2MB_data");
  4675. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4676. EXPECT_TRUE(files[1].name == "hello");
  4677. EXPECT_TRUE(files[1].content == "world");
  4678. EXPECT_TRUE(files[1].filename == "");
  4679. EXPECT_TRUE(files[1].content_type == "");
  4680. } else {
  4681. std::string body;
  4682. content_reader([&](const char *data, size_t data_length) {
  4683. body.append(data, data_length);
  4684. return true;
  4685. });
  4686. }
  4687. });
  4688. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4689. while (!svr.is_running()) {
  4690. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4691. }
  4692. std::this_thread::sleep_for(std::chrono::seconds(1));
  4693. {
  4694. std::string data(1024 * 1024 * 2, '&');
  4695. std::stringstream buffer;
  4696. buffer << data;
  4697. Client cli("https://localhost:8080");
  4698. cli.enable_server_certificate_verification(false);
  4699. MultipartFormDataItems items{
  4700. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4701. {"hello", "world", "", ""},
  4702. };
  4703. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  4704. ASSERT_TRUE(res);
  4705. ASSERT_EQ(200, res->status);
  4706. }
  4707. svr.stop();
  4708. t.join();
  4709. }
  4710. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  4711. std::this_thread::sleep_for(std::chrono::seconds(1));
  4712. std::string data(1024 * 1024 * 2, '&');
  4713. std::stringstream buffer;
  4714. buffer << data;
  4715. Client cli("https://localhost:8080");
  4716. cli.enable_server_certificate_verification(false);
  4717. MultipartFormDataItems items{
  4718. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4719. {"hello", "world", "", ""},
  4720. };
  4721. for (const char &c : " \t\r\n") {
  4722. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  4723. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  4724. ASSERT_FALSE(res);
  4725. }
  4726. }
  4727. #endif
  4728. #ifndef _WIN32
  4729. class UnixSocketTest : public ::testing::Test {
  4730. protected:
  4731. void TearDown() override { std::remove(pathname_.c_str()); }
  4732. void client_GET(const std::string &addr) {
  4733. httplib::Client cli{addr};
  4734. cli.set_address_family(AF_UNIX);
  4735. ASSERT_TRUE(cli.is_valid());
  4736. const auto &result = cli.Get(pattern_);
  4737. ASSERT_TRUE(result) << "error: " << result.error();
  4738. const auto &resp = result.value();
  4739. EXPECT_EQ(resp.status, 200);
  4740. EXPECT_EQ(resp.body, content_);
  4741. }
  4742. const std::string pathname_{"./httplib-server.sock"};
  4743. const std::string pattern_{"/hi"};
  4744. const std::string content_{"Hello World!"};
  4745. };
  4746. TEST_F(UnixSocketTest, pathname) {
  4747. httplib::Server svr;
  4748. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  4749. res.set_content(content_, "text/plain");
  4750. });
  4751. std::thread t{[&] {
  4752. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  4753. }};
  4754. while (!svr.is_running()) {
  4755. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4756. }
  4757. ASSERT_TRUE(svr.is_running());
  4758. client_GET(pathname_);
  4759. svr.stop();
  4760. t.join();
  4761. }
  4762. #if defined(__linux__) || \
  4763. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  4764. TEST_F(UnixSocketTest, PeerPid) {
  4765. httplib::Server svr;
  4766. std::string remote_port_val;
  4767. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  4768. res.set_content(content_, "text/plain");
  4769. remote_port_val = req.get_header_value("REMOTE_PORT");
  4770. });
  4771. std::thread t{[&] {
  4772. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  4773. }};
  4774. while (!svr.is_running()) {
  4775. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4776. }
  4777. ASSERT_TRUE(svr.is_running());
  4778. client_GET(pathname_);
  4779. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  4780. svr.stop();
  4781. t.join();
  4782. }
  4783. #endif
  4784. #ifdef __linux__
  4785. TEST_F(UnixSocketTest, abstract) {
  4786. constexpr char svr_path[]{"\x00httplib-server.sock"};
  4787. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  4788. httplib::Server svr;
  4789. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  4790. res.set_content(content_, "text/plain");
  4791. });
  4792. std::thread t{[&] {
  4793. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  4794. }};
  4795. while (!svr.is_running()) {
  4796. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4797. }
  4798. ASSERT_TRUE(svr.is_running());
  4799. client_GET(abstract_addr);
  4800. svr.stop();
  4801. t.join();
  4802. }
  4803. #endif
  4804. TEST(SocketStream, is_writable_UNIX) {
  4805. int fds[2];
  4806. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  4807. const auto asSocketStream = [&](socket_t fd,
  4808. std::function<bool(Stream &)> func) {
  4809. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  4810. };
  4811. asSocketStream(fds[0], [&](Stream &s0) {
  4812. EXPECT_EQ(s0.socket(), fds[0]);
  4813. EXPECT_TRUE(s0.is_writable());
  4814. EXPECT_EQ(0, close(fds[1]));
  4815. EXPECT_FALSE(s0.is_writable());
  4816. return true;
  4817. });
  4818. EXPECT_EQ(0, close(fds[0]));
  4819. }
  4820. TEST(SocketStream, is_writable_INET) {
  4821. sockaddr_in addr;
  4822. memset(&addr, 0, sizeof(addr));
  4823. addr.sin_family = AF_INET;
  4824. addr.sin_port = htons(PORT + 1);
  4825. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4826. int disconnected_svr_sock = -1;
  4827. std::thread svr{[&] {
  4828. const int s = socket(AF_INET, SOCK_STREAM, 0);
  4829. ASSERT_LE(0, s);
  4830. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4831. ASSERT_EQ(0, listen(s, 1));
  4832. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  4833. ASSERT_EQ(0, close(s));
  4834. }};
  4835. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4836. std::thread cli{[&] {
  4837. const int s = socket(AF_INET, SOCK_STREAM, 0);
  4838. ASSERT_LE(0, s);
  4839. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4840. ASSERT_EQ(0, close(s));
  4841. }};
  4842. cli.join();
  4843. svr.join();
  4844. ASSERT_NE(disconnected_svr_sock, -1);
  4845. const auto asSocketStream = [&](socket_t fd,
  4846. std::function<bool(Stream &)> func) {
  4847. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  4848. };
  4849. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  4850. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  4851. EXPECT_FALSE(ss.is_writable());
  4852. return true;
  4853. });
  4854. ASSERT_EQ(0, close(disconnected_svr_sock));
  4855. }
  4856. #endif // #ifndef _WIN32
  4857. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  4858. static constexpr unsigned int number_of_task{1000000};
  4859. std::atomic_uint count{0};
  4860. std::unique_ptr<TaskQueue> task_queue{
  4861. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  4862. for (unsigned int i = 0; i < number_of_task; ++i) {
  4863. task_queue->enqueue(
  4864. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  4865. }
  4866. EXPECT_NO_THROW(task_queue->shutdown());
  4867. EXPECT_EQ(number_of_task, count.load());
  4868. }