crow_all.h 495 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316
  1. // SPDX-License-Identifier: BSD-3-Clause AND ISC AND MIT
  2. /*BSD 3-Clause License
  3. Copyright (c) 2014-2017, ipkn
  4. 2020-2022, CrowCpp
  5. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above copyright notice, this
  9. list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above copyright notice,
  11. this list of conditions and the following disclaimer in the documentation
  12. and/or other materials provided with the distribution.
  13. * Neither the name of the author nor the names of its
  14. contributors may be used to endorse or promote products derived from
  15. this software without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. The Crow logo and other graphic material (excluding third party logos) used are under exclusive Copyright (c) 2021-2022, Farook Al-Sammarraie (The-EDev), All rights reserved.
  27. */
  28. #pragma once
  29. // This file is generated from nginx/conf/mime.types using nginx_mime2cpp.py on 2021-12-03.
  30. #include <unordered_map>
  31. #include <string>
  32. namespace crow
  33. {
  34. const std::unordered_map<std::string, std::string> mime_types{
  35. {"shtml", "text/html"},
  36. {"htm", "text/html"},
  37. {"html", "text/html"},
  38. {"css", "text/css"},
  39. {"xml", "text/xml"},
  40. {"gif", "image/gif"},
  41. {"jpg", "image/jpeg"},
  42. {"jpeg", "image/jpeg"},
  43. {"js", "application/javascript"},
  44. {"atom", "application/atom+xml"},
  45. {"rss", "application/rss+xml"},
  46. {"mml", "text/mathml"},
  47. {"txt", "text/plain"},
  48. {"jad", "text/vnd.sun.j2me.app-descriptor"},
  49. {"wml", "text/vnd.wap.wml"},
  50. {"htc", "text/x-component"},
  51. {"avif", "image/avif"},
  52. {"png", "image/png"},
  53. {"svgz", "image/svg+xml"},
  54. {"svg", "image/svg+xml"},
  55. {"tiff", "image/tiff"},
  56. {"tif", "image/tiff"},
  57. {"wbmp", "image/vnd.wap.wbmp"},
  58. {"webp", "image/webp"},
  59. {"ico", "image/x-icon"},
  60. {"jng", "image/x-jng"},
  61. {"bmp", "image/x-ms-bmp"},
  62. {"woff", "font/woff"},
  63. {"woff2", "font/woff2"},
  64. {"ear", "application/java-archive"},
  65. {"war", "application/java-archive"},
  66. {"jar", "application/java-archive"},
  67. {"json", "application/json"},
  68. {"hqx", "application/mac-binhex40"},
  69. {"doc", "application/msword"},
  70. {"pdf", "application/pdf"},
  71. {"ai", "application/postscript"},
  72. {"eps", "application/postscript"},
  73. {"ps", "application/postscript"},
  74. {"rtf", "application/rtf"},
  75. {"m3u8", "application/vnd.apple.mpegurl"},
  76. {"kml", "application/vnd.google-earth.kml+xml"},
  77. {"kmz", "application/vnd.google-earth.kmz"},
  78. {"xls", "application/vnd.ms-excel"},
  79. {"eot", "application/vnd.ms-fontobject"},
  80. {"ppt", "application/vnd.ms-powerpoint"},
  81. {"odg", "application/vnd.oasis.opendocument.graphics"},
  82. {"odp", "application/vnd.oasis.opendocument.presentation"},
  83. {"ods", "application/vnd.oasis.opendocument.spreadsheet"},
  84. {"odt", "application/vnd.oasis.opendocument.text"},
  85. {"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
  86. {"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
  87. {"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
  88. {"wmlc", "application/vnd.wap.wmlc"},
  89. {"wasm", "application/wasm"},
  90. {"7z", "application/x-7z-compressed"},
  91. {"cco", "application/x-cocoa"},
  92. {"jardiff", "application/x-java-archive-diff"},
  93. {"jnlp", "application/x-java-jnlp-file"},
  94. {"run", "application/x-makeself"},
  95. {"pm", "application/x-perl"},
  96. {"pl", "application/x-perl"},
  97. {"pdb", "application/x-pilot"},
  98. {"prc", "application/x-pilot"},
  99. {"rar", "application/x-rar-compressed"},
  100. {"rpm", "application/x-redhat-package-manager"},
  101. {"sea", "application/x-sea"},
  102. {"swf", "application/x-shockwave-flash"},
  103. {"sit", "application/x-stuffit"},
  104. {"tk", "application/x-tcl"},
  105. {"tcl", "application/x-tcl"},
  106. {"crt", "application/x-x509-ca-cert"},
  107. {"pem", "application/x-x509-ca-cert"},
  108. {"der", "application/x-x509-ca-cert"},
  109. {"xpi", "application/x-xpinstall"},
  110. {"xhtml", "application/xhtml+xml"},
  111. {"xspf", "application/xspf+xml"},
  112. {"zip", "application/zip"},
  113. {"dll", "application/octet-stream"},
  114. {"exe", "application/octet-stream"},
  115. {"bin", "application/octet-stream"},
  116. {"deb", "application/octet-stream"},
  117. {"dmg", "application/octet-stream"},
  118. {"img", "application/octet-stream"},
  119. {"iso", "application/octet-stream"},
  120. {"msm", "application/octet-stream"},
  121. {"msp", "application/octet-stream"},
  122. {"msi", "application/octet-stream"},
  123. {"kar", "audio/midi"},
  124. {"midi", "audio/midi"},
  125. {"mid", "audio/midi"},
  126. {"mp3", "audio/mpeg"},
  127. {"ogg", "audio/ogg"},
  128. {"m4a", "audio/x-m4a"},
  129. {"ra", "audio/x-realaudio"},
  130. {"3gp", "video/3gpp"},
  131. {"3gpp", "video/3gpp"},
  132. {"ts", "video/mp2t"},
  133. {"mp4", "video/mp4"},
  134. {"mpg", "video/mpeg"},
  135. {"mpeg", "video/mpeg"},
  136. {"mov", "video/quicktime"},
  137. {"webm", "video/webm"},
  138. {"flv", "video/x-flv"},
  139. {"m4v", "video/x-m4v"},
  140. {"mng", "video/x-mng"},
  141. {"asf", "video/x-ms-asf"},
  142. {"asx", "video/x-ms-asf"},
  143. {"wmv", "video/x-ms-wmv"},
  144. {"avi", "video/x-msvideo"}};
  145. }
  146. #include <string>
  147. namespace crow
  148. {
  149. /// An abstract class that allows any other class to be returned by a handler.
  150. struct returnable
  151. {
  152. std::string content_type;
  153. virtual std::string dump() const = 0;
  154. returnable(std::string ctype):
  155. content_type{ctype}
  156. {}
  157. virtual ~returnable(){};
  158. };
  159. } // namespace crow
  160. #include <stdio.h>
  161. #include <string.h>
  162. #include <string>
  163. #include <vector>
  164. #include <unordered_map>
  165. #include <iostream>
  166. #include <memory>
  167. namespace crow
  168. {
  169. // ----------------------------------------------------------------------------
  170. // qs_parse (modified)
  171. // https://github.com/bartgrantham/qs_parse
  172. // ----------------------------------------------------------------------------
  173. /* Similar to strncmp, but handles URL-encoding for either string */
  174. int qs_strncmp(const char* s, const char* qs, size_t n);
  175. /* Finds the beginning of each key/value pair and stores a pointer in qs_kv.
  176. * Also decodes the value portion of the k/v pair *in-place*. In a future
  177. * enhancement it will also have a compile-time option of sorting qs_kv
  178. * alphabetically by key. */
  179. size_t qs_parse(char* qs, char* qs_kv[], size_t qs_kv_size, bool parse_url);
  180. /* Used by qs_parse to decode the value portion of a k/v pair */
  181. int qs_decode(char * qs);
  182. /* Looks up the value according to the key on a pre-processed query string
  183. * A future enhancement will be a compile-time option to look up the key
  184. * in a pre-sorted qs_kv array via a binary search. */
  185. //char * qs_k2v(const char * key, char * qs_kv[], int qs_kv_size);
  186. char * qs_k2v(const char * key, char * const * qs_kv, size_t qs_kv_size, int nth);
  187. /* Non-destructive lookup of value, based on key. User provides the
  188. * destinaton string and length. */
  189. char * qs_scanvalue(const char * key, const char * qs, char * val, size_t val_len);
  190. // TODO: implement sorting of the qs_kv array; for now ensure it's not compiled
  191. #undef _qsSORTING
  192. // isxdigit _is_ available in <ctype.h>, but let's avoid another header instead
  193. #define CROW_QS_ISHEX(x) ((((x)>='0'&&(x)<='9') || ((x)>='A'&&(x)<='F') || ((x)>='a'&&(x)<='f')) ? 1 : 0)
  194. #define CROW_QS_HEX2DEC(x) (((x)>='0'&&(x)<='9') ? (x)-48 : ((x)>='A'&&(x)<='F') ? (x)-55 : ((x)>='a'&&(x)<='f') ? (x)-87 : 0)
  195. #define CROW_QS_ISQSCHR(x) ((((x)=='=')||((x)=='#')||((x)=='&')||((x)=='\0')) ? 0 : 1)
  196. inline int qs_strncmp(const char * s, const char * qs, size_t n)
  197. {
  198. unsigned char u1, u2, unyb, lnyb;
  199. while(n-- > 0)
  200. {
  201. u1 = static_cast<unsigned char>(*s++);
  202. u2 = static_cast<unsigned char>(*qs++);
  203. if ( ! CROW_QS_ISQSCHR(u1) ) { u1 = '\0'; }
  204. if ( ! CROW_QS_ISQSCHR(u2) ) { u2 = '\0'; }
  205. if ( u1 == '+' ) { u1 = ' '; }
  206. if ( u1 == '%' ) // easier/safer than scanf
  207. {
  208. unyb = static_cast<unsigned char>(*s++);
  209. lnyb = static_cast<unsigned char>(*s++);
  210. if ( CROW_QS_ISHEX(unyb) && CROW_QS_ISHEX(lnyb) )
  211. u1 = (CROW_QS_HEX2DEC(unyb) * 16) + CROW_QS_HEX2DEC(lnyb);
  212. else
  213. u1 = '\0';
  214. }
  215. if ( u2 == '+' ) { u2 = ' '; }
  216. if ( u2 == '%' ) // easier/safer than scanf
  217. {
  218. unyb = static_cast<unsigned char>(*qs++);
  219. lnyb = static_cast<unsigned char>(*qs++);
  220. if ( CROW_QS_ISHEX(unyb) && CROW_QS_ISHEX(lnyb) )
  221. u2 = (CROW_QS_HEX2DEC(unyb) * 16) + CROW_QS_HEX2DEC(lnyb);
  222. else
  223. u2 = '\0';
  224. }
  225. if ( u1 != u2 )
  226. return u1 - u2;
  227. if ( u1 == '\0' )
  228. return 0;
  229. }
  230. if ( CROW_QS_ISQSCHR(*qs) )
  231. return -1;
  232. else
  233. return 0;
  234. }
  235. inline size_t qs_parse(char* qs, char* qs_kv[], size_t qs_kv_size, bool parse_url = true)
  236. {
  237. size_t i, j;
  238. char * substr_ptr;
  239. for(i=0; i<qs_kv_size; i++) qs_kv[i] = NULL;
  240. // find the beginning of the k/v substrings or the fragment
  241. substr_ptr = parse_url ? qs + strcspn(qs, "?#") : qs;
  242. if (parse_url)
  243. {
  244. if (substr_ptr[0] != '\0')
  245. substr_ptr++;
  246. else
  247. return 0; // no query or fragment
  248. }
  249. i=0;
  250. while(i<qs_kv_size)
  251. {
  252. qs_kv[i] = substr_ptr;
  253. j = strcspn(substr_ptr, "&");
  254. if ( substr_ptr[j] == '\0' ) { i++; break; } // x &'s -> means x iterations of this loop -> means *x+1* k/v pairs
  255. substr_ptr += j + 1;
  256. i++;
  257. }
  258. // we only decode the values in place, the keys could have '='s in them
  259. // which will hose our ability to distinguish keys from values later
  260. for(j=0; j<i; j++)
  261. {
  262. substr_ptr = qs_kv[j] + strcspn(qs_kv[j], "=&#");
  263. if ( substr_ptr[0] == '&' || substr_ptr[0] == '\0') // blank value: skip decoding
  264. substr_ptr[0] = '\0';
  265. else
  266. qs_decode(++substr_ptr);
  267. }
  268. #ifdef _qsSORTING
  269. // TODO: qsort qs_kv, using qs_strncmp() for the comparison
  270. #endif
  271. return i;
  272. }
  273. inline int qs_decode(char * qs)
  274. {
  275. int i=0, j=0;
  276. while( CROW_QS_ISQSCHR(qs[j]) )
  277. {
  278. if ( qs[j] == '+' ) { qs[i] = ' '; }
  279. else if ( qs[j] == '%' ) // easier/safer than scanf
  280. {
  281. if ( ! CROW_QS_ISHEX(qs[j+1]) || ! CROW_QS_ISHEX(qs[j+2]) )
  282. {
  283. qs[i] = '\0';
  284. return i;
  285. }
  286. qs[i] = (CROW_QS_HEX2DEC(qs[j+1]) * 16) + CROW_QS_HEX2DEC(qs[j+2]);
  287. j+=2;
  288. }
  289. else
  290. {
  291. qs[i] = qs[j];
  292. }
  293. i++; j++;
  294. }
  295. qs[i] = '\0';
  296. return i;
  297. }
  298. inline char * qs_k2v(const char * key, char * const * qs_kv, size_t qs_kv_size, int nth = 0)
  299. {
  300. size_t i;
  301. size_t key_len, skip;
  302. key_len = strlen(key);
  303. #ifdef _qsSORTING
  304. // TODO: binary search for key in the sorted qs_kv
  305. #else // _qsSORTING
  306. for(i=0; i<qs_kv_size; i++)
  307. {
  308. // we rely on the unambiguous '=' to find the value in our k/v pair
  309. if ( qs_strncmp(key, qs_kv[i], key_len) == 0 )
  310. {
  311. skip = strcspn(qs_kv[i], "=");
  312. if ( qs_kv[i][skip] == '=' )
  313. skip++;
  314. // return (zero-char value) ? ptr to trailing '\0' : ptr to value
  315. if(nth == 0)
  316. return qs_kv[i] + skip;
  317. else
  318. --nth;
  319. }
  320. }
  321. #endif // _qsSORTING
  322. return nullptr;
  323. }
  324. inline std::unique_ptr<std::pair<std::string, std::string>> qs_dict_name2kv(const char * dict_name, char * const * qs_kv, size_t qs_kv_size, int nth = 0)
  325. {
  326. size_t i;
  327. size_t name_len, skip_to_eq, skip_to_brace_open, skip_to_brace_close;
  328. name_len = strlen(dict_name);
  329. #ifdef _qsSORTING
  330. // TODO: binary search for key in the sorted qs_kv
  331. #else // _qsSORTING
  332. for(i=0; i<qs_kv_size; i++)
  333. {
  334. if ( strncmp(dict_name, qs_kv[i], name_len) == 0 )
  335. {
  336. skip_to_eq = strcspn(qs_kv[i], "=");
  337. if ( qs_kv[i][skip_to_eq] == '=' )
  338. skip_to_eq++;
  339. skip_to_brace_open = strcspn(qs_kv[i], "[");
  340. if ( qs_kv[i][skip_to_brace_open] == '[' )
  341. skip_to_brace_open++;
  342. skip_to_brace_close = strcspn(qs_kv[i], "]");
  343. if ( skip_to_brace_open <= skip_to_brace_close &&
  344. skip_to_brace_open > 0 &&
  345. skip_to_brace_close > 0 &&
  346. nth == 0 )
  347. {
  348. auto key = std::string(qs_kv[i] + skip_to_brace_open, skip_to_brace_close - skip_to_brace_open);
  349. auto value = std::string(qs_kv[i] + skip_to_eq);
  350. return std::unique_ptr<std::pair<std::string, std::string>>(new std::pair<std::string, std::string>(key, value));
  351. }
  352. else
  353. {
  354. --nth;
  355. }
  356. }
  357. }
  358. #endif // _qsSORTING
  359. return nullptr;
  360. }
  361. inline char * qs_scanvalue(const char * key, const char * qs, char * val, size_t val_len)
  362. {
  363. size_t i, key_len;
  364. const char * tmp;
  365. // find the beginning of the k/v substrings
  366. if ( (tmp = strchr(qs, '?')) != NULL )
  367. qs = tmp + 1;
  368. key_len = strlen(key);
  369. while(qs[0] != '#' && qs[0] != '\0')
  370. {
  371. if ( qs_strncmp(key, qs, key_len) == 0 )
  372. break;
  373. qs += strcspn(qs, "&") + 1;
  374. }
  375. if ( qs[0] == '\0' ) return NULL;
  376. qs += strcspn(qs, "=&#");
  377. if ( qs[0] == '=' )
  378. {
  379. qs++;
  380. i = strcspn(qs, "&=#");
  381. #ifdef _MSC_VER
  382. strncpy_s(val, val_len, qs, (val_len - 1)<(i + 1) ? (val_len - 1) : (i + 1));
  383. #else
  384. strncpy(val, qs, (val_len - 1)<(i + 1) ? (val_len - 1) : (i + 1));
  385. #endif
  386. qs_decode(val);
  387. }
  388. else
  389. {
  390. if ( val_len > 0 )
  391. val[0] = '\0';
  392. }
  393. return val;
  394. }
  395. }
  396. // ----------------------------------------------------------------------------
  397. namespace crow
  398. {
  399. struct request;
  400. /// A class to represent any data coming after the `?` in the request URL into key-value pairs.
  401. class query_string
  402. {
  403. public:
  404. static const int MAX_KEY_VALUE_PAIRS_COUNT = 256;
  405. query_string() = default;
  406. query_string(const query_string& qs):
  407. url_(qs.url_)
  408. {
  409. for (auto p : qs.key_value_pairs_)
  410. {
  411. key_value_pairs_.push_back((char*)(p - qs.url_.c_str() + url_.c_str()));
  412. }
  413. }
  414. query_string& operator=(const query_string& qs)
  415. {
  416. url_ = qs.url_;
  417. key_value_pairs_.clear();
  418. for (auto p : qs.key_value_pairs_)
  419. {
  420. key_value_pairs_.push_back((char*)(p - qs.url_.c_str() + url_.c_str()));
  421. }
  422. return *this;
  423. }
  424. query_string& operator=(query_string&& qs) noexcept
  425. {
  426. key_value_pairs_ = std::move(qs.key_value_pairs_);
  427. char* old_data = (char*)qs.url_.c_str();
  428. url_ = std::move(qs.url_);
  429. for (auto& p : key_value_pairs_)
  430. {
  431. p += (char*)url_.c_str() - old_data;
  432. }
  433. return *this;
  434. }
  435. query_string(std::string params, bool url = true):
  436. url_(std::move(params))
  437. {
  438. if (url_.empty())
  439. return;
  440. key_value_pairs_.resize(MAX_KEY_VALUE_PAIRS_COUNT);
  441. size_t count = qs_parse(&url_[0], &key_value_pairs_[0], MAX_KEY_VALUE_PAIRS_COUNT, url);
  442. key_value_pairs_.resize(count);
  443. key_value_pairs_.shrink_to_fit();
  444. }
  445. void clear()
  446. {
  447. key_value_pairs_.clear();
  448. url_.clear();
  449. }
  450. friend std::ostream& operator<<(std::ostream& os, const query_string& qs)
  451. {
  452. os << "[ ";
  453. for (size_t i = 0; i < qs.key_value_pairs_.size(); ++i)
  454. {
  455. if (i)
  456. os << ", ";
  457. os << qs.key_value_pairs_[i];
  458. }
  459. os << " ]";
  460. return os;
  461. }
  462. /// Get a value from a name, used for `?name=value`.
  463. ///
  464. /// Note: this method returns the value of the first occurrence of the key only, to return all occurrences, see \ref get_list().
  465. char* get(const std::string& name) const
  466. {
  467. char* ret = qs_k2v(name.c_str(), key_value_pairs_.data(), key_value_pairs_.size());
  468. return ret;
  469. }
  470. /// Works similar to \ref get() except it removes the item from the query string.
  471. char* pop(const std::string& name)
  472. {
  473. char* ret = get(name);
  474. if (ret != nullptr)
  475. {
  476. for (unsigned int i = 0; i < key_value_pairs_.size(); i++)
  477. {
  478. std::string str_item(key_value_pairs_[i]);
  479. if (str_item.substr(0, name.size() + 1) == name + '=')
  480. {
  481. key_value_pairs_.erase(key_value_pairs_.begin() + i);
  482. break;
  483. }
  484. }
  485. }
  486. return ret;
  487. }
  488. /// Returns a list of values, passed as `?name[]=value1&name[]=value2&...name[]=valuen` with n being the size of the list.
  489. ///
  490. /// Note: Square brackets in the above example are controlled by `use_brackets` boolean (true by default). If set to false, the example becomes `?name=value1,name=value2...name=valuen`
  491. std::vector<char*> get_list(const std::string& name, bool use_brackets = true) const
  492. {
  493. std::vector<char*> ret;
  494. std::string plus = name + (use_brackets ? "[]" : "");
  495. char* element = nullptr;
  496. int count = 0;
  497. while (1)
  498. {
  499. element = qs_k2v(plus.c_str(), key_value_pairs_.data(), key_value_pairs_.size(), count++);
  500. if (!element)
  501. break;
  502. ret.push_back(element);
  503. }
  504. return ret;
  505. }
  506. /// Similar to \ref get_list() but it removes the
  507. std::vector<char*> pop_list(const std::string& name, bool use_brackets = true)
  508. {
  509. std::vector<char*> ret = get_list(name, use_brackets);
  510. if (!ret.empty())
  511. {
  512. for (unsigned int i = 0; i < key_value_pairs_.size(); i++)
  513. {
  514. std::string str_item(key_value_pairs_[i]);
  515. if ((use_brackets ? (str_item.substr(0, name.size() + 3) == name + "[]=") : (str_item.substr(0, name.size() + 1) == name + '=')))
  516. {
  517. key_value_pairs_.erase(key_value_pairs_.begin() + i--);
  518. }
  519. }
  520. }
  521. return ret;
  522. }
  523. /// Works similar to \ref get_list() except the brackets are mandatory must not be empty.
  524. ///
  525. /// For example calling `get_dict(yourname)` on `?yourname[sub1]=42&yourname[sub2]=84` would give a map containing `{sub1 : 42, sub2 : 84}`.
  526. ///
  527. /// if your query string has both empty brackets and ones with a key inside, use pop_list() to get all the values without a key before running this method.
  528. std::unordered_map<std::string, std::string> get_dict(const std::string& name) const
  529. {
  530. std::unordered_map<std::string, std::string> ret;
  531. int count = 0;
  532. while (1)
  533. {
  534. if (auto element = qs_dict_name2kv(name.c_str(), key_value_pairs_.data(), key_value_pairs_.size(), count++))
  535. ret.insert(*element);
  536. else
  537. break;
  538. }
  539. return ret;
  540. }
  541. /// Works the same as \ref get_dict() but removes the values from the query string.
  542. std::unordered_map<std::string, std::string> pop_dict(const std::string& name)
  543. {
  544. std::unordered_map<std::string, std::string> ret = get_dict(name);
  545. if (!ret.empty())
  546. {
  547. for (unsigned int i = 0; i < key_value_pairs_.size(); i++)
  548. {
  549. std::string str_item(key_value_pairs_[i]);
  550. if (str_item.substr(0, name.size() + 1) == name + '[')
  551. {
  552. key_value_pairs_.erase(key_value_pairs_.begin() + i--);
  553. }
  554. }
  555. }
  556. return ret;
  557. }
  558. std::vector<std::string> keys() const
  559. {
  560. std::vector<std::string> keys;
  561. keys.reserve(key_value_pairs_.size());
  562. for (const char* const element : key_value_pairs_)
  563. {
  564. const char* delimiter = strchr(element, '=');
  565. if (delimiter)
  566. keys.emplace_back(element, delimiter);
  567. else
  568. keys.emplace_back(element);
  569. }
  570. return keys;
  571. }
  572. private:
  573. std::string url_;
  574. std::vector<char*> key_value_pairs_;
  575. };
  576. } // namespace crow
  577. #ifdef CROW_ENABLE_COMPRESSION
  578. #include <string>
  579. #include <zlib.h>
  580. // http://zlib.net/manual.html
  581. namespace crow // NOTE: Already documented in "crow/app.h"
  582. {
  583. namespace compression
  584. {
  585. // Values used in the 'windowBits' parameter for deflateInit2.
  586. enum algorithm
  587. {
  588. // 15 is the default value for deflate
  589. DEFLATE = 15,
  590. // windowBits can also be greater than 15 for optional gzip encoding.
  591. // Add 16 to windowBits to write a simple gzip header and trailer around the compressed data instead of a zlib wrapper.
  592. GZIP = 15 | 16,
  593. };
  594. inline std::string compress_string(std::string const& str, algorithm algo)
  595. {
  596. std::string compressed_str;
  597. z_stream stream{};
  598. // Initialize with the default values
  599. if (::deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, algo, 8, Z_DEFAULT_STRATEGY) == Z_OK)
  600. {
  601. char buffer[8192];
  602. stream.avail_in = str.size();
  603. // zlib does not take a const pointer. The data is not altered.
  604. stream.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(str.c_str()));
  605. int code = Z_OK;
  606. do
  607. {
  608. stream.avail_out = sizeof(buffer);
  609. stream.next_out = reinterpret_cast<Bytef*>(&buffer[0]);
  610. code = ::deflate(&stream, Z_FINISH);
  611. // Successful and non-fatal error code returned by deflate when used with Z_FINISH flush
  612. if (code == Z_OK || code == Z_STREAM_END)
  613. {
  614. std::copy(&buffer[0], &buffer[sizeof(buffer) - stream.avail_out], std::back_inserter(compressed_str));
  615. }
  616. } while (code == Z_OK);
  617. if (code != Z_STREAM_END)
  618. compressed_str.clear();
  619. ::deflateEnd(&stream);
  620. }
  621. return compressed_str;
  622. }
  623. inline std::string decompress_string(std::string const& deflated_string)
  624. {
  625. std::string inflated_string;
  626. Bytef tmp[8192];
  627. z_stream zstream{};
  628. zstream.avail_in = deflated_string.size();
  629. // Nasty const_cast but zlib won't alter its contents
  630. zstream.next_in = const_cast<Bytef*>(reinterpret_cast<Bytef const*>(deflated_string.c_str()));
  631. // Initialize with automatic header detection, for gzip support
  632. if (::inflateInit2(&zstream, MAX_WBITS | 32) == Z_OK)
  633. {
  634. do
  635. {
  636. zstream.avail_out = sizeof(tmp);
  637. zstream.next_out = &tmp[0];
  638. auto ret = ::inflate(&zstream, Z_NO_FLUSH);
  639. if (ret == Z_OK || ret == Z_STREAM_END)
  640. {
  641. std::copy(&tmp[0], &tmp[sizeof(tmp) - zstream.avail_out], std::back_inserter(inflated_string));
  642. }
  643. else
  644. {
  645. // Something went wrong with inflate; make sure we return an empty string
  646. inflated_string.clear();
  647. break;
  648. }
  649. } while (zstream.avail_out == 0);
  650. // Free zlib's internal memory
  651. ::inflateEnd(&zstream);
  652. }
  653. return inflated_string;
  654. }
  655. } // namespace compression
  656. } // namespace crow
  657. #endif
  658. /*
  659. * SHA1 Wikipedia Page: http://en.wikipedia.org/wiki/SHA-1
  660. *
  661. * Copyright (c) 2012-22 SAURAV MOHAPATRA <[email protected]>
  662. *
  663. * Permission to use, copy, modify, and distribute this software for any
  664. * purpose with or without fee is hereby granted, provided that the above
  665. * copyright notice and this permission notice appear in all copies.
  666. *
  667. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  668. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  669. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  670. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  671. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  672. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  673. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  674. */
  675. /**
  676. * \file TinySHA1.hpp
  677. * \author SAURAV MOHAPATRA <[email protected]>
  678. * \date 2012-22
  679. * \brief TinySHA1 - a header only implementation of the SHA1 algorithm in C++. Based
  680. * on the implementation in boost::uuid::details.
  681. *
  682. * In this file are defined:
  683. * - sha1::SHA1
  684. */
  685. #ifndef _TINY_SHA1_HPP_
  686. #define _TINY_SHA1_HPP_
  687. #include <cstdio>
  688. #include <cstdlib>
  689. #include <cstring>
  690. #include <stdint.h>
  691. /**
  692. * \namespace sha1
  693. * \brief Here is defined the SHA1 class
  694. */
  695. namespace sha1
  696. {
  697. /**
  698. * \class SHA1
  699. * \brief A tiny SHA1 algorithm implementation used internally in the
  700. * Crow server (specifically in crow/websocket.h).
  701. */
  702. class SHA1
  703. {
  704. public:
  705. typedef uint32_t digest32_t[5];
  706. typedef uint8_t digest8_t[20];
  707. inline static uint32_t LeftRotate(uint32_t value, size_t count) {
  708. return (value << count) ^ (value >> (32-count));
  709. }
  710. SHA1(){ reset(); }
  711. virtual ~SHA1() {}
  712. SHA1(const SHA1& s) { *this = s; }
  713. const SHA1& operator = (const SHA1& s) {
  714. memcpy(m_digest, s.m_digest, 5 * sizeof(uint32_t));
  715. memcpy(m_block, s.m_block, 64);
  716. m_blockByteIndex = s.m_blockByteIndex;
  717. m_byteCount = s.m_byteCount;
  718. return *this;
  719. }
  720. SHA1& reset() {
  721. m_digest[0] = 0x67452301;
  722. m_digest[1] = 0xEFCDAB89;
  723. m_digest[2] = 0x98BADCFE;
  724. m_digest[3] = 0x10325476;
  725. m_digest[4] = 0xC3D2E1F0;
  726. m_blockByteIndex = 0;
  727. m_byteCount = 0;
  728. return *this;
  729. }
  730. SHA1& processByte(uint8_t octet) {
  731. this->m_block[this->m_blockByteIndex++] = octet;
  732. ++this->m_byteCount;
  733. if(m_blockByteIndex == 64) {
  734. this->m_blockByteIndex = 0;
  735. processBlock();
  736. }
  737. return *this;
  738. }
  739. SHA1& processBlock(const void* const start, const void* const end) {
  740. const uint8_t* begin = static_cast<const uint8_t*>(start);
  741. const uint8_t* finish = static_cast<const uint8_t*>(end);
  742. while(begin != finish) {
  743. processByte(*begin);
  744. begin++;
  745. }
  746. return *this;
  747. }
  748. SHA1& processBytes(const void* const data, size_t len) {
  749. const uint8_t* block = static_cast<const uint8_t*>(data);
  750. processBlock(block, block + len);
  751. return *this;
  752. }
  753. const uint32_t* getDigest(digest32_t digest) {
  754. size_t bitCount = this->m_byteCount * 8;
  755. processByte(0x80);
  756. if (this->m_blockByteIndex > 56) {
  757. while (m_blockByteIndex != 0) {
  758. processByte(0);
  759. }
  760. while (m_blockByteIndex < 56) {
  761. processByte(0);
  762. }
  763. } else {
  764. while (m_blockByteIndex < 56) {
  765. processByte(0);
  766. }
  767. }
  768. processByte(0);
  769. processByte(0);
  770. processByte(0);
  771. processByte(0);
  772. processByte( static_cast<unsigned char>((bitCount>>24) & 0xFF));
  773. processByte( static_cast<unsigned char>((bitCount>>16) & 0xFF));
  774. processByte( static_cast<unsigned char>((bitCount>>8 ) & 0xFF));
  775. processByte( static_cast<unsigned char>((bitCount) & 0xFF));
  776. memcpy(digest, m_digest, 5 * sizeof(uint32_t));
  777. return digest;
  778. }
  779. const uint8_t* getDigestBytes(digest8_t digest) {
  780. digest32_t d32;
  781. getDigest(d32);
  782. size_t di = 0;
  783. digest[di++] = ((d32[0] >> 24) & 0xFF);
  784. digest[di++] = ((d32[0] >> 16) & 0xFF);
  785. digest[di++] = ((d32[0] >> 8) & 0xFF);
  786. digest[di++] = ((d32[0]) & 0xFF);
  787. digest[di++] = ((d32[1] >> 24) & 0xFF);
  788. digest[di++] = ((d32[1] >> 16) & 0xFF);
  789. digest[di++] = ((d32[1] >> 8) & 0xFF);
  790. digest[di++] = ((d32[1]) & 0xFF);
  791. digest[di++] = ((d32[2] >> 24) & 0xFF);
  792. digest[di++] = ((d32[2] >> 16) & 0xFF);
  793. digest[di++] = ((d32[2] >> 8) & 0xFF);
  794. digest[di++] = ((d32[2]) & 0xFF);
  795. digest[di++] = ((d32[3] >> 24) & 0xFF);
  796. digest[di++] = ((d32[3] >> 16) & 0xFF);
  797. digest[di++] = ((d32[3] >> 8) & 0xFF);
  798. digest[di++] = ((d32[3]) & 0xFF);
  799. digest[di++] = ((d32[4] >> 24) & 0xFF);
  800. digest[di++] = ((d32[4] >> 16) & 0xFF);
  801. digest[di++] = ((d32[4] >> 8) & 0xFF);
  802. digest[di++] = ((d32[4]) & 0xFF);
  803. return digest;
  804. }
  805. protected:
  806. void processBlock() {
  807. uint32_t w[80];
  808. for (size_t i = 0; i < 16; i++) {
  809. w[i] = (m_block[i*4 + 0] << 24);
  810. w[i] |= (m_block[i*4 + 1] << 16);
  811. w[i] |= (m_block[i*4 + 2] << 8);
  812. w[i] |= (m_block[i*4 + 3]);
  813. }
  814. for (size_t i = 16; i < 80; i++) {
  815. w[i] = LeftRotate((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1);
  816. }
  817. uint32_t a = m_digest[0];
  818. uint32_t b = m_digest[1];
  819. uint32_t c = m_digest[2];
  820. uint32_t d = m_digest[3];
  821. uint32_t e = m_digest[4];
  822. for (std::size_t i=0; i<80; ++i) {
  823. uint32_t f = 0;
  824. uint32_t k = 0;
  825. if (i<20) {
  826. f = (b & c) | (~b & d);
  827. k = 0x5A827999;
  828. } else if (i<40) {
  829. f = b ^ c ^ d;
  830. k = 0x6ED9EBA1;
  831. } else if (i<60) {
  832. f = (b & c) | (b & d) | (c & d);
  833. k = 0x8F1BBCDC;
  834. } else {
  835. f = b ^ c ^ d;
  836. k = 0xCA62C1D6;
  837. }
  838. uint32_t temp = LeftRotate(a, 5) + f + e + k + w[i];
  839. e = d;
  840. d = c;
  841. c = LeftRotate(b, 30);
  842. b = a;
  843. a = temp;
  844. }
  845. m_digest[0] += a;
  846. m_digest[1] += b;
  847. m_digest[2] += c;
  848. m_digest[3] += d;
  849. m_digest[4] += e;
  850. }
  851. private:
  852. digest32_t m_digest;
  853. uint8_t m_block[64];
  854. size_t m_blockByteIndex;
  855. size_t m_byteCount;
  856. };
  857. }
  858. #endif
  859. // settings for crow
  860. // TODO(ipkn) replace with runtime config. libucl?
  861. /* #ifdef - enables debug mode */
  862. //#define CROW_ENABLE_DEBUG
  863. /* #ifdef - enables logging */
  864. #define CROW_ENABLE_LOGGING
  865. /* #ifdef - enforces section 5.2 and 6.1 of RFC6455 (only accepting masked messages from clients) */
  866. //#define CROW_ENFORCE_WS_SPEC
  867. /* #define - specifies log level */
  868. /*
  869. Debug = 0
  870. Info = 1
  871. Warning = 2
  872. Error = 3
  873. Critical = 4
  874. default to INFO
  875. */
  876. #ifndef CROW_LOG_LEVEL
  877. #define CROW_LOG_LEVEL 1
  878. #endif
  879. #ifndef CROW_STATIC_DIRECTORY
  880. #define CROW_STATIC_DIRECTORY "static/"
  881. #endif
  882. #ifndef CROW_STATIC_ENDPOINT
  883. #define CROW_STATIC_ENDPOINT "/static/<path>"
  884. #endif
  885. // compiler flags
  886. #if defined(_MSVC_LANG) && _MSVC_LANG >= 201402L
  887. #define CROW_CAN_USE_CPP14
  888. #endif
  889. #if __cplusplus >= 201402L
  890. #define CROW_CAN_USE_CPP14
  891. #endif
  892. #if defined(_MSVC_LANG) && _MSVC_LANG >= 201703L
  893. #define CROW_CAN_USE_CPP17
  894. #endif
  895. #if __cplusplus >= 201703L
  896. #define CROW_CAN_USE_CPP17
  897. #if defined(__GNUC__) && __GNUC__ < 8
  898. #define CROW_FILESYSTEM_IS_EXPERIMENTAL
  899. #endif
  900. #endif
  901. #if defined(_MSC_VER)
  902. #if _MSC_VER < 1900
  903. #define CROW_MSVC_WORKAROUND
  904. #define constexpr const
  905. #define noexcept throw()
  906. #endif
  907. #endif
  908. #if defined(__GNUC__) && __GNUC__ == 8 && __GNUC_MINOR__ < 4
  909. #if __cplusplus > 201103L
  910. #define CROW_GCC83_WORKAROUND
  911. #else
  912. #error "GCC 8.1 - 8.3 has a bug that prevents Crow from compiling with C++11. Please update GCC to > 8.3 or use C++ > 11."
  913. #endif
  914. #endif
  915. #ifdef CROW_USE_BOOST
  916. #include <boost/asio.hpp>
  917. #include <boost/asio/version.hpp>
  918. #ifdef CROW_ENABLE_SSL
  919. #include <boost/asio/ssl.hpp>
  920. #endif
  921. #else
  922. #ifndef ASIO_STANDALONE
  923. #define ASIO_STANDALONE
  924. #endif
  925. #include <asio.hpp>
  926. #include <asio/version.hpp>
  927. #ifdef CROW_ENABLE_SSL
  928. #include <asio/ssl.hpp>
  929. #endif
  930. #endif
  931. #if (CROW_USE_BOOST && BOOST_VERSION >= 107000) || (ASIO_VERSION >= 101300)
  932. #define GET_IO_SERVICE(s) ((asio::io_context&)(s).get_executor().context())
  933. #else
  934. #define GET_IO_SERVICE(s) ((s).get_io_service())
  935. #endif
  936. namespace crow
  937. {
  938. #ifdef CROW_USE_BOOST
  939. namespace asio = boost::asio;
  940. using error_code = boost::system::error_code;
  941. #else
  942. using error_code = asio::error_code;
  943. #endif
  944. using tcp = asio::ip::tcp;
  945. /// A wrapper for the asio::ip::tcp::socket and asio::ssl::stream
  946. struct SocketAdaptor
  947. {
  948. using context = void;
  949. SocketAdaptor(asio::io_service& io_service, context*):
  950. socket_(io_service)
  951. {}
  952. asio::io_service& get_io_service()
  953. {
  954. return GET_IO_SERVICE(socket_);
  955. }
  956. /// Get the TCP socket handling data trasfers, regardless of what layer is handling transfers on top of the socket.
  957. tcp::socket& raw_socket()
  958. {
  959. return socket_;
  960. }
  961. /// Get the object handling data transfers, this can be either a TCP socket or an SSL stream (if SSL is enabled).
  962. tcp::socket& socket()
  963. {
  964. return socket_;
  965. }
  966. tcp::endpoint remote_endpoint()
  967. {
  968. return socket_.remote_endpoint();
  969. }
  970. bool is_open()
  971. {
  972. return socket_.is_open();
  973. }
  974. void close()
  975. {
  976. error_code ec;
  977. socket_.close(ec);
  978. }
  979. void shutdown_readwrite()
  980. {
  981. error_code ec;
  982. socket_.shutdown(asio::socket_base::shutdown_type::shutdown_both, ec);
  983. }
  984. void shutdown_write()
  985. {
  986. error_code ec;
  987. socket_.shutdown(asio::socket_base::shutdown_type::shutdown_send, ec);
  988. }
  989. void shutdown_read()
  990. {
  991. error_code ec;
  992. socket_.shutdown(asio::socket_base::shutdown_type::shutdown_receive, ec);
  993. }
  994. template<typename F>
  995. void start(F f)
  996. {
  997. f(error_code());
  998. }
  999. tcp::socket socket_;
  1000. };
  1001. #ifdef CROW_ENABLE_SSL
  1002. struct SSLAdaptor
  1003. {
  1004. using context = asio::ssl::context;
  1005. using ssl_socket_t = asio::ssl::stream<tcp::socket>;
  1006. SSLAdaptor(asio::io_service& io_service, context* ctx):
  1007. ssl_socket_(new ssl_socket_t(io_service, *ctx))
  1008. {}
  1009. asio::ssl::stream<tcp::socket>& socket()
  1010. {
  1011. return *ssl_socket_;
  1012. }
  1013. tcp::socket::lowest_layer_type&
  1014. raw_socket()
  1015. {
  1016. return ssl_socket_->lowest_layer();
  1017. }
  1018. tcp::endpoint remote_endpoint()
  1019. {
  1020. return raw_socket().remote_endpoint();
  1021. }
  1022. bool is_open()
  1023. {
  1024. return ssl_socket_ ? raw_socket().is_open() : false;
  1025. }
  1026. void close()
  1027. {
  1028. if (is_open())
  1029. {
  1030. error_code ec;
  1031. raw_socket().close(ec);
  1032. }
  1033. }
  1034. void shutdown_readwrite()
  1035. {
  1036. if (is_open())
  1037. {
  1038. error_code ec;
  1039. raw_socket().shutdown(asio::socket_base::shutdown_type::shutdown_both, ec);
  1040. }
  1041. }
  1042. void shutdown_write()
  1043. {
  1044. if (is_open())
  1045. {
  1046. error_code ec;
  1047. raw_socket().shutdown(asio::socket_base::shutdown_type::shutdown_send, ec);
  1048. }
  1049. }
  1050. void shutdown_read()
  1051. {
  1052. if (is_open())
  1053. {
  1054. error_code ec;
  1055. raw_socket().shutdown(asio::socket_base::shutdown_type::shutdown_receive, ec);
  1056. }
  1057. }
  1058. asio::io_service& get_io_service()
  1059. {
  1060. return GET_IO_SERVICE(raw_socket());
  1061. }
  1062. template<typename F>
  1063. void start(F f)
  1064. {
  1065. ssl_socket_->async_handshake(asio::ssl::stream_base::server,
  1066. [f](const error_code& ec) {
  1067. f(ec);
  1068. });
  1069. }
  1070. std::unique_ptr<asio::ssl::stream<tcp::socket>> ssl_socket_;
  1071. };
  1072. #endif
  1073. } // namespace crow
  1074. #include <cstdint>
  1075. #include <stdexcept>
  1076. #include <tuple>
  1077. #include <type_traits>
  1078. #include <cstring>
  1079. #include <cctype>
  1080. #include <functional>
  1081. #include <string>
  1082. #include <sstream>
  1083. #include <unordered_map>
  1084. #include <random>
  1085. #include <algorithm>
  1086. #if defined(CROW_CAN_USE_CPP17) && !defined(CROW_FILESYSTEM_IS_EXPERIMENTAL)
  1087. #include <filesystem>
  1088. #endif
  1089. // TODO(EDev): Adding C++20's [[likely]] and [[unlikely]] attributes might be useful
  1090. #if defined(__GNUG__) || defined(__clang__)
  1091. #define CROW_LIKELY(X) __builtin_expect(!!(X), 1)
  1092. #define CROW_UNLIKELY(X) __builtin_expect(!!(X), 0)
  1093. #else
  1094. #define CROW_LIKELY(X) (X)
  1095. #define CROW_UNLIKELY(X) (X)
  1096. #endif
  1097. namespace crow
  1098. {
  1099. /// @cond SKIP
  1100. namespace black_magic
  1101. {
  1102. #ifndef CROW_MSVC_WORKAROUND
  1103. /// Out of Range Exception for const_str
  1104. struct OutOfRange
  1105. {
  1106. OutOfRange(unsigned /*pos*/, unsigned /*length*/) {}
  1107. };
  1108. /// Helper function to throw an exception if i is larger than len
  1109. constexpr unsigned requires_in_range(unsigned i, unsigned len)
  1110. {
  1111. return i >= len ? throw OutOfRange(i, len) : i;
  1112. }
  1113. /// A constant string implementation.
  1114. class const_str
  1115. {
  1116. const char* const begin_;
  1117. unsigned size_;
  1118. public:
  1119. template<unsigned N>
  1120. constexpr const_str(const char (&arr)[N]):
  1121. begin_(arr), size_(N - 1)
  1122. {
  1123. static_assert(N >= 1, "not a string literal");
  1124. }
  1125. constexpr char operator[](unsigned i) const
  1126. {
  1127. return requires_in_range(i, size_), begin_[i];
  1128. }
  1129. constexpr operator const char*() const
  1130. {
  1131. return begin_;
  1132. }
  1133. constexpr const char* begin() const { return begin_; }
  1134. constexpr const char* end() const { return begin_ + size_; }
  1135. constexpr unsigned size() const
  1136. {
  1137. return size_;
  1138. }
  1139. };
  1140. constexpr unsigned find_closing_tag(const_str s, unsigned p)
  1141. {
  1142. return s[p] == '>' ? p : find_closing_tag(s, p + 1);
  1143. }
  1144. /// Check that the CROW_ROUTE string is valid
  1145. constexpr bool is_valid(const_str s, unsigned i = 0, int f = 0)
  1146. {
  1147. return i == s.size() ? f == 0 :
  1148. f < 0 || f >= 2 ? false :
  1149. s[i] == '<' ? is_valid(s, i + 1, f + 1) :
  1150. s[i] == '>' ? is_valid(s, i + 1, f - 1) :
  1151. is_valid(s, i + 1, f);
  1152. }
  1153. constexpr bool is_equ_p(const char* a, const char* b, unsigned n)
  1154. {
  1155. return *a == 0 && *b == 0 && n == 0 ? true :
  1156. (*a == 0 || *b == 0) ? false :
  1157. n == 0 ? true :
  1158. *a != *b ? false :
  1159. is_equ_p(a + 1, b + 1, n - 1);
  1160. }
  1161. constexpr bool is_equ_n(const_str a, unsigned ai, const_str b, unsigned bi, unsigned n)
  1162. {
  1163. return ai + n > a.size() || bi + n > b.size() ? false :
  1164. n == 0 ? true :
  1165. a[ai] != b[bi] ? false :
  1166. is_equ_n(a, ai + 1, b, bi + 1, n - 1);
  1167. }
  1168. constexpr bool is_int(const_str s, unsigned i)
  1169. {
  1170. return is_equ_n(s, i, "<int>", 0, 5);
  1171. }
  1172. constexpr bool is_uint(const_str s, unsigned i)
  1173. {
  1174. return is_equ_n(s, i, "<uint>", 0, 6);
  1175. }
  1176. constexpr bool is_float(const_str s, unsigned i)
  1177. {
  1178. return is_equ_n(s, i, "<float>", 0, 7) ||
  1179. is_equ_n(s, i, "<double>", 0, 8);
  1180. }
  1181. constexpr bool is_str(const_str s, unsigned i)
  1182. {
  1183. return is_equ_n(s, i, "<str>", 0, 5) ||
  1184. is_equ_n(s, i, "<string>", 0, 8);
  1185. }
  1186. constexpr bool is_path(const_str s, unsigned i)
  1187. {
  1188. return is_equ_n(s, i, "<path>", 0, 6);
  1189. }
  1190. #endif
  1191. template<typename T>
  1192. struct parameter_tag
  1193. {
  1194. static const int value = 0;
  1195. };
  1196. #define CROW_INTERNAL_PARAMETER_TAG(t, i) \
  1197. template<> \
  1198. struct parameter_tag<t> \
  1199. { \
  1200. static const int value = i; \
  1201. }
  1202. CROW_INTERNAL_PARAMETER_TAG(int, 1);
  1203. CROW_INTERNAL_PARAMETER_TAG(char, 1);
  1204. CROW_INTERNAL_PARAMETER_TAG(short, 1);
  1205. CROW_INTERNAL_PARAMETER_TAG(long, 1);
  1206. CROW_INTERNAL_PARAMETER_TAG(long long, 1);
  1207. CROW_INTERNAL_PARAMETER_TAG(unsigned int, 2);
  1208. CROW_INTERNAL_PARAMETER_TAG(unsigned char, 2);
  1209. CROW_INTERNAL_PARAMETER_TAG(unsigned short, 2);
  1210. CROW_INTERNAL_PARAMETER_TAG(unsigned long, 2);
  1211. CROW_INTERNAL_PARAMETER_TAG(unsigned long long, 2);
  1212. CROW_INTERNAL_PARAMETER_TAG(double, 3);
  1213. CROW_INTERNAL_PARAMETER_TAG(std::string, 4);
  1214. #undef CROW_INTERNAL_PARAMETER_TAG
  1215. template<typename... Args>
  1216. struct compute_parameter_tag_from_args_list;
  1217. template<>
  1218. struct compute_parameter_tag_from_args_list<>
  1219. {
  1220. static const int value = 0;
  1221. };
  1222. template<typename Arg, typename... Args>
  1223. struct compute_parameter_tag_from_args_list<Arg, Args...>
  1224. {
  1225. static const int sub_value =
  1226. compute_parameter_tag_from_args_list<Args...>::value;
  1227. static const int value =
  1228. parameter_tag<typename std::decay<Arg>::type>::value ? sub_value * 6 + parameter_tag<typename std::decay<Arg>::type>::value : sub_value;
  1229. };
  1230. static inline bool is_parameter_tag_compatible(uint64_t a, uint64_t b)
  1231. {
  1232. if (a == 0)
  1233. return b == 0;
  1234. if (b == 0)
  1235. return a == 0;
  1236. int sa = a % 6;
  1237. int sb = a % 6;
  1238. if (sa == 5) sa = 4;
  1239. if (sb == 5) sb = 4;
  1240. if (sa != sb)
  1241. return false;
  1242. return is_parameter_tag_compatible(a / 6, b / 6);
  1243. }
  1244. static inline unsigned find_closing_tag_runtime(const char* s, unsigned p)
  1245. {
  1246. return s[p] == 0 ? throw std::runtime_error("unmatched tag <") :
  1247. s[p] == '>' ? p :
  1248. find_closing_tag_runtime(s, p + 1);
  1249. }
  1250. static inline uint64_t get_parameter_tag_runtime(const char* s, unsigned p = 0)
  1251. {
  1252. return s[p] == 0 ? 0 :
  1253. s[p] == '<' ? (
  1254. std::strncmp(s + p, "<int>", 5) == 0 ? get_parameter_tag_runtime(s, find_closing_tag_runtime(s, p)) * 6 + 1 :
  1255. std::strncmp(s + p, "<uint>", 6) == 0 ? get_parameter_tag_runtime(s, find_closing_tag_runtime(s, p)) * 6 + 2 :
  1256. (std::strncmp(s + p, "<float>", 7) == 0 ||
  1257. std::strncmp(s + p, "<double>", 8) == 0) ?
  1258. get_parameter_tag_runtime(s, find_closing_tag_runtime(s, p)) * 6 + 3 :
  1259. (std::strncmp(s + p, "<str>", 5) == 0 ||
  1260. std::strncmp(s + p, "<string>", 8) == 0) ?
  1261. get_parameter_tag_runtime(s, find_closing_tag_runtime(s, p)) * 6 + 4 :
  1262. std::strncmp(s + p, "<path>", 6) == 0 ? get_parameter_tag_runtime(s, find_closing_tag_runtime(s, p)) * 6 + 5 :
  1263. throw std::runtime_error("invalid parameter type")) :
  1264. get_parameter_tag_runtime(s, p + 1);
  1265. }
  1266. #ifndef CROW_MSVC_WORKAROUND
  1267. constexpr uint64_t get_parameter_tag(const_str s, unsigned p = 0)
  1268. {
  1269. return p == s.size() ? 0 :
  1270. s[p] == '<' ? (
  1271. is_int(s, p) ? get_parameter_tag(s, find_closing_tag(s, p)) * 6 + 1 :
  1272. is_uint(s, p) ? get_parameter_tag(s, find_closing_tag(s, p)) * 6 + 2 :
  1273. is_float(s, p) ? get_parameter_tag(s, find_closing_tag(s, p)) * 6 + 3 :
  1274. is_str(s, p) ? get_parameter_tag(s, find_closing_tag(s, p)) * 6 + 4 :
  1275. is_path(s, p) ? get_parameter_tag(s, find_closing_tag(s, p)) * 6 + 5 :
  1276. throw std::runtime_error("invalid parameter type")) :
  1277. get_parameter_tag(s, p + 1);
  1278. }
  1279. #endif
  1280. template<typename... T>
  1281. struct S
  1282. {
  1283. template<typename U>
  1284. using push = S<U, T...>;
  1285. template<typename U>
  1286. using push_back = S<T..., U>;
  1287. template<template<typename... Args> class U>
  1288. using rebind = U<T...>;
  1289. };
  1290. // Check whether the template function can be called with specific arguments
  1291. template<typename F, typename Set>
  1292. struct CallHelper;
  1293. template<typename F, typename... Args>
  1294. struct CallHelper<F, S<Args...>>
  1295. {
  1296. template<typename F1, typename... Args1, typename = decltype(std::declval<F1>()(std::declval<Args1>()...))>
  1297. static char __test(int);
  1298. template<typename...>
  1299. static int __test(...);
  1300. static constexpr bool value = sizeof(__test<F, Args...>(0)) == sizeof(char);
  1301. };
  1302. // Check Tuple contains type T
  1303. template<typename T, typename Tuple>
  1304. struct has_type;
  1305. template<typename T>
  1306. struct has_type<T, std::tuple<>> : std::false_type
  1307. {};
  1308. template<typename T, typename U, typename... Ts>
  1309. struct has_type<T, std::tuple<U, Ts...>> : has_type<T, std::tuple<Ts...>>
  1310. {};
  1311. template<typename T, typename... Ts>
  1312. struct has_type<T, std::tuple<T, Ts...>> : std::true_type
  1313. {};
  1314. // Find index of type in tuple
  1315. template<class T, class Tuple>
  1316. struct tuple_index;
  1317. template<class T, class... Types>
  1318. struct tuple_index<T, std::tuple<T, Types...>>
  1319. {
  1320. static const int value = 0;
  1321. };
  1322. template<class T, class U, class... Types>
  1323. struct tuple_index<T, std::tuple<U, Types...>>
  1324. {
  1325. static const int value = 1 + tuple_index<T, std::tuple<Types...>>::value;
  1326. };
  1327. // Extract element from forward tuple or get default
  1328. #ifdef CROW_CAN_USE_CPP14
  1329. template<typename T, typename Tup>
  1330. typename std::enable_if<has_type<T&, Tup>::value, typename std::decay<T>::type&&>::type
  1331. tuple_extract(Tup& tup)
  1332. {
  1333. return std::move(std::get<T&>(tup));
  1334. }
  1335. #else
  1336. template<typename T, typename Tup>
  1337. typename std::enable_if<has_type<T&, Tup>::value, T&&>::type
  1338. tuple_extract(Tup& tup)
  1339. {
  1340. return std::move(std::get<tuple_index<T&, Tup>::value>(tup));
  1341. }
  1342. #endif
  1343. template<typename T, typename Tup>
  1344. typename std::enable_if<!has_type<T&, Tup>::value, T>::type
  1345. tuple_extract(Tup&)
  1346. {
  1347. return T{};
  1348. }
  1349. // Kind of fold expressions in C++11
  1350. template<bool...>
  1351. struct bool_pack;
  1352. template<bool... bs>
  1353. using all_true = std::is_same<bool_pack<bs..., true>, bool_pack<true, bs...>>;
  1354. template<int N>
  1355. struct single_tag_to_type
  1356. {};
  1357. template<>
  1358. struct single_tag_to_type<1>
  1359. {
  1360. using type = int64_t;
  1361. };
  1362. template<>
  1363. struct single_tag_to_type<2>
  1364. {
  1365. using type = uint64_t;
  1366. };
  1367. template<>
  1368. struct single_tag_to_type<3>
  1369. {
  1370. using type = double;
  1371. };
  1372. template<>
  1373. struct single_tag_to_type<4>
  1374. {
  1375. using type = std::string;
  1376. };
  1377. template<>
  1378. struct single_tag_to_type<5>
  1379. {
  1380. using type = std::string;
  1381. };
  1382. template<uint64_t Tag>
  1383. struct arguments
  1384. {
  1385. using subarguments = typename arguments<Tag / 6>::type;
  1386. using type =
  1387. typename subarguments::template push<typename single_tag_to_type<Tag % 6>::type>;
  1388. };
  1389. template<>
  1390. struct arguments<0>
  1391. {
  1392. using type = S<>;
  1393. };
  1394. template<typename... T>
  1395. struct last_element_type
  1396. {
  1397. using type = typename std::tuple_element<sizeof...(T) - 1, std::tuple<T...>>::type;
  1398. };
  1399. template<>
  1400. struct last_element_type<>
  1401. {};
  1402. // from http://stackoverflow.com/questions/13072359/c11-compile-time-array-with-logarithmic-evaluation-depth
  1403. template<class T>
  1404. using Invoke = typename T::type;
  1405. template<unsigned...>
  1406. struct seq
  1407. {
  1408. using type = seq;
  1409. };
  1410. template<class S1, class S2>
  1411. struct concat;
  1412. template<unsigned... I1, unsigned... I2>
  1413. struct concat<seq<I1...>, seq<I2...>> : seq<I1..., (sizeof...(I1) + I2)...>
  1414. {};
  1415. template<class S1, class S2>
  1416. using Concat = Invoke<concat<S1, S2>>;
  1417. template<unsigned N>
  1418. struct gen_seq;
  1419. template<unsigned N>
  1420. using GenSeq = Invoke<gen_seq<N>>;
  1421. template<unsigned N>
  1422. struct gen_seq : Concat<GenSeq<N / 2>, GenSeq<N - N / 2>>
  1423. {};
  1424. template<>
  1425. struct gen_seq<0> : seq<>
  1426. {};
  1427. template<>
  1428. struct gen_seq<1> : seq<0>
  1429. {};
  1430. template<typename Seq, typename Tuple>
  1431. struct pop_back_helper;
  1432. template<unsigned... N, typename Tuple>
  1433. struct pop_back_helper<seq<N...>, Tuple>
  1434. {
  1435. template<template<typename... Args> class U>
  1436. using rebind = U<typename std::tuple_element<N, Tuple>::type...>;
  1437. };
  1438. template<typename... T>
  1439. struct pop_back //: public pop_back_helper<typename gen_seq<sizeof...(T)-1>::type, std::tuple<T...>>
  1440. {
  1441. template<template<typename... Args> class U>
  1442. using rebind = typename pop_back_helper<typename gen_seq<sizeof...(T) - 1>::type, std::tuple<T...>>::template rebind<U>;
  1443. };
  1444. template<>
  1445. struct pop_back<>
  1446. {
  1447. template<template<typename... Args> class U>
  1448. using rebind = U<>;
  1449. };
  1450. // from http://stackoverflow.com/questions/2118541/check-if-c0x-parameter-pack-contains-a-type
  1451. template<typename Tp, typename... List>
  1452. struct contains : std::true_type
  1453. {};
  1454. template<typename Tp, typename Head, typename... Rest>
  1455. struct contains<Tp, Head, Rest...> : std::conditional<std::is_same<Tp, Head>::value, std::true_type, contains<Tp, Rest...>>::type
  1456. {};
  1457. template<typename Tp>
  1458. struct contains<Tp> : std::false_type
  1459. {};
  1460. template<typename T>
  1461. struct empty_context
  1462. {};
  1463. template<typename T>
  1464. struct promote
  1465. {
  1466. using type = T;
  1467. };
  1468. #define CROW_INTERNAL_PROMOTE_TYPE(t1, t2) \
  1469. template<> \
  1470. struct promote<t1> \
  1471. { \
  1472. using type = t2; \
  1473. }
  1474. CROW_INTERNAL_PROMOTE_TYPE(char, int64_t);
  1475. CROW_INTERNAL_PROMOTE_TYPE(short, int64_t);
  1476. CROW_INTERNAL_PROMOTE_TYPE(int, int64_t);
  1477. CROW_INTERNAL_PROMOTE_TYPE(long, int64_t);
  1478. CROW_INTERNAL_PROMOTE_TYPE(long long, int64_t);
  1479. CROW_INTERNAL_PROMOTE_TYPE(unsigned char, uint64_t);
  1480. CROW_INTERNAL_PROMOTE_TYPE(unsigned short, uint64_t);
  1481. CROW_INTERNAL_PROMOTE_TYPE(unsigned int, uint64_t);
  1482. CROW_INTERNAL_PROMOTE_TYPE(unsigned long, uint64_t);
  1483. CROW_INTERNAL_PROMOTE_TYPE(unsigned long long, uint64_t);
  1484. CROW_INTERNAL_PROMOTE_TYPE(float, double);
  1485. #undef CROW_INTERNAL_PROMOTE_TYPE
  1486. template<typename T>
  1487. using promote_t = typename promote<T>::type;
  1488. } // namespace black_magic
  1489. namespace detail
  1490. {
  1491. template<class T, std::size_t N, class... Args>
  1492. struct get_index_of_element_from_tuple_by_type_impl
  1493. {
  1494. static constexpr auto value = N;
  1495. };
  1496. template<class T, std::size_t N, class... Args>
  1497. struct get_index_of_element_from_tuple_by_type_impl<T, N, T, Args...>
  1498. {
  1499. static constexpr auto value = N;
  1500. };
  1501. template<class T, std::size_t N, class U, class... Args>
  1502. struct get_index_of_element_from_tuple_by_type_impl<T, N, U, Args...>
  1503. {
  1504. static constexpr auto value = get_index_of_element_from_tuple_by_type_impl<T, N + 1, Args...>::value;
  1505. };
  1506. } // namespace detail
  1507. namespace utility
  1508. {
  1509. template<class T, class... Args>
  1510. T& get_element_by_type(std::tuple<Args...>& t)
  1511. {
  1512. return std::get<detail::get_index_of_element_from_tuple_by_type_impl<T, 0, Args...>::value>(t);
  1513. }
  1514. template<typename T>
  1515. struct function_traits;
  1516. #ifndef CROW_MSVC_WORKAROUND
  1517. template<typename T>
  1518. struct function_traits : public function_traits<decltype(&T::operator())>
  1519. {
  1520. using parent_t = function_traits<decltype(&T::operator())>;
  1521. static const size_t arity = parent_t::arity;
  1522. using result_type = typename parent_t::result_type;
  1523. template<size_t i>
  1524. using arg = typename parent_t::template arg<i>;
  1525. };
  1526. #endif
  1527. template<typename ClassType, typename R, typename... Args>
  1528. struct function_traits<R (ClassType::*)(Args...) const>
  1529. {
  1530. static const size_t arity = sizeof...(Args);
  1531. typedef R result_type;
  1532. template<size_t i>
  1533. using arg = typename std::tuple_element<i, std::tuple<Args...>>::type;
  1534. };
  1535. template<typename ClassType, typename R, typename... Args>
  1536. struct function_traits<R (ClassType::*)(Args...)>
  1537. {
  1538. static const size_t arity = sizeof...(Args);
  1539. typedef R result_type;
  1540. template<size_t i>
  1541. using arg = typename std::tuple_element<i, std::tuple<Args...>>::type;
  1542. };
  1543. template<typename R, typename... Args>
  1544. struct function_traits<std::function<R(Args...)>>
  1545. {
  1546. static const size_t arity = sizeof...(Args);
  1547. typedef R result_type;
  1548. template<size_t i>
  1549. using arg = typename std::tuple_element<i, std::tuple<Args...>>::type;
  1550. };
  1551. /// @endcond
  1552. inline static std::string base64encode(const unsigned char* data, size_t size, const char* key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
  1553. {
  1554. std::string ret;
  1555. ret.resize((size + 2) / 3 * 4);
  1556. auto it = ret.begin();
  1557. while (size >= 3)
  1558. {
  1559. *it++ = key[(static_cast<unsigned char>(*data) & 0xFC) >> 2];
  1560. unsigned char h = (static_cast<unsigned char>(*data++) & 0x03) << 4;
  1561. *it++ = key[h | ((static_cast<unsigned char>(*data) & 0xF0) >> 4)];
  1562. h = (static_cast<unsigned char>(*data++) & 0x0F) << 2;
  1563. *it++ = key[h | ((static_cast<unsigned char>(*data) & 0xC0) >> 6)];
  1564. *it++ = key[static_cast<unsigned char>(*data++) & 0x3F];
  1565. size -= 3;
  1566. }
  1567. if (size == 1)
  1568. {
  1569. *it++ = key[(static_cast<unsigned char>(*data) & 0xFC) >> 2];
  1570. unsigned char h = (static_cast<unsigned char>(*data++) & 0x03) << 4;
  1571. *it++ = key[h];
  1572. *it++ = '=';
  1573. *it++ = '=';
  1574. }
  1575. else if (size == 2)
  1576. {
  1577. *it++ = key[(static_cast<unsigned char>(*data) & 0xFC) >> 2];
  1578. unsigned char h = (static_cast<unsigned char>(*data++) & 0x03) << 4;
  1579. *it++ = key[h | ((static_cast<unsigned char>(*data) & 0xF0) >> 4)];
  1580. h = (static_cast<unsigned char>(*data++) & 0x0F) << 2;
  1581. *it++ = key[h];
  1582. *it++ = '=';
  1583. }
  1584. return ret;
  1585. }
  1586. inline static std::string base64encode(std::string data, size_t size, const char* key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
  1587. {
  1588. return base64encode((const unsigned char*)data.c_str(), size, key);
  1589. }
  1590. inline static std::string base64encode_urlsafe(const unsigned char* data, size_t size)
  1591. {
  1592. return base64encode(data, size, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
  1593. }
  1594. inline static std::string base64encode_urlsafe(std::string data, size_t size)
  1595. {
  1596. return base64encode((const unsigned char*)data.c_str(), size, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
  1597. }
  1598. inline static std::string base64decode(const char* data, size_t size)
  1599. {
  1600. // We accept both regular and url encoding here, as there does not seem to be any downside to that.
  1601. // If we want to distinguish that we should use +/ for non-url and -_ for url.
  1602. // Mapping logic from characters to [0-63]
  1603. auto key = [](char c) -> unsigned char {
  1604. if ((c >= 'A') && (c <= 'Z')) return c - 'A';
  1605. if ((c >= 'a') && (c <= 'z')) return c - 'a' + 26;
  1606. if ((c >= '0') && (c <= '9')) return c - '0' + 52;
  1607. if ((c == '+') || (c == '-')) return 62;
  1608. if ((c == '/') || (c == '_')) return 63;
  1609. return 0;
  1610. };
  1611. // Not padded
  1612. if (size % 4 == 2) // missing last 2 characters
  1613. size = (size / 4 * 3) + 1; // Not subtracting extra characters because they're truncated in int division
  1614. else if (size % 4 == 3) // missing last character
  1615. size = (size / 4 * 3) + 2; // Not subtracting extra characters because they're truncated in int division
  1616. // Padded
  1617. else if (data[size - 2] == '=') // padded with '=='
  1618. size = (size / 4 * 3) - 2; // == padding means the last block only has 1 character instead of 3, hence the '-2'
  1619. else if (data[size - 1] == '=') // padded with '='
  1620. size = (size / 4 * 3) - 1; // = padding means the last block only has 2 character instead of 3, hence the '-1'
  1621. // Padding not needed
  1622. else
  1623. size = size / 4 * 3;
  1624. std::string ret;
  1625. ret.resize(size);
  1626. auto it = ret.begin();
  1627. // These will be used to decode 1 character at a time
  1628. unsigned char odd; // char1 and char3
  1629. unsigned char even; // char2 and char4
  1630. // Take 4 character blocks to turn into 3
  1631. while (size >= 3)
  1632. {
  1633. // dec_char1 = (char1 shifted 2 bits to the left) OR ((char2 AND 00110000) shifted 4 bits to the right))
  1634. odd = key(*data++);
  1635. even = key(*data++);
  1636. *it++ = (odd << 2) | ((even & 0x30) >> 4);
  1637. // dec_char2 = ((char2 AND 00001111) shifted 4 bits left) OR ((char3 AND 00111100) shifted 2 bits right))
  1638. odd = key(*data++);
  1639. *it++ = ((even & 0x0F) << 4) | ((odd & 0x3C) >> 2);
  1640. // dec_char3 = ((char3 AND 00000011) shifted 6 bits left) OR (char4)
  1641. even = key(*data++);
  1642. *it++ = ((odd & 0x03) << 6) | (even);
  1643. size -= 3;
  1644. }
  1645. if (size == 2)
  1646. {
  1647. // d_char1 = (char1 shifted 2 bits to the left) OR ((char2 AND 00110000) shifted 4 bits to the right))
  1648. odd = key(*data++);
  1649. even = key(*data++);
  1650. *it++ = (odd << 2) | ((even & 0x30) >> 4);
  1651. // d_char2 = ((char2 AND 00001111) shifted 4 bits left) OR ((char3 AND 00111100) shifted 2 bits right))
  1652. odd = key(*data++);
  1653. *it++ = ((even & 0x0F) << 4) | ((odd & 0x3C) >> 2);
  1654. }
  1655. else if (size == 1)
  1656. {
  1657. // d_char1 = (char1 shifted 2 bits to the left) OR ((char2 AND 00110000) shifted 4 bits to the right))
  1658. odd = key(*data++);
  1659. even = key(*data++);
  1660. *it++ = (odd << 2) | ((even & 0x30) >> 4);
  1661. }
  1662. return ret;
  1663. }
  1664. inline static std::string base64decode(const std::string& data, size_t size)
  1665. {
  1666. return base64decode(data.data(), size);
  1667. }
  1668. inline static std::string base64decode(const std::string& data)
  1669. {
  1670. return base64decode(data.data(), data.length());
  1671. }
  1672. inline static std::string normalize_path(const std::string& directoryPath)
  1673. {
  1674. std::string normalizedPath = directoryPath;
  1675. std::replace(normalizedPath.begin(), normalizedPath.end(), '\\', '/');
  1676. if (!normalizedPath.empty() && normalizedPath.back() != '/')
  1677. normalizedPath += '/';
  1678. return normalizedPath;
  1679. }
  1680. inline static void sanitize_filename(std::string& data, char replacement = '_')
  1681. {
  1682. if (data.length() > 255)
  1683. data.resize(255);
  1684. static const auto toUpper = [](char c) {
  1685. return ((c >= 'a') && (c <= 'z')) ? (c - ('a' - 'A')) : c;
  1686. };
  1687. // Check for special device names. The Windows behavior is really odd here, it will consider both AUX and AUX.txt
  1688. // a special device. Thus we search for the string (case-insensitive), and then check if the string ends or if
  1689. // is has a dangerous follow up character (.:\/)
  1690. auto sanitizeSpecialFile = [](std::string& source, unsigned ofs, const char* pattern, bool includeNumber, char replacement) {
  1691. unsigned i = ofs;
  1692. size_t len = source.length();
  1693. const char* p = pattern;
  1694. while (*p)
  1695. {
  1696. if (i >= len) return;
  1697. if (toUpper(source[i]) != *p) return;
  1698. ++i;
  1699. ++p;
  1700. }
  1701. if (includeNumber)
  1702. {
  1703. if ((i >= len) || (source[i] < '1') || (source[i] > '9')) return;
  1704. ++i;
  1705. }
  1706. if ((i >= len) || (source[i] == '.') || (source[i] == ':') || (source[i] == '/') || (source[i] == '\\'))
  1707. {
  1708. source.erase(ofs + 1, (i - ofs) - 1);
  1709. source[ofs] = replacement;
  1710. }
  1711. };
  1712. bool checkForSpecialEntries = true;
  1713. for (unsigned i = 0; i < data.length(); ++i)
  1714. {
  1715. // Recognize directory traversals and the special devices CON/PRN/AUX/NULL/COM[1-]/LPT[1-9]
  1716. if (checkForSpecialEntries)
  1717. {
  1718. checkForSpecialEntries = false;
  1719. switch (toUpper(data[i]))
  1720. {
  1721. case 'A':
  1722. sanitizeSpecialFile(data, i, "AUX", false, replacement);
  1723. break;
  1724. case 'C':
  1725. sanitizeSpecialFile(data, i, "CON", false, replacement);
  1726. sanitizeSpecialFile(data, i, "COM", true, replacement);
  1727. break;
  1728. case 'L':
  1729. sanitizeSpecialFile(data, i, "LPT", true, replacement);
  1730. break;
  1731. case 'N':
  1732. sanitizeSpecialFile(data, i, "NUL", false, replacement);
  1733. break;
  1734. case 'P':
  1735. sanitizeSpecialFile(data, i, "PRN", false, replacement);
  1736. break;
  1737. case '.':
  1738. sanitizeSpecialFile(data, i, "..", false, replacement);
  1739. break;
  1740. }
  1741. }
  1742. // Sanitize individual characters
  1743. unsigned char c = data[i];
  1744. if ((c < ' ') || ((c >= 0x80) && (c <= 0x9F)) || (c == '?') || (c == '<') || (c == '>') || (c == ':') || (c == '*') || (c == '|') || (c == '\"'))
  1745. {
  1746. data[i] = replacement;
  1747. }
  1748. else if ((c == '/') || (c == '\\'))
  1749. {
  1750. if (CROW_UNLIKELY(i == 0)) //Prevent Unix Absolute Paths (Windows Absolute Paths are prevented with `(c == ':')`)
  1751. {
  1752. data[i] = replacement;
  1753. }
  1754. else
  1755. {
  1756. checkForSpecialEntries = true;
  1757. }
  1758. }
  1759. }
  1760. }
  1761. inline static std::string random_alphanum(std::size_t size)
  1762. {
  1763. static const char alphabet[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  1764. std::random_device dev;
  1765. std::mt19937 rng(dev());
  1766. std::uniform_int_distribution<std::mt19937::result_type> dist(0, sizeof(alphabet) - 2);
  1767. std::string out;
  1768. out.reserve(size);
  1769. for (std::size_t i = 0; i < size; i++)
  1770. out.push_back(alphabet[dist(rng)]);
  1771. return out;
  1772. }
  1773. inline static std::string join_path(std::string path, const std::string& fname)
  1774. {
  1775. #if defined(CROW_CAN_USE_CPP17) && !defined(CROW_FILESYSTEM_IS_EXPERIMENTAL)
  1776. return (std::filesystem::path(path) / fname).string();
  1777. #else
  1778. if (!(path.back() == '/' || path.back() == '\\'))
  1779. path += '/';
  1780. path += fname;
  1781. return path;
  1782. #endif
  1783. }
  1784. /**
  1785. * @brief Checks two string for equality.
  1786. * Always returns false if strings differ in size.
  1787. * Defaults to case-insensitive comparison.
  1788. */
  1789. inline static bool string_equals(const std::string& l, const std::string& r, bool case_sensitive = false)
  1790. {
  1791. if (l.length() != r.length())
  1792. return false;
  1793. for (size_t i = 0; i < l.length(); i++)
  1794. {
  1795. if (case_sensitive)
  1796. {
  1797. if (l[i] != r[i])
  1798. return false;
  1799. }
  1800. else
  1801. {
  1802. if (std::toupper(l[i]) != std::toupper(r[i]))
  1803. return false;
  1804. }
  1805. }
  1806. return true;
  1807. }
  1808. template<typename T, typename U>
  1809. inline static T lexical_cast(const U& v)
  1810. {
  1811. std::stringstream stream;
  1812. T res;
  1813. stream << v;
  1814. stream >> res;
  1815. return res;
  1816. }
  1817. template<typename T>
  1818. inline static T lexical_cast(const char* v, size_t count)
  1819. {
  1820. std::stringstream stream;
  1821. T res;
  1822. stream.write(v, count);
  1823. stream >> res;
  1824. return res;
  1825. }
  1826. /// Return a copy of the given string with its
  1827. /// leading and trailing whitespaces removed.
  1828. inline static std::string trim(const std::string& v)
  1829. {
  1830. if (v.empty())
  1831. return "";
  1832. size_t begin = 0, end = v.length();
  1833. size_t i;
  1834. for (i = 0; i < v.length(); i++)
  1835. {
  1836. if (!std::isspace(v[i]))
  1837. {
  1838. begin = i;
  1839. break;
  1840. }
  1841. }
  1842. if (i == v.length())
  1843. return "";
  1844. for (i = v.length(); i > 0; i--)
  1845. {
  1846. if (!std::isspace(v[i - 1]))
  1847. {
  1848. end = i;
  1849. break;
  1850. }
  1851. }
  1852. return v.substr(begin, end - begin);
  1853. }
  1854. } // namespace utility
  1855. } // namespace crow
  1856. #include <locale>
  1857. #include <unordered_map>
  1858. namespace crow
  1859. {
  1860. /// Hashing function for ci_map (unordered_multimap).
  1861. struct ci_hash
  1862. {
  1863. size_t operator()(const std::string& key) const
  1864. {
  1865. std::size_t seed = 0;
  1866. std::locale locale;
  1867. for (auto c : key)
  1868. hash_combine(seed, std::toupper(c, locale));
  1869. return seed;
  1870. }
  1871. private:
  1872. static inline void hash_combine(std::size_t& seed, char v)
  1873. {
  1874. std::hash<char> hasher;
  1875. seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
  1876. }
  1877. };
  1878. /// Equals function for ci_map (unordered_multimap).
  1879. struct ci_key_eq
  1880. {
  1881. bool operator()(const std::string& l, const std::string& r) const
  1882. {
  1883. return utility::string_equals(l, r);
  1884. }
  1885. };
  1886. using ci_map = std::unordered_multimap<std::string, std::string, ci_hash, ci_key_eq>;
  1887. } // namespace crow
  1888. #include <vector>
  1889. #include <string>
  1890. #include <stdexcept>
  1891. #include <iostream>
  1892. namespace crow
  1893. {
  1894. const char cr = '\r';
  1895. const char lf = '\n';
  1896. const std::string crlf("\r\n");
  1897. enum class HTTPMethod : char
  1898. {
  1899. #ifndef DELETE
  1900. DELETE = 0,
  1901. GET,
  1902. HEAD,
  1903. POST,
  1904. PUT,
  1905. CONNECT,
  1906. OPTIONS,
  1907. TRACE,
  1908. PATCH,
  1909. PURGE,
  1910. COPY,
  1911. LOCK,
  1912. MKCOL,
  1913. MOVE,
  1914. PROPFIND,
  1915. PROPPATCH,
  1916. SEARCH,
  1917. UNLOCK,
  1918. BIND,
  1919. REBIND,
  1920. UNBIND,
  1921. ACL,
  1922. REPORT,
  1923. MKACTIVITY,
  1924. CHECKOUT,
  1925. MERGE,
  1926. MSEARCH,
  1927. NOTIFY,
  1928. SUBSCRIBE,
  1929. UNSUBSCRIBE,
  1930. MKCALENDAR,
  1931. LINK,
  1932. UNLINK,
  1933. SOURCE,
  1934. #endif
  1935. Delete = 0,
  1936. Get,
  1937. Head,
  1938. Post,
  1939. Put,
  1940. Connect,
  1941. Options,
  1942. Trace,
  1943. Patch,
  1944. Purge,
  1945. Copy,
  1946. Lock,
  1947. MkCol,
  1948. Move,
  1949. Propfind,
  1950. Proppatch,
  1951. Search,
  1952. Unlock,
  1953. Bind,
  1954. Rebind,
  1955. Unbind,
  1956. Acl,
  1957. Report,
  1958. MkActivity,
  1959. Checkout,
  1960. Merge,
  1961. MSearch,
  1962. Notify,
  1963. Subscribe,
  1964. Unsubscribe,
  1965. MkCalendar,
  1966. Link,
  1967. Unlink,
  1968. Source,
  1969. InternalMethodCount,
  1970. // should not add an item below this line: used for array count
  1971. };
  1972. constexpr const char* method_strings[] =
  1973. {
  1974. "DELETE",
  1975. "GET",
  1976. "HEAD",
  1977. "POST",
  1978. "PUT",
  1979. "CONNECT",
  1980. "OPTIONS",
  1981. "TRACE",
  1982. "PATCH",
  1983. "PURGE",
  1984. "COPY",
  1985. "LOCK",
  1986. "MKCOL",
  1987. "MOVE",
  1988. "PROPFIND",
  1989. "PROPPATCH",
  1990. "SEARCH",
  1991. "UNLOCK",
  1992. "BIND",
  1993. "REBIND",
  1994. "UNBIND",
  1995. "ACL",
  1996. "REPORT",
  1997. "MKACTIVITY",
  1998. "CHECKOUT",
  1999. "MERGE",
  2000. "M-SEARCH",
  2001. "NOTIFY",
  2002. "SUBSCRIBE",
  2003. "UNSUBSCRIBE",
  2004. "MKCALENDAR",
  2005. "LINK",
  2006. "UNLINK",
  2007. "SOURCE"};
  2008. inline std::string method_name(HTTPMethod method)
  2009. {
  2010. if (CROW_LIKELY(method < HTTPMethod::InternalMethodCount))
  2011. {
  2012. return method_strings[(unsigned char)method];
  2013. }
  2014. return "invalid";
  2015. }
  2016. // clang-format off
  2017. enum status
  2018. {
  2019. CONTINUE = 100,
  2020. SWITCHING_PROTOCOLS = 101,
  2021. OK = 200,
  2022. CREATED = 201,
  2023. ACCEPTED = 202,
  2024. NON_AUTHORITATIVE_INFORMATION = 203,
  2025. NO_CONTENT = 204,
  2026. RESET_CONTENT = 205,
  2027. PARTIAL_CONTENT = 206,
  2028. MULTIPLE_CHOICES = 300,
  2029. MOVED_PERMANENTLY = 301,
  2030. FOUND = 302,
  2031. SEE_OTHER = 303,
  2032. NOT_MODIFIED = 304,
  2033. TEMPORARY_REDIRECT = 307,
  2034. PERMANENT_REDIRECT = 308,
  2035. BAD_REQUEST = 400,
  2036. UNAUTHORIZED = 401,
  2037. FORBIDDEN = 403,
  2038. NOT_FOUND = 404,
  2039. METHOD_NOT_ALLOWED = 405,
  2040. NOT_ACCEPTABLE = 406,
  2041. PROXY_AUTHENTICATION_REQUIRED = 407,
  2042. CONFLICT = 409,
  2043. GONE = 410,
  2044. PAYLOAD_TOO_LARGE = 413,
  2045. UNSUPPORTED_MEDIA_TYPE = 415,
  2046. RANGE_NOT_SATISFIABLE = 416,
  2047. EXPECTATION_FAILED = 417,
  2048. PRECONDITION_REQUIRED = 428,
  2049. TOO_MANY_REQUESTS = 429,
  2050. UNAVAILABLE_FOR_LEGAL_REASONS = 451,
  2051. INTERNAL_SERVER_ERROR = 500,
  2052. NOT_IMPLEMENTED = 501,
  2053. BAD_GATEWAY = 502,
  2054. SERVICE_UNAVAILABLE = 503,
  2055. GATEWAY_TIMEOUT = 504,
  2056. VARIANT_ALSO_NEGOTIATES = 506
  2057. };
  2058. // clang-format on
  2059. enum class ParamType : char
  2060. {
  2061. INT,
  2062. UINT,
  2063. DOUBLE,
  2064. STRING,
  2065. PATH,
  2066. MAX
  2067. };
  2068. /// @cond SKIP
  2069. struct routing_params
  2070. {
  2071. std::vector<int64_t> int_params;
  2072. std::vector<uint64_t> uint_params;
  2073. std::vector<double> double_params;
  2074. std::vector<std::string> string_params;
  2075. void debug_print() const
  2076. {
  2077. std::cerr << "routing_params" << std::endl;
  2078. for (auto i : int_params)
  2079. std::cerr << i << ", ";
  2080. std::cerr << std::endl;
  2081. for (auto i : uint_params)
  2082. std::cerr << i << ", ";
  2083. std::cerr << std::endl;
  2084. for (auto i : double_params)
  2085. std::cerr << i << ", ";
  2086. std::cerr << std::endl;
  2087. for (auto& i : string_params)
  2088. std::cerr << i << ", ";
  2089. std::cerr << std::endl;
  2090. }
  2091. template<typename T>
  2092. T get(unsigned) const;
  2093. };
  2094. template<>
  2095. inline int64_t routing_params::get<int64_t>(unsigned index) const
  2096. {
  2097. return int_params[index];
  2098. }
  2099. template<>
  2100. inline uint64_t routing_params::get<uint64_t>(unsigned index) const
  2101. {
  2102. return uint_params[index];
  2103. }
  2104. template<>
  2105. inline double routing_params::get<double>(unsigned index) const
  2106. {
  2107. return double_params[index];
  2108. }
  2109. template<>
  2110. inline std::string routing_params::get<std::string>(unsigned index) const
  2111. {
  2112. return string_params[index];
  2113. }
  2114. /// @endcond
  2115. struct routing_handle_result
  2116. {
  2117. uint16_t rule_index;
  2118. std::vector<uint16_t> blueprint_indices;
  2119. routing_params r_params;
  2120. HTTPMethod method;
  2121. routing_handle_result() {}
  2122. routing_handle_result(uint16_t rule_index_, std::vector<uint16_t> blueprint_indices_, routing_params r_params_):
  2123. rule_index(rule_index_),
  2124. blueprint_indices(blueprint_indices_),
  2125. r_params(r_params_) {}
  2126. routing_handle_result(uint16_t rule_index_, std::vector<uint16_t> blueprint_indices_, routing_params r_params_, HTTPMethod method_):
  2127. rule_index(rule_index_),
  2128. blueprint_indices(blueprint_indices_),
  2129. r_params(r_params_),
  2130. method(method_) {}
  2131. };
  2132. } // namespace crow
  2133. // clang-format off
  2134. #ifndef CROW_MSVC_WORKAROUND
  2135. constexpr crow::HTTPMethod method_from_string(const char* str)
  2136. {
  2137. return crow::black_magic::is_equ_p(str, "GET", 3) ? crow::HTTPMethod::Get :
  2138. crow::black_magic::is_equ_p(str, "DELETE", 6) ? crow::HTTPMethod::Delete :
  2139. crow::black_magic::is_equ_p(str, "HEAD", 4) ? crow::HTTPMethod::Head :
  2140. crow::black_magic::is_equ_p(str, "POST", 4) ? crow::HTTPMethod::Post :
  2141. crow::black_magic::is_equ_p(str, "PUT", 3) ? crow::HTTPMethod::Put :
  2142. crow::black_magic::is_equ_p(str, "OPTIONS", 7) ? crow::HTTPMethod::Options :
  2143. crow::black_magic::is_equ_p(str, "CONNECT", 7) ? crow::HTTPMethod::Connect :
  2144. crow::black_magic::is_equ_p(str, "TRACE", 5) ? crow::HTTPMethod::Trace :
  2145. crow::black_magic::is_equ_p(str, "PATCH", 5) ? crow::HTTPMethod::Patch :
  2146. crow::black_magic::is_equ_p(str, "PURGE", 5) ? crow::HTTPMethod::Purge :
  2147. crow::black_magic::is_equ_p(str, "COPY", 4) ? crow::HTTPMethod::Copy :
  2148. crow::black_magic::is_equ_p(str, "LOCK", 4) ? crow::HTTPMethod::Lock :
  2149. crow::black_magic::is_equ_p(str, "MKCOL", 5) ? crow::HTTPMethod::MkCol :
  2150. crow::black_magic::is_equ_p(str, "MOVE", 4) ? crow::HTTPMethod::Move :
  2151. crow::black_magic::is_equ_p(str, "PROPFIND", 8) ? crow::HTTPMethod::Propfind :
  2152. crow::black_magic::is_equ_p(str, "PROPPATCH", 9) ? crow::HTTPMethod::Proppatch :
  2153. crow::black_magic::is_equ_p(str, "SEARCH", 6) ? crow::HTTPMethod::Search :
  2154. crow::black_magic::is_equ_p(str, "UNLOCK", 6) ? crow::HTTPMethod::Unlock :
  2155. crow::black_magic::is_equ_p(str, "BIND", 4) ? crow::HTTPMethod::Bind :
  2156. crow::black_magic::is_equ_p(str, "REBIND", 6) ? crow::HTTPMethod::Rebind :
  2157. crow::black_magic::is_equ_p(str, "UNBIND", 6) ? crow::HTTPMethod::Unbind :
  2158. crow::black_magic::is_equ_p(str, "ACL", 3) ? crow::HTTPMethod::Acl :
  2159. crow::black_magic::is_equ_p(str, "REPORT", 6) ? crow::HTTPMethod::Report :
  2160. crow::black_magic::is_equ_p(str, "MKACTIVITY", 10) ? crow::HTTPMethod::MkActivity :
  2161. crow::black_magic::is_equ_p(str, "CHECKOUT", 8) ? crow::HTTPMethod::Checkout :
  2162. crow::black_magic::is_equ_p(str, "MERGE", 5) ? crow::HTTPMethod::Merge :
  2163. crow::black_magic::is_equ_p(str, "MSEARCH", 7) ? crow::HTTPMethod::MSearch :
  2164. crow::black_magic::is_equ_p(str, "NOTIFY", 6) ? crow::HTTPMethod::Notify :
  2165. crow::black_magic::is_equ_p(str, "SUBSCRIBE", 9) ? crow::HTTPMethod::Subscribe :
  2166. crow::black_magic::is_equ_p(str, "UNSUBSCRIBE", 11) ? crow::HTTPMethod::Unsubscribe :
  2167. crow::black_magic::is_equ_p(str, "MKCALENDAR", 10) ? crow::HTTPMethod::MkCalendar :
  2168. crow::black_magic::is_equ_p(str, "LINK", 4) ? crow::HTTPMethod::Link :
  2169. crow::black_magic::is_equ_p(str, "UNLINK", 6) ? crow::HTTPMethod::Unlink :
  2170. crow::black_magic::is_equ_p(str, "SOURCE", 6) ? crow::HTTPMethod::Source :
  2171. throw std::runtime_error("invalid http method");
  2172. }
  2173. constexpr crow::HTTPMethod operator"" _method(const char* str, size_t /*len*/)
  2174. {
  2175. return method_from_string( str );
  2176. }
  2177. #endif
  2178. // clang-format on
  2179. #ifdef CROW_USE_BOOST
  2180. #include <boost/asio.hpp>
  2181. #else
  2182. #ifndef ASIO_STANDALONE
  2183. #define ASIO_STANDALONE
  2184. #endif
  2185. #include <asio.hpp>
  2186. #endif
  2187. namespace crow // NOTE: Already documented in "crow/app.h"
  2188. {
  2189. #ifdef CROW_USE_BOOST
  2190. namespace asio = boost::asio;
  2191. #endif
  2192. /// Find and return the value associated with the key. (returns an empty string if nothing is found)
  2193. template<typename T>
  2194. inline const std::string& get_header_value(const T& headers, const std::string& key)
  2195. {
  2196. if (headers.count(key))
  2197. {
  2198. return headers.find(key)->second;
  2199. }
  2200. static std::string empty;
  2201. return empty;
  2202. }
  2203. /// An HTTP request.
  2204. struct request
  2205. {
  2206. HTTPMethod method;
  2207. std::string raw_url; ///< The full URL containing the `?` and URL parameters.
  2208. std::string url; ///< The endpoint without any parameters.
  2209. query_string url_params; ///< The parameters associated with the request. (everything after the `?` in the URL)
  2210. ci_map headers;
  2211. std::string body;
  2212. std::string remote_ip_address; ///< The IP address from which the request was sent.
  2213. unsigned char http_ver_major, http_ver_minor;
  2214. bool keep_alive, ///< Whether or not the server should send a `connection: Keep-Alive` header to the client.
  2215. close_connection, ///< Whether or not the server should shut down the TCP connection once a response is sent.
  2216. upgrade; ///< Whether or noth the server should change the HTTP connection to a different connection.
  2217. void* middleware_context{};
  2218. void* middleware_container{};
  2219. asio::io_service* io_service{};
  2220. /// Construct an empty request. (sets the method to `GET`)
  2221. request():
  2222. method(HTTPMethod::Get)
  2223. {}
  2224. /// Construct a request with all values assigned.
  2225. request(HTTPMethod method, std::string raw_url, std::string url, query_string url_params, ci_map headers, std::string body, unsigned char http_major, unsigned char http_minor, bool has_keep_alive, bool has_close_connection, bool is_upgrade):
  2226. method(method), raw_url(std::move(raw_url)), url(std::move(url)), url_params(std::move(url_params)), headers(std::move(headers)), body(std::move(body)), http_ver_major(http_major), http_ver_minor(http_minor), keep_alive(has_keep_alive), close_connection(has_close_connection), upgrade(is_upgrade)
  2227. {}
  2228. void add_header(std::string key, std::string value)
  2229. {
  2230. headers.emplace(std::move(key), std::move(value));
  2231. }
  2232. const std::string& get_header_value(const std::string& key) const
  2233. {
  2234. return crow::get_header_value(headers, key);
  2235. }
  2236. bool check_version(unsigned char major, unsigned char minor) const
  2237. {
  2238. return http_ver_major == major && http_ver_minor == minor;
  2239. }
  2240. /// Get the body as parameters in QS format.
  2241. ///
  2242. /// This is meant to be used with requests of type "application/x-www-form-urlencoded"
  2243. const query_string get_body_params() const
  2244. {
  2245. return query_string(body, false);
  2246. }
  2247. /// Send data to whoever made this request with a completion handler and return immediately.
  2248. template<typename CompletionHandler>
  2249. void post(CompletionHandler handler)
  2250. {
  2251. io_service->post(handler);
  2252. }
  2253. /// Send data to whoever made this request with a completion handler.
  2254. template<typename CompletionHandler>
  2255. void dispatch(CompletionHandler handler)
  2256. {
  2257. io_service->dispatch(handler);
  2258. }
  2259. };
  2260. } // namespace crow
  2261. #include <string>
  2262. #include <vector>
  2263. #include <sstream>
  2264. namespace crow
  2265. {
  2266. /// Encapsulates anything related to processing and organizing `multipart/xyz` messages
  2267. namespace multipart
  2268. {
  2269. const std::string dd = "--";
  2270. /// The first part in a section, contains metadata about the part
  2271. struct header
  2272. {
  2273. std::string value; ///< The first part of the header, usually `Content-Type` or `Content-Disposition`
  2274. std::unordered_map<std::string, std::string> params; ///< The parameters of the header, come after the `value`
  2275. operator int() const { return std::stoi(value); } ///< Returns \ref value as integer
  2276. operator double() const { return std::stod(value); } ///< Returns \ref value as double
  2277. };
  2278. /// Multipart header map (key is header key).
  2279. using mph_map = std::unordered_multimap<std::string, header, ci_hash, ci_key_eq>;
  2280. /// Find and return the value object associated with the key. (returns an empty class if nothing is found)
  2281. template<typename O, typename T>
  2282. inline const O& get_header_value_object(const T& headers, const std::string& key)
  2283. {
  2284. if (headers.count(key))
  2285. {
  2286. return headers.find(key)->second;
  2287. }
  2288. static O empty;
  2289. return empty;
  2290. }
  2291. /// Same as \ref get_header_value_object() but for \ref multipart.header
  2292. template<typename T>
  2293. inline const header& get_header_object(const T& headers, const std::string& key)
  2294. {
  2295. return get_header_value_object<header>(headers, key);
  2296. }
  2297. ///One part of the multipart message
  2298. ///
  2299. /// It is usually separated from other sections by a `boundary`
  2300. struct part
  2301. {
  2302. mph_map headers; ///< (optional) The first part before the data, Contains information regarding the type of data and encoding
  2303. std::string body; ///< The actual data in the part
  2304. operator int() const { return std::stoi(body); } ///< Returns \ref body as integer
  2305. operator double() const { return std::stod(body); } ///< Returns \ref body as double
  2306. const header& get_header_object(const std::string& key) const
  2307. {
  2308. return multipart::get_header_object(headers, key);
  2309. }
  2310. };
  2311. /// Multipart map (key is the name parameter).
  2312. using mp_map = std::unordered_multimap<std::string, part, ci_hash, ci_key_eq>;
  2313. /// The parsed multipart request/response
  2314. struct message : public returnable
  2315. {
  2316. ci_map headers; ///< The request/response headers
  2317. std::string boundary; ///< The text boundary that separates different `parts`
  2318. std::vector<part> parts; ///< The individual parts of the message
  2319. mp_map part_map; ///< The individual parts of the message, organized in a map with the `name` header parameter being the key
  2320. const std::string& get_header_value(const std::string& key) const
  2321. {
  2322. return crow::get_header_value(headers, key);
  2323. }
  2324. part get_part_by_name(const std::string& name)
  2325. {
  2326. mp_map::iterator result = part_map.find(name);
  2327. if (result != part_map.end())
  2328. return result->second;
  2329. else
  2330. return {};
  2331. }
  2332. /// Represent all parts as a string (**does not include message headers**)
  2333. std::string dump() const override
  2334. {
  2335. std::stringstream str;
  2336. std::string delimiter = dd + boundary;
  2337. for (unsigned i = 0; i < parts.size(); i++)
  2338. {
  2339. str << delimiter << crlf;
  2340. str << dump(i);
  2341. }
  2342. str << delimiter << dd << crlf;
  2343. return str.str();
  2344. }
  2345. /// Represent an individual part as a string
  2346. std::string dump(int part_) const
  2347. {
  2348. std::stringstream str;
  2349. part item = parts[part_];
  2350. for (auto& item_h : item.headers)
  2351. {
  2352. str << item_h.first << ": " << item_h.second.value;
  2353. for (auto& it : item_h.second.params)
  2354. {
  2355. str << "; " << it.first << '=' << pad(it.second);
  2356. }
  2357. str << crlf;
  2358. }
  2359. str << crlf;
  2360. str << item.body << crlf;
  2361. return str.str();
  2362. }
  2363. /// Default constructor using default values
  2364. message(const ci_map& headers, const std::string& boundary, const std::vector<part>& sections):
  2365. returnable("multipart/form-data; boundary=CROW-BOUNDARY"), headers(headers), boundary(boundary), parts(sections)
  2366. {
  2367. if (!boundary.empty())
  2368. content_type = "multipart/form-data; boundary=" + boundary;
  2369. for (auto& item : parts)
  2370. {
  2371. part_map.emplace(
  2372. (get_header_object(item.headers, "Content-Disposition").params.find("name")->second),
  2373. item);
  2374. }
  2375. }
  2376. /// Create a multipart message from a request data
  2377. message(const request& req):
  2378. returnable("multipart/form-data; boundary=CROW-BOUNDARY"),
  2379. headers(req.headers),
  2380. boundary(get_boundary(get_header_value("Content-Type")))
  2381. {
  2382. if (!boundary.empty())
  2383. content_type = "multipart/form-data; boundary=" + boundary;
  2384. parse_body(req.body, parts, part_map);
  2385. }
  2386. private:
  2387. std::string get_boundary(const std::string& header) const
  2388. {
  2389. constexpr char boundary_text[] = "boundary=";
  2390. size_t found = header.find(boundary_text);
  2391. if (found != std::string::npos)
  2392. {
  2393. std::string to_return(header.substr(found + strlen(boundary_text)));
  2394. if (to_return[0] == '\"')
  2395. {
  2396. to_return = to_return.substr(1, to_return.length() - 2);
  2397. }
  2398. return to_return;
  2399. }
  2400. return std::string();
  2401. }
  2402. void parse_body(std::string body, std::vector<part>& sections, mp_map& part_map)
  2403. {
  2404. std::string delimiter = dd + boundary;
  2405. // TODO(EDev): Exit on error
  2406. while (body != (crlf))
  2407. {
  2408. size_t found = body.find(delimiter);
  2409. if (found == std::string::npos)
  2410. {
  2411. // did not find delimiter; probably an ill-formed body; ignore the rest
  2412. break;
  2413. }
  2414. std::string section = body.substr(0, found);
  2415. // +2 is the CRLF.
  2416. // We don't check it and delete it so that the same delimiter can be used for The last delimiter (--delimiter--CRLF).
  2417. body.erase(0, found + delimiter.length() + 2);
  2418. if (!section.empty())
  2419. {
  2420. part parsed_section(parse_section(section));
  2421. part_map.emplace(
  2422. (get_header_object(parsed_section.headers, "Content-Disposition").params.find("name")->second),
  2423. parsed_section);
  2424. sections.push_back(std::move(parsed_section));
  2425. }
  2426. }
  2427. }
  2428. part parse_section(std::string& section)
  2429. {
  2430. struct part to_return;
  2431. size_t found = section.find(crlf + crlf);
  2432. std::string head_line = section.substr(0, found + 2);
  2433. section.erase(0, found + 4);
  2434. parse_section_head(head_line, to_return);
  2435. to_return.body = section.substr(0, section.length() - 2);
  2436. return to_return;
  2437. }
  2438. void parse_section_head(std::string& lines, part& part)
  2439. {
  2440. while (!lines.empty())
  2441. {
  2442. header to_add;
  2443. size_t found = lines.find(crlf);
  2444. std::string line = lines.substr(0, found);
  2445. std::string key;
  2446. lines.erase(0, found + 2);
  2447. // Add the header if available
  2448. if (!line.empty())
  2449. {
  2450. size_t found = line.find("; ");
  2451. std::string header = line.substr(0, found);
  2452. if (found != std::string::npos)
  2453. line.erase(0, found + 2);
  2454. else
  2455. line = std::string();
  2456. size_t header_split = header.find(": ");
  2457. key = header.substr(0, header_split);
  2458. to_add.value = header.substr(header_split + 2);
  2459. }
  2460. // Add the parameters
  2461. while (!line.empty())
  2462. {
  2463. size_t found = line.find("; ");
  2464. std::string param = line.substr(0, found);
  2465. if (found != std::string::npos)
  2466. line.erase(0, found + 2);
  2467. else
  2468. line = std::string();
  2469. size_t param_split = param.find('=');
  2470. std::string value = param.substr(param_split + 1);
  2471. to_add.params.emplace(param.substr(0, param_split), trim(value));
  2472. }
  2473. part.headers.emplace(key, to_add);
  2474. }
  2475. }
  2476. inline std::string trim(std::string& string, const char& excess = '"') const
  2477. {
  2478. if (string.length() > 1 && string[0] == excess && string[string.length() - 1] == excess)
  2479. return string.substr(1, string.length() - 2);
  2480. return string;
  2481. }
  2482. inline std::string pad(std::string& string, const char& padding = '"') const
  2483. {
  2484. return (padding + string + padding);
  2485. }
  2486. };
  2487. } // namespace multipart
  2488. } // namespace crow
  2489. /* merged revision: 5b951d74bd66ec9d38448e0a85b1cf8b85d97db3 */
  2490. /* updated to : e13b274770da9b82a1085dec29182acfea72e7a7 (beyond v2.9.5) */
  2491. /* commits not included:
  2492. * 091ebb87783a58b249062540bbea07de2a11e9cf
  2493. * 6132d1fefa03f769a3979355d1f5da0b8889cad2
  2494. * 7ba312397c2a6c851a4b5efe6c1603b1e1bda6ff
  2495. * d7675453a6c03180572f084e95eea0d02df39164
  2496. * dff604db203986e532e5a679bafd0e7382c6bdd9 (Might be useful to actually add [upgrade requests with a body])
  2497. * e01811e7f4894d7f0f7f4bd8492cccec6f6b4038 (related to above)
  2498. * 05525c5fde1fc562481f6ae08fa7056185325daf (also related to above)
  2499. * 350258965909f249f9c59823aac240313e0d0120 (cannot be implemented due to upgrade)
  2500. */
  2501. // clang-format off
  2502. extern "C" {
  2503. #include <stddef.h>
  2504. #if defined(_WIN32) && !defined(__MINGW32__) && \
  2505. (!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
  2506. #include <BaseTsd.h>
  2507. typedef __int8 int8_t;
  2508. typedef unsigned __int8 uint8_t;
  2509. typedef __int16 int16_t;
  2510. typedef unsigned __int16 uint16_t;
  2511. typedef __int32 int32_t;
  2512. typedef unsigned __int32 uint32_t;
  2513. typedef __int64 int64_t;
  2514. typedef unsigned __int64 uint64_t;
  2515. #elif (defined(__sun) || defined(__sun__)) && defined(__SunOS_5_9)
  2516. #include <sys/inttypes.h>
  2517. #else
  2518. #include <stdint.h>
  2519. #endif
  2520. #include <assert.h>
  2521. #include <ctype.h>
  2522. #include <string.h>
  2523. #include <limits.h>
  2524. }
  2525. namespace crow
  2526. {
  2527. /* Maximium header size allowed. If the macro is not defined
  2528. * before including this header then the default is used. To
  2529. * change the maximum header size, define the macro in the build
  2530. * environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
  2531. * the effective limit on the size of the header, define the macro
  2532. * to a very large number (e.g. -DCROW_HTTP_MAX_HEADER_SIZE=0x7fffffff)
  2533. */
  2534. #ifndef CROW_HTTP_MAX_HEADER_SIZE
  2535. # define CROW_HTTP_MAX_HEADER_SIZE (80*1024)
  2536. #endif
  2537. typedef struct http_parser http_parser;
  2538. typedef struct http_parser_settings http_parser_settings;
  2539. /* Callbacks should return non-zero to indicate an error. The parser will
  2540. * then halt execution.
  2541. *
  2542. * The one exception is on_headers_complete. In a HTTP_RESPONSE parser
  2543. * returning '1' from on_headers_complete will tell the parser that it
  2544. * should not expect a body. This is used when receiving a response to a
  2545. * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
  2546. * chunked' headers that indicate the presence of a body.
  2547. *
  2548. * Returning `2` from on_headers_complete will tell parser that it should not
  2549. * expect neither a body nor any futher responses on this connection. This is
  2550. * useful for handling responses to a CONNECT request which may not contain
  2551. * `Upgrade` or `Connection: upgrade` headers.
  2552. *
  2553. * http_data_cb does not return data chunks. It will be called arbitrarally
  2554. * many times for each string. E.G. you might get 10 callbacks for "on_url"
  2555. * each providing just a few characters more data.
  2556. */
  2557. typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
  2558. typedef int (*http_cb) (http_parser*);
  2559. /* Flag values for http_parser.flags field */
  2560. enum http_connection_flags // This is basically 7 booleans placed into 1 integer. Uses 4 bytes instead of n bytes (7 currently).
  2561. { F_CHUNKED = 1 << 0 // 00000000 00000000 00000000 00000001
  2562. , F_CONNECTION_KEEP_ALIVE = 1 << 1 // 00000000 00000000 00000000 00000010
  2563. , F_CONNECTION_CLOSE = 1 << 2 // 00000000 00000000 00000000 00000100
  2564. , F_TRAILING = 1 << 3 // 00000000 00000000 00000000 00001000
  2565. , F_UPGRADE = 1 << 4 // 00000000 00000000 00000000 00010000
  2566. , F_SKIPBODY = 1 << 5 // 00000000 00000000 00000000 00100000
  2567. , F_CONTENTLENGTH = 1 << 6 // 00000000 00000000 00000000 01000000
  2568. };
  2569. /* Map for errno-related constants
  2570. *
  2571. * The provided argument should be a macro that takes 2 arguments.
  2572. */
  2573. #define CROW_HTTP_ERRNO_MAP(CROW_XX) \
  2574. /* No error */ \
  2575. CROW_XX(OK, "success") \
  2576. \
  2577. /* Callback-related errors */ \
  2578. CROW_XX(CB_message_begin, "the on_message_begin callback failed") \
  2579. CROW_XX(CB_method, "the on_method callback failed") \
  2580. CROW_XX(CB_url, "the \"on_url\" callback failed") \
  2581. CROW_XX(CB_header_field, "the \"on_header_field\" callback failed") \
  2582. CROW_XX(CB_header_value, "the \"on_header_value\" callback failed") \
  2583. CROW_XX(CB_headers_complete, "the \"on_headers_complete\" callback failed") \
  2584. CROW_XX(CB_body, "the \"on_body\" callback failed") \
  2585. CROW_XX(CB_message_complete, "the \"on_message_complete\" callback failed") \
  2586. CROW_XX(CB_status, "the \"on_status\" callback failed") \
  2587. \
  2588. /* Parsing-related errors */ \
  2589. CROW_XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \
  2590. CROW_XX(HEADER_OVERFLOW, "too many header bytes seen; overflow detected") \
  2591. CROW_XX(CLOSED_CONNECTION, "data received after completed connection: close message") \
  2592. CROW_XX(INVALID_VERSION, "invalid HTTP version") \
  2593. CROW_XX(INVALID_STATUS, "invalid HTTP status code") \
  2594. CROW_XX(INVALID_METHOD, "invalid HTTP method") \
  2595. CROW_XX(INVALID_URL, "invalid URL") \
  2596. CROW_XX(INVALID_HOST, "invalid host") \
  2597. CROW_XX(INVALID_PORT, "invalid port") \
  2598. CROW_XX(INVALID_PATH, "invalid path") \
  2599. CROW_XX(INVALID_QUERY_STRING, "invalid query string") \
  2600. CROW_XX(INVALID_FRAGMENT, "invalid fragment") \
  2601. CROW_XX(LF_EXPECTED, "LF character expected") \
  2602. CROW_XX(INVALID_HEADER_TOKEN, "invalid character in header") \
  2603. CROW_XX(INVALID_CONTENT_LENGTH, "invalid character in content-length header") \
  2604. CROW_XX(UNEXPECTED_CONTENT_LENGTH, "unexpected content-length header") \
  2605. CROW_XX(INVALID_CHUNK_SIZE, "invalid character in chunk size header") \
  2606. CROW_XX(INVALID_CONSTANT, "invalid constant string") \
  2607. CROW_XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state") \
  2608. CROW_XX(STRICT, "strict mode assertion failed") \
  2609. CROW_XX(UNKNOWN, "an unknown error occurred") \
  2610. CROW_XX(INVALID_TRANSFER_ENCODING, "request has invalid transfer-encoding") \
  2611. /* Define CHPE_* values for each errno value above */
  2612. #define CROW_HTTP_ERRNO_GEN(n, s) CHPE_##n,
  2613. enum http_errno {
  2614. CROW_HTTP_ERRNO_MAP(CROW_HTTP_ERRNO_GEN)
  2615. };
  2616. #undef CROW_HTTP_ERRNO_GEN
  2617. /* Get an http_errno value from an http_parser */
  2618. #define CROW_HTTP_PARSER_ERRNO(p) ((enum http_errno)(p)->http_errno)
  2619. struct http_parser
  2620. {
  2621. /** PRIVATE **/
  2622. unsigned int flags : 7; /* F_* values from 'flags' enum; semi-public */
  2623. unsigned int state : 8; /* enum state from http_parser.c */
  2624. unsigned int header_state : 7; /* enum header_state from http_parser.c */
  2625. unsigned int index : 5; /* index into current matcher */
  2626. unsigned int uses_transfer_encoding : 1; /* Transfer-Encoding header is present */
  2627. unsigned int allow_chunked_length : 1; /* Allow headers with both `Content-Length` and `Transfer-Encoding: chunked` set */
  2628. unsigned int lenient_http_headers : 1;
  2629. uint32_t nread; /* # bytes read in various scenarios */
  2630. uint64_t content_length; /* # bytes in body. `(uint64_t) -1` (all bits one) if no Content-Length header. */
  2631. unsigned long qs_point;
  2632. /** READ-ONLY **/
  2633. unsigned char http_major;
  2634. unsigned char http_minor;
  2635. unsigned int method : 8; /* requests only */
  2636. unsigned int http_errno : 7;
  2637. /* 1 = Upgrade header was present and the parser has exited because of that.
  2638. * 0 = No upgrade header present.
  2639. * Should be checked when http_parser_execute() returns in addition to
  2640. * error checking.
  2641. */
  2642. unsigned int upgrade : 1;
  2643. /** PUBLIC **/
  2644. void* data; /* A pointer to get hook to the "connection" or "socket" object */
  2645. };
  2646. struct http_parser_settings
  2647. {
  2648. http_cb on_message_begin;
  2649. http_cb on_method;
  2650. http_data_cb on_url;
  2651. http_data_cb on_header_field;
  2652. http_data_cb on_header_value;
  2653. http_cb on_headers_complete;
  2654. http_data_cb on_body;
  2655. http_cb on_message_complete;
  2656. };
  2657. // SOURCE (.c) CODE
  2658. static uint32_t max_header_size = CROW_HTTP_MAX_HEADER_SIZE;
  2659. #ifndef CROW_ULLONG_MAX
  2660. # define CROW_ULLONG_MAX ((uint64_t) -1) /* 2^64-1 */
  2661. #endif
  2662. #ifndef CROW_MIN
  2663. # define CROW_MIN(a,b) ((a) < (b) ? (a) : (b))
  2664. #endif
  2665. #ifndef CROW_ARRAY_SIZE
  2666. # define CROW_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
  2667. #endif
  2668. #ifndef CROW_BIT_AT
  2669. # define CROW_BIT_AT(a, i) \
  2670. (!!((unsigned int) (a)[(unsigned int) (i) >> 3] & \
  2671. (1 << ((unsigned int) (i) & 7))))
  2672. #endif
  2673. #define CROW_SET_ERRNO(e) \
  2674. do { \
  2675. parser->nread = nread; \
  2676. parser->http_errno = (e); \
  2677. } while(0)
  2678. /* Run the notify callback FOR, returning ER if it fails */
  2679. #define CROW_CALLBACK_NOTIFY_(FOR, ER) \
  2680. do { \
  2681. assert(CROW_HTTP_PARSER_ERRNO(parser) == CHPE_OK); \
  2682. \
  2683. if (CROW_LIKELY(settings->on_##FOR)) { \
  2684. if (CROW_UNLIKELY(0 != settings->on_##FOR(parser))) { \
  2685. CROW_SET_ERRNO(CHPE_CB_##FOR); \
  2686. } \
  2687. \
  2688. /* We either errored above or got paused; get out */ \
  2689. if (CROW_UNLIKELY(CROW_HTTP_PARSER_ERRNO(parser) != CHPE_OK)) { \
  2690. return (ER); \
  2691. } \
  2692. } \
  2693. } while (0)
  2694. /* Run the notify callback FOR and consume the current byte */
  2695. #define CROW_CALLBACK_NOTIFY(FOR) CROW_CALLBACK_NOTIFY_(FOR, p - data + 1)
  2696. /* Run the notify callback FOR and don't consume the current byte */
  2697. #define CROW_CALLBACK_NOTIFY_NOADVANCE(FOR) CROW_CALLBACK_NOTIFY_(FOR, p - data)
  2698. /* Run data callback FOR with LEN bytes, returning ER if it fails */
  2699. #define CROW_CALLBACK_DATA_(FOR, LEN, ER) \
  2700. do { \
  2701. assert(CROW_HTTP_PARSER_ERRNO(parser) == CHPE_OK); \
  2702. \
  2703. if (FOR##_mark) { \
  2704. if (CROW_LIKELY(settings->on_##FOR)) { \
  2705. if (CROW_UNLIKELY(0 != \
  2706. settings->on_##FOR(parser, FOR##_mark, (LEN)))) { \
  2707. CROW_SET_ERRNO(CHPE_CB_##FOR); \
  2708. } \
  2709. \
  2710. /* We either errored above or got paused; get out */ \
  2711. if (CROW_UNLIKELY(CROW_HTTP_PARSER_ERRNO(parser) != CHPE_OK)) {\
  2712. return (ER); \
  2713. } \
  2714. } \
  2715. FOR##_mark = NULL; \
  2716. } \
  2717. } while (0)
  2718. /* Run the data callback FOR and consume the current byte */
  2719. #define CROW_CALLBACK_DATA(FOR) \
  2720. CROW_CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1)
  2721. /* Run the data callback FOR and don't consume the current byte */
  2722. #define CROW_CALLBACK_DATA_NOADVANCE(FOR) \
  2723. CROW_CALLBACK_DATA_(FOR, p - FOR##_mark, p - data)
  2724. /* Set the mark FOR; non-destructive if mark is already set */
  2725. #define CROW_MARK(FOR) \
  2726. do { \
  2727. if (!FOR##_mark) { \
  2728. FOR##_mark = p; \
  2729. } \
  2730. } while (0)
  2731. /* Don't allow the total size of the HTTP headers (including the status
  2732. * line) to exceed max_header_size. This check is here to protect
  2733. * embedders against denial-of-service attacks where the attacker feeds
  2734. * us a never-ending header that the embedder keeps buffering.
  2735. *
  2736. * This check is arguably the responsibility of embedders but we're doing
  2737. * it on the embedder's behalf because most won't bother and this way we
  2738. * make the web a little safer. max_header_size is still far bigger
  2739. * than any reasonable request or response so this should never affect
  2740. * day-to-day operation.
  2741. */
  2742. #define CROW_COUNT_HEADER_SIZE(V) \
  2743. do { \
  2744. nread += (uint32_t)(V); \
  2745. if (CROW_UNLIKELY(nread > max_header_size)) { \
  2746. CROW_SET_ERRNO(CHPE_HEADER_OVERFLOW); \
  2747. goto error; \
  2748. } \
  2749. } while (0)
  2750. #define CROW_REEXECUTE() \
  2751. goto reexecute; \
  2752. #define CROW_PROXY_CONNECTION "proxy-connection"
  2753. #define CROW_CONNECTION "connection"
  2754. #define CROW_CONTENT_LENGTH "content-length"
  2755. #define CROW_TRANSFER_ENCODING "transfer-encoding"
  2756. #define CROW_UPGRADE "upgrade"
  2757. #define CROW_CHUNKED "chunked"
  2758. #define CROW_KEEP_ALIVE "keep-alive"
  2759. #define CROW_CLOSE "close"
  2760. enum state
  2761. {
  2762. s_dead = 1 /* important that this is > 0 */
  2763. ,
  2764. s_start_req
  2765. ,
  2766. s_req_method,
  2767. s_req_spaces_before_url,
  2768. s_req_schema,
  2769. s_req_schema_slash,
  2770. s_req_schema_slash_slash,
  2771. s_req_server_start,
  2772. s_req_server, // }
  2773. s_req_server_with_at, // |
  2774. s_req_path, // | The parser recognizes how to switch between these states,
  2775. s_req_query_string_start, // | however it doesn't process them any differently.
  2776. s_req_query_string, // }
  2777. s_req_http_start,
  2778. s_req_http_H,
  2779. s_req_http_HT,
  2780. s_req_http_HTT,
  2781. s_req_http_HTTP,
  2782. s_req_http_I,
  2783. s_req_http_IC,
  2784. s_req_http_major,
  2785. s_req_http_dot,
  2786. s_req_http_minor,
  2787. s_req_http_end,
  2788. s_req_line_almost_done
  2789. ,
  2790. s_header_field_start,
  2791. s_header_field,
  2792. s_header_value_discard_ws,
  2793. s_header_value_discard_ws_almost_done,
  2794. s_header_value_discard_lws,
  2795. s_header_value_start,
  2796. s_header_value,
  2797. s_header_value_lws
  2798. ,
  2799. s_header_almost_done
  2800. ,
  2801. s_chunk_size_start,
  2802. s_chunk_size,
  2803. s_chunk_parameters,
  2804. s_chunk_size_almost_done
  2805. ,
  2806. s_headers_almost_done,
  2807. s_headers_done
  2808. /* Important: 's_headers_done' must be the last 'header' state. All
  2809. * states beyond this must be 'body' states. It is used for overflow
  2810. * checking. See the CROW_PARSING_HEADER() macro.
  2811. */
  2812. ,
  2813. s_chunk_data,
  2814. s_chunk_data_almost_done,
  2815. s_chunk_data_done
  2816. ,
  2817. s_body_identity,
  2818. s_body_identity_eof
  2819. ,
  2820. s_message_done
  2821. };
  2822. #define CROW_PARSING_HEADER(state) (state <= s_headers_done)
  2823. enum header_states
  2824. { h_general = 0
  2825. , h_C
  2826. , h_CO
  2827. , h_CON
  2828. , h_matching_connection
  2829. , h_matching_proxy_connection
  2830. , h_matching_content_length
  2831. , h_matching_transfer_encoding
  2832. , h_matching_upgrade
  2833. , h_connection
  2834. , h_content_length
  2835. , h_content_length_num
  2836. , h_content_length_ws
  2837. , h_transfer_encoding
  2838. , h_upgrade
  2839. , h_matching_transfer_encoding_token_start
  2840. , h_matching_transfer_encoding_chunked
  2841. , h_matching_transfer_encoding_token
  2842. , h_matching_connection_keep_alive
  2843. , h_matching_connection_close
  2844. , h_transfer_encoding_chunked
  2845. , h_connection_keep_alive
  2846. , h_connection_close
  2847. };
  2848. enum http_host_state
  2849. {
  2850. s_http_host_dead = 1
  2851. , s_http_userinfo_start
  2852. , s_http_userinfo
  2853. , s_http_host_start
  2854. , s_http_host_v6_start
  2855. , s_http_host
  2856. , s_http_host_v6
  2857. , s_http_host_v6_end
  2858. , s_http_host_v6_zone_start
  2859. , s_http_host_v6_zone
  2860. , s_http_host_port_start
  2861. , s_http_host_port
  2862. };
  2863. /* Macros for character classes; depends on strict-mode */
  2864. #define CROW_LOWER(c) (unsigned char)(c | 0x20)
  2865. #define CROW_IS_ALPHA(c) (CROW_LOWER(c) >= 'a' && CROW_LOWER(c) <= 'z')
  2866. #define CROW_IS_NUM(c) ((c) >= '0' && (c) <= '9')
  2867. #define CROW_IS_ALPHANUM(c) (CROW_IS_ALPHA(c) || CROW_IS_NUM(c))
  2868. //#define CROW_IS_HEX(c) (CROW_IS_NUM(c) || (CROW_LOWER(c) >= 'a' && CROW_LOWER(c) <= 'f'))
  2869. #define CROW_IS_MARK(c) ((c) == '-' || (c) == '_' || (c) == '.' || \
  2870. (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \
  2871. (c) == ')')
  2872. #define CROW_IS_USERINFO_CHAR(c) (CROW_IS_ALPHANUM(c) || CROW_IS_MARK(c) || (c) == '%' || \
  2873. (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \
  2874. (c) == '$' || (c) == ',')
  2875. #define CROW_TOKEN(c) (tokens[(unsigned char)c])
  2876. #define CROW_IS_URL_CHAR(c) (CROW_BIT_AT(normal_url_char, (unsigned char)c))
  2877. //#define CROW_IS_HOST_CHAR(c) (CROW_IS_ALPHANUM(c) || (c) == '.' || (c) == '-')
  2878. /**
  2879. * Verify that a char is a valid visible (printable) US-ASCII
  2880. * character or %x80-FF
  2881. **/
  2882. #define CROW_IS_HEADER_CHAR(ch) \
  2883. (ch == cr || ch == lf || ch == 9 || ((unsigned char)ch > 31 && ch != 127))
  2884. #define CROW_start_state s_start_req
  2885. # define CROW_STRICT_CHECK(cond) \
  2886. do { \
  2887. if (cond) { \
  2888. CROW_SET_ERRNO(CHPE_STRICT); \
  2889. goto error; \
  2890. } \
  2891. } while (0)
  2892. #define CROW_NEW_MESSAGE() (CROW_start_state)
  2893. /* Our URL parser.
  2894. *
  2895. * This is designed to be shared by http_parser_execute() for URL validation,
  2896. * hence it has a state transition + byte-for-byte interface. In addition, it
  2897. * is meant to be embedded in http_parser_parse_url(), which does the dirty
  2898. * work of turning state transitions URL components for its API.
  2899. *
  2900. * This function should only be invoked with non-space characters. It is
  2901. * assumed that the caller cares about (and can detect) the transition between
  2902. * URL and non-URL states by looking for these.
  2903. */
  2904. inline enum state
  2905. parse_url_char(enum state s, const char ch, http_parser *parser, const char* url_mark, const char* p)
  2906. {
  2907. # define CROW_T(v) 0
  2908. static const uint8_t normal_url_char[32] = {
  2909. /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */
  2910. 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
  2911. /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */
  2912. 0 |CROW_T(2)| 0 | 0 |CROW_T(16)| 0 | 0 | 0,
  2913. /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */
  2914. 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
  2915. /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */
  2916. 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0,
  2917. /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */
  2918. 0 | 2 | 4 | 0 | 16 | 32 | 64 | 128,
  2919. /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */
  2920. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
  2921. /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */
  2922. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
  2923. /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */
  2924. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0,
  2925. /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */
  2926. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
  2927. /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */
  2928. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
  2929. /* 80 P 81 Q 82 R 83 S 84 CROW_T 85 U 86 V 87 W */
  2930. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
  2931. /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */
  2932. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
  2933. /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */
  2934. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
  2935. /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */
  2936. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
  2937. /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */
  2938. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128,
  2939. /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */
  2940. 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, };
  2941. #undef CROW_T
  2942. if (ch == ' ' || ch == '\r' || ch == '\n') {
  2943. return s_dead;
  2944. }
  2945. if (ch == '\t' || ch == '\f') {
  2946. return s_dead;
  2947. }
  2948. switch (s) {
  2949. case s_req_spaces_before_url:
  2950. /* Proxied requests are followed by scheme of an absolute URI (alpha).
  2951. * All methods except CONNECT are followed by '/' or '*'.
  2952. */
  2953. if (ch == '/' || ch == '*') {
  2954. return s_req_path;
  2955. }
  2956. if (CROW_IS_ALPHA(ch)) {
  2957. return s_req_schema;
  2958. }
  2959. break;
  2960. case s_req_schema:
  2961. if (CROW_IS_ALPHA(ch)) {
  2962. return s;
  2963. }
  2964. if (ch == ':') {
  2965. return s_req_schema_slash;
  2966. }
  2967. break;
  2968. case s_req_schema_slash:
  2969. if (ch == '/') {
  2970. return s_req_schema_slash_slash;
  2971. }
  2972. break;
  2973. case s_req_schema_slash_slash:
  2974. if (ch == '/') {
  2975. return s_req_server_start;
  2976. }
  2977. break;
  2978. case s_req_server_with_at:
  2979. if (ch == '@') {
  2980. return s_dead;
  2981. }
  2982. /* fall through */
  2983. case s_req_server_start:
  2984. case s_req_server:
  2985. if (ch == '/') {
  2986. return s_req_path;
  2987. }
  2988. if (ch == '?') {
  2989. parser->qs_point = p - url_mark;
  2990. return s_req_query_string_start;
  2991. }
  2992. if (ch == '@') {
  2993. return s_req_server_with_at;
  2994. }
  2995. if (CROW_IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') {
  2996. return s_req_server;
  2997. }
  2998. break;
  2999. case s_req_path:
  3000. if (CROW_IS_URL_CHAR(ch)) {
  3001. return s;
  3002. }
  3003. else if (ch == '?')
  3004. {
  3005. parser->qs_point = p - url_mark;
  3006. return s_req_query_string_start;
  3007. }
  3008. break;
  3009. case s_req_query_string_start:
  3010. case s_req_query_string:
  3011. if (CROW_IS_URL_CHAR(ch)) {
  3012. return s_req_query_string;
  3013. }
  3014. else if (ch == '?')
  3015. {
  3016. return s_req_query_string;
  3017. }
  3018. break;
  3019. default:
  3020. break;
  3021. }
  3022. /* We should never fall out of the switch above unless there's an error */
  3023. return s_dead;
  3024. }
  3025. inline size_t http_parser_execute (http_parser *parser,
  3026. const http_parser_settings *settings,
  3027. const char *data,
  3028. size_t len)
  3029. {
  3030. /* Tokens as defined by rfc 2616. Also lowercases them.
  3031. * token = 1*<any CHAR except CTLs or separators>
  3032. * separators = "(" | ")" | "<" | ">" | "@"
  3033. * | "," | ";" | ":" | "\" | <">
  3034. * | "/" | "[" | "]" | "?" | "="
  3035. * | "{" | "}" | SP | HT
  3036. */
  3037. static const char tokens[256] = {
  3038. /* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */
  3039. 0, 0, 0, 0, 0, 0, 0, 0,
  3040. /* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */
  3041. 0, 0, 0, 0, 0, 0, 0, 0,
  3042. /* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */
  3043. 0, 0, 0, 0, 0, 0, 0, 0,
  3044. /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */
  3045. 0, 0, 0, 0, 0, 0, 0, 0,
  3046. /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */
  3047. 0, '!', 0, '#', '$', '%', '&', '\'',
  3048. /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */
  3049. 0, 0, '*', '+', 0, '-', '.', 0,
  3050. /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */
  3051. '0', '1', '2', '3', '4', '5', '6', '7',
  3052. /* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */
  3053. '8', '9', 0, 0, 0, 0, 0, 0,
  3054. /* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */
  3055. 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  3056. /* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */
  3057. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  3058. /* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */
  3059. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
  3060. /* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */
  3061. 'x', 'y', 'z', 0, 0, 0, '^', '_',
  3062. /* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */
  3063. '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
  3064. /* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */
  3065. 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
  3066. /* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */
  3067. 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
  3068. /* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */
  3069. 'x', 'y', 'z', 0, '|', 0, '~', 0 };
  3070. static const int8_t unhex[256] =
  3071. {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
  3072. ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
  3073. ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
  3074. , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
  3075. ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
  3076. ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
  3077. ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
  3078. ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
  3079. };
  3080. char c, ch;
  3081. int8_t unhex_val;
  3082. const char *p = data;
  3083. const char *header_field_mark = 0;
  3084. const char *header_value_mark = 0;
  3085. const char *url_mark = 0;
  3086. const char *url_start_mark = 0;
  3087. const char *body_mark = 0;
  3088. const unsigned int lenient = parser->lenient_http_headers;
  3089. const unsigned int allow_chunked_length = parser->allow_chunked_length;
  3090. uint32_t nread = parser->nread;
  3091. /* We're in an error state. Don't bother doing anything. */
  3092. if (CROW_HTTP_PARSER_ERRNO(parser) != CHPE_OK) {
  3093. return 0;
  3094. }
  3095. if (len == 0) {
  3096. switch (parser->state) {
  3097. case s_body_identity_eof:
  3098. /* Use of CROW_CALLBACK_NOTIFY() here would erroneously return 1 byte read if we got paused. */
  3099. CROW_CALLBACK_NOTIFY_NOADVANCE(message_complete);
  3100. return 0;
  3101. case s_dead:
  3102. case s_start_req:
  3103. return 0;
  3104. default:
  3105. CROW_SET_ERRNO(CHPE_INVALID_EOF_STATE);
  3106. return 1;
  3107. }
  3108. }
  3109. if (parser->state == s_header_field)
  3110. header_field_mark = data;
  3111. if (parser->state == s_header_value)
  3112. header_value_mark = data;
  3113. switch (parser->state) {
  3114. case s_req_path:
  3115. case s_req_schema:
  3116. case s_req_schema_slash:
  3117. case s_req_schema_slash_slash:
  3118. case s_req_server_start:
  3119. case s_req_server:
  3120. case s_req_server_with_at:
  3121. case s_req_query_string_start:
  3122. case s_req_query_string:
  3123. url_mark = data;
  3124. break;
  3125. default:
  3126. break;
  3127. }
  3128. for (p=data; p != data + len; p++) {
  3129. ch = *p;
  3130. if (CROW_PARSING_HEADER(parser->state))
  3131. CROW_COUNT_HEADER_SIZE(1);
  3132. reexecute:
  3133. switch (parser->state) {
  3134. case s_dead:
  3135. /* this state is used after a 'Connection: close' message
  3136. * the parser will error out if it reads another message
  3137. */
  3138. if (CROW_LIKELY(ch == cr || ch == lf))
  3139. break;
  3140. CROW_SET_ERRNO(CHPE_CLOSED_CONNECTION);
  3141. goto error;
  3142. case s_start_req:
  3143. {
  3144. if (ch == cr || ch == lf)
  3145. break;
  3146. parser->flags = 0;
  3147. parser->uses_transfer_encoding = 0;
  3148. parser->content_length = CROW_ULLONG_MAX;
  3149. if (CROW_UNLIKELY(!CROW_IS_ALPHA(ch))) {
  3150. CROW_SET_ERRNO(CHPE_INVALID_METHOD);
  3151. goto error;
  3152. }
  3153. parser->method = 0;
  3154. parser->index = 1;
  3155. switch (ch) {
  3156. case 'A': parser->method = (unsigned)HTTPMethod::Acl; break;
  3157. case 'B': parser->method = (unsigned)HTTPMethod::Bind; break;
  3158. case 'C': parser->method = (unsigned)HTTPMethod::Connect; /* or COPY, CHECKOUT */ break;
  3159. case 'D': parser->method = (unsigned)HTTPMethod::Delete; break;
  3160. case 'G': parser->method = (unsigned)HTTPMethod::Get; break;
  3161. case 'H': parser->method = (unsigned)HTTPMethod::Head; break;
  3162. case 'L': parser->method = (unsigned)HTTPMethod::Lock; /* or LINK */ break;
  3163. case 'M': parser->method = (unsigned)HTTPMethod::MkCol; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break;
  3164. case 'N': parser->method = (unsigned)HTTPMethod::Notify; break;
  3165. case 'O': parser->method = (unsigned)HTTPMethod::Options; break;
  3166. case 'P': parser->method = (unsigned)HTTPMethod::Post; /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */ break;
  3167. case 'R': parser->method = (unsigned)HTTPMethod::Report; /* or REBIND */ break;
  3168. case 'S': parser->method = (unsigned)HTTPMethod::Subscribe; /* or SEARCH, SOURCE */ break;
  3169. case 'T': parser->method = (unsigned)HTTPMethod::Trace; break;
  3170. case 'U': parser->method = (unsigned)HTTPMethod::Unlock; /* or UNSUBSCRIBE, UNBIND, UNLINK */ break;
  3171. default:
  3172. CROW_SET_ERRNO(CHPE_INVALID_METHOD);
  3173. goto error;
  3174. }
  3175. parser->state = s_req_method;
  3176. CROW_CALLBACK_NOTIFY(message_begin);
  3177. break;
  3178. }
  3179. case s_req_method:
  3180. {
  3181. const char *matcher;
  3182. if (CROW_UNLIKELY(ch == '\0')) {
  3183. CROW_SET_ERRNO(CHPE_INVALID_METHOD);
  3184. goto error;
  3185. }
  3186. matcher = method_strings[parser->method];
  3187. if (ch == ' ' && matcher[parser->index] == '\0') {
  3188. parser->state = s_req_spaces_before_url;
  3189. } else if (ch == matcher[parser->index]) {
  3190. ; /* nada */
  3191. } else if ((ch >= 'A' && ch <= 'Z') || ch == '-') {
  3192. switch (parser->method << 16 | parser->index << 8 | ch) {
  3193. #define CROW_XX(meth, pos, ch, new_meth) \
  3194. case ((unsigned)HTTPMethod::meth << 16 | pos << 8 | ch): \
  3195. parser->method = (unsigned)HTTPMethod::new_meth; break;
  3196. CROW_XX(Post, 1, 'U', Put)
  3197. CROW_XX(Post, 1, 'A', Patch)
  3198. CROW_XX(Post, 1, 'R', Propfind)
  3199. CROW_XX(Put, 2, 'R', Purge)
  3200. CROW_XX(Connect, 1, 'H', Checkout)
  3201. CROW_XX(Connect, 2, 'P', Copy)
  3202. CROW_XX(MkCol, 1, 'O', Move)
  3203. CROW_XX(MkCol, 1, 'E', Merge)
  3204. CROW_XX(MkCol, 1, '-', MSearch)
  3205. CROW_XX(MkCol, 2, 'A', MkActivity)
  3206. CROW_XX(MkCol, 3, 'A', MkCalendar)
  3207. CROW_XX(Subscribe, 1, 'E', Search)
  3208. CROW_XX(Subscribe, 1, 'O', Source)
  3209. CROW_XX(Report, 2, 'B', Rebind)
  3210. CROW_XX(Propfind, 4, 'P', Proppatch)
  3211. CROW_XX(Lock, 1, 'I', Link)
  3212. CROW_XX(Unlock, 2, 'S', Unsubscribe)
  3213. CROW_XX(Unlock, 2, 'B', Unbind)
  3214. CROW_XX(Unlock, 3, 'I', Unlink)
  3215. #undef CROW_XX
  3216. default:
  3217. CROW_SET_ERRNO(CHPE_INVALID_METHOD);
  3218. goto error;
  3219. }
  3220. } else {
  3221. CROW_SET_ERRNO(CHPE_INVALID_METHOD);
  3222. goto error;
  3223. }
  3224. CROW_CALLBACK_NOTIFY_NOADVANCE(method);
  3225. ++parser->index;
  3226. break;
  3227. }
  3228. case s_req_spaces_before_url:
  3229. {
  3230. if (ch == ' ') break;
  3231. CROW_MARK(url);
  3232. CROW_MARK(url_start);
  3233. if (parser->method == (unsigned)HTTPMethod::Connect) {
  3234. parser->state = s_req_server_start;
  3235. }
  3236. parser->state = parse_url_char(static_cast<state>(parser->state), ch, parser, url_start_mark, p);
  3237. if (CROW_UNLIKELY(parser->state == s_dead)) {
  3238. CROW_SET_ERRNO(CHPE_INVALID_URL);
  3239. goto error;
  3240. }
  3241. break;
  3242. }
  3243. case s_req_schema:
  3244. case s_req_schema_slash:
  3245. case s_req_schema_slash_slash:
  3246. case s_req_server_start:
  3247. {
  3248. switch (ch) {
  3249. /* No whitespace allowed here */
  3250. case ' ':
  3251. case cr:
  3252. case lf:
  3253. CROW_SET_ERRNO(CHPE_INVALID_URL);
  3254. goto error;
  3255. default:
  3256. parser->state = parse_url_char(static_cast<state>(parser->state), ch, parser, url_start_mark, p);
  3257. if (CROW_UNLIKELY(parser->state == s_dead)) {
  3258. CROW_SET_ERRNO(CHPE_INVALID_URL);
  3259. goto error;
  3260. }
  3261. }
  3262. break;
  3263. }
  3264. case s_req_server:
  3265. case s_req_server_with_at:
  3266. case s_req_path:
  3267. case s_req_query_string_start:
  3268. case s_req_query_string:
  3269. {
  3270. switch (ch) {
  3271. case ' ':
  3272. parser->state = s_req_http_start;
  3273. CROW_CALLBACK_DATA(url);
  3274. break;
  3275. case cr: // No space after URL means no HTTP version. Which means the request is using HTTP/0.9
  3276. case lf:
  3277. if (CROW_UNLIKELY(parser->method != (unsigned)HTTPMethod::Get)) // HTTP/0.9 doesn't define any method other than GET
  3278. {
  3279. parser->state = s_dead;
  3280. CROW_SET_ERRNO(CHPE_INVALID_VERSION);
  3281. goto error;
  3282. }
  3283. parser->http_major = 0;
  3284. parser->http_minor = 9;
  3285. parser->state = (ch == cr) ?
  3286. s_req_line_almost_done :
  3287. s_header_field_start;
  3288. CROW_CALLBACK_DATA(url);
  3289. break;
  3290. default:
  3291. parser->state = parse_url_char(static_cast<state>(parser->state), ch, parser, url_start_mark, p);
  3292. if (CROW_UNLIKELY(parser->state == s_dead)) {
  3293. CROW_SET_ERRNO(CHPE_INVALID_URL);
  3294. goto error;
  3295. }
  3296. }
  3297. break;
  3298. }
  3299. case s_req_http_start:
  3300. switch (ch) {
  3301. case ' ':
  3302. break;
  3303. case 'H':
  3304. parser->state = s_req_http_H;
  3305. break;
  3306. case 'I':
  3307. if (parser->method == (unsigned)HTTPMethod::Source) {
  3308. parser->state = s_req_http_I;
  3309. break;
  3310. }
  3311. /* fall through */
  3312. default:
  3313. CROW_SET_ERRNO(CHPE_INVALID_CONSTANT);
  3314. goto error;
  3315. }
  3316. break;
  3317. case s_req_http_H:
  3318. CROW_STRICT_CHECK(ch != 'T');
  3319. parser->state = s_req_http_HT;
  3320. break;
  3321. case s_req_http_HT:
  3322. CROW_STRICT_CHECK(ch != 'T');
  3323. parser->state = s_req_http_HTT;
  3324. break;
  3325. case s_req_http_HTT:
  3326. CROW_STRICT_CHECK(ch != 'P');
  3327. parser->state = s_req_http_HTTP;
  3328. break;
  3329. case s_req_http_I:
  3330. CROW_STRICT_CHECK(ch != 'C');
  3331. parser->state = s_req_http_IC;
  3332. break;
  3333. case s_req_http_IC:
  3334. CROW_STRICT_CHECK(ch != 'E');
  3335. parser->state = s_req_http_HTTP; /* Treat "ICE" as "HTTP". */
  3336. break;
  3337. case s_req_http_HTTP:
  3338. CROW_STRICT_CHECK(ch != '/');
  3339. parser->state = s_req_http_major;
  3340. break;
  3341. /* dot */
  3342. case s_req_http_major:
  3343. if (CROW_UNLIKELY(!CROW_IS_NUM(ch))) {
  3344. CROW_SET_ERRNO(CHPE_INVALID_VERSION);
  3345. goto error;
  3346. }
  3347. parser->http_major = ch - '0';
  3348. parser->state = s_req_http_dot;
  3349. break;
  3350. case s_req_http_dot:
  3351. {
  3352. if (CROW_UNLIKELY(ch != '.')) {
  3353. CROW_SET_ERRNO(CHPE_INVALID_VERSION);
  3354. goto error;
  3355. }
  3356. parser->state = s_req_http_minor;
  3357. break;
  3358. }
  3359. /* minor HTTP version */
  3360. case s_req_http_minor:
  3361. if (CROW_UNLIKELY(!CROW_IS_NUM(ch))) {
  3362. CROW_SET_ERRNO(CHPE_INVALID_VERSION);
  3363. goto error;
  3364. }
  3365. parser->http_minor = ch - '0';
  3366. parser->state = s_req_http_end;
  3367. break;
  3368. /* end of request line */
  3369. case s_req_http_end:
  3370. {
  3371. if (ch == cr) {
  3372. parser->state = s_req_line_almost_done;
  3373. break;
  3374. }
  3375. if (ch == lf) {
  3376. parser->state = s_header_field_start;
  3377. break;
  3378. }
  3379. CROW_SET_ERRNO(CHPE_INVALID_VERSION);
  3380. goto error;
  3381. break;
  3382. }
  3383. /* end of request line */
  3384. case s_req_line_almost_done:
  3385. {
  3386. if (CROW_UNLIKELY(ch != lf)) {
  3387. CROW_SET_ERRNO(CHPE_LF_EXPECTED);
  3388. goto error;
  3389. }
  3390. parser->state = s_header_field_start;
  3391. break;
  3392. }
  3393. case s_header_field_start:
  3394. {
  3395. if (ch == cr) {
  3396. parser->state = s_headers_almost_done;
  3397. break;
  3398. }
  3399. if (ch == lf) {
  3400. /* they might be just sending \n instead of \r\n so this would be
  3401. * the second \n to denote the end of headers*/
  3402. parser->state = s_headers_almost_done;
  3403. CROW_REEXECUTE();
  3404. }
  3405. c = CROW_TOKEN(ch);
  3406. if (CROW_UNLIKELY(!c)) {
  3407. CROW_SET_ERRNO(CHPE_INVALID_HEADER_TOKEN);
  3408. goto error;
  3409. }
  3410. CROW_MARK(header_field);
  3411. parser->index = 0;
  3412. parser->state = s_header_field;
  3413. switch (c) {
  3414. case 'c':
  3415. parser->header_state = h_C;
  3416. break;
  3417. case 'p':
  3418. parser->header_state = h_matching_proxy_connection;
  3419. break;
  3420. case 't':
  3421. parser->header_state = h_matching_transfer_encoding;
  3422. break;
  3423. case 'u':
  3424. parser->header_state = h_matching_upgrade;
  3425. break;
  3426. default:
  3427. parser->header_state = h_general;
  3428. break;
  3429. }
  3430. break;
  3431. }
  3432. case s_header_field:
  3433. {
  3434. const char* start = p;
  3435. for (; p != data + len; p++) {
  3436. ch = *p;
  3437. c = CROW_TOKEN(ch);
  3438. if (!c)
  3439. break;
  3440. switch (parser->header_state) {
  3441. case h_general: {
  3442. size_t left = data + len - p;
  3443. const char* pe = p + CROW_MIN(left, max_header_size);
  3444. while (p+1 < pe && CROW_TOKEN(p[1])) {
  3445. p++;
  3446. }
  3447. break;
  3448. }
  3449. case h_C:
  3450. parser->index++;
  3451. parser->header_state = (c == 'o' ? h_CO : h_general);
  3452. break;
  3453. case h_CO:
  3454. parser->index++;
  3455. parser->header_state = (c == 'n' ? h_CON : h_general);
  3456. break;
  3457. case h_CON:
  3458. parser->index++;
  3459. switch (c) {
  3460. case 'n':
  3461. parser->header_state = h_matching_connection;
  3462. break;
  3463. case 't':
  3464. parser->header_state = h_matching_content_length;
  3465. break;
  3466. default:
  3467. parser->header_state = h_general;
  3468. break;
  3469. }
  3470. break;
  3471. /* connection */
  3472. case h_matching_connection:
  3473. parser->index++;
  3474. if (parser->index > sizeof(CROW_CONNECTION)-1 || c != CROW_CONNECTION[parser->index]) {
  3475. parser->header_state = h_general;
  3476. } else if (parser->index == sizeof(CROW_CONNECTION)-2) {
  3477. parser->header_state = h_connection;
  3478. }
  3479. break;
  3480. /* proxy-connection */
  3481. case h_matching_proxy_connection:
  3482. parser->index++;
  3483. if (parser->index > sizeof(CROW_PROXY_CONNECTION)-1 || c != CROW_PROXY_CONNECTION[parser->index]) {
  3484. parser->header_state = h_general;
  3485. } else if (parser->index == sizeof(CROW_PROXY_CONNECTION)-2) {
  3486. parser->header_state = h_connection;
  3487. }
  3488. break;
  3489. /* content-length */
  3490. case h_matching_content_length:
  3491. parser->index++;
  3492. if (parser->index > sizeof(CROW_CONTENT_LENGTH)-1 || c != CROW_CONTENT_LENGTH[parser->index]) {
  3493. parser->header_state = h_general;
  3494. } else if (parser->index == sizeof(CROW_CONTENT_LENGTH)-2) {
  3495. parser->header_state = h_content_length;
  3496. }
  3497. break;
  3498. /* transfer-encoding */
  3499. case h_matching_transfer_encoding:
  3500. parser->index++;
  3501. if (parser->index > sizeof(CROW_TRANSFER_ENCODING)-1 || c != CROW_TRANSFER_ENCODING[parser->index]) {
  3502. parser->header_state = h_general;
  3503. } else if (parser->index == sizeof(CROW_TRANSFER_ENCODING)-2) {
  3504. parser->header_state = h_transfer_encoding;
  3505. parser->uses_transfer_encoding = 1;
  3506. }
  3507. break;
  3508. /* upgrade */
  3509. case h_matching_upgrade:
  3510. parser->index++;
  3511. if (parser->index > sizeof(CROW_UPGRADE)-1 || c != CROW_UPGRADE[parser->index]) {
  3512. parser->header_state = h_general;
  3513. } else if (parser->index == sizeof(CROW_UPGRADE)-2) {
  3514. parser->header_state = h_upgrade;
  3515. }
  3516. break;
  3517. case h_connection:
  3518. case h_content_length:
  3519. case h_transfer_encoding:
  3520. case h_upgrade:
  3521. if (ch != ' ') parser->header_state = h_general;
  3522. break;
  3523. default:
  3524. assert(0 && "Unknown header_state");
  3525. break;
  3526. }
  3527. }
  3528. if (p == data + len) {
  3529. --p;
  3530. CROW_COUNT_HEADER_SIZE(p - start);
  3531. break;
  3532. }
  3533. CROW_COUNT_HEADER_SIZE(p - start);
  3534. if (ch == ':') {
  3535. parser->state = s_header_value_discard_ws;
  3536. CROW_CALLBACK_DATA(header_field);
  3537. break;
  3538. }
  3539. /* RFC-7230 Sec 3.2.4 expressly forbids line-folding in header field-names.
  3540. if (ch == cr) {
  3541. parser->state = s_header_almost_done;
  3542. CROW_CALLBACK_DATA(header_field);
  3543. break;
  3544. }
  3545. if (ch == lf) {
  3546. parser->state = s_header_field_start;
  3547. CROW_CALLBACK_DATA(header_field);
  3548. break;
  3549. }
  3550. */
  3551. CROW_SET_ERRNO(CHPE_INVALID_HEADER_TOKEN);
  3552. goto error;
  3553. }
  3554. case s_header_value_discard_ws:
  3555. if (ch == ' ' || ch == '\t') break;
  3556. if (ch == cr) {
  3557. parser->state = s_header_value_discard_ws_almost_done;
  3558. break;
  3559. }
  3560. if (ch == lf) {
  3561. parser->state = s_header_value_discard_lws;
  3562. break;
  3563. }
  3564. /* fall through */
  3565. case s_header_value_start:
  3566. {
  3567. CROW_MARK(header_value);
  3568. parser->state = s_header_value;
  3569. parser->index = 0;
  3570. c = CROW_LOWER(ch);
  3571. switch (parser->header_state) {
  3572. case h_upgrade:
  3573. // Crow does not support HTTP/2 at the moment.
  3574. // According to the RFC https://datatracker.ietf.org/doc/html/rfc7540#section-3.2
  3575. // "A server that does not support HTTP/2 can respond to the request as though the Upgrade header field were absent"
  3576. // => `F_UPGRADE` is not set if the header starts by "h2".
  3577. // This prevents the parser from skipping the request body.
  3578. if (ch != 'h' || p+1 == (data + len) || *(p+1) != '2') {
  3579. parser->flags |= F_UPGRADE;
  3580. }
  3581. parser->header_state = h_general;
  3582. break;
  3583. case h_transfer_encoding:
  3584. /* looking for 'Transfer-Encoding: chunked' */
  3585. if ('c' == c) {
  3586. parser->header_state = h_matching_transfer_encoding_chunked;
  3587. } else {
  3588. parser->header_state = h_matching_transfer_encoding_token;
  3589. }
  3590. break;
  3591. /* Multi-value `Transfer-Encoding` header */
  3592. case h_matching_transfer_encoding_token_start:
  3593. break;
  3594. case h_content_length:
  3595. if (CROW_UNLIKELY(!CROW_IS_NUM(ch))) {
  3596. CROW_SET_ERRNO(CHPE_INVALID_CONTENT_LENGTH);
  3597. goto error;
  3598. }
  3599. if (parser->flags & F_CONTENTLENGTH) {
  3600. CROW_SET_ERRNO(CHPE_UNEXPECTED_CONTENT_LENGTH);
  3601. goto error;
  3602. }
  3603. parser->flags |= F_CONTENTLENGTH;
  3604. parser->content_length = ch - '0';
  3605. parser->header_state = h_content_length_num;
  3606. break;
  3607. /* when obsolete line folding is encountered for content length
  3608. * continue to the s_header_value state */
  3609. case h_content_length_ws:
  3610. break;
  3611. case h_connection:
  3612. /* looking for 'Connection: keep-alive' */
  3613. if (c == 'k') {
  3614. parser->header_state = h_matching_connection_keep_alive;
  3615. /* looking for 'Connection: close' */
  3616. } else if (c == 'c') {
  3617. parser->header_state = h_matching_connection_close;
  3618. } else if (c == ' ' || c == '\t') {
  3619. /* Skip lws */
  3620. } else {
  3621. parser->header_state = h_general;
  3622. }
  3623. break;
  3624. default:
  3625. parser->header_state = h_general;
  3626. break;
  3627. }
  3628. break;
  3629. }
  3630. case s_header_value:
  3631. {
  3632. const char* start = p;
  3633. enum header_states h_state = static_cast<header_states>(parser->header_state);
  3634. for (; p != data + len; p++) {
  3635. ch = *p;
  3636. if (ch == cr) {
  3637. parser->state = s_header_almost_done;
  3638. parser->header_state = h_state;
  3639. CROW_CALLBACK_DATA(header_value);
  3640. break;
  3641. }
  3642. if (ch == lf) {
  3643. parser->state = s_header_almost_done;
  3644. CROW_COUNT_HEADER_SIZE(p - start);
  3645. parser->header_state = h_state;
  3646. CROW_CALLBACK_DATA_NOADVANCE(header_value);
  3647. CROW_REEXECUTE();
  3648. }
  3649. if (!lenient && !CROW_IS_HEADER_CHAR(ch)) {
  3650. CROW_SET_ERRNO(CHPE_INVALID_HEADER_TOKEN);
  3651. goto error;
  3652. }
  3653. c = CROW_LOWER(ch);
  3654. switch (h_state) {
  3655. case h_general:
  3656. {
  3657. size_t left = data + len - p;
  3658. const char* pe = p + CROW_MIN(left, max_header_size);
  3659. for (; p != pe; p++) {
  3660. ch = *p;
  3661. if (ch == cr || ch == lf) {
  3662. --p;
  3663. break;
  3664. }
  3665. if (!lenient && !CROW_IS_HEADER_CHAR(ch)) {
  3666. CROW_SET_ERRNO(CHPE_INVALID_HEADER_TOKEN);
  3667. goto error;
  3668. }
  3669. }
  3670. if (p == data + len)
  3671. --p;
  3672. break;
  3673. }
  3674. case h_connection:
  3675. case h_transfer_encoding:
  3676. assert(0 && "Shouldn't get here.");
  3677. break;
  3678. case h_content_length:
  3679. if (ch == ' ') break;
  3680. h_state = h_content_length_num;
  3681. /* fall through */
  3682. case h_content_length_num:
  3683. {
  3684. uint64_t t;
  3685. if (ch == ' ') {
  3686. h_state = h_content_length_ws;
  3687. break;
  3688. }
  3689. if (CROW_UNLIKELY(!CROW_IS_NUM(ch))) {
  3690. CROW_SET_ERRNO(CHPE_INVALID_CONTENT_LENGTH);
  3691. parser->header_state = h_state;
  3692. goto error;
  3693. }
  3694. t = parser->content_length;
  3695. t *= 10;
  3696. t += ch - '0';
  3697. /* Overflow? Test against a conservative limit for simplicity. */
  3698. if (CROW_UNLIKELY((CROW_ULLONG_MAX - 10) / 10 < parser->content_length)) {
  3699. CROW_SET_ERRNO(CHPE_INVALID_CONTENT_LENGTH);
  3700. parser->header_state = h_state;
  3701. goto error;
  3702. }
  3703. parser->content_length = t;
  3704. break;
  3705. }
  3706. case h_content_length_ws:
  3707. if (ch == ' ') break;
  3708. CROW_SET_ERRNO(CHPE_INVALID_CONTENT_LENGTH);
  3709. parser->header_state = h_state;
  3710. goto error;
  3711. /* Transfer-Encoding: chunked */
  3712. case h_matching_transfer_encoding_token_start:
  3713. /* looking for 'Transfer-Encoding: chunked' */
  3714. if ('c' == c) {
  3715. h_state = h_matching_transfer_encoding_chunked;
  3716. } else if (CROW_TOKEN(c)) {
  3717. /* TODO(indutny): similar code below does this, but why?
  3718. * At the very least it seems to be inconsistent given that
  3719. * h_matching_transfer_encoding_token does not check for
  3720. * `STRICT_TOKEN`
  3721. */
  3722. h_state = h_matching_transfer_encoding_token;
  3723. } else if (c == ' ' || c == '\t') {
  3724. /* Skip lws */
  3725. } else {
  3726. h_state = h_general;
  3727. }
  3728. break;
  3729. case h_matching_transfer_encoding_chunked:
  3730. parser->index++;
  3731. if (parser->index > sizeof(CROW_CHUNKED)-1 || c != CROW_CHUNKED[parser->index]) {
  3732. h_state = h_matching_transfer_encoding_token;
  3733. } else if (parser->index == sizeof(CROW_CHUNKED)-2) {
  3734. h_state = h_transfer_encoding_chunked;
  3735. }
  3736. break;
  3737. case h_matching_transfer_encoding_token:
  3738. if (ch == ',') {
  3739. h_state = h_matching_transfer_encoding_token_start;
  3740. parser->index = 0;
  3741. }
  3742. break;
  3743. /* looking for 'Connection: keep-alive' */
  3744. case h_matching_connection_keep_alive:
  3745. parser->index++;
  3746. if (parser->index > sizeof(CROW_KEEP_ALIVE)-1 || c != CROW_KEEP_ALIVE[parser->index]) {
  3747. h_state = h_general;
  3748. } else if (parser->index == sizeof(CROW_KEEP_ALIVE)-2) {
  3749. h_state = h_connection_keep_alive;
  3750. }
  3751. break;
  3752. /* looking for 'Connection: close' */
  3753. case h_matching_connection_close:
  3754. parser->index++;
  3755. if (parser->index > sizeof(CROW_CLOSE)-1 || c != CROW_CLOSE[parser->index]) {
  3756. h_state = h_general;
  3757. } else if (parser->index == sizeof(CROW_CLOSE)-2) {
  3758. h_state = h_connection_close;
  3759. }
  3760. break;
  3761. // Edited from original (because of commits that werent included)
  3762. case h_transfer_encoding_chunked:
  3763. if (ch != ' ') h_state = h_matching_transfer_encoding_token;
  3764. break;
  3765. case h_connection_keep_alive:
  3766. case h_connection_close:
  3767. if (ch != ' ') h_state = h_general;
  3768. break;
  3769. default:
  3770. parser->state = s_header_value;
  3771. h_state = h_general;
  3772. break;
  3773. }
  3774. }
  3775. parser->header_state = h_state;
  3776. if (p == data + len)
  3777. --p;
  3778. CROW_COUNT_HEADER_SIZE(p - start);
  3779. break;
  3780. }
  3781. case s_header_almost_done:
  3782. {
  3783. if (CROW_UNLIKELY(ch != lf)) {
  3784. CROW_SET_ERRNO(CHPE_LF_EXPECTED);
  3785. goto error;
  3786. }
  3787. parser->state = s_header_value_lws;
  3788. break;
  3789. }
  3790. case s_header_value_lws:
  3791. {
  3792. if (ch == ' ' || ch == '\t') {
  3793. if (parser->header_state == h_content_length_num) {
  3794. /* treat obsolete line folding as space */
  3795. parser->header_state = h_content_length_ws;
  3796. }
  3797. parser->state = s_header_value_start;
  3798. CROW_REEXECUTE();
  3799. }
  3800. /* finished the header */
  3801. switch (parser->header_state) {
  3802. case h_connection_keep_alive:
  3803. parser->flags |= F_CONNECTION_KEEP_ALIVE;
  3804. break;
  3805. case h_connection_close:
  3806. parser->flags |= F_CONNECTION_CLOSE;
  3807. break;
  3808. case h_transfer_encoding_chunked:
  3809. parser->flags |= F_CHUNKED;
  3810. break;
  3811. default:
  3812. break;
  3813. }
  3814. parser->state = s_header_field_start;
  3815. CROW_REEXECUTE();
  3816. }
  3817. case s_header_value_discard_ws_almost_done:
  3818. {
  3819. CROW_STRICT_CHECK(ch != lf);
  3820. parser->state = s_header_value_discard_lws;
  3821. break;
  3822. }
  3823. case s_header_value_discard_lws:
  3824. {
  3825. if (ch == ' ' || ch == '\t') {
  3826. parser->state = s_header_value_discard_ws;
  3827. break;
  3828. } else {
  3829. /* header value was empty */
  3830. CROW_MARK(header_value);
  3831. parser->state = s_header_field_start;
  3832. CROW_CALLBACK_DATA_NOADVANCE(header_value);
  3833. CROW_REEXECUTE();
  3834. }
  3835. }
  3836. case s_headers_almost_done:
  3837. {
  3838. CROW_STRICT_CHECK(ch != lf);
  3839. if (parser->flags & F_TRAILING) {
  3840. /* End of a chunked request */
  3841. CROW_CALLBACK_NOTIFY(message_complete);
  3842. break;
  3843. }
  3844. /* Cannot use transfer-encoding and a content-length header together
  3845. per the HTTP specification. (RFC 7230 Section 3.3.3) */
  3846. if ((parser->uses_transfer_encoding == 1) &&
  3847. (parser->flags & F_CONTENTLENGTH)) {
  3848. /* Allow it for lenient parsing as long as `Transfer-Encoding` is
  3849. * not `chunked` or allow_length_with_encoding is set
  3850. */
  3851. if (parser->flags & F_CHUNKED) {
  3852. if (!allow_chunked_length) {
  3853. CROW_SET_ERRNO(CHPE_UNEXPECTED_CONTENT_LENGTH);
  3854. goto error;
  3855. }
  3856. } else if (!lenient) {
  3857. CROW_SET_ERRNO(CHPE_UNEXPECTED_CONTENT_LENGTH);
  3858. goto error;
  3859. }
  3860. }
  3861. parser->state = s_headers_done;
  3862. /* Set this here so that on_headers_complete() callbacks can see it */
  3863. parser->upgrade =
  3864. (parser->flags & F_UPGRADE || parser->method == (unsigned)HTTPMethod::Connect);
  3865. /* Here we call the headers_complete callback. This is somewhat
  3866. * different than other callbacks because if the user returns 1, we
  3867. * will interpret that as saying that this message has no body. This
  3868. * is needed for the annoying case of recieving a response to a HEAD
  3869. * request.
  3870. *
  3871. * We'd like to use CROW_CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so
  3872. * we have to simulate it by handling a change in errno below.
  3873. */
  3874. if (settings->on_headers_complete) {
  3875. switch (settings->on_headers_complete(parser)) {
  3876. case 0:
  3877. break;
  3878. case 2:
  3879. parser->upgrade = 1;
  3880. //break;
  3881. /* fall through */
  3882. case 1:
  3883. parser->flags |= F_SKIPBODY;
  3884. break;
  3885. default:
  3886. CROW_SET_ERRNO(CHPE_CB_headers_complete);
  3887. parser->nread = nread;
  3888. return p - data; /* Error */
  3889. }
  3890. }
  3891. if (CROW_HTTP_PARSER_ERRNO(parser) != CHPE_OK) {
  3892. parser->nread = nread;
  3893. return p - data;
  3894. }
  3895. CROW_REEXECUTE();
  3896. }
  3897. case s_headers_done:
  3898. {
  3899. CROW_STRICT_CHECK(ch != lf);
  3900. parser->nread = 0;
  3901. nread = 0;
  3902. /* Exit, the rest of the connect is in a different protocol. */
  3903. if (parser->upgrade) {
  3904. CROW_CALLBACK_NOTIFY(message_complete);
  3905. parser->nread = nread;
  3906. return (p - data) + 1;
  3907. }
  3908. if (parser->flags & F_SKIPBODY) {
  3909. CROW_CALLBACK_NOTIFY(message_complete);
  3910. } else if (parser->flags & F_CHUNKED) {
  3911. /* chunked encoding - ignore Content-Length header,
  3912. * prepare for a chunk */
  3913. parser->state = s_chunk_size_start;
  3914. }
  3915. else if (parser->uses_transfer_encoding == 1)
  3916. {
  3917. if (!lenient)
  3918. {
  3919. /* RFC 7230 3.3.3 */
  3920. /* If a Transfer-Encoding header field
  3921. * is present in a request and the chunked transfer coding is not
  3922. * the final encoding, the message body length cannot be determined
  3923. * reliably; the server MUST respond with the 400 (Bad Request)
  3924. * status code and then close the connection.
  3925. */
  3926. CROW_SET_ERRNO(CHPE_INVALID_TRANSFER_ENCODING);
  3927. parser->nread = nread;
  3928. return (p - data); /* Error */
  3929. }
  3930. else
  3931. {
  3932. /* RFC 7230 3.3.3 */
  3933. /* If a Transfer-Encoding header field is present in a response and
  3934. * the chunked transfer coding is not the final encoding, the
  3935. * message body length is determined by reading the connection until
  3936. * it is closed by the server.
  3937. */
  3938. parser->state = s_body_identity_eof;
  3939. }
  3940. }
  3941. else
  3942. {
  3943. if (parser->content_length == 0)
  3944. {
  3945. /* Content-Length header given but zero: Content-Length: 0\r\n */
  3946. CROW_CALLBACK_NOTIFY(message_complete);
  3947. }
  3948. else if (parser->content_length != CROW_ULLONG_MAX)
  3949. {
  3950. /* Content-Length header given and non-zero */
  3951. parser->state = s_body_identity;
  3952. }
  3953. else
  3954. {
  3955. /* Assume content-length 0 - read the next */
  3956. CROW_CALLBACK_NOTIFY(message_complete);
  3957. }
  3958. }
  3959. break;
  3960. }
  3961. case s_body_identity:
  3962. {
  3963. uint64_t to_read = CROW_MIN(parser->content_length,
  3964. (uint64_t) ((data + len) - p));
  3965. assert(parser->content_length != 0
  3966. && parser->content_length != CROW_ULLONG_MAX);
  3967. /* The difference between advancing content_length and p is because
  3968. * the latter will automaticaly advance on the next loop iteration.
  3969. * Further, if content_length ends up at 0, we want to see the last
  3970. * byte again for our message complete callback.
  3971. */
  3972. CROW_MARK(body);
  3973. parser->content_length -= to_read;
  3974. p += to_read - 1;
  3975. if (parser->content_length == 0) {
  3976. parser->state = s_message_done;
  3977. /* Mimic CROW_CALLBACK_DATA_NOADVANCE() but with one extra byte.
  3978. *
  3979. * The alternative to doing this is to wait for the next byte to
  3980. * trigger the data callback, just as in every other case. The
  3981. * problem with this is that this makes it difficult for the test
  3982. * harness to distinguish between complete-on-EOF and
  3983. * complete-on-length. It's not clear that this distinction is
  3984. * important for applications, but let's keep it for now.
  3985. */
  3986. CROW_CALLBACK_DATA_(body, p - body_mark + 1, p - data);
  3987. CROW_REEXECUTE();
  3988. }
  3989. break;
  3990. }
  3991. /* read until EOF */
  3992. case s_body_identity_eof:
  3993. CROW_MARK(body);
  3994. p = data + len - 1;
  3995. break;
  3996. case s_message_done:
  3997. CROW_CALLBACK_NOTIFY(message_complete);
  3998. break;
  3999. case s_chunk_size_start:
  4000. {
  4001. assert(nread == 1);
  4002. assert(parser->flags & F_CHUNKED);
  4003. unhex_val = unhex[static_cast<unsigned char>(ch)];
  4004. if (CROW_UNLIKELY(unhex_val == -1)) {
  4005. CROW_SET_ERRNO(CHPE_INVALID_CHUNK_SIZE);
  4006. goto error;
  4007. }
  4008. parser->content_length = unhex_val;
  4009. parser->state = s_chunk_size;
  4010. break;
  4011. }
  4012. case s_chunk_size:
  4013. {
  4014. uint64_t t;
  4015. assert(parser->flags & F_CHUNKED);
  4016. if (ch == cr) {
  4017. parser->state = s_chunk_size_almost_done;
  4018. break;
  4019. }
  4020. unhex_val = unhex[static_cast<unsigned char>(ch)];
  4021. if (unhex_val == -1) {
  4022. if (ch == ';' || ch == ' ') {
  4023. parser->state = s_chunk_parameters;
  4024. break;
  4025. }
  4026. CROW_SET_ERRNO(CHPE_INVALID_CHUNK_SIZE);
  4027. goto error;
  4028. }
  4029. t = parser->content_length;
  4030. t *= 16;
  4031. t += unhex_val;
  4032. /* Overflow? Test against a conservative limit for simplicity. */
  4033. if (CROW_UNLIKELY((CROW_ULLONG_MAX - 16) / 16 < parser->content_length)) {
  4034. CROW_SET_ERRNO(CHPE_INVALID_CONTENT_LENGTH);
  4035. goto error;
  4036. }
  4037. parser->content_length = t;
  4038. break;
  4039. }
  4040. case s_chunk_parameters:
  4041. {
  4042. assert(parser->flags & F_CHUNKED);
  4043. /* just ignore this shit. TODO check for overflow */
  4044. if (ch == cr) {
  4045. parser->state = s_chunk_size_almost_done;
  4046. break;
  4047. }
  4048. break;
  4049. }
  4050. case s_chunk_size_almost_done:
  4051. {
  4052. assert(parser->flags & F_CHUNKED);
  4053. CROW_STRICT_CHECK(ch != lf);
  4054. parser->nread = 0;
  4055. nread = 0;
  4056. if (parser->content_length == 0) {
  4057. parser->flags |= F_TRAILING;
  4058. parser->state = s_header_field_start;
  4059. } else {
  4060. parser->state = s_chunk_data;
  4061. }
  4062. break;
  4063. }
  4064. case s_chunk_data:
  4065. {
  4066. uint64_t to_read = CROW_MIN(parser->content_length,
  4067. (uint64_t) ((data + len) - p));
  4068. assert(parser->flags & F_CHUNKED);
  4069. assert(parser->content_length != 0
  4070. && parser->content_length != CROW_ULLONG_MAX);
  4071. /* See the explanation in s_body_identity for why the content
  4072. * length and data pointers are managed this way.
  4073. */
  4074. CROW_MARK(body);
  4075. parser->content_length -= to_read;
  4076. p += to_read - 1;
  4077. if (parser->content_length == 0) {
  4078. parser->state = s_chunk_data_almost_done;
  4079. }
  4080. break;
  4081. }
  4082. case s_chunk_data_almost_done:
  4083. assert(parser->flags & F_CHUNKED);
  4084. assert(parser->content_length == 0);
  4085. CROW_STRICT_CHECK(ch != cr);
  4086. parser->state = s_chunk_data_done;
  4087. CROW_CALLBACK_DATA(body);
  4088. break;
  4089. case s_chunk_data_done:
  4090. assert(parser->flags & F_CHUNKED);
  4091. CROW_STRICT_CHECK(ch != lf);
  4092. parser->nread = 0;
  4093. nread = 0;
  4094. parser->state = s_chunk_size_start;
  4095. break;
  4096. default:
  4097. assert(0 && "unhandled state");
  4098. CROW_SET_ERRNO(CHPE_INVALID_INTERNAL_STATE);
  4099. goto error;
  4100. }
  4101. }
  4102. /* Run callbacks for any marks that we have leftover after we ran out of
  4103. * bytes. There should be at most one of these set, so it's OK to invoke
  4104. * them in series (unset marks will not result in callbacks).
  4105. *
  4106. * We use the NOADVANCE() variety of callbacks here because 'p' has already
  4107. * overflowed 'data' and this allows us to correct for the off-by-one that
  4108. * we'd otherwise have (since CROW_CALLBACK_DATA() is meant to be run with a 'p'
  4109. * value that's in-bounds).
  4110. */
  4111. assert(((header_field_mark ? 1 : 0) +
  4112. (header_value_mark ? 1 : 0) +
  4113. (url_mark ? 1 : 0) +
  4114. (body_mark ? 1 : 0)) <= 1);
  4115. CROW_CALLBACK_DATA_NOADVANCE(header_field);
  4116. CROW_CALLBACK_DATA_NOADVANCE(header_value);
  4117. CROW_CALLBACK_DATA_NOADVANCE(url);
  4118. CROW_CALLBACK_DATA_NOADVANCE(body);
  4119. parser->nread = nread;
  4120. return len;
  4121. error:
  4122. if (CROW_HTTP_PARSER_ERRNO(parser) == CHPE_OK) {
  4123. CROW_SET_ERRNO(CHPE_UNKNOWN);
  4124. }
  4125. parser->nread = nread;
  4126. return (p - data);
  4127. }
  4128. inline void
  4129. http_parser_init(http_parser* parser)
  4130. {
  4131. void *data = parser->data; /* preserve application data */
  4132. memset(parser, 0, sizeof(*parser));
  4133. parser->data = data;
  4134. parser->state = s_start_req;
  4135. parser->http_errno = CHPE_OK;
  4136. }
  4137. /* Return a string name of the given error */
  4138. inline const char *
  4139. http_errno_name(enum http_errno err) {
  4140. /* Map errno values to strings for human-readable output */
  4141. #define CROW_HTTP_STRERROR_GEN(n, s) { "CHPE_" #n, s },
  4142. static struct {
  4143. const char *name;
  4144. const char *description;
  4145. } http_strerror_tab[] = {
  4146. CROW_HTTP_ERRNO_MAP(CROW_HTTP_STRERROR_GEN)
  4147. };
  4148. #undef CROW_HTTP_STRERROR_GEN
  4149. assert(((size_t) err) < CROW_ARRAY_SIZE(http_strerror_tab));
  4150. return http_strerror_tab[err].name;
  4151. }
  4152. /* Return a string description of the given error */
  4153. inline const char *
  4154. http_errno_description(enum http_errno err) {
  4155. /* Map errno values to strings for human-readable output */
  4156. #define CROW_HTTP_STRERROR_GEN(n, s) { "CHPE_" #n, s },
  4157. static struct {
  4158. const char *name;
  4159. const char *description;
  4160. } http_strerror_tab[] = {
  4161. CROW_HTTP_ERRNO_MAP(CROW_HTTP_STRERROR_GEN)
  4162. };
  4163. #undef CROW_HTTP_STRERROR_GEN
  4164. assert(((size_t) err) < CROW_ARRAY_SIZE(http_strerror_tab));
  4165. return http_strerror_tab[err].description;
  4166. }
  4167. /* Checks if this is the final chunk of the body. */
  4168. inline int
  4169. http_body_is_final(const struct http_parser *parser) {
  4170. return parser->state == s_message_done;
  4171. }
  4172. /* Change the maximum header size provided at compile time. */
  4173. inline void
  4174. http_parser_set_max_header_size(uint32_t size) {
  4175. max_header_size = size;
  4176. }
  4177. #undef CROW_HTTP_ERRNO_MAP
  4178. #undef CROW_SET_ERRNO
  4179. #undef CROW_CALLBACK_NOTIFY_
  4180. #undef CROW_CALLBACK_NOTIFY
  4181. #undef CROW_CALLBACK_NOTIFY_NOADVANCE
  4182. #undef CROW_CALLBACK_DATA_
  4183. #undef CROW_CALLBACK_DATA
  4184. #undef CROW_CALLBACK_DATA_NOADVANCE
  4185. #undef CROW_MARK
  4186. #undef CROW_PROXY_CONNECTION
  4187. #undef CROW_CONNECTION
  4188. #undef CROW_CONTENT_LENGTH
  4189. #undef CROW_TRANSFER_ENCODING
  4190. #undef CROW_UPGRADE
  4191. #undef CROW_CHUNKED
  4192. #undef CROW_KEEP_ALIVE
  4193. #undef CROW_CLOSE
  4194. #undef CROW_PARSING_HEADER
  4195. #undef CROW_LOWER
  4196. #undef CROW_IS_ALPHA
  4197. #undef CROW_IS_NUM
  4198. #undef CROW_IS_ALPHANUM
  4199. //#undef CROW_IS_HEX
  4200. #undef CROW_IS_MARK
  4201. #undef CROW_IS_USERINFO_CHAR
  4202. #undef CROW_TOKEN
  4203. #undef CROW_IS_URL_CHAR
  4204. //#undef CROW_IS_HOST_CHAR
  4205. #undef CROW_STRICT_CHECK
  4206. }
  4207. // clang-format on
  4208. #include <string>
  4209. #include <unordered_map>
  4210. #include <algorithm>
  4211. namespace crow
  4212. {
  4213. /// A wrapper for `nodejs/http-parser`.
  4214. ///
  4215. /// Used to generate a \ref crow.request from the TCP socket buffer.
  4216. template<typename Handler>
  4217. struct HTTPParser : public http_parser
  4218. {
  4219. static int on_message_begin(http_parser*)
  4220. {
  4221. return 0;
  4222. }
  4223. static int on_method(http_parser* self_)
  4224. {
  4225. HTTPParser* self = static_cast<HTTPParser*>(self_);
  4226. self->req.method = static_cast<HTTPMethod>(self->method);
  4227. return 0;
  4228. }
  4229. static int on_url(http_parser* self_, const char* at, size_t length)
  4230. {
  4231. HTTPParser* self = static_cast<HTTPParser*>(self_);
  4232. self->req.raw_url.insert(self->req.raw_url.end(), at, at + length);
  4233. self->req.url_params = query_string(self->req.raw_url);
  4234. self->req.url = self->req.raw_url.substr(0, self->qs_point != 0 ? self->qs_point : std::string::npos);
  4235. self->process_url();
  4236. return 0;
  4237. }
  4238. static int on_header_field(http_parser* self_, const char* at, size_t length)
  4239. {
  4240. HTTPParser* self = static_cast<HTTPParser*>(self_);
  4241. switch (self->header_building_state)
  4242. {
  4243. case 0:
  4244. if (!self->header_value.empty())
  4245. {
  4246. self->req.headers.emplace(std::move(self->header_field), std::move(self->header_value));
  4247. }
  4248. self->header_field.assign(at, at + length);
  4249. self->header_building_state = 1;
  4250. break;
  4251. case 1:
  4252. self->header_field.insert(self->header_field.end(), at, at + length);
  4253. break;
  4254. }
  4255. return 0;
  4256. }
  4257. static int on_header_value(http_parser* self_, const char* at, size_t length)
  4258. {
  4259. HTTPParser* self = static_cast<HTTPParser*>(self_);
  4260. switch (self->header_building_state)
  4261. {
  4262. case 0:
  4263. self->header_value.insert(self->header_value.end(), at, at + length);
  4264. break;
  4265. case 1:
  4266. self->header_building_state = 0;
  4267. self->header_value.assign(at, at + length);
  4268. break;
  4269. }
  4270. return 0;
  4271. }
  4272. static int on_headers_complete(http_parser* self_)
  4273. {
  4274. HTTPParser* self = static_cast<HTTPParser*>(self_);
  4275. if (!self->header_field.empty())
  4276. {
  4277. self->req.headers.emplace(std::move(self->header_field), std::move(self->header_value));
  4278. }
  4279. self->set_connection_parameters();
  4280. self->process_header();
  4281. return 0;
  4282. }
  4283. static int on_body(http_parser* self_, const char* at, size_t length)
  4284. {
  4285. HTTPParser* self = static_cast<HTTPParser*>(self_);
  4286. self->req.body.insert(self->req.body.end(), at, at + length);
  4287. return 0;
  4288. }
  4289. static int on_message_complete(http_parser* self_)
  4290. {
  4291. HTTPParser* self = static_cast<HTTPParser*>(self_);
  4292. self->message_complete = true;
  4293. self->process_message();
  4294. return 0;
  4295. }
  4296. HTTPParser(Handler* handler):
  4297. handler_(handler)
  4298. {
  4299. http_parser_init(this);
  4300. }
  4301. // return false on error
  4302. /// Parse a buffer into the different sections of an HTTP request.
  4303. bool feed(const char* buffer, int length)
  4304. {
  4305. if (message_complete)
  4306. return true;
  4307. const static http_parser_settings settings_{
  4308. on_message_begin,
  4309. on_method,
  4310. on_url,
  4311. on_header_field,
  4312. on_header_value,
  4313. on_headers_complete,
  4314. on_body,
  4315. on_message_complete,
  4316. };
  4317. int nparsed = http_parser_execute(this, &settings_, buffer, length);
  4318. if (http_errno != CHPE_OK)
  4319. {
  4320. return false;
  4321. }
  4322. return nparsed == length;
  4323. }
  4324. bool done()
  4325. {
  4326. return feed(nullptr, 0);
  4327. }
  4328. void clear()
  4329. {
  4330. req = crow::request();
  4331. header_field.clear();
  4332. header_value.clear();
  4333. header_building_state = 0;
  4334. qs_point = 0;
  4335. message_complete = false;
  4336. state = CROW_NEW_MESSAGE();
  4337. }
  4338. inline void process_url()
  4339. {
  4340. handler_->handle_url();
  4341. }
  4342. inline void process_header()
  4343. {
  4344. handler_->handle_header();
  4345. }
  4346. inline void process_message()
  4347. {
  4348. handler_->handle();
  4349. }
  4350. inline void set_connection_parameters()
  4351. {
  4352. req.http_ver_major = http_major;
  4353. req.http_ver_minor = http_minor;
  4354. //NOTE(EDev): it seems that the problem is with crow's policy on closing the connection for HTTP_VERSION < 1.0, the behaviour for that in crow is "don't close the connection, but don't send a keep-alive either"
  4355. // HTTP1.1 = always send keep_alive, HTTP1.0 = only send if header exists, HTTP?.? = never send
  4356. req.keep_alive = (http_major == 1 && http_minor == 0) ?
  4357. ((flags & F_CONNECTION_KEEP_ALIVE) ? true : false) :
  4358. ((http_major == 1 && http_minor == 1) ? true : false);
  4359. // HTTP1.1 = only close if close header exists, HTTP1.0 = always close unless keep_alive header exists, HTTP?.?= never close
  4360. req.close_connection = (http_major == 1 && http_minor == 0) ?
  4361. ((flags & F_CONNECTION_KEEP_ALIVE) ? false : true) :
  4362. ((http_major == 1 && http_minor == 1) ? ((flags & F_CONNECTION_CLOSE) ? true : false) : false);
  4363. req.upgrade = static_cast<bool>(upgrade);
  4364. }
  4365. /// The final request that this parser outputs.
  4366. ///
  4367. /// Data parsed is put directly into this object as soon as the related callback returns. (e.g. the request will have the cooorect method as soon as on_method() returns)
  4368. request req;
  4369. private:
  4370. int header_building_state = 0;
  4371. bool message_complete = false;
  4372. std::string header_field;
  4373. std::string header_value;
  4374. Handler* handler_; ///< This is currently an HTTP connection object (\ref crow.Connection).
  4375. };
  4376. } // namespace crow
  4377. #undef CROW_NEW_MESSAGE
  4378. #undef CROW_start_state
  4379. #include <cstdio>
  4380. #include <cstdlib>
  4381. #include <ctime>
  4382. #include <iostream>
  4383. #include <sstream>
  4384. #include <string>
  4385. namespace crow
  4386. {
  4387. enum class LogLevel
  4388. {
  4389. #ifndef ERROR
  4390. #ifndef DEBUG
  4391. DEBUG = 0,
  4392. INFO,
  4393. WARNING,
  4394. ERROR,
  4395. CRITICAL,
  4396. #endif
  4397. #endif
  4398. Debug = 0,
  4399. Info,
  4400. Warning,
  4401. Error,
  4402. Critical,
  4403. };
  4404. class ILogHandler
  4405. {
  4406. public:
  4407. virtual ~ILogHandler() = default;
  4408. virtual void log(std::string message, LogLevel level) = 0;
  4409. };
  4410. class CerrLogHandler : public ILogHandler
  4411. {
  4412. public:
  4413. void log(std::string message, LogLevel level) override
  4414. {
  4415. std::string prefix;
  4416. switch (level)
  4417. {
  4418. case LogLevel::Debug:
  4419. prefix = "DEBUG ";
  4420. break;
  4421. case LogLevel::Info:
  4422. prefix = "INFO ";
  4423. break;
  4424. case LogLevel::Warning:
  4425. prefix = "WARNING ";
  4426. break;
  4427. case LogLevel::Error:
  4428. prefix = "ERROR ";
  4429. break;
  4430. case LogLevel::Critical:
  4431. prefix = "CRITICAL";
  4432. break;
  4433. }
  4434. std::cerr << std::string("(") + timestamp() + std::string(") [") + prefix + std::string("] ") + message << std::endl;
  4435. }
  4436. private:
  4437. static std::string timestamp()
  4438. {
  4439. char date[32];
  4440. time_t t = time(0);
  4441. tm my_tm;
  4442. #if defined(_MSC_VER) || defined(__MINGW32__)
  4443. #ifdef CROW_USE_LOCALTIMEZONE
  4444. localtime_s(&my_tm, &t);
  4445. #else
  4446. gmtime_s(&my_tm, &t);
  4447. #endif
  4448. #else
  4449. #ifdef CROW_USE_LOCALTIMEZONE
  4450. localtime_r(&t, &my_tm);
  4451. #else
  4452. gmtime_r(&t, &my_tm);
  4453. #endif
  4454. #endif
  4455. size_t sz = strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", &my_tm);
  4456. return std::string(date, date + sz);
  4457. }
  4458. };
  4459. class logger
  4460. {
  4461. public:
  4462. logger(LogLevel level):
  4463. level_(level)
  4464. {}
  4465. ~logger()
  4466. {
  4467. #ifdef CROW_ENABLE_LOGGING
  4468. if (level_ >= get_current_log_level())
  4469. {
  4470. get_handler_ref()->log(stringstream_.str(), level_);
  4471. }
  4472. #endif
  4473. }
  4474. //
  4475. template<typename T>
  4476. logger& operator<<(T const& value)
  4477. {
  4478. #ifdef CROW_ENABLE_LOGGING
  4479. if (level_ >= get_current_log_level())
  4480. {
  4481. stringstream_ << value;
  4482. }
  4483. #endif
  4484. return *this;
  4485. }
  4486. //
  4487. static void setLogLevel(LogLevel level) { get_log_level_ref() = level; }
  4488. static void setHandler(ILogHandler* handler) { get_handler_ref() = handler; }
  4489. static LogLevel get_current_log_level() { return get_log_level_ref(); }
  4490. private:
  4491. //
  4492. static LogLevel& get_log_level_ref()
  4493. {
  4494. static LogLevel current_level = static_cast<LogLevel>(CROW_LOG_LEVEL);
  4495. return current_level;
  4496. }
  4497. static ILogHandler*& get_handler_ref()
  4498. {
  4499. static CerrLogHandler default_handler;
  4500. static ILogHandler* current_handler = &default_handler;
  4501. return current_handler;
  4502. }
  4503. //
  4504. std::ostringstream stringstream_;
  4505. LogLevel level_;
  4506. };
  4507. } // namespace crow
  4508. #define CROW_LOG_CRITICAL \
  4509. if (crow::logger::get_current_log_level() <= crow::LogLevel::Critical) \
  4510. crow::logger(crow::LogLevel::Critical)
  4511. #define CROW_LOG_ERROR \
  4512. if (crow::logger::get_current_log_level() <= crow::LogLevel::Error) \
  4513. crow::logger(crow::LogLevel::Error)
  4514. #define CROW_LOG_WARNING \
  4515. if (crow::logger::get_current_log_level() <= crow::LogLevel::Warning) \
  4516. crow::logger(crow::LogLevel::Warning)
  4517. #define CROW_LOG_INFO \
  4518. if (crow::logger::get_current_log_level() <= crow::LogLevel::Info) \
  4519. crow::logger(crow::LogLevel::Info)
  4520. #define CROW_LOG_DEBUG \
  4521. if (crow::logger::get_current_log_level() <= crow::LogLevel::Debug) \
  4522. crow::logger(crow::LogLevel::Debug)
  4523. //#define CROW_JSON_NO_ERROR_CHECK
  4524. //#define CROW_JSON_USE_MAP
  4525. #include <string>
  4526. #ifdef CROW_JSON_USE_MAP
  4527. #include <map>
  4528. #else
  4529. #include <unordered_map>
  4530. #endif
  4531. #include <iostream>
  4532. #include <algorithm>
  4533. #include <memory>
  4534. #include <vector>
  4535. #include <cmath>
  4536. #include <cfloat>
  4537. using std::isinf;
  4538. using std::isnan;
  4539. namespace crow // NOTE: Already documented in "crow/app.h"
  4540. {
  4541. namespace mustache
  4542. {
  4543. class template_t;
  4544. }
  4545. namespace json
  4546. {
  4547. inline void escape(const std::string& str, std::string& ret)
  4548. {
  4549. ret.reserve(ret.size() + str.size() + str.size() / 4);
  4550. for (auto c : str)
  4551. {
  4552. switch (c)
  4553. {
  4554. case '"': ret += "\\\""; break;
  4555. case '\\': ret += "\\\\"; break;
  4556. case '\n': ret += "\\n"; break;
  4557. case '\b': ret += "\\b"; break;
  4558. case '\f': ret += "\\f"; break;
  4559. case '\r': ret += "\\r"; break;
  4560. case '\t': ret += "\\t"; break;
  4561. default:
  4562. if (c >= 0 && c < 0x20)
  4563. {
  4564. ret += "\\u00";
  4565. auto to_hex = [](char c) {
  4566. c = c & 0xf;
  4567. if (c < 10)
  4568. return '0' + c;
  4569. return 'a' + c - 10;
  4570. };
  4571. ret += to_hex(c / 16);
  4572. ret += to_hex(c % 16);
  4573. }
  4574. else
  4575. ret += c;
  4576. break;
  4577. }
  4578. }
  4579. }
  4580. inline std::string escape(const std::string& str)
  4581. {
  4582. std::string ret;
  4583. escape(str, ret);
  4584. return ret;
  4585. }
  4586. enum class type : char
  4587. {
  4588. Null,
  4589. False,
  4590. True,
  4591. Number,
  4592. String,
  4593. List,
  4594. Object,
  4595. Function
  4596. };
  4597. inline const char* get_type_str(type t)
  4598. {
  4599. switch (t)
  4600. {
  4601. case type::Number: return "Number";
  4602. case type::False: return "False";
  4603. case type::True: return "True";
  4604. case type::List: return "List";
  4605. case type::String: return "String";
  4606. case type::Object: return "Object";
  4607. case type::Function: return "Function";
  4608. default: return "Unknown";
  4609. }
  4610. }
  4611. enum class num_type : char
  4612. {
  4613. Signed_integer,
  4614. Unsigned_integer,
  4615. Floating_point,
  4616. Null,
  4617. Double_precision_floating_point
  4618. };
  4619. class rvalue;
  4620. rvalue load(const char* data, size_t size);
  4621. namespace detail
  4622. {
  4623. /// A read string implementation with comparison functionality.
  4624. struct r_string
  4625. {
  4626. r_string(){};
  4627. r_string(char* s, char* e):
  4628. s_(s), e_(e){};
  4629. ~r_string()
  4630. {
  4631. if (owned_)
  4632. delete[] s_;
  4633. }
  4634. r_string(const r_string& r)
  4635. {
  4636. *this = r;
  4637. }
  4638. r_string(r_string&& r)
  4639. {
  4640. *this = r;
  4641. }
  4642. r_string& operator=(r_string&& r)
  4643. {
  4644. s_ = r.s_;
  4645. e_ = r.e_;
  4646. owned_ = r.owned_;
  4647. if (r.owned_)
  4648. r.owned_ = 0;
  4649. return *this;
  4650. }
  4651. r_string& operator=(const r_string& r)
  4652. {
  4653. s_ = r.s_;
  4654. e_ = r.e_;
  4655. owned_ = 0;
  4656. return *this;
  4657. }
  4658. operator std::string() const
  4659. {
  4660. return std::string(s_, e_);
  4661. }
  4662. const char* begin() const { return s_; }
  4663. const char* end() const { return e_; }
  4664. size_t size() const { return end() - begin(); }
  4665. using iterator = const char*;
  4666. using const_iterator = const char*;
  4667. char* s_; ///< Start.
  4668. mutable char* e_; ///< End.
  4669. uint8_t owned_{0};
  4670. friend std::ostream& operator<<(std::ostream& os, const r_string& s)
  4671. {
  4672. os << static_cast<std::string>(s);
  4673. return os;
  4674. }
  4675. private:
  4676. void force(char* s, uint32_t length)
  4677. {
  4678. s_ = s;
  4679. e_ = s_ + length;
  4680. owned_ = 1;
  4681. }
  4682. friend rvalue crow::json::load(const char* data, size_t size);
  4683. friend bool operator==(const r_string& l, const r_string& r);
  4684. friend bool operator==(const std::string& l, const r_string& r);
  4685. friend bool operator==(const r_string& l, const std::string& r);
  4686. template<typename T, typename U>
  4687. inline static bool equals(const T& l, const U& r)
  4688. {
  4689. if (l.size() != r.size())
  4690. return false;
  4691. for (size_t i = 0; i < l.size(); i++)
  4692. {
  4693. if (*(l.begin() + i) != *(r.begin() + i))
  4694. return false;
  4695. }
  4696. return true;
  4697. }
  4698. };
  4699. inline bool operator<(const r_string& l, const r_string& r)
  4700. {
  4701. return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
  4702. }
  4703. inline bool operator<(const r_string& l, const std::string& r)
  4704. {
  4705. return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
  4706. }
  4707. inline bool operator<(const std::string& l, const r_string& r)
  4708. {
  4709. return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
  4710. }
  4711. inline bool operator>(const r_string& l, const r_string& r)
  4712. {
  4713. return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
  4714. }
  4715. inline bool operator>(const r_string& l, const std::string& r)
  4716. {
  4717. return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
  4718. }
  4719. inline bool operator>(const std::string& l, const r_string& r)
  4720. {
  4721. return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
  4722. }
  4723. inline bool operator==(const r_string& l, const r_string& r)
  4724. {
  4725. return r_string::equals(l, r);
  4726. }
  4727. inline bool operator==(const r_string& l, const std::string& r)
  4728. {
  4729. return r_string::equals(l, r);
  4730. }
  4731. inline bool operator==(const std::string& l, const r_string& r)
  4732. {
  4733. return r_string::equals(l, r);
  4734. }
  4735. inline bool operator!=(const r_string& l, const r_string& r)
  4736. {
  4737. return !(l == r);
  4738. }
  4739. inline bool operator!=(const r_string& l, const std::string& r)
  4740. {
  4741. return !(l == r);
  4742. }
  4743. inline bool operator!=(const std::string& l, const r_string& r)
  4744. {
  4745. return !(l == r);
  4746. }
  4747. } // namespace detail
  4748. /// JSON read value.
  4749. ///
  4750. /// Value can mean any json value, including a JSON object.
  4751. /// Read means this class is used to primarily read strings into a JSON value.
  4752. class rvalue
  4753. {
  4754. static const int cached_bit = 2;
  4755. static const int error_bit = 4;
  4756. public:
  4757. rvalue() noexcept:
  4758. option_{error_bit}
  4759. {
  4760. }
  4761. rvalue(type t) noexcept:
  4762. lsize_{}, lremain_{}, t_{t}
  4763. {
  4764. }
  4765. rvalue(type t, char* s, char* e) noexcept:
  4766. start_{s}, end_{e}, t_{t}
  4767. {
  4768. determine_num_type();
  4769. }
  4770. rvalue(const rvalue& r):
  4771. start_(r.start_), end_(r.end_), key_(r.key_), t_(r.t_), nt_(r.nt_), option_(r.option_)
  4772. {
  4773. copy_l(r);
  4774. }
  4775. rvalue(rvalue&& r) noexcept
  4776. {
  4777. *this = std::move(r);
  4778. }
  4779. rvalue& operator=(const rvalue& r)
  4780. {
  4781. start_ = r.start_;
  4782. end_ = r.end_;
  4783. key_ = r.key_;
  4784. t_ = r.t_;
  4785. nt_ = r.nt_;
  4786. option_ = r.option_;
  4787. copy_l(r);
  4788. return *this;
  4789. }
  4790. rvalue& operator=(rvalue&& r) noexcept
  4791. {
  4792. start_ = r.start_;
  4793. end_ = r.end_;
  4794. key_ = std::move(r.key_);
  4795. l_ = std::move(r.l_);
  4796. lsize_ = r.lsize_;
  4797. lremain_ = r.lremain_;
  4798. t_ = r.t_;
  4799. nt_ = r.nt_;
  4800. option_ = r.option_;
  4801. return *this;
  4802. }
  4803. explicit operator bool() const noexcept
  4804. {
  4805. return (option_ & error_bit) == 0;
  4806. }
  4807. explicit operator int64_t() const
  4808. {
  4809. return i();
  4810. }
  4811. explicit operator uint64_t() const
  4812. {
  4813. return u();
  4814. }
  4815. explicit operator int() const
  4816. {
  4817. return static_cast<int>(i());
  4818. }
  4819. /// Return any json value (not object or list) as a string.
  4820. explicit operator std::string() const
  4821. {
  4822. #ifndef CROW_JSON_NO_ERROR_CHECK
  4823. if (t() == type::Object || t() == type::List)
  4824. throw std::runtime_error("json type container");
  4825. #endif
  4826. switch (t())
  4827. {
  4828. case type::String:
  4829. return std::string(s());
  4830. case type::Null:
  4831. return std::string("null");
  4832. case type::True:
  4833. return std::string("true");
  4834. case type::False:
  4835. return std::string("false");
  4836. default:
  4837. return std::string(start_, end_ - start_);
  4838. }
  4839. }
  4840. /// The type of the JSON value.
  4841. type t() const
  4842. {
  4843. #ifndef CROW_JSON_NO_ERROR_CHECK
  4844. if (option_ & error_bit)
  4845. {
  4846. throw std::runtime_error("invalid json object");
  4847. }
  4848. #endif
  4849. return t_;
  4850. }
  4851. /// The number type of the JSON value.
  4852. num_type nt() const
  4853. {
  4854. #ifndef CROW_JSON_NO_ERROR_CHECK
  4855. if (option_ & error_bit)
  4856. {
  4857. throw std::runtime_error("invalid json object");
  4858. }
  4859. #endif
  4860. return nt_;
  4861. }
  4862. /// The integer value.
  4863. int64_t i() const
  4864. {
  4865. #ifndef CROW_JSON_NO_ERROR_CHECK
  4866. switch (t())
  4867. {
  4868. case type::Number:
  4869. case type::String:
  4870. return utility::lexical_cast<int64_t>(start_, end_ - start_);
  4871. default:
  4872. const std::string msg = "expected number, got: " + std::string(get_type_str(t()));
  4873. throw std::runtime_error(msg);
  4874. }
  4875. #endif
  4876. return utility::lexical_cast<int64_t>(start_, end_ - start_);
  4877. }
  4878. /// The unsigned integer value.
  4879. uint64_t u() const
  4880. {
  4881. #ifndef CROW_JSON_NO_ERROR_CHECK
  4882. switch (t())
  4883. {
  4884. case type::Number:
  4885. case type::String:
  4886. return utility::lexical_cast<uint64_t>(start_, end_ - start_);
  4887. default:
  4888. throw std::runtime_error(std::string("expected number, got: ") + get_type_str(t()));
  4889. }
  4890. #endif
  4891. return utility::lexical_cast<uint64_t>(start_, end_ - start_);
  4892. }
  4893. /// The double precision floating-point number value.
  4894. double d() const
  4895. {
  4896. #ifndef CROW_JSON_NO_ERROR_CHECK
  4897. if (t() != type::Number)
  4898. throw std::runtime_error("value is not number");
  4899. #endif
  4900. return utility::lexical_cast<double>(start_, end_ - start_);
  4901. }
  4902. /// The boolean value.
  4903. bool b() const
  4904. {
  4905. #ifndef CROW_JSON_NO_ERROR_CHECK
  4906. if (t() != type::True && t() != type::False)
  4907. throw std::runtime_error("value is not boolean");
  4908. #endif
  4909. return t() == type::True;
  4910. }
  4911. /// The string value.
  4912. detail::r_string s() const
  4913. {
  4914. #ifndef CROW_JSON_NO_ERROR_CHECK
  4915. if (t() != type::String)
  4916. throw std::runtime_error("value is not string");
  4917. #endif
  4918. unescape();
  4919. return detail::r_string{start_, end_};
  4920. }
  4921. /// The list or object value
  4922. std::vector<rvalue> lo()
  4923. {
  4924. #ifndef CROW_JSON_NO_ERROR_CHECK
  4925. if (t() != type::Object && t() != type::List)
  4926. throw std::runtime_error("value is not a container");
  4927. #endif
  4928. std::vector<rvalue> ret;
  4929. ret.reserve(lsize_);
  4930. for (uint32_t i = 0; i < lsize_; i++)
  4931. {
  4932. ret.emplace_back(l_[i]);
  4933. }
  4934. return ret;
  4935. }
  4936. /// Convert escaped string character to their original form ("\\n" -> '\n').
  4937. void unescape() const
  4938. {
  4939. if (*(start_ - 1))
  4940. {
  4941. char* head = start_;
  4942. char* tail = start_;
  4943. while (head != end_)
  4944. {
  4945. if (*head == '\\')
  4946. {
  4947. switch (*++head)
  4948. {
  4949. case '"': *tail++ = '"'; break;
  4950. case '\\': *tail++ = '\\'; break;
  4951. case '/': *tail++ = '/'; break;
  4952. case 'b': *tail++ = '\b'; break;
  4953. case 'f': *tail++ = '\f'; break;
  4954. case 'n': *tail++ = '\n'; break;
  4955. case 'r': *tail++ = '\r'; break;
  4956. case 't': *tail++ = '\t'; break;
  4957. case 'u':
  4958. {
  4959. auto from_hex = [](char c) {
  4960. if (c >= 'a')
  4961. return c - 'a' + 10;
  4962. if (c >= 'A')
  4963. return c - 'A' + 10;
  4964. return c - '0';
  4965. };
  4966. unsigned int code =
  4967. (from_hex(head[1]) << 12) +
  4968. (from_hex(head[2]) << 8) +
  4969. (from_hex(head[3]) << 4) +
  4970. from_hex(head[4]);
  4971. if (code >= 0x800)
  4972. {
  4973. *tail++ = 0xE0 | (code >> 12);
  4974. *tail++ = 0x80 | ((code >> 6) & 0x3F);
  4975. *tail++ = 0x80 | (code & 0x3F);
  4976. }
  4977. else if (code >= 0x80)
  4978. {
  4979. *tail++ = 0xC0 | (code >> 6);
  4980. *tail++ = 0x80 | (code & 0x3F);
  4981. }
  4982. else
  4983. {
  4984. *tail++ = code;
  4985. }
  4986. head += 4;
  4987. }
  4988. break;
  4989. }
  4990. }
  4991. else
  4992. *tail++ = *head;
  4993. head++;
  4994. }
  4995. end_ = tail;
  4996. *end_ = 0;
  4997. *(start_ - 1) = 0;
  4998. }
  4999. }
  5000. /// Check if the json object has the passed string as a key.
  5001. bool has(const char* str) const
  5002. {
  5003. return has(std::string(str));
  5004. }
  5005. bool has(const std::string& str) const
  5006. {
  5007. struct Pred
  5008. {
  5009. bool operator()(const rvalue& l, const rvalue& r) const
  5010. {
  5011. return l.key_ < r.key_;
  5012. };
  5013. bool operator()(const rvalue& l, const std::string& r) const
  5014. {
  5015. return l.key_ < r;
  5016. };
  5017. bool operator()(const std::string& l, const rvalue& r) const
  5018. {
  5019. return l < r.key_;
  5020. };
  5021. };
  5022. if (!is_cached())
  5023. {
  5024. std::sort(begin(), end(), Pred());
  5025. set_cached();
  5026. }
  5027. auto it = lower_bound(begin(), end(), str, Pred());
  5028. return it != end() && it->key_ == str;
  5029. }
  5030. int count(const std::string& str)
  5031. {
  5032. return has(str) ? 1 : 0;
  5033. }
  5034. rvalue* begin() const
  5035. {
  5036. #ifndef CROW_JSON_NO_ERROR_CHECK
  5037. if (t() != type::Object && t() != type::List)
  5038. throw std::runtime_error("value is not a container");
  5039. #endif
  5040. return l_.get();
  5041. }
  5042. rvalue* end() const
  5043. {
  5044. #ifndef CROW_JSON_NO_ERROR_CHECK
  5045. if (t() != type::Object && t() != type::List)
  5046. throw std::runtime_error("value is not a container");
  5047. #endif
  5048. return l_.get() + lsize_;
  5049. }
  5050. const detail::r_string& key() const
  5051. {
  5052. return key_;
  5053. }
  5054. size_t size() const
  5055. {
  5056. if (t() == type::String)
  5057. return s().size();
  5058. #ifndef CROW_JSON_NO_ERROR_CHECK
  5059. if (t() != type::Object && t() != type::List)
  5060. throw std::runtime_error("value is not a container");
  5061. #endif
  5062. return lsize_;
  5063. }
  5064. const rvalue& operator[](int index) const
  5065. {
  5066. #ifndef CROW_JSON_NO_ERROR_CHECK
  5067. if (t() != type::List)
  5068. throw std::runtime_error("value is not a list");
  5069. if (index >= static_cast<int>(lsize_) || index < 0)
  5070. throw std::runtime_error("list out of bound");
  5071. #endif
  5072. return l_[index];
  5073. }
  5074. const rvalue& operator[](size_t index) const
  5075. {
  5076. #ifndef CROW_JSON_NO_ERROR_CHECK
  5077. if (t() != type::List)
  5078. throw std::runtime_error("value is not a list");
  5079. if (index >= lsize_)
  5080. throw std::runtime_error("list out of bound");
  5081. #endif
  5082. return l_[index];
  5083. }
  5084. const rvalue& operator[](const char* str) const
  5085. {
  5086. return this->operator[](std::string(str));
  5087. }
  5088. const rvalue& operator[](const std::string& str) const
  5089. {
  5090. #ifndef CROW_JSON_NO_ERROR_CHECK
  5091. if (t() != type::Object)
  5092. throw std::runtime_error("value is not an object");
  5093. #endif
  5094. struct Pred
  5095. {
  5096. bool operator()(const rvalue& l, const rvalue& r) const
  5097. {
  5098. return l.key_ < r.key_;
  5099. };
  5100. bool operator()(const rvalue& l, const std::string& r) const
  5101. {
  5102. return l.key_ < r;
  5103. };
  5104. bool operator()(const std::string& l, const rvalue& r) const
  5105. {
  5106. return l < r.key_;
  5107. };
  5108. };
  5109. if (!is_cached())
  5110. {
  5111. std::sort(begin(), end(), Pred());
  5112. set_cached();
  5113. }
  5114. auto it = lower_bound(begin(), end(), str, Pred());
  5115. if (it != end() && it->key_ == str)
  5116. return *it;
  5117. #ifndef CROW_JSON_NO_ERROR_CHECK
  5118. throw std::runtime_error("cannot find key");
  5119. #else
  5120. static rvalue nullValue;
  5121. return nullValue;
  5122. #endif
  5123. }
  5124. void set_error()
  5125. {
  5126. option_ |= error_bit;
  5127. }
  5128. bool error() const
  5129. {
  5130. return (option_ & error_bit) != 0;
  5131. }
  5132. std::vector<std::string> keys() const
  5133. {
  5134. #ifndef CROW_JSON_NO_ERROR_CHECK
  5135. if (t() != type::Object)
  5136. throw std::runtime_error("value is not an object");
  5137. #endif
  5138. std::vector<std::string> ret;
  5139. ret.reserve(lsize_);
  5140. for (uint32_t i = 0; i < lsize_; i++)
  5141. {
  5142. ret.emplace_back(std::string(l_[i].key()));
  5143. }
  5144. return ret;
  5145. }
  5146. private:
  5147. bool is_cached() const
  5148. {
  5149. return (option_ & cached_bit) != 0;
  5150. }
  5151. void set_cached() const
  5152. {
  5153. option_ |= cached_bit;
  5154. }
  5155. void copy_l(const rvalue& r)
  5156. {
  5157. if (r.t() != type::Object && r.t() != type::List)
  5158. return;
  5159. lsize_ = r.lsize_;
  5160. lremain_ = 0;
  5161. l_.reset(new rvalue[lsize_]);
  5162. std::copy(r.begin(), r.end(), begin());
  5163. }
  5164. void emplace_back(rvalue&& v)
  5165. {
  5166. if (!lremain_)
  5167. {
  5168. int new_size = lsize_ + lsize_;
  5169. if (new_size - lsize_ > 60000)
  5170. new_size = lsize_ + 60000;
  5171. if (new_size < 4)
  5172. new_size = 4;
  5173. rvalue* p = new rvalue[new_size];
  5174. rvalue* p2 = p;
  5175. for (auto& x : *this)
  5176. *p2++ = std::move(x);
  5177. l_.reset(p);
  5178. lremain_ = new_size - lsize_;
  5179. }
  5180. l_[lsize_++] = std::move(v);
  5181. lremain_--;
  5182. }
  5183. /// Determines num_type from the string.
  5184. void determine_num_type()
  5185. {
  5186. if (t_ != type::Number)
  5187. {
  5188. nt_ = num_type::Null;
  5189. return;
  5190. }
  5191. const std::size_t len = end_ - start_;
  5192. const bool has_minus = std::memchr(start_, '-', len) != nullptr;
  5193. const bool has_e = std::memchr(start_, 'e', len) != nullptr || std::memchr(start_, 'E', len) != nullptr;
  5194. const bool has_dec_sep = std::memchr(start_, '.', len) != nullptr;
  5195. if (has_dec_sep || has_e)
  5196. nt_ = num_type::Floating_point;
  5197. else if (has_minus)
  5198. nt_ = num_type::Signed_integer;
  5199. else
  5200. nt_ = num_type::Unsigned_integer;
  5201. }
  5202. mutable char* start_;
  5203. mutable char* end_;
  5204. detail::r_string key_;
  5205. std::unique_ptr<rvalue[]> l_;
  5206. uint32_t lsize_;
  5207. uint16_t lremain_;
  5208. type t_;
  5209. num_type nt_{num_type::Null};
  5210. mutable uint8_t option_{0};
  5211. friend rvalue load_nocopy_internal(char* data, size_t size);
  5212. friend rvalue load(const char* data, size_t size);
  5213. friend std::ostream& operator<<(std::ostream& os, const rvalue& r)
  5214. {
  5215. switch (r.t_)
  5216. {
  5217. case type::Null: os << "null"; break;
  5218. case type::False: os << "false"; break;
  5219. case type::True: os << "true"; break;
  5220. case type::Number:
  5221. {
  5222. switch (r.nt())
  5223. {
  5224. case num_type::Floating_point: os << r.d(); break;
  5225. case num_type::Double_precision_floating_point: os << r.d(); break;
  5226. case num_type::Signed_integer: os << r.i(); break;
  5227. case num_type::Unsigned_integer: os << r.u(); break;
  5228. case num_type::Null: throw std::runtime_error("Number with num_type Null");
  5229. }
  5230. }
  5231. break;
  5232. case type::String: os << '"' << r.s() << '"'; break;
  5233. case type::List:
  5234. {
  5235. os << '[';
  5236. bool first = true;
  5237. for (auto& x : r)
  5238. {
  5239. if (!first)
  5240. os << ',';
  5241. first = false;
  5242. os << x;
  5243. }
  5244. os << ']';
  5245. }
  5246. break;
  5247. case type::Object:
  5248. {
  5249. os << '{';
  5250. bool first = true;
  5251. for (auto& x : r)
  5252. {
  5253. if (!first)
  5254. os << ',';
  5255. os << '"' << escape(x.key_) << "\":";
  5256. first = false;
  5257. os << x;
  5258. }
  5259. os << '}';
  5260. }
  5261. break;
  5262. case type::Function: os << "custom function"; break;
  5263. }
  5264. return os;
  5265. }
  5266. };
  5267. namespace detail
  5268. {
  5269. }
  5270. inline bool operator==(const rvalue& l, const std::string& r)
  5271. {
  5272. return l.s() == r;
  5273. }
  5274. inline bool operator==(const std::string& l, const rvalue& r)
  5275. {
  5276. return l == r.s();
  5277. }
  5278. inline bool operator!=(const rvalue& l, const std::string& r)
  5279. {
  5280. return l.s() != r;
  5281. }
  5282. inline bool operator!=(const std::string& l, const rvalue& r)
  5283. {
  5284. return l != r.s();
  5285. }
  5286. inline bool operator==(const rvalue& l, double r)
  5287. {
  5288. return l.d() == r;
  5289. }
  5290. inline bool operator==(double l, const rvalue& r)
  5291. {
  5292. return l == r.d();
  5293. }
  5294. inline bool operator!=(const rvalue& l, double r)
  5295. {
  5296. return l.d() != r;
  5297. }
  5298. inline bool operator!=(double l, const rvalue& r)
  5299. {
  5300. return l != r.d();
  5301. }
  5302. inline rvalue load_nocopy_internal(char* data, size_t size)
  5303. {
  5304. // Defend against excessive recursion
  5305. static constexpr unsigned max_depth = 10000;
  5306. //static const char* escaped = "\"\\/\b\f\n\r\t";
  5307. struct Parser
  5308. {
  5309. Parser(char* data, size_t /*size*/):
  5310. data(data)
  5311. {
  5312. }
  5313. bool consume(char c)
  5314. {
  5315. if (CROW_UNLIKELY(*data != c))
  5316. return false;
  5317. data++;
  5318. return true;
  5319. }
  5320. void ws_skip()
  5321. {
  5322. while (*data == ' ' || *data == '\t' || *data == '\r' || *data == '\n')
  5323. ++data;
  5324. };
  5325. rvalue decode_string()
  5326. {
  5327. if (CROW_UNLIKELY(!consume('"')))
  5328. return {};
  5329. char* start = data;
  5330. uint8_t has_escaping = 0;
  5331. while (1)
  5332. {
  5333. if (CROW_LIKELY(*data != '"' && *data != '\\' && *data != '\0'))
  5334. {
  5335. data++;
  5336. }
  5337. else if (*data == '"')
  5338. {
  5339. *data = 0;
  5340. *(start - 1) = has_escaping;
  5341. data++;
  5342. return {type::String, start, data - 1};
  5343. }
  5344. else if (*data == '\\')
  5345. {
  5346. has_escaping = 1;
  5347. data++;
  5348. switch (*data)
  5349. {
  5350. case 'u':
  5351. {
  5352. auto check = [](char c) {
  5353. return ('0' <= c && c <= '9') ||
  5354. ('a' <= c && c <= 'f') ||
  5355. ('A' <= c && c <= 'F');
  5356. };
  5357. if (!(check(*(data + 1)) &&
  5358. check(*(data + 2)) &&
  5359. check(*(data + 3)) &&
  5360. check(*(data + 4))))
  5361. return {};
  5362. }
  5363. data += 5;
  5364. break;
  5365. case '"':
  5366. case '\\':
  5367. case '/':
  5368. case 'b':
  5369. case 'f':
  5370. case 'n':
  5371. case 'r':
  5372. case 't':
  5373. data++;
  5374. break;
  5375. default:
  5376. return {};
  5377. }
  5378. }
  5379. else
  5380. return {};
  5381. }
  5382. return {};
  5383. }
  5384. rvalue decode_list(unsigned depth)
  5385. {
  5386. rvalue ret(type::List);
  5387. if (CROW_UNLIKELY(!consume('[')) || CROW_UNLIKELY(depth > max_depth))
  5388. {
  5389. ret.set_error();
  5390. return ret;
  5391. }
  5392. ws_skip();
  5393. if (CROW_UNLIKELY(*data == ']'))
  5394. {
  5395. data++;
  5396. return ret;
  5397. }
  5398. while (1)
  5399. {
  5400. auto v = decode_value(depth + 1);
  5401. if (CROW_UNLIKELY(!v))
  5402. {
  5403. ret.set_error();
  5404. break;
  5405. }
  5406. ws_skip();
  5407. ret.emplace_back(std::move(v));
  5408. if (*data == ']')
  5409. {
  5410. data++;
  5411. break;
  5412. }
  5413. if (CROW_UNLIKELY(!consume(',')))
  5414. {
  5415. ret.set_error();
  5416. break;
  5417. }
  5418. ws_skip();
  5419. }
  5420. return ret;
  5421. }
  5422. rvalue decode_number()
  5423. {
  5424. char* start = data;
  5425. enum NumberParsingState
  5426. {
  5427. Minus,
  5428. AfterMinus,
  5429. ZeroFirst,
  5430. Digits,
  5431. DigitsAfterPoints,
  5432. E,
  5433. DigitsAfterE,
  5434. Invalid,
  5435. } state{Minus};
  5436. while (CROW_LIKELY(state != Invalid))
  5437. {
  5438. switch (*data)
  5439. {
  5440. case '0':
  5441. state = static_cast<NumberParsingState>("\2\2\7\3\4\6\6"[state]);
  5442. /*if (state == NumberParsingState::Minus || state == NumberParsingState::AfterMinus)
  5443. {
  5444. state = NumberParsingState::ZeroFirst;
  5445. }
  5446. else if (state == NumberParsingState::Digits ||
  5447. state == NumberParsingState::DigitsAfterE ||
  5448. state == NumberParsingState::DigitsAfterPoints)
  5449. {
  5450. // ok; pass
  5451. }
  5452. else if (state == NumberParsingState::E)
  5453. {
  5454. state = NumberParsingState::DigitsAfterE;
  5455. }
  5456. else
  5457. return {};*/
  5458. break;
  5459. case '1':
  5460. case '2':
  5461. case '3':
  5462. case '4':
  5463. case '5':
  5464. case '6':
  5465. case '7':
  5466. case '8':
  5467. case '9':
  5468. state = static_cast<NumberParsingState>("\3\3\7\3\4\6\6"[state]);
  5469. while (*(data + 1) >= '0' && *(data + 1) <= '9')
  5470. data++;
  5471. /*if (state == NumberParsingState::Minus || state == NumberParsingState::AfterMinus)
  5472. {
  5473. state = NumberParsingState::Digits;
  5474. }
  5475. else if (state == NumberParsingState::Digits ||
  5476. state == NumberParsingState::DigitsAfterE ||
  5477. state == NumberParsingState::DigitsAfterPoints)
  5478. {
  5479. // ok; pass
  5480. }
  5481. else if (state == NumberParsingState::E)
  5482. {
  5483. state = NumberParsingState::DigitsAfterE;
  5484. }
  5485. else
  5486. return {};*/
  5487. break;
  5488. case '.':
  5489. state = static_cast<NumberParsingState>("\7\7\4\4\7\7\7"[state]);
  5490. /*
  5491. if (state == NumberParsingState::Digits || state == NumberParsingState::ZeroFirst)
  5492. {
  5493. state = NumberParsingState::DigitsAfterPoints;
  5494. }
  5495. else
  5496. return {};
  5497. */
  5498. break;
  5499. case '-':
  5500. state = static_cast<NumberParsingState>("\1\7\7\7\7\6\7"[state]);
  5501. /*if (state == NumberParsingState::Minus)
  5502. {
  5503. state = NumberParsingState::AfterMinus;
  5504. }
  5505. else if (state == NumberParsingState::E)
  5506. {
  5507. state = NumberParsingState::DigitsAfterE;
  5508. }
  5509. else
  5510. return {};*/
  5511. break;
  5512. case '+':
  5513. state = static_cast<NumberParsingState>("\7\7\7\7\7\6\7"[state]);
  5514. /*if (state == NumberParsingState::E)
  5515. {
  5516. state = NumberParsingState::DigitsAfterE;
  5517. }
  5518. else
  5519. return {};*/
  5520. break;
  5521. case 'e':
  5522. case 'E':
  5523. state = static_cast<NumberParsingState>("\7\7\7\5\5\7\7"[state]);
  5524. /*if (state == NumberParsingState::Digits ||
  5525. state == NumberParsingState::DigitsAfterPoints)
  5526. {
  5527. state = NumberParsingState::E;
  5528. }
  5529. else
  5530. return {};*/
  5531. break;
  5532. default:
  5533. if (CROW_LIKELY(state == NumberParsingState::ZeroFirst ||
  5534. state == NumberParsingState::Digits ||
  5535. state == NumberParsingState::DigitsAfterPoints ||
  5536. state == NumberParsingState::DigitsAfterE))
  5537. return {type::Number, start, data};
  5538. else
  5539. return {};
  5540. }
  5541. data++;
  5542. }
  5543. return {};
  5544. }
  5545. rvalue decode_value(unsigned depth)
  5546. {
  5547. switch (*data)
  5548. {
  5549. case '[':
  5550. return decode_list(depth + 1);
  5551. case '{':
  5552. return decode_object(depth + 1);
  5553. case '"':
  5554. return decode_string();
  5555. case 't':
  5556. if ( //e-data >= 4 &&
  5557. data[1] == 'r' &&
  5558. data[2] == 'u' &&
  5559. data[3] == 'e')
  5560. {
  5561. data += 4;
  5562. return {type::True};
  5563. }
  5564. else
  5565. return {};
  5566. case 'f':
  5567. if ( //e-data >= 5 &&
  5568. data[1] == 'a' &&
  5569. data[2] == 'l' &&
  5570. data[3] == 's' &&
  5571. data[4] == 'e')
  5572. {
  5573. data += 5;
  5574. return {type::False};
  5575. }
  5576. else
  5577. return {};
  5578. case 'n':
  5579. if ( //e-data >= 4 &&
  5580. data[1] == 'u' &&
  5581. data[2] == 'l' &&
  5582. data[3] == 'l')
  5583. {
  5584. data += 4;
  5585. return {type::Null};
  5586. }
  5587. else
  5588. return {};
  5589. //case '1': case '2': case '3':
  5590. //case '4': case '5': case '6':
  5591. //case '7': case '8': case '9':
  5592. //case '0': case '-':
  5593. default:
  5594. return decode_number();
  5595. }
  5596. return {};
  5597. }
  5598. rvalue decode_object(unsigned depth)
  5599. {
  5600. rvalue ret(type::Object);
  5601. if (CROW_UNLIKELY(!consume('{')) || CROW_UNLIKELY(depth > max_depth))
  5602. {
  5603. ret.set_error();
  5604. return ret;
  5605. }
  5606. ws_skip();
  5607. if (CROW_UNLIKELY(*data == '}'))
  5608. {
  5609. data++;
  5610. return ret;
  5611. }
  5612. while (1)
  5613. {
  5614. auto t = decode_string();
  5615. if (CROW_UNLIKELY(!t))
  5616. {
  5617. ret.set_error();
  5618. break;
  5619. }
  5620. ws_skip();
  5621. if (CROW_UNLIKELY(!consume(':')))
  5622. {
  5623. ret.set_error();
  5624. break;
  5625. }
  5626. // TODO(ipkn) caching key to speed up (flyweight?)
  5627. // I have no idea how flyweight could apply here, but maybe some speedup can happen if we stopped checking type since decode_string returns a string anyway
  5628. auto key = t.s();
  5629. ws_skip();
  5630. auto v = decode_value(depth + 1);
  5631. if (CROW_UNLIKELY(!v))
  5632. {
  5633. ret.set_error();
  5634. break;
  5635. }
  5636. ws_skip();
  5637. v.key_ = std::move(key);
  5638. ret.emplace_back(std::move(v));
  5639. if (CROW_UNLIKELY(*data == '}'))
  5640. {
  5641. data++;
  5642. break;
  5643. }
  5644. if (CROW_UNLIKELY(!consume(',')))
  5645. {
  5646. ret.set_error();
  5647. break;
  5648. }
  5649. ws_skip();
  5650. }
  5651. return ret;
  5652. }
  5653. rvalue parse()
  5654. {
  5655. ws_skip();
  5656. auto ret = decode_value(0); // or decode object?
  5657. ws_skip();
  5658. if (ret && *data != '\0')
  5659. ret.set_error();
  5660. return ret;
  5661. }
  5662. char* data;
  5663. };
  5664. return Parser(data, size).parse();
  5665. }
  5666. inline rvalue load(const char* data, size_t size)
  5667. {
  5668. char* s = new char[size + 1];
  5669. memcpy(s, data, size);
  5670. s[size] = 0;
  5671. auto ret = load_nocopy_internal(s, size);
  5672. if (ret)
  5673. ret.key_.force(s, size);
  5674. else
  5675. delete[] s;
  5676. return ret;
  5677. }
  5678. inline rvalue load(const char* data)
  5679. {
  5680. return load(data, strlen(data));
  5681. }
  5682. inline rvalue load(const std::string& str)
  5683. {
  5684. return load(str.data(), str.size());
  5685. }
  5686. struct wvalue_reader;
  5687. /// JSON write value.
  5688. ///
  5689. /// Value can mean any json value, including a JSON object.<br>
  5690. /// Write means this class is used to primarily assemble JSON objects using keys and values and export those into a string.
  5691. class wvalue : public returnable
  5692. {
  5693. friend class crow::mustache::template_t;
  5694. friend struct wvalue_reader;
  5695. public:
  5696. using object =
  5697. #ifdef CROW_JSON_USE_MAP
  5698. std::map<std::string, wvalue>;
  5699. #else
  5700. std::unordered_map<std::string, wvalue>;
  5701. #endif
  5702. using list = std::vector<wvalue>;
  5703. type t() const { return t_; }
  5704. /// Create an empty json value (outputs "{}" instead of a "null" string)
  5705. static crow::json::wvalue empty_object() { return crow::json::wvalue::object(); }
  5706. private:
  5707. type t_{type::Null}; ///< The type of the value.
  5708. num_type nt{num_type::Null}; ///< The specific type of the number if \ref t_ is a number.
  5709. union number
  5710. {
  5711. double d;
  5712. int64_t si;
  5713. uint64_t ui;
  5714. public:
  5715. constexpr number() noexcept:
  5716. ui() {} /* default constructor initializes unsigned integer. */
  5717. constexpr number(std::uint64_t value) noexcept:
  5718. ui(value) {}
  5719. constexpr number(std::int64_t value) noexcept:
  5720. si(value) {}
  5721. explicit constexpr number(double value) noexcept:
  5722. d(value) {}
  5723. explicit constexpr number(float value) noexcept:
  5724. d(value) {}
  5725. } num; ///< Value if type is a number.
  5726. std::string s; ///< Value if type is a string.
  5727. std::unique_ptr<list> l; ///< Value if type is a list.
  5728. std::unique_ptr<object> o; ///< Value if type is a JSON object.
  5729. std::function<std::string(std::string&)> f; ///< Value if type is a function (C++ lambda)
  5730. public:
  5731. wvalue():
  5732. returnable("application/json") {}
  5733. wvalue(std::nullptr_t):
  5734. returnable("application/json"), t_(type::Null) {}
  5735. wvalue(bool value):
  5736. returnable("application/json"), t_(value ? type::True : type::False) {}
  5737. wvalue(std::uint8_t value):
  5738. returnable("application/json"), t_(type::Number), nt(num_type::Unsigned_integer), num(static_cast<std::uint64_t>(value)) {}
  5739. wvalue(std::uint16_t value):
  5740. returnable("application/json"), t_(type::Number), nt(num_type::Unsigned_integer), num(static_cast<std::uint64_t>(value)) {}
  5741. wvalue(std::uint32_t value):
  5742. returnable("application/json"), t_(type::Number), nt(num_type::Unsigned_integer), num(static_cast<std::uint64_t>(value)) {}
  5743. wvalue(std::uint64_t value):
  5744. returnable("application/json"), t_(type::Number), nt(num_type::Unsigned_integer), num(static_cast<std::uint64_t>(value)) {}
  5745. wvalue(std::int8_t value):
  5746. returnable("application/json"), t_(type::Number), nt(num_type::Signed_integer), num(static_cast<std::int64_t>(value)) {}
  5747. wvalue(std::int16_t value):
  5748. returnable("application/json"), t_(type::Number), nt(num_type::Signed_integer), num(static_cast<std::int64_t>(value)) {}
  5749. wvalue(std::int32_t value):
  5750. returnable("application/json"), t_(type::Number), nt(num_type::Signed_integer), num(static_cast<std::int64_t>(value)) {}
  5751. wvalue(std::int64_t value):
  5752. returnable("application/json"), t_(type::Number), nt(num_type::Signed_integer), num(static_cast<std::int64_t>(value)) {}
  5753. wvalue(float value):
  5754. returnable("application/json"), t_(type::Number), nt(num_type::Floating_point), num(static_cast<double>(value)) {}
  5755. wvalue(double value):
  5756. returnable("application/json"), t_(type::Number), nt(num_type::Double_precision_floating_point), num(static_cast<double>(value)) {}
  5757. wvalue(char const* value):
  5758. returnable("application/json"), t_(type::String), s(value) {}
  5759. wvalue(std::string const& value):
  5760. returnable("application/json"), t_(type::String), s(value) {}
  5761. wvalue(std::string&& value):
  5762. returnable("application/json"), t_(type::String), s(std::move(value)) {}
  5763. wvalue(std::initializer_list<std::pair<std::string const, wvalue>> initializer_list):
  5764. returnable("application/json"), t_(type::Object), o(new object(initializer_list)) {}
  5765. wvalue(object const& value):
  5766. returnable("application/json"), t_(type::Object), o(new object(value)) {}
  5767. wvalue(object&& value):
  5768. returnable("application/json"), t_(type::Object), o(new object(std::move(value))) {}
  5769. wvalue(const list& r):
  5770. returnable("application/json")
  5771. {
  5772. t_ = type::List;
  5773. l = std::unique_ptr<list>(new list{});
  5774. l->reserve(r.size());
  5775. for (auto it = r.begin(); it != r.end(); ++it)
  5776. l->emplace_back(*it);
  5777. }
  5778. wvalue(list& r):
  5779. returnable("application/json")
  5780. {
  5781. t_ = type::List;
  5782. l = std::unique_ptr<list>(new list{});
  5783. l->reserve(r.size());
  5784. for (auto it = r.begin(); it != r.end(); ++it)
  5785. l->emplace_back(*it);
  5786. }
  5787. /// Create a write value from a read value (useful for editing JSON strings).
  5788. wvalue(const rvalue& r):
  5789. returnable("application/json")
  5790. {
  5791. t_ = r.t();
  5792. switch (r.t())
  5793. {
  5794. case type::Null:
  5795. case type::False:
  5796. case type::True:
  5797. case type::Function:
  5798. return;
  5799. case type::Number:
  5800. nt = r.nt();
  5801. if (nt == num_type::Floating_point || nt == num_type::Double_precision_floating_point)
  5802. num.d = r.d();
  5803. else if (nt == num_type::Signed_integer)
  5804. num.si = r.i();
  5805. else
  5806. num.ui = r.u();
  5807. return;
  5808. case type::String:
  5809. s = r.s();
  5810. return;
  5811. case type::List:
  5812. l = std::unique_ptr<list>(new list{});
  5813. l->reserve(r.size());
  5814. for (auto it = r.begin(); it != r.end(); ++it)
  5815. l->emplace_back(*it);
  5816. return;
  5817. case type::Object:
  5818. o = std::unique_ptr<object>(new object{});
  5819. for (auto it = r.begin(); it != r.end(); ++it)
  5820. o->emplace(it->key(), *it);
  5821. return;
  5822. }
  5823. }
  5824. wvalue(const wvalue& r):
  5825. returnable("application/json")
  5826. {
  5827. t_ = r.t();
  5828. switch (r.t())
  5829. {
  5830. case type::Null:
  5831. case type::False:
  5832. case type::True:
  5833. return;
  5834. case type::Number:
  5835. nt = r.nt;
  5836. if (nt == num_type::Floating_point || nt == num_type::Double_precision_floating_point)
  5837. num.d = r.num.d;
  5838. else if (nt == num_type::Signed_integer)
  5839. num.si = r.num.si;
  5840. else
  5841. num.ui = r.num.ui;
  5842. return;
  5843. case type::String:
  5844. s = r.s;
  5845. return;
  5846. case type::List:
  5847. l = std::unique_ptr<list>(new list{});
  5848. l->reserve(r.size());
  5849. for (auto it = r.l->begin(); it != r.l->end(); ++it)
  5850. l->emplace_back(*it);
  5851. return;
  5852. case type::Object:
  5853. o = std::unique_ptr<object>(new object{});
  5854. o->insert(r.o->begin(), r.o->end());
  5855. return;
  5856. case type::Function:
  5857. f = r.f;
  5858. }
  5859. }
  5860. wvalue(wvalue&& r):
  5861. returnable("application/json")
  5862. {
  5863. *this = std::move(r);
  5864. }
  5865. wvalue& operator=(wvalue&& r)
  5866. {
  5867. t_ = r.t_;
  5868. nt = r.nt;
  5869. num = r.num;
  5870. s = std::move(r.s);
  5871. l = std::move(r.l);
  5872. o = std::move(r.o);
  5873. return *this;
  5874. }
  5875. /// Used for compatibility, same as \ref reset()
  5876. void clear()
  5877. {
  5878. reset();
  5879. }
  5880. void reset()
  5881. {
  5882. t_ = type::Null;
  5883. l.reset();
  5884. o.reset();
  5885. }
  5886. wvalue& operator=(std::nullptr_t)
  5887. {
  5888. reset();
  5889. return *this;
  5890. }
  5891. wvalue& operator=(bool value)
  5892. {
  5893. reset();
  5894. if (value)
  5895. t_ = type::True;
  5896. else
  5897. t_ = type::False;
  5898. return *this;
  5899. }
  5900. wvalue& operator=(float value)
  5901. {
  5902. reset();
  5903. t_ = type::Number;
  5904. num.d = value;
  5905. nt = num_type::Floating_point;
  5906. return *this;
  5907. }
  5908. wvalue& operator=(double value)
  5909. {
  5910. reset();
  5911. t_ = type::Number;
  5912. num.d = value;
  5913. nt = num_type::Double_precision_floating_point;
  5914. return *this;
  5915. }
  5916. wvalue& operator=(unsigned short value)
  5917. {
  5918. reset();
  5919. t_ = type::Number;
  5920. num.ui = value;
  5921. nt = num_type::Unsigned_integer;
  5922. return *this;
  5923. }
  5924. wvalue& operator=(short value)
  5925. {
  5926. reset();
  5927. t_ = type::Number;
  5928. num.si = value;
  5929. nt = num_type::Signed_integer;
  5930. return *this;
  5931. }
  5932. wvalue& operator=(long long value)
  5933. {
  5934. reset();
  5935. t_ = type::Number;
  5936. num.si = value;
  5937. nt = num_type::Signed_integer;
  5938. return *this;
  5939. }
  5940. wvalue& operator=(long value)
  5941. {
  5942. reset();
  5943. t_ = type::Number;
  5944. num.si = value;
  5945. nt = num_type::Signed_integer;
  5946. return *this;
  5947. }
  5948. wvalue& operator=(int value)
  5949. {
  5950. reset();
  5951. t_ = type::Number;
  5952. num.si = value;
  5953. nt = num_type::Signed_integer;
  5954. return *this;
  5955. }
  5956. wvalue& operator=(unsigned long long value)
  5957. {
  5958. reset();
  5959. t_ = type::Number;
  5960. num.ui = value;
  5961. nt = num_type::Unsigned_integer;
  5962. return *this;
  5963. }
  5964. wvalue& operator=(unsigned long value)
  5965. {
  5966. reset();
  5967. t_ = type::Number;
  5968. num.ui = value;
  5969. nt = num_type::Unsigned_integer;
  5970. return *this;
  5971. }
  5972. wvalue& operator=(unsigned int value)
  5973. {
  5974. reset();
  5975. t_ = type::Number;
  5976. num.ui = value;
  5977. nt = num_type::Unsigned_integer;
  5978. return *this;
  5979. }
  5980. wvalue& operator=(const char* str)
  5981. {
  5982. reset();
  5983. t_ = type::String;
  5984. s = str;
  5985. return *this;
  5986. }
  5987. wvalue& operator=(const std::string& str)
  5988. {
  5989. reset();
  5990. t_ = type::String;
  5991. s = str;
  5992. return *this;
  5993. }
  5994. wvalue& operator=(list&& v)
  5995. {
  5996. if (t_ != type::List)
  5997. reset();
  5998. t_ = type::List;
  5999. if (!l)
  6000. l = std::unique_ptr<list>(new list{});
  6001. l->clear();
  6002. l->resize(v.size());
  6003. size_t idx = 0;
  6004. for (auto& x : v)
  6005. {
  6006. (*l)[idx++] = std::move(x);
  6007. }
  6008. return *this;
  6009. }
  6010. template<typename T>
  6011. wvalue& operator=(const std::vector<T>& v)
  6012. {
  6013. if (t_ != type::List)
  6014. reset();
  6015. t_ = type::List;
  6016. if (!l)
  6017. l = std::unique_ptr<list>(new list{});
  6018. l->clear();
  6019. l->resize(v.size());
  6020. size_t idx = 0;
  6021. for (auto& x : v)
  6022. {
  6023. (*l)[idx++] = x;
  6024. }
  6025. return *this;
  6026. }
  6027. wvalue& operator=(std::initializer_list<std::pair<std::string const, wvalue>> initializer_list)
  6028. {
  6029. if (t_ != type::Object)
  6030. {
  6031. reset();
  6032. t_ = type::Object;
  6033. o = std::unique_ptr<object>(new object(initializer_list));
  6034. }
  6035. else
  6036. {
  6037. #if defined(__APPLE__) || defined(__MACH__) || defined(__FreeBSD__) || defined(__ANDROID__) || defined(_LIBCPP_VERSION)
  6038. o = std::unique_ptr<object>(new object(initializer_list));
  6039. #else
  6040. (*o) = initializer_list;
  6041. #endif
  6042. }
  6043. return *this;
  6044. }
  6045. wvalue& operator=(object const& value)
  6046. {
  6047. if (t_ != type::Object)
  6048. {
  6049. reset();
  6050. t_ = type::Object;
  6051. o = std::unique_ptr<object>(new object(value));
  6052. }
  6053. else
  6054. {
  6055. #if defined(__APPLE__) || defined(__MACH__) || defined(__FreeBSD__) || defined(__ANDROID__) || defined(_LIBCPP_VERSION)
  6056. o = std::unique_ptr<object>(new object(value));
  6057. #else
  6058. (*o) = value;
  6059. #endif
  6060. }
  6061. return *this;
  6062. }
  6063. wvalue& operator=(object&& value)
  6064. {
  6065. if (t_ != type::Object)
  6066. {
  6067. reset();
  6068. t_ = type::Object;
  6069. o = std::unique_ptr<object>(new object(std::move(value)));
  6070. }
  6071. else
  6072. {
  6073. (*o) = std::move(value);
  6074. }
  6075. return *this;
  6076. }
  6077. wvalue& operator=(std::function<std::string(std::string&)>&& func)
  6078. {
  6079. reset();
  6080. t_ = type::Function;
  6081. f = std::move(func);
  6082. return *this;
  6083. }
  6084. wvalue& operator[](unsigned index)
  6085. {
  6086. if (t_ != type::List)
  6087. reset();
  6088. t_ = type::List;
  6089. if (!l)
  6090. l = std::unique_ptr<list>(new list{});
  6091. if (l->size() < index + 1)
  6092. l->resize(index + 1);
  6093. return (*l)[index];
  6094. }
  6095. const wvalue& operator[](unsigned index) const
  6096. {
  6097. return const_cast<wvalue*>(this)->operator[](index);
  6098. }
  6099. int count(const std::string& str) const
  6100. {
  6101. if (t_ != type::Object)
  6102. return 0;
  6103. if (!o)
  6104. return 0;
  6105. return o->count(str);
  6106. }
  6107. wvalue& operator[](const std::string& str)
  6108. {
  6109. if (t_ != type::Object)
  6110. reset();
  6111. t_ = type::Object;
  6112. if (!o)
  6113. o = std::unique_ptr<object>(new object{});
  6114. return (*o)[str];
  6115. }
  6116. const wvalue& operator[](const std::string& str) const
  6117. {
  6118. return const_cast<wvalue*>(this)->operator[](str);
  6119. }
  6120. std::vector<std::string> keys() const
  6121. {
  6122. if (t_ != type::Object)
  6123. return {};
  6124. std::vector<std::string> result;
  6125. for (auto& kv : *o)
  6126. {
  6127. result.push_back(kv.first);
  6128. }
  6129. return result;
  6130. }
  6131. std::string execute(std::string txt = "") const //Not using reference because it cannot be used with a default rvalue
  6132. {
  6133. if (t_ != type::Function)
  6134. return "";
  6135. return f(txt);
  6136. }
  6137. /// If the wvalue is a list, it returns the length of the list, otherwise it returns 1.
  6138. std::size_t size() const
  6139. {
  6140. if (t_ != type::List)
  6141. return 1;
  6142. return l->size();
  6143. }
  6144. /// Returns an estimated size of the value in bytes.
  6145. size_t estimate_length() const
  6146. {
  6147. switch (t_)
  6148. {
  6149. case type::Null: return 4;
  6150. case type::False: return 5;
  6151. case type::True: return 4;
  6152. case type::Number: return 30;
  6153. case type::String: return 2 + s.size() + s.size() / 2;
  6154. case type::List:
  6155. {
  6156. size_t sum{};
  6157. if (l)
  6158. {
  6159. for (auto& x : *l)
  6160. {
  6161. sum += 1;
  6162. sum += x.estimate_length();
  6163. }
  6164. }
  6165. return sum + 2;
  6166. }
  6167. case type::Object:
  6168. {
  6169. size_t sum{};
  6170. if (o)
  6171. {
  6172. for (auto& kv : *o)
  6173. {
  6174. sum += 2;
  6175. sum += 2 + kv.first.size() + kv.first.size() / 2;
  6176. sum += kv.second.estimate_length();
  6177. }
  6178. }
  6179. return sum + 2;
  6180. }
  6181. case type::Function:
  6182. return 0;
  6183. }
  6184. return 1;
  6185. }
  6186. private:
  6187. inline void dump_string(const std::string& str, std::string& out) const
  6188. {
  6189. out.push_back('"');
  6190. escape(str, out);
  6191. out.push_back('"');
  6192. }
  6193. inline void dump_indentation_part(std::string& out, const int indent, const char separator, const int indent_level) const
  6194. {
  6195. out.push_back('\n');
  6196. out.append(indent_level * indent, separator);
  6197. }
  6198. inline void dump_internal(const wvalue& v, std::string& out, const int indent, const char separator, const int indent_level = 0) const
  6199. {
  6200. switch (v.t_)
  6201. {
  6202. case type::Null: out += "null"; break;
  6203. case type::False: out += "false"; break;
  6204. case type::True: out += "true"; break;
  6205. case type::Number:
  6206. {
  6207. if (v.nt == num_type::Floating_point || v.nt == num_type::Double_precision_floating_point)
  6208. {
  6209. if (isnan(v.num.d) || isinf(v.num.d))
  6210. {
  6211. out += "null";
  6212. CROW_LOG_WARNING << "Invalid JSON value detected (" << v.num.d << "), value set to null";
  6213. break;
  6214. }
  6215. enum
  6216. {
  6217. start,
  6218. decp, // Decimal point
  6219. zero
  6220. } f_state;
  6221. char outbuf[128];
  6222. if (v.nt == num_type::Double_precision_floating_point)
  6223. {
  6224. #ifdef _MSC_VER
  6225. sprintf_s(outbuf, sizeof(outbuf), "%.*g", DECIMAL_DIG, v.num.d);
  6226. #else
  6227. snprintf(outbuf, sizeof(outbuf), "%.*g", DECIMAL_DIG, v.num.d);
  6228. #endif
  6229. }
  6230. else
  6231. {
  6232. #ifdef _MSC_VER
  6233. sprintf_s(outbuf, sizeof(outbuf), "%f", v.num.d);
  6234. #else
  6235. snprintf(outbuf, sizeof(outbuf), "%f", v.num.d);
  6236. #endif
  6237. }
  6238. char *p = &outbuf[0], *o = nullptr; // o is the position of the first trailing 0
  6239. f_state = start;
  6240. while (*p != '\0')
  6241. {
  6242. //std::cout << *p << std::endl;
  6243. char ch = *p;
  6244. switch (f_state)
  6245. {
  6246. case start: // Loop and lookahead until a decimal point is found
  6247. if (ch == '.')
  6248. {
  6249. char fch = *(p + 1);
  6250. // if the first character is 0, leave it be (this is so that "1.00000" becomes "1.0" and not "1.")
  6251. if (fch != '\0' && fch == '0') p++;
  6252. f_state = decp;
  6253. }
  6254. p++;
  6255. break;
  6256. case decp: // Loop until a 0 is found, if found, record its position
  6257. if (ch == '0')
  6258. {
  6259. f_state = zero;
  6260. o = p;
  6261. }
  6262. p++;
  6263. break;
  6264. case zero: // if a non 0 is found (e.g. 1.00004) remove the earlier recorded 0 position and look for more trailing 0s
  6265. if (ch != '0')
  6266. {
  6267. o = nullptr;
  6268. f_state = decp;
  6269. }
  6270. p++;
  6271. break;
  6272. }
  6273. }
  6274. if (o != nullptr) // if any trailing 0s are found, terminate the string where they begin
  6275. *o = '\0';
  6276. out += outbuf;
  6277. }
  6278. else if (v.nt == num_type::Signed_integer)
  6279. {
  6280. out += std::to_string(v.num.si);
  6281. }
  6282. else
  6283. {
  6284. out += std::to_string(v.num.ui);
  6285. }
  6286. }
  6287. break;
  6288. case type::String: dump_string(v.s, out); break;
  6289. case type::List:
  6290. {
  6291. out.push_back('[');
  6292. if (indent >= 0)
  6293. {
  6294. dump_indentation_part(out, indent, separator, indent_level + 1);
  6295. }
  6296. if (v.l)
  6297. {
  6298. bool first = true;
  6299. for (auto& x : *v.l)
  6300. {
  6301. if (!first)
  6302. {
  6303. out.push_back(',');
  6304. if (indent >= 0)
  6305. {
  6306. dump_indentation_part(out, indent, separator, indent_level + 1);
  6307. }
  6308. }
  6309. first = false;
  6310. dump_internal(x, out, indent, separator, indent_level + 1);
  6311. }
  6312. }
  6313. if (indent >= 0)
  6314. {
  6315. dump_indentation_part(out, indent, separator, indent_level);
  6316. }
  6317. out.push_back(']');
  6318. }
  6319. break;
  6320. case type::Object:
  6321. {
  6322. out.push_back('{');
  6323. if (indent >= 0)
  6324. {
  6325. dump_indentation_part(out, indent, separator, indent_level + 1);
  6326. }
  6327. if (v.o)
  6328. {
  6329. bool first = true;
  6330. for (auto& kv : *v.o)
  6331. {
  6332. if (!first)
  6333. {
  6334. out.push_back(',');
  6335. if (indent >= 0)
  6336. {
  6337. dump_indentation_part(out, indent, separator, indent_level + 1);
  6338. }
  6339. }
  6340. first = false;
  6341. dump_string(kv.first, out);
  6342. out.push_back(':');
  6343. if (indent >= 0)
  6344. {
  6345. out.push_back(' ');
  6346. }
  6347. dump_internal(kv.second, out, indent, separator, indent_level + 1);
  6348. }
  6349. }
  6350. if (indent >= 0)
  6351. {
  6352. dump_indentation_part(out, indent, separator, indent_level);
  6353. }
  6354. out.push_back('}');
  6355. }
  6356. break;
  6357. case type::Function:
  6358. out += "custom function";
  6359. break;
  6360. }
  6361. }
  6362. public:
  6363. std::string dump(const int indent, const char separator = ' ') const
  6364. {
  6365. std::string ret;
  6366. ret.reserve(estimate_length());
  6367. dump_internal(*this, ret, indent, separator);
  6368. return ret;
  6369. }
  6370. std::string dump() const
  6371. {
  6372. static constexpr int DontIndent = -1;
  6373. return dump(DontIndent);
  6374. }
  6375. };
  6376. // Used for accessing the internals of a wvalue
  6377. struct wvalue_reader
  6378. {
  6379. int64_t get(int64_t fallback)
  6380. {
  6381. if (ref.t() != type::Number || ref.nt == num_type::Floating_point ||
  6382. ref.nt == num_type::Double_precision_floating_point)
  6383. return fallback;
  6384. return ref.num.si;
  6385. }
  6386. double get(double fallback)
  6387. {
  6388. if (ref.t() != type::Number || ref.nt != num_type::Floating_point ||
  6389. ref.nt == num_type::Double_precision_floating_point)
  6390. return fallback;
  6391. return ref.num.d;
  6392. }
  6393. bool get(bool fallback)
  6394. {
  6395. if (ref.t() == type::True) return true;
  6396. if (ref.t() == type::False) return false;
  6397. return fallback;
  6398. }
  6399. std::string get(const std::string& fallback)
  6400. {
  6401. if (ref.t() != type::String) return fallback;
  6402. return ref.s;
  6403. }
  6404. const wvalue& ref;
  6405. };
  6406. //std::vector<asio::const_buffer> dump_ref(wvalue& v)
  6407. //{
  6408. //}
  6409. } // namespace json
  6410. } // namespace crow
  6411. #include <string>
  6412. #include <unordered_map>
  6413. #include <ios>
  6414. #include <fstream>
  6415. #include <sstream>
  6416. // S_ISREG is not defined for windows
  6417. // This defines it like suggested in https://stackoverflow.com/a/62371749
  6418. #if defined(_MSC_VER)
  6419. #define _CRT_INTERNAL_NONSTDC_NAMES 1
  6420. #endif
  6421. #include <sys/stat.h>
  6422. #if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
  6423. #define S_ISREG(m) (((m)&S_IFMT) == S_IFREG)
  6424. #endif
  6425. namespace crow
  6426. {
  6427. template<typename Adaptor, typename Handler, typename... Middlewares>
  6428. class Connection;
  6429. class Router;
  6430. /// HTTP response
  6431. struct response
  6432. {
  6433. template<typename Adaptor, typename Handler, typename... Middlewares>
  6434. friend class crow::Connection;
  6435. friend class Router;
  6436. int code{200}; ///< The Status code for the response.
  6437. std::string body; ///< The actual payload containing the response data.
  6438. ci_map headers; ///< HTTP headers.
  6439. #ifdef CROW_ENABLE_COMPRESSION
  6440. bool compressed = true; ///< If compression is enabled and this is false, the individual response will not be compressed.
  6441. #endif
  6442. bool skip_body = false; ///< Whether this is a response to a HEAD request.
  6443. bool manual_length_header = false; ///< Whether Crow should automatically add a "Content-Length" header.
  6444. /// Set the value of an existing header in the response.
  6445. void set_header(std::string key, std::string value)
  6446. {
  6447. headers.erase(key);
  6448. headers.emplace(std::move(key), std::move(value));
  6449. }
  6450. /// Add a new header to the response.
  6451. void add_header(std::string key, std::string value)
  6452. {
  6453. headers.emplace(std::move(key), std::move(value));
  6454. }
  6455. const std::string& get_header_value(const std::string& key)
  6456. {
  6457. return crow::get_header_value(headers, key);
  6458. }
  6459. // naive validation of a mime-type string
  6460. static bool validate_mime_type(const std::string& candidate) noexcept
  6461. {
  6462. // Here we simply check that the candidate type starts with
  6463. // a valid parent type, and has at least one character afterwards.
  6464. std::array<std::string, 10> valid_parent_types = {
  6465. "application/", "audio/", "font/", "example/",
  6466. "image/", "message/", "model/", "multipart/",
  6467. "text/", "video/"};
  6468. for (const std::string& parent : valid_parent_types)
  6469. {
  6470. // ensure the candidate is *longer* than the parent,
  6471. // to avoid unnecessary string comparison and to
  6472. // reject zero-length subtypes.
  6473. if (candidate.size() <= parent.size())
  6474. {
  6475. continue;
  6476. }
  6477. // strncmp is used rather than substr to avoid allocation,
  6478. // but a string_view approach would be better if Crow
  6479. // migrates to C++17.
  6480. if (strncmp(parent.c_str(), candidate.c_str(), parent.size()) == 0)
  6481. {
  6482. return true;
  6483. }
  6484. }
  6485. return false;
  6486. }
  6487. // Find the mime type from the content type either by lookup,
  6488. // or by the content type itself, if it is a valid a mime type.
  6489. // Defaults to text/plain.
  6490. static std::string get_mime_type(const std::string& contentType)
  6491. {
  6492. const auto mimeTypeIterator = mime_types.find(contentType);
  6493. if (mimeTypeIterator != mime_types.end())
  6494. {
  6495. return mimeTypeIterator->second;
  6496. }
  6497. else if (validate_mime_type(contentType))
  6498. {
  6499. return contentType;
  6500. }
  6501. else
  6502. {
  6503. CROW_LOG_WARNING << "Unable to interpret mime type for content type '" << contentType << "'. Defaulting to text/plain.";
  6504. return "text/plain";
  6505. }
  6506. }
  6507. // clang-format off
  6508. response() {}
  6509. explicit response(int code) : code(code) {}
  6510. response(std::string body) : body(std::move(body)) {}
  6511. response(int code, std::string body) : code(code), body(std::move(body)) {}
  6512. // clang-format on
  6513. response(returnable&& value)
  6514. {
  6515. body = value.dump();
  6516. set_header("Content-Type", value.content_type);
  6517. }
  6518. response(returnable& value)
  6519. {
  6520. body = value.dump();
  6521. set_header("Content-Type", value.content_type);
  6522. }
  6523. response(int code, returnable& value):
  6524. code(code)
  6525. {
  6526. body = value.dump();
  6527. set_header("Content-Type", value.content_type);
  6528. }
  6529. response(int code, returnable&& value):
  6530. code(code), body(value.dump())
  6531. {
  6532. set_header("Content-Type", std::move(value.content_type));
  6533. }
  6534. response(response&& r)
  6535. {
  6536. *this = std::move(r);
  6537. }
  6538. response(std::string contentType, std::string body):
  6539. body(std::move(body))
  6540. {
  6541. set_header("Content-Type", get_mime_type(contentType));
  6542. }
  6543. response(int code, std::string contentType, std::string body):
  6544. code(code), body(std::move(body))
  6545. {
  6546. set_header("Content-Type", get_mime_type(contentType));
  6547. }
  6548. response& operator=(const response& r) = delete;
  6549. response& operator=(response&& r) noexcept
  6550. {
  6551. body = std::move(r.body);
  6552. code = r.code;
  6553. headers = std::move(r.headers);
  6554. completed_ = r.completed_;
  6555. file_info = std::move(r.file_info);
  6556. return *this;
  6557. }
  6558. /// Check if the response has completed (whether response.end() has been called)
  6559. bool is_completed() const noexcept
  6560. {
  6561. return completed_;
  6562. }
  6563. void clear()
  6564. {
  6565. body.clear();
  6566. code = 200;
  6567. headers.clear();
  6568. completed_ = false;
  6569. file_info = static_file_info{};
  6570. }
  6571. /// Return a "Temporary Redirect" response.
  6572. ///
  6573. /// Location can either be a route or a full URL.
  6574. void redirect(const std::string& location)
  6575. {
  6576. code = 307;
  6577. set_header("Location", location);
  6578. }
  6579. /// Return a "Permanent Redirect" response.
  6580. ///
  6581. /// Location can either be a route or a full URL.
  6582. void redirect_perm(const std::string& location)
  6583. {
  6584. code = 308;
  6585. set_header("Location", location);
  6586. }
  6587. /// Return a "Found (Moved Temporarily)" response.
  6588. ///
  6589. /// Location can either be a route or a full URL.
  6590. void moved(const std::string& location)
  6591. {
  6592. code = 302;
  6593. set_header("Location", location);
  6594. }
  6595. /// Return a "Moved Permanently" response.
  6596. ///
  6597. /// Location can either be a route or a full URL.
  6598. void moved_perm(const std::string& location)
  6599. {
  6600. code = 301;
  6601. set_header("Location", location);
  6602. }
  6603. void write(const std::string& body_part)
  6604. {
  6605. body += body_part;
  6606. }
  6607. /// Set the response completion flag and call the handler (to send the response).
  6608. void end()
  6609. {
  6610. if (!completed_)
  6611. {
  6612. completed_ = true;
  6613. if (skip_body)
  6614. {
  6615. set_header("Content-Length", std::to_string(body.size()));
  6616. body = "";
  6617. manual_length_header = true;
  6618. }
  6619. if (complete_request_handler_)
  6620. {
  6621. complete_request_handler_();
  6622. manual_length_header = false;
  6623. skip_body = false;
  6624. }
  6625. }
  6626. }
  6627. /// Same as end() except it adds a body part right before ending.
  6628. void end(const std::string& body_part)
  6629. {
  6630. body += body_part;
  6631. end();
  6632. }
  6633. /// Check if the connection is still alive (usually by checking the socket status).
  6634. bool is_alive()
  6635. {
  6636. return is_alive_helper_ && is_alive_helper_();
  6637. }
  6638. /// Check whether the response has a static file defined.
  6639. bool is_static_type()
  6640. {
  6641. return file_info.path.size();
  6642. }
  6643. /// This constains metadata (coming from the `stat` command) related to any static files associated with this response.
  6644. ///
  6645. /// Either a static file or a string body can be returned as 1 response.
  6646. struct static_file_info
  6647. {
  6648. std::string path = "";
  6649. struct stat statbuf;
  6650. int statResult;
  6651. };
  6652. /// Return a static file as the response body
  6653. void set_static_file_info(std::string path)
  6654. {
  6655. utility::sanitize_filename(path);
  6656. set_static_file_info_unsafe(path);
  6657. }
  6658. /// Return a static file as the response body without sanitizing the path (use set_static_file_info instead)
  6659. void set_static_file_info_unsafe(std::string path)
  6660. {
  6661. file_info.path = path;
  6662. file_info.statResult = stat(file_info.path.c_str(), &file_info.statbuf);
  6663. #ifdef CROW_ENABLE_COMPRESSION
  6664. compressed = false;
  6665. #endif
  6666. if (file_info.statResult == 0 && S_ISREG(file_info.statbuf.st_mode))
  6667. {
  6668. std::size_t last_dot = path.find_last_of(".");
  6669. std::string extension = path.substr(last_dot + 1);
  6670. code = 200;
  6671. this->add_header("Content-Length", std::to_string(file_info.statbuf.st_size));
  6672. if (!extension.empty())
  6673. {
  6674. this->add_header("Content-Type", get_mime_type(extension));
  6675. }
  6676. }
  6677. else
  6678. {
  6679. code = 404;
  6680. file_info.path.clear();
  6681. }
  6682. }
  6683. private:
  6684. bool completed_{};
  6685. std::function<void()> complete_request_handler_;
  6686. std::function<bool()> is_alive_helper_;
  6687. static_file_info file_info;
  6688. };
  6689. } // namespace crow
  6690. namespace crow
  6691. {
  6692. struct UTF8
  6693. {
  6694. struct context
  6695. {};
  6696. void before_handle(request& /*req*/, response& /*res*/, context& /*ctx*/)
  6697. {}
  6698. void after_handle(request& /*req*/, response& res, context& /*ctx*/)
  6699. {
  6700. if (get_header_value(res.headers, "Content-Type").empty())
  6701. {
  6702. res.set_header("Content-Type", "text/plain; charset=utf-8");
  6703. }
  6704. }
  6705. };
  6706. } // namespace crow
  6707. #include <iomanip>
  6708. #include <memory>
  6709. namespace crow
  6710. {
  6711. // Any middleware requires following 3 members:
  6712. // struct context;
  6713. // storing data for the middleware; can be read from another middleware or handlers
  6714. // before_handle
  6715. // called before handling the request.
  6716. // if res.end() is called, the operation is halted.
  6717. // (still call after_handle of this middleware)
  6718. // 2 signatures:
  6719. // void before_handle(request& req, response& res, context& ctx)
  6720. // if you only need to access this middlewares context.
  6721. // template <typename AllContext>
  6722. // void before_handle(request& req, response& res, context& ctx, AllContext& all_ctx)
  6723. // you can access another middlewares' context by calling `all_ctx.template get<MW>()'
  6724. // ctx == all_ctx.template get<CurrentMiddleware>()
  6725. // after_handle
  6726. // called after handling the request.
  6727. // void after_handle(request& req, response& res, context& ctx)
  6728. // template <typename AllContext>
  6729. // void after_handle(request& req, response& res, context& ctx, AllContext& all_ctx)
  6730. struct CookieParser
  6731. {
  6732. // Cookie stores key, value and attributes
  6733. struct Cookie
  6734. {
  6735. enum class SameSitePolicy
  6736. {
  6737. Strict,
  6738. Lax,
  6739. None
  6740. };
  6741. template<typename U>
  6742. Cookie(const std::string& key, U&& value):
  6743. Cookie()
  6744. {
  6745. key_ = key;
  6746. value_ = std::forward<U>(value);
  6747. }
  6748. Cookie(const std::string& key):
  6749. Cookie(key, "") {}
  6750. // format cookie to HTTP header format
  6751. std::string dump() const
  6752. {
  6753. const static char* HTTP_DATE_FORMAT = "%a, %d %b %Y %H:%M:%S GMT";
  6754. std::stringstream ss;
  6755. ss << key_ << '=';
  6756. ss << (value_.empty() ? "\"\"" : value_);
  6757. dumpString(ss, !domain_.empty(), "Domain=", domain_);
  6758. dumpString(ss, !path_.empty(), "Path=", path_);
  6759. dumpString(ss, secure_, "Secure");
  6760. dumpString(ss, httponly_, "HttpOnly");
  6761. if (expires_at_)
  6762. {
  6763. ss << DIVIDER << "Expires="
  6764. << std::put_time(expires_at_.get(), HTTP_DATE_FORMAT);
  6765. }
  6766. if (max_age_)
  6767. {
  6768. ss << DIVIDER << "Max-Age=" << *max_age_;
  6769. }
  6770. if (same_site_)
  6771. {
  6772. ss << DIVIDER << "SameSite=";
  6773. switch (*same_site_)
  6774. {
  6775. case SameSitePolicy::Strict:
  6776. ss << "Strict";
  6777. break;
  6778. case SameSitePolicy::Lax:
  6779. ss << "Lax";
  6780. break;
  6781. case SameSitePolicy::None:
  6782. ss << "None";
  6783. break;
  6784. }
  6785. }
  6786. return ss.str();
  6787. }
  6788. const std::string& name()
  6789. {
  6790. return key_;
  6791. }
  6792. template<typename U>
  6793. Cookie& value(U&& value)
  6794. {
  6795. value_ = std::forward<U>(value);
  6796. return *this;
  6797. }
  6798. // Expires attribute
  6799. Cookie& expires(const std::tm& time)
  6800. {
  6801. expires_at_ = std::unique_ptr<std::tm>(new std::tm(time));
  6802. return *this;
  6803. }
  6804. // Max-Age attribute
  6805. Cookie& max_age(long long seconds)
  6806. {
  6807. max_age_ = std::unique_ptr<long long>(new long long(seconds));
  6808. return *this;
  6809. }
  6810. // Domain attribute
  6811. Cookie& domain(const std::string& name)
  6812. {
  6813. domain_ = name;
  6814. return *this;
  6815. }
  6816. // Path attribute
  6817. Cookie& path(const std::string& path)
  6818. {
  6819. path_ = path;
  6820. return *this;
  6821. }
  6822. // Secured attribute
  6823. Cookie& secure()
  6824. {
  6825. secure_ = true;
  6826. return *this;
  6827. }
  6828. // HttpOnly attribute
  6829. Cookie& httponly()
  6830. {
  6831. httponly_ = true;
  6832. return *this;
  6833. }
  6834. // SameSite attribute
  6835. Cookie& same_site(SameSitePolicy ssp)
  6836. {
  6837. same_site_ = std::unique_ptr<SameSitePolicy>(new SameSitePolicy(ssp));
  6838. return *this;
  6839. }
  6840. Cookie(const Cookie& c):
  6841. key_(c.key_),
  6842. value_(c.value_),
  6843. domain_(c.domain_),
  6844. path_(c.path_),
  6845. secure_(c.secure_),
  6846. httponly_(c.httponly_)
  6847. {
  6848. if (c.max_age_)
  6849. max_age_ = std::unique_ptr<long long>(new long long(*c.max_age_));
  6850. if (c.expires_at_)
  6851. expires_at_ = std::unique_ptr<std::tm>(new std::tm(*c.expires_at_));
  6852. if (c.same_site_)
  6853. same_site_ = std::unique_ptr<SameSitePolicy>(new SameSitePolicy(*c.same_site_));
  6854. }
  6855. private:
  6856. Cookie() = default;
  6857. static void dumpString(std::stringstream& ss, bool cond, const char* prefix,
  6858. const std::string& value = "")
  6859. {
  6860. if (cond)
  6861. {
  6862. ss << DIVIDER << prefix << value;
  6863. }
  6864. }
  6865. private:
  6866. std::string key_;
  6867. std::string value_;
  6868. std::unique_ptr<long long> max_age_{};
  6869. std::string domain_ = "";
  6870. std::string path_ = "";
  6871. bool secure_ = false;
  6872. bool httponly_ = false;
  6873. std::unique_ptr<std::tm> expires_at_{};
  6874. std::unique_ptr<SameSitePolicy> same_site_{};
  6875. static constexpr const char* DIVIDER = "; ";
  6876. };
  6877. struct context
  6878. {
  6879. std::unordered_map<std::string, std::string> jar;
  6880. std::string get_cookie(const std::string& key) const
  6881. {
  6882. auto cookie = jar.find(key);
  6883. if (cookie != jar.end())
  6884. return cookie->second;
  6885. return {};
  6886. }
  6887. template<typename U>
  6888. Cookie& set_cookie(const std::string& key, U&& value)
  6889. {
  6890. cookies_to_add.emplace_back(key, std::forward<U>(value));
  6891. return cookies_to_add.back();
  6892. }
  6893. Cookie& set_cookie(Cookie cookie)
  6894. {
  6895. cookies_to_add.push_back(std::move(cookie));
  6896. return cookies_to_add.back();
  6897. }
  6898. private:
  6899. friend struct CookieParser;
  6900. std::vector<Cookie> cookies_to_add;
  6901. };
  6902. void before_handle(request& req, response& res, context& ctx)
  6903. {
  6904. // TODO(dranikpg): remove copies, use string_view with c++17
  6905. int count = req.headers.count("Cookie");
  6906. if (!count)
  6907. return;
  6908. if (count > 1)
  6909. {
  6910. res.code = 400;
  6911. res.end();
  6912. return;
  6913. }
  6914. std::string cookies = req.get_header_value("Cookie");
  6915. size_t pos = 0;
  6916. while (pos < cookies.size())
  6917. {
  6918. size_t pos_equal = cookies.find('=', pos);
  6919. if (pos_equal == cookies.npos)
  6920. break;
  6921. std::string name = cookies.substr(pos, pos_equal - pos);
  6922. name = utility::trim(name);
  6923. pos = pos_equal + 1;
  6924. if (pos == cookies.size())
  6925. break;
  6926. size_t pos_semicolon = cookies.find(';', pos);
  6927. std::string value = cookies.substr(pos, pos_semicolon - pos);
  6928. value = utility::trim(value);
  6929. if (value[0] == '"' && value[value.size() - 1] == '"')
  6930. {
  6931. value = value.substr(1, value.size() - 2);
  6932. }
  6933. ctx.jar.emplace(std::move(name), std::move(value));
  6934. pos = pos_semicolon;
  6935. if (pos == cookies.npos)
  6936. break;
  6937. pos++;
  6938. }
  6939. }
  6940. void after_handle(request& /*req*/, response& res, context& ctx)
  6941. {
  6942. for (const auto& cookie : ctx.cookies_to_add)
  6943. {
  6944. res.add_header("Set-Cookie", cookie.dump());
  6945. }
  6946. }
  6947. };
  6948. /*
  6949. App<CookieParser, AnotherJarMW> app;
  6950. A B C
  6951. A::context
  6952. int aa;
  6953. ctx1 : public A::context
  6954. ctx2 : public ctx1, public B::context
  6955. ctx3 : public ctx2, public C::context
  6956. C depends on A
  6957. C::handle
  6958. context.aaa
  6959. App::context : private CookieParser::context, ...
  6960. {
  6961. jar
  6962. }
  6963. SimpleApp
  6964. */
  6965. } // namespace crow
  6966. #include <unordered_map>
  6967. #include <unordered_set>
  6968. #include <set>
  6969. #include <queue>
  6970. #include <memory>
  6971. #include <string>
  6972. #include <cstdio>
  6973. #include <mutex>
  6974. #include <fstream>
  6975. #include <sstream>
  6976. #include <type_traits>
  6977. #include <functional>
  6978. #include <chrono>
  6979. #ifdef CROW_CAN_USE_CPP17
  6980. #include <variant>
  6981. #endif
  6982. namespace
  6983. {
  6984. // convert all integer values to int64_t
  6985. template<typename T>
  6986. using wrap_integral_t = typename std::conditional<
  6987. std::is_integral<T>::value && !std::is_same<bool, T>::value
  6988. // except for uint64_t because that could lead to overflow on conversion
  6989. && !std::is_same<uint64_t, T>::value,
  6990. int64_t, T>::type;
  6991. // convert char[]/char* to std::string
  6992. template<typename T>
  6993. using wrap_char_t = typename std::conditional<
  6994. std::is_same<typename std::decay<T>::type, char*>::value,
  6995. std::string, T>::type;
  6996. // Upgrade to correct type for multi_variant use
  6997. template<typename T>
  6998. using wrap_mv_t = wrap_char_t<wrap_integral_t<T>>;
  6999. } // namespace
  7000. namespace crow
  7001. {
  7002. namespace session
  7003. {
  7004. #ifdef CROW_CAN_USE_CPP17
  7005. using multi_value_types = black_magic::S<bool, int64_t, double, std::string>;
  7006. /// A multi_value is a safe variant wrapper with json conversion support
  7007. struct multi_value
  7008. {
  7009. json::wvalue json() const
  7010. {
  7011. // clang-format off
  7012. return std::visit([](auto arg) {
  7013. return json::wvalue(arg);
  7014. }, v_);
  7015. // clang-format on
  7016. }
  7017. static multi_value from_json(const json::rvalue&);
  7018. std::string string() const
  7019. {
  7020. // clang-format off
  7021. return std::visit([](auto arg) {
  7022. if constexpr (std::is_same_v<decltype(arg), std::string>)
  7023. return arg;
  7024. else
  7025. return std::to_string(arg);
  7026. }, v_);
  7027. // clang-format on
  7028. }
  7029. template<typename T, typename RT = wrap_mv_t<T>>
  7030. RT get(const T& fallback)
  7031. {
  7032. if (const RT* val = std::get_if<RT>(&v_)) return *val;
  7033. return fallback;
  7034. }
  7035. template<typename T, typename RT = wrap_mv_t<T>>
  7036. void set(T val)
  7037. {
  7038. v_ = RT(std::move(val));
  7039. }
  7040. typename multi_value_types::rebind<std::variant> v_;
  7041. };
  7042. inline multi_value multi_value::from_json(const json::rvalue& rv)
  7043. {
  7044. using namespace json;
  7045. switch (rv.t())
  7046. {
  7047. case type::Number:
  7048. {
  7049. if (rv.nt() == num_type::Floating_point || rv.nt() == num_type::Double_precision_floating_point)
  7050. return multi_value{rv.d()};
  7051. else if (rv.nt() == num_type::Unsigned_integer)
  7052. return multi_value{int64_t(rv.u())};
  7053. else
  7054. return multi_value{rv.i()};
  7055. }
  7056. case type::False: return multi_value{false};
  7057. case type::True: return multi_value{true};
  7058. case type::String: return multi_value{std::string(rv)};
  7059. default: return multi_value{false};
  7060. }
  7061. }
  7062. #else
  7063. // Fallback for C++11/14 that uses a raw json::wvalue internally.
  7064. // This implementation consumes significantly more memory
  7065. // than the variant-based version
  7066. struct multi_value
  7067. {
  7068. json::wvalue json() const { return v_; }
  7069. static multi_value from_json(const json::rvalue&);
  7070. std::string string() const { return v_.dump(); }
  7071. template<typename T, typename RT = wrap_mv_t<T>>
  7072. RT get(const T& fallback)
  7073. {
  7074. return json::wvalue_reader{v_}.get((const RT&)(fallback));
  7075. }
  7076. template<typename T, typename RT = wrap_mv_t<T>>
  7077. void set(T val)
  7078. {
  7079. v_ = RT(std::move(val));
  7080. }
  7081. json::wvalue v_;
  7082. };
  7083. inline multi_value multi_value::from_json(const json::rvalue& rv)
  7084. {
  7085. return {rv};
  7086. }
  7087. #endif
  7088. /// Expiration tracker keeps track of soonest-to-expire keys
  7089. struct ExpirationTracker
  7090. {
  7091. using DataPair = std::pair<uint64_t /*time*/, std::string /*key*/>;
  7092. /// Add key with time to tracker.
  7093. /// If the key is already present, it will be updated
  7094. void add(std::string key, uint64_t time)
  7095. {
  7096. auto it = times_.find(key);
  7097. if (it != times_.end()) remove(key);
  7098. times_[key] = time;
  7099. queue_.insert({time, std::move(key)});
  7100. }
  7101. void remove(const std::string& key)
  7102. {
  7103. auto it = times_.find(key);
  7104. if (it != times_.end())
  7105. {
  7106. queue_.erase({it->second, key});
  7107. times_.erase(it);
  7108. }
  7109. }
  7110. /// Get expiration time of soonest-to-expire entry
  7111. uint64_t peek_first() const
  7112. {
  7113. if (queue_.empty()) return std::numeric_limits<uint64_t>::max();
  7114. return queue_.begin()->first;
  7115. }
  7116. std::string pop_first()
  7117. {
  7118. auto it = times_.find(queue_.begin()->second);
  7119. auto key = it->first;
  7120. times_.erase(it);
  7121. queue_.erase(queue_.begin());
  7122. return key;
  7123. }
  7124. using iterator = typename std::set<DataPair>::const_iterator;
  7125. iterator begin() const { return queue_.cbegin(); }
  7126. iterator end() const { return queue_.cend(); }
  7127. private:
  7128. std::set<DataPair> queue_;
  7129. std::unordered_map<std::string, uint64_t> times_;
  7130. };
  7131. /// CachedSessions are shared across requests
  7132. struct CachedSession
  7133. {
  7134. std::string session_id;
  7135. std::string requested_session_id; // session hasn't been created yet, but a key was requested
  7136. std::unordered_map<std::string, multi_value> entries;
  7137. std::unordered_set<std::string> dirty; // values that were changed after last load
  7138. void* store_data;
  7139. bool requested_refresh;
  7140. // number of references held - used for correctly destroying the cache.
  7141. // No need to be atomic, all SessionMiddleware accesses are synchronized
  7142. int referrers;
  7143. std::recursive_mutex mutex;
  7144. };
  7145. } // namespace session
  7146. // SessionMiddleware allows storing securely and easily small snippets of user information
  7147. template<typename Store>
  7148. struct SessionMiddleware
  7149. {
  7150. #ifdef CROW_CAN_USE_CPP17
  7151. using lock = std::scoped_lock<std::mutex>;
  7152. using rc_lock = std::scoped_lock<std::recursive_mutex>;
  7153. #else
  7154. using lock = std::lock_guard<std::mutex>;
  7155. using rc_lock = std::lock_guard<std::recursive_mutex>;
  7156. #endif
  7157. struct context
  7158. {
  7159. // Get a mutex for locking this session
  7160. std::recursive_mutex& mutex()
  7161. {
  7162. check_node();
  7163. return node->mutex;
  7164. }
  7165. // Check whether this session is already present
  7166. bool exists() { return bool(node); }
  7167. // Get a value by key or fallback if it doesn't exist or is of another type
  7168. template<typename F>
  7169. auto get(const std::string& key, const F& fallback = F())
  7170. // This trick lets the multi_value deduce the return type from the fallback
  7171. // which allows both:
  7172. // context.get<std::string>("key")
  7173. // context.get("key", "") -> char[] is transformed into string by multivalue
  7174. // to return a string
  7175. -> decltype(std::declval<session::multi_value>().get<F>(std::declval<F>()))
  7176. {
  7177. if (!node) return fallback;
  7178. rc_lock l(node->mutex);
  7179. auto it = node->entries.find(key);
  7180. if (it != node->entries.end()) return it->second.get<F>(fallback);
  7181. return fallback;
  7182. }
  7183. // Set a value by key
  7184. template<typename T>
  7185. void set(const std::string& key, T value)
  7186. {
  7187. check_node();
  7188. rc_lock l(node->mutex);
  7189. node->dirty.insert(key);
  7190. node->entries[key].set(std::move(value));
  7191. }
  7192. bool contains(const std::string& key)
  7193. {
  7194. if (!node) return false;
  7195. return node->entries.find(key) != node->entries.end();
  7196. }
  7197. // Atomically mutate a value with a function
  7198. template<typename Func>
  7199. void apply(const std::string& key, const Func& f)
  7200. {
  7201. using traits = utility::function_traits<Func>;
  7202. using arg = typename std::decay<typename traits::template arg<0>>::type;
  7203. using retv = typename std::decay<typename traits::result_type>::type;
  7204. check_node();
  7205. rc_lock l(node->mutex);
  7206. node->dirty.insert(key);
  7207. node->entries[key].set<retv>(f(node->entries[key].get(arg{})));
  7208. }
  7209. // Remove a value from the session
  7210. void remove(const std::string& key)
  7211. {
  7212. if (!node) return;
  7213. rc_lock l(node->mutex);
  7214. node->dirty.insert(key);
  7215. node->entries.erase(key);
  7216. }
  7217. // Format value by key as a string
  7218. std::string string(const std::string& key)
  7219. {
  7220. if (!node) return "";
  7221. rc_lock l(node->mutex);
  7222. auto it = node->entries.find(key);
  7223. if (it != node->entries.end()) return it->second.string();
  7224. return "";
  7225. }
  7226. // Get a list of keys present in session
  7227. std::vector<std::string> keys()
  7228. {
  7229. if (!node) return {};
  7230. rc_lock l(node->mutex);
  7231. std::vector<std::string> out;
  7232. for (const auto& p : node->entries)
  7233. out.push_back(p.first);
  7234. return out;
  7235. }
  7236. // Delay expiration by issuing another cookie with an updated expiration time
  7237. // and notifying the store
  7238. void refresh_expiration()
  7239. {
  7240. if (!node) return;
  7241. node->requested_refresh = true;
  7242. }
  7243. private:
  7244. friend struct SessionMiddleware;
  7245. void check_node()
  7246. {
  7247. if (!node) node = std::make_shared<session::CachedSession>();
  7248. }
  7249. std::shared_ptr<session::CachedSession> node;
  7250. };
  7251. template<typename... Ts>
  7252. SessionMiddleware(
  7253. CookieParser::Cookie cookie,
  7254. int id_length,
  7255. Ts... ts):
  7256. id_length_(id_length),
  7257. cookie_(cookie),
  7258. store_(std::forward<Ts>(ts)...), mutex_(new std::mutex{})
  7259. {}
  7260. template<typename... Ts>
  7261. SessionMiddleware(Ts... ts):
  7262. SessionMiddleware(
  7263. CookieParser::Cookie("session").path("/").max_age(/*month*/ 30 * 24 * 60 * 60),
  7264. /*id_length */ 20, // around 10^34 possible combinations, but small enough to fit into SSO
  7265. std::forward<Ts>(ts)...)
  7266. {}
  7267. template<typename AllContext>
  7268. void before_handle(request& /*req*/, response& /*res*/, context& ctx, AllContext& all_ctx)
  7269. {
  7270. lock l(*mutex_);
  7271. auto& cookies = all_ctx.template get<CookieParser>();
  7272. auto session_id = load_id(cookies);
  7273. if (session_id == "") return;
  7274. // search entry in cache
  7275. auto it = cache_.find(session_id);
  7276. if (it != cache_.end())
  7277. {
  7278. it->second->referrers++;
  7279. ctx.node = it->second;
  7280. return;
  7281. }
  7282. // check this is a valid entry before loading
  7283. if (!store_.contains(session_id)) return;
  7284. auto node = std::make_shared<session::CachedSession>();
  7285. node->session_id = session_id;
  7286. node->referrers = 1;
  7287. try
  7288. {
  7289. store_.load(*node);
  7290. }
  7291. catch (...)
  7292. {
  7293. CROW_LOG_ERROR << "Exception occurred during session load";
  7294. return;
  7295. }
  7296. ctx.node = node;
  7297. cache_[session_id] = node;
  7298. }
  7299. template<typename AllContext>
  7300. void after_handle(request& /*req*/, response& /*res*/, context& ctx, AllContext& all_ctx)
  7301. {
  7302. lock l(*mutex_);
  7303. if (!ctx.node || --ctx.node->referrers > 0) return;
  7304. ctx.node->requested_refresh |= ctx.node->session_id == "";
  7305. // generate new id
  7306. if (ctx.node->session_id == "")
  7307. {
  7308. // check for requested id
  7309. ctx.node->session_id = std::move(ctx.node->requested_session_id);
  7310. if (ctx.node->session_id == "")
  7311. {
  7312. ctx.node->session_id = utility::random_alphanum(id_length_);
  7313. }
  7314. }
  7315. else
  7316. {
  7317. cache_.erase(ctx.node->session_id);
  7318. }
  7319. if (ctx.node->requested_refresh)
  7320. {
  7321. auto& cookies = all_ctx.template get<CookieParser>();
  7322. store_id(cookies, ctx.node->session_id);
  7323. }
  7324. try
  7325. {
  7326. store_.save(*ctx.node);
  7327. }
  7328. catch (...)
  7329. {
  7330. CROW_LOG_ERROR << "Exception occurred during session save";
  7331. return;
  7332. }
  7333. }
  7334. private:
  7335. std::string next_id()
  7336. {
  7337. std::string id;
  7338. do
  7339. {
  7340. id = utility::random_alphanum(id_length_);
  7341. } while (store_.contains(id));
  7342. return id;
  7343. }
  7344. std::string load_id(const CookieParser::context& cookies)
  7345. {
  7346. return cookies.get_cookie(cookie_.name());
  7347. }
  7348. void store_id(CookieParser::context& cookies, const std::string& session_id)
  7349. {
  7350. cookie_.value(session_id);
  7351. cookies.set_cookie(cookie_);
  7352. }
  7353. private:
  7354. int id_length_;
  7355. // prototype for cookie
  7356. CookieParser::Cookie cookie_;
  7357. Store store_;
  7358. // mutexes are immovable
  7359. std::unique_ptr<std::mutex> mutex_;
  7360. std::unordered_map<std::string, std::shared_ptr<session::CachedSession>> cache_;
  7361. };
  7362. /// InMemoryStore stores all entries in memory
  7363. struct InMemoryStore
  7364. {
  7365. // Load a value into the session cache.
  7366. // A load is always followed by a save, no loads happen consecutively
  7367. void load(session::CachedSession& cn)
  7368. {
  7369. // load & stores happen sequentially, so moving is safe
  7370. cn.entries = std::move(entries[cn.session_id]);
  7371. }
  7372. // Persist session data
  7373. void save(session::CachedSession& cn)
  7374. {
  7375. entries[cn.session_id] = std::move(cn.entries);
  7376. // cn.dirty is a list of changed keys since the last load
  7377. }
  7378. bool contains(const std::string& key)
  7379. {
  7380. return entries.count(key) > 0;
  7381. }
  7382. std::unordered_map<std::string, std::unordered_map<std::string, session::multi_value>> entries;
  7383. };
  7384. // FileStore stores all data as json files in a folder.
  7385. // Files are deleted after expiration. Expiration refreshes are automatically picked up.
  7386. struct FileStore
  7387. {
  7388. FileStore(const std::string& folder, uint64_t expiration_seconds = /*month*/ 30 * 24 * 60 * 60):
  7389. path_(folder), expiration_seconds_(expiration_seconds)
  7390. {
  7391. std::ifstream ifs(get_filename(".expirations", false));
  7392. auto current_ts = chrono_time();
  7393. std::string key;
  7394. uint64_t time;
  7395. while (ifs >> key >> time)
  7396. {
  7397. if (current_ts > time)
  7398. {
  7399. evict(key);
  7400. }
  7401. else if (contains(key))
  7402. {
  7403. expirations_.add(key, time);
  7404. }
  7405. }
  7406. }
  7407. ~FileStore()
  7408. {
  7409. std::ofstream ofs(get_filename(".expirations", false), std::ios::trunc);
  7410. for (const auto& p : expirations_)
  7411. ofs << p.second << " " << p.first << "\n";
  7412. }
  7413. // Delete expired entries
  7414. // At most 3 to prevent freezes
  7415. void handle_expired()
  7416. {
  7417. int deleted = 0;
  7418. auto current_ts = chrono_time();
  7419. while (current_ts > expirations_.peek_first() && deleted < 3)
  7420. {
  7421. evict(expirations_.pop_first());
  7422. deleted++;
  7423. }
  7424. }
  7425. void load(session::CachedSession& cn)
  7426. {
  7427. handle_expired();
  7428. std::ifstream file(get_filename(cn.session_id));
  7429. std::stringstream buffer;
  7430. buffer << file.rdbuf() << std::endl;
  7431. for (const auto& p : json::load(buffer.str()))
  7432. cn.entries[p.key()] = session::multi_value::from_json(p);
  7433. }
  7434. void save(session::CachedSession& cn)
  7435. {
  7436. if (cn.requested_refresh)
  7437. expirations_.add(cn.session_id, chrono_time() + expiration_seconds_);
  7438. if (cn.dirty.empty()) return;
  7439. std::ofstream file(get_filename(cn.session_id));
  7440. json::wvalue jw;
  7441. for (const auto& p : cn.entries)
  7442. jw[p.first] = p.second.json();
  7443. file << jw.dump() << std::flush;
  7444. }
  7445. std::string get_filename(const std::string& key, bool suffix = true)
  7446. {
  7447. return utility::join_path(path_, key + (suffix ? ".json" : ""));
  7448. }
  7449. bool contains(const std::string& key)
  7450. {
  7451. std::ifstream file(get_filename(key));
  7452. return file.good();
  7453. }
  7454. void evict(const std::string& key)
  7455. {
  7456. std::remove(get_filename(key).c_str());
  7457. }
  7458. uint64_t chrono_time() const
  7459. {
  7460. return std::chrono::duration_cast<std::chrono::seconds>(
  7461. std::chrono::system_clock::now().time_since_epoch())
  7462. .count();
  7463. }
  7464. std::string path_;
  7465. uint64_t expiration_seconds_;
  7466. session::ExpirationTracker expirations_;
  7467. };
  7468. } // namespace crow
  7469. #include <tuple>
  7470. #include <type_traits>
  7471. #include <iostream>
  7472. #include <utility>
  7473. namespace crow // NOTE: Already documented in "crow/app.h"
  7474. {
  7475. /// Local middleware should extend ILocalMiddleware
  7476. struct ILocalMiddleware
  7477. {
  7478. using call_global = std::false_type;
  7479. };
  7480. namespace detail
  7481. {
  7482. template<typename MW>
  7483. struct check_before_handle_arity_3_const
  7484. {
  7485. template<typename T, void (T::*)(request&, response&, typename MW::context&) const = &T::before_handle>
  7486. struct get
  7487. {};
  7488. };
  7489. template<typename MW>
  7490. struct check_before_handle_arity_3
  7491. {
  7492. template<typename T, void (T::*)(request&, response&, typename MW::context&) = &T::before_handle>
  7493. struct get
  7494. {};
  7495. };
  7496. template<typename MW>
  7497. struct check_after_handle_arity_3_const
  7498. {
  7499. template<typename T, void (T::*)(request&, response&, typename MW::context&) const = &T::after_handle>
  7500. struct get
  7501. {};
  7502. };
  7503. template<typename MW>
  7504. struct check_after_handle_arity_3
  7505. {
  7506. template<typename T, void (T::*)(request&, response&, typename MW::context&) = &T::after_handle>
  7507. struct get
  7508. {};
  7509. };
  7510. template<typename MW>
  7511. struct check_global_call_false
  7512. {
  7513. template<typename T, typename std::enable_if<T::call_global::value == false, bool>::type = true>
  7514. struct get
  7515. {};
  7516. };
  7517. template<typename T>
  7518. struct is_before_handle_arity_3_impl
  7519. {
  7520. template<typename C>
  7521. static std::true_type f(typename check_before_handle_arity_3_const<T>::template get<C>*);
  7522. template<typename C>
  7523. static std::true_type f(typename check_before_handle_arity_3<T>::template get<C>*);
  7524. template<typename C>
  7525. static std::false_type f(...);
  7526. public:
  7527. static const bool value = decltype(f<T>(nullptr))::value;
  7528. };
  7529. template<typename T>
  7530. struct is_after_handle_arity_3_impl
  7531. {
  7532. template<typename C>
  7533. static std::true_type f(typename check_after_handle_arity_3_const<T>::template get<C>*);
  7534. template<typename C>
  7535. static std::true_type f(typename check_after_handle_arity_3<T>::template get<C>*);
  7536. template<typename C>
  7537. static std::false_type f(...);
  7538. public:
  7539. static constexpr bool value = decltype(f<T>(nullptr))::value;
  7540. };
  7541. template<typename MW>
  7542. struct is_middleware_global
  7543. {
  7544. template<typename C>
  7545. static std::false_type f(typename check_global_call_false<MW>::template get<C>*);
  7546. template<typename C>
  7547. static std::true_type f(...);
  7548. static const bool value = decltype(f<MW>(nullptr))::value;
  7549. };
  7550. template<typename MW, typename Context, typename ParentContext>
  7551. typename std::enable_if<!is_before_handle_arity_3_impl<MW>::value>::type
  7552. before_handler_call(MW& mw, request& req, response& res, Context& ctx, ParentContext& /*parent_ctx*/)
  7553. {
  7554. mw.before_handle(req, res, ctx.template get<MW>(), ctx);
  7555. }
  7556. template<typename MW, typename Context, typename ParentContext>
  7557. typename std::enable_if<is_before_handle_arity_3_impl<MW>::value>::type
  7558. before_handler_call(MW& mw, request& req, response& res, Context& ctx, ParentContext& /*parent_ctx*/)
  7559. {
  7560. mw.before_handle(req, res, ctx.template get<MW>());
  7561. }
  7562. template<typename MW, typename Context, typename ParentContext>
  7563. typename std::enable_if<!is_after_handle_arity_3_impl<MW>::value>::type
  7564. after_handler_call(MW& mw, request& req, response& res, Context& ctx, ParentContext& /*parent_ctx*/)
  7565. {
  7566. mw.after_handle(req, res, ctx.template get<MW>(), ctx);
  7567. }
  7568. template<typename MW, typename Context, typename ParentContext>
  7569. typename std::enable_if<is_after_handle_arity_3_impl<MW>::value>::type
  7570. after_handler_call(MW& mw, request& req, response& res, Context& ctx, ParentContext& /*parent_ctx*/)
  7571. {
  7572. mw.after_handle(req, res, ctx.template get<MW>());
  7573. }
  7574. template<typename CallCriteria,
  7575. int N, typename Context, typename Container>
  7576. typename std::enable_if<(N < std::tuple_size<typename std::remove_reference<Container>::type>::value), bool>::type
  7577. middleware_call_helper(const CallCriteria& cc, Container& middlewares, request& req, response& res, Context& ctx)
  7578. {
  7579. using CurrentMW = typename std::tuple_element<N, typename std::remove_reference<Container>::type>::type;
  7580. if (!cc.template enabled<CurrentMW>(N))
  7581. {
  7582. return middleware_call_helper<CallCriteria, N + 1, Context, Container>(cc, middlewares, req, res, ctx);
  7583. }
  7584. using parent_context_t = typename Context::template partial<N - 1>;
  7585. before_handler_call<CurrentMW, Context, parent_context_t>(std::get<N>(middlewares), req, res, ctx, static_cast<parent_context_t&>(ctx));
  7586. if (res.is_completed())
  7587. {
  7588. after_handler_call<CurrentMW, Context, parent_context_t>(std::get<N>(middlewares), req, res, ctx, static_cast<parent_context_t&>(ctx));
  7589. return true;
  7590. }
  7591. if (middleware_call_helper<CallCriteria, N + 1, Context, Container>(cc, middlewares, req, res, ctx))
  7592. {
  7593. after_handler_call<CurrentMW, Context, parent_context_t>(std::get<N>(middlewares), req, res, ctx, static_cast<parent_context_t&>(ctx));
  7594. return true;
  7595. }
  7596. return false;
  7597. }
  7598. template<typename CallCriteria, int N, typename Context, typename Container>
  7599. typename std::enable_if<(N >= std::tuple_size<typename std::remove_reference<Container>::type>::value), bool>::type
  7600. middleware_call_helper(const CallCriteria& /*cc*/, Container& /*middlewares*/, request& /*req*/, response& /*res*/, Context& /*ctx*/)
  7601. {
  7602. return false;
  7603. }
  7604. template<typename CallCriteria, int N, typename Context, typename Container>
  7605. typename std::enable_if<(N < 0)>::type
  7606. after_handlers_call_helper(const CallCriteria& /*cc*/, Container& /*middlewares*/, Context& /*context*/, request& /*req*/, response& /*res*/)
  7607. {
  7608. }
  7609. template<typename CallCriteria, int N, typename Context, typename Container>
  7610. typename std::enable_if<(N == 0)>::type after_handlers_call_helper(const CallCriteria& cc, Container& middlewares, Context& ctx, request& req, response& res)
  7611. {
  7612. using parent_context_t = typename Context::template partial<N - 1>;
  7613. using CurrentMW = typename std::tuple_element<N, typename std::remove_reference<Container>::type>::type;
  7614. if (cc.template enabled<CurrentMW>(N))
  7615. {
  7616. after_handler_call<CurrentMW, Context, parent_context_t>(std::get<N>(middlewares), req, res, ctx, static_cast<parent_context_t&>(ctx));
  7617. }
  7618. }
  7619. template<typename CallCriteria, int N, typename Context, typename Container>
  7620. typename std::enable_if<(N > 0)>::type after_handlers_call_helper(const CallCriteria& cc, Container& middlewares, Context& ctx, request& req, response& res)
  7621. {
  7622. using parent_context_t = typename Context::template partial<N - 1>;
  7623. using CurrentMW = typename std::tuple_element<N, typename std::remove_reference<Container>::type>::type;
  7624. if (cc.template enabled<CurrentMW>(N))
  7625. {
  7626. after_handler_call<CurrentMW, Context, parent_context_t>(std::get<N>(middlewares), req, res, ctx, static_cast<parent_context_t&>(ctx));
  7627. }
  7628. after_handlers_call_helper<CallCriteria, N - 1, Context, Container>(cc, middlewares, ctx, req, res);
  7629. }
  7630. // A CallCriteria that accepts only global middleware
  7631. struct middleware_call_criteria_only_global
  7632. {
  7633. template<typename MW>
  7634. constexpr bool enabled(int) const
  7635. {
  7636. return is_middleware_global<MW>::value;
  7637. }
  7638. };
  7639. template<typename F, typename... Args>
  7640. typename std::enable_if<black_magic::CallHelper<F, black_magic::S<Args...>>::value, void>::type
  7641. wrapped_handler_call(crow::request& /*req*/, crow::response& res, const F& f, Args&&... args)
  7642. {
  7643. static_assert(!std::is_same<void, decltype(f(std::declval<Args>()...))>::value,
  7644. "Handler function cannot have void return type; valid return types: string, int, crow::response, crow::returnable");
  7645. res = crow::response(f(std::forward<Args>(args)...));
  7646. res.end();
  7647. }
  7648. template<typename F, typename... Args>
  7649. typename std::enable_if<
  7650. !black_magic::CallHelper<F, black_magic::S<Args...>>::value &&
  7651. black_magic::CallHelper<F, black_magic::S<crow::request&, Args...>>::value,
  7652. void>::type
  7653. wrapped_handler_call(crow::request& req, crow::response& res, const F& f, Args&&... args)
  7654. {
  7655. static_assert(!std::is_same<void, decltype(f(std::declval<crow::request>(), std::declval<Args>()...))>::value,
  7656. "Handler function cannot have void return type; valid return types: string, int, crow::response, crow::returnable");
  7657. res = crow::response(f(req, std::forward<Args>(args)...));
  7658. res.end();
  7659. }
  7660. template<typename F, typename... Args>
  7661. typename std::enable_if<
  7662. !black_magic::CallHelper<F, black_magic::S<Args...>>::value &&
  7663. !black_magic::CallHelper<F, black_magic::S<crow::request&, Args...>>::value &&
  7664. black_magic::CallHelper<F, black_magic::S<crow::response&, Args...>>::value,
  7665. void>::type
  7666. wrapped_handler_call(crow::request& /*req*/, crow::response& res, const F& f, Args&&... args)
  7667. {
  7668. static_assert(std::is_same<void, decltype(f(std::declval<crow::response&>(), std::declval<Args>()...))>::value,
  7669. "Handler function with response argument should have void return type");
  7670. f(res, std::forward<Args>(args)...);
  7671. }
  7672. template<typename F, typename... Args>
  7673. typename std::enable_if<
  7674. !black_magic::CallHelper<F, black_magic::S<Args...>>::value &&
  7675. !black_magic::CallHelper<F, black_magic::S<crow::request&, Args...>>::value &&
  7676. !black_magic::CallHelper<F, black_magic::S<crow::response&, Args...>>::value &&
  7677. black_magic::CallHelper<F, black_magic::S<const crow::request&, crow::response&, Args...>>::value,
  7678. void>::type
  7679. wrapped_handler_call(crow::request& req, crow::response& res, const F& f, Args&&... args)
  7680. {
  7681. static_assert(std::is_same<void, decltype(f(std::declval<crow::request&>(), std::declval<crow::response&>(), std::declval<Args>()...))>::value,
  7682. "Handler function with response argument should have void return type");
  7683. f(req, res, std::forward<Args>(args)...);
  7684. }
  7685. // wrapped_handler_call transparently wraps a handler call behind (req, res, args...)
  7686. template<typename F, typename... Args>
  7687. typename std::enable_if<
  7688. !black_magic::CallHelper<F, black_magic::S<Args...>>::value &&
  7689. !black_magic::CallHelper<F, black_magic::S<crow::request&, Args...>>::value &&
  7690. !black_magic::CallHelper<F, black_magic::S<crow::response&, Args...>>::value &&
  7691. !black_magic::CallHelper<F, black_magic::S<const crow::request&, crow::response&, Args...>>::value,
  7692. void>::type
  7693. wrapped_handler_call(crow::request& req, crow::response& res, const F& f, Args&&... args)
  7694. {
  7695. static_assert(std::is_same<void, decltype(f(std::declval<crow::request&>(), std::declval<crow::response&>(), std::declval<Args>()...))>::value,
  7696. "Handler function with response argument should have void return type");
  7697. f(req, res, std::forward<Args>(args)...);
  7698. }
  7699. template<bool Reversed>
  7700. struct middleware_call_criteria_dynamic
  7701. {};
  7702. template<>
  7703. struct middleware_call_criteria_dynamic<false>
  7704. {
  7705. middleware_call_criteria_dynamic(const std::vector<int>& indices):
  7706. indices(indices), slider(0) {}
  7707. template<typename>
  7708. bool enabled(int mw_index) const
  7709. {
  7710. if (slider < int(indices.size()) && indices[slider] == mw_index)
  7711. {
  7712. slider++;
  7713. return true;
  7714. }
  7715. return false;
  7716. }
  7717. private:
  7718. const std::vector<int>& indices;
  7719. mutable int slider;
  7720. };
  7721. template<>
  7722. struct middleware_call_criteria_dynamic<true>
  7723. {
  7724. middleware_call_criteria_dynamic(const std::vector<int>& indices):
  7725. indices(indices), slider(int(indices.size()) - 1) {}
  7726. template<typename>
  7727. bool enabled(int mw_index) const
  7728. {
  7729. if (slider >= 0 && indices[slider] == mw_index)
  7730. {
  7731. slider--;
  7732. return true;
  7733. }
  7734. return false;
  7735. }
  7736. private:
  7737. const std::vector<int>& indices;
  7738. mutable int slider;
  7739. };
  7740. } // namespace detail
  7741. } // namespace crow
  7742. namespace crow
  7743. {
  7744. namespace detail
  7745. {
  7746. template<typename... Middlewares>
  7747. struct partial_context : public black_magic::pop_back<Middlewares...>::template rebind<partial_context>, public black_magic::last_element_type<Middlewares...>::type::context
  7748. {
  7749. using parent_context = typename black_magic::pop_back<Middlewares...>::template rebind<::crow::detail::partial_context>;
  7750. template<int N>
  7751. using partial = typename std::conditional<N == sizeof...(Middlewares) - 1, partial_context, typename parent_context::template partial<N>>::type;
  7752. template<typename T>
  7753. typename T::context& get()
  7754. {
  7755. return static_cast<typename T::context&>(*this);
  7756. }
  7757. };
  7758. template<>
  7759. struct partial_context<>
  7760. {
  7761. template<int>
  7762. using partial = partial_context;
  7763. };
  7764. template<typename... Middlewares>
  7765. struct context : private partial_context<Middlewares...>
  7766. //struct context : private Middlewares::context... // simple but less type-safe
  7767. {
  7768. template<typename CallCriteria, int N, typename Context, typename Container>
  7769. friend typename std::enable_if<(N == 0)>::type after_handlers_call_helper(const CallCriteria& cc, Container& middlewares, Context& ctx, request& req, response& res);
  7770. template<typename CallCriteria, int N, typename Context, typename Container>
  7771. friend typename std::enable_if<(N > 0)>::type after_handlers_call_helper(const CallCriteria& cc, Container& middlewares, Context& ctx, request& req, response& res);
  7772. template<typename CallCriteria, int N, typename Context, typename Container>
  7773. friend typename std::enable_if<(N < std::tuple_size<typename std::remove_reference<Container>::type>::value), bool>::type
  7774. middleware_call_helper(const CallCriteria& cc, Container& middlewares, request& req, response& res, Context& ctx);
  7775. template<typename T>
  7776. typename T::context& get()
  7777. {
  7778. return static_cast<typename T::context&>(*this);
  7779. }
  7780. template<int N>
  7781. using partial = typename partial_context<Middlewares...>::template partial<N>;
  7782. };
  7783. } // namespace detail
  7784. } // namespace crow
  7785. #ifdef CROW_USE_BOOST
  7786. #include <boost/asio.hpp>
  7787. #include <boost/asio/basic_waitable_timer.hpp>
  7788. #else
  7789. #ifndef ASIO_STANDALONE
  7790. #define ASIO_STANDALONE
  7791. #endif
  7792. #include <asio.hpp>
  7793. #include <asio/basic_waitable_timer.hpp>
  7794. #endif
  7795. #include <chrono>
  7796. #include <functional>
  7797. #include <map>
  7798. #include <vector>
  7799. namespace crow
  7800. {
  7801. #ifdef CROW_USE_BOOST
  7802. namespace asio = boost::asio;
  7803. using error_code = boost::system::error_code;
  7804. #else
  7805. using error_code = asio::error_code;
  7806. #endif
  7807. namespace detail
  7808. {
  7809. /// A class for scheduling functions to be called after a specific amount of ticks. A tick is equal to 1 second.
  7810. class task_timer
  7811. {
  7812. public:
  7813. using task_type = std::function<void()>;
  7814. using identifier_type = size_t;
  7815. private:
  7816. using clock_type = std::chrono::steady_clock;
  7817. using time_type = clock_type::time_point;
  7818. public:
  7819. task_timer(asio::io_service& io_service):
  7820. io_service_(io_service), timer_(io_service_)
  7821. {
  7822. timer_.expires_after(std::chrono::seconds(1));
  7823. timer_.async_wait(
  7824. std::bind(&task_timer::tick_handler, this, std::placeholders::_1));
  7825. }
  7826. ~task_timer() { timer_.cancel(); }
  7827. void cancel(identifier_type id)
  7828. {
  7829. tasks_.erase(id);
  7830. CROW_LOG_DEBUG << "task_timer cancelled: " << this << ' ' << id;
  7831. }
  7832. /// Schedule the given task to be executed after the default amount of ticks.
  7833. ///
  7834. /// \return identifier_type Used to cancel the thread.
  7835. /// It is not bound to this task_timer instance and in some cases could lead to
  7836. /// undefined behavior if used with other task_timer objects or after the task
  7837. /// has been successfully executed.
  7838. identifier_type schedule(const task_type& task)
  7839. {
  7840. tasks_.insert(
  7841. {++highest_id_,
  7842. {clock_type::now() + std::chrono::seconds(get_default_timeout()),
  7843. task}});
  7844. CROW_LOG_DEBUG << "task_timer scheduled: " << this << ' ' << highest_id_;
  7845. return highest_id_;
  7846. }
  7847. /// Schedule the given task to be executed after the given time.
  7848. ///
  7849. /// \param timeout The amount of ticks (seconds) to wait before execution.
  7850. ///
  7851. /// \return identifier_type Used to cancel the thread.
  7852. /// It is not bound to this task_timer instance and in some cases could lead to
  7853. /// undefined behavior if used with other task_timer objects or after the task
  7854. /// has been successfully executed.
  7855. identifier_type schedule(const task_type& task, std::uint8_t timeout)
  7856. {
  7857. tasks_.insert({++highest_id_,
  7858. {clock_type::now() + std::chrono::seconds(timeout), task}});
  7859. CROW_LOG_DEBUG << "task_timer scheduled: " << this << ' ' << highest_id_;
  7860. return highest_id_;
  7861. }
  7862. /// Set the default timeout for this task_timer instance. (Default: 5)
  7863. ///
  7864. /// \param timeout The amount of ticks (seconds) to wait before execution.
  7865. void set_default_timeout(std::uint8_t timeout) { default_timeout_ = timeout; }
  7866. /// Get the default timeout. (Default: 5)
  7867. std::uint8_t get_default_timeout() const { return default_timeout_; }
  7868. private:
  7869. void process_tasks()
  7870. {
  7871. time_type current_time = clock_type::now();
  7872. std::vector<identifier_type> finished_tasks;
  7873. for (const auto& task : tasks_)
  7874. {
  7875. if (task.second.first < current_time)
  7876. {
  7877. (task.second.second)();
  7878. finished_tasks.push_back(task.first);
  7879. CROW_LOG_DEBUG << "task_timer called: " << this << ' ' << task.first;
  7880. }
  7881. }
  7882. for (const auto& task : finished_tasks)
  7883. tasks_.erase(task);
  7884. // If no task is currently scheduled, reset the issued ids back to 0.
  7885. if (tasks_.empty()) highest_id_ = 0;
  7886. }
  7887. void tick_handler(const error_code& ec)
  7888. {
  7889. if (ec) return;
  7890. process_tasks();
  7891. timer_.expires_after(std::chrono::seconds(1));
  7892. timer_.async_wait(
  7893. std::bind(&task_timer::tick_handler, this, std::placeholders::_1));
  7894. }
  7895. private:
  7896. std::uint8_t default_timeout_{5};
  7897. asio::io_service& io_service_;
  7898. asio::basic_waitable_timer<clock_type> timer_;
  7899. std::map<identifier_type, std::pair<time_type, task_type>> tasks_;
  7900. // A continuosly increasing number to be issued to threads to identify them.
  7901. // If no tasks are scheduled, it will be reset to 0.
  7902. identifier_type highest_id_{0};
  7903. };
  7904. } // namespace detail
  7905. } // namespace crow
  7906. #ifdef CROW_USE_BOOST
  7907. #include <boost/asio.hpp>
  7908. #else
  7909. #ifndef ASIO_STANDALONE
  7910. #define ASIO_STANDALONE
  7911. #endif
  7912. #include <asio.hpp>
  7913. #endif
  7914. #include <algorithm>
  7915. #include <atomic>
  7916. #include <chrono>
  7917. #include <memory>
  7918. #include <vector>
  7919. namespace crow
  7920. {
  7921. #ifdef CROW_USE_BOOST
  7922. namespace asio = boost::asio;
  7923. using error_code = boost::system::error_code;
  7924. #else
  7925. using error_code = asio::error_code;
  7926. #endif
  7927. using tcp = asio::ip::tcp;
  7928. #ifdef CROW_ENABLE_DEBUG
  7929. static std::atomic<int> connectionCount;
  7930. #endif
  7931. /// An HTTP connection.
  7932. template<typename Adaptor, typename Handler, typename... Middlewares>
  7933. class Connection: public std::enable_shared_from_this<Connection<Adaptor, Handler, Middlewares...>>
  7934. {
  7935. friend struct crow::response;
  7936. public:
  7937. Connection(
  7938. asio::io_service& io_service,
  7939. Handler* handler,
  7940. const std::string& server_name,
  7941. std::tuple<Middlewares...>* middlewares,
  7942. std::function<std::string()>& get_cached_date_str_f,
  7943. detail::task_timer& task_timer,
  7944. typename Adaptor::context* adaptor_ctx_,
  7945. std::atomic<unsigned int>& queue_length):
  7946. adaptor_(io_service, adaptor_ctx_),
  7947. handler_(handler),
  7948. parser_(this),
  7949. req_(parser_.req),
  7950. server_name_(server_name),
  7951. middlewares_(middlewares),
  7952. get_cached_date_str(get_cached_date_str_f),
  7953. task_timer_(task_timer),
  7954. res_stream_threshold_(handler->stream_threshold()),
  7955. queue_length_(queue_length)
  7956. {
  7957. #ifdef CROW_ENABLE_DEBUG
  7958. connectionCount++;
  7959. CROW_LOG_DEBUG << "Connection (" << this << ") allocated, total: " << connectionCount;
  7960. #endif
  7961. }
  7962. ~Connection()
  7963. {
  7964. #ifdef CROW_ENABLE_DEBUG
  7965. connectionCount--;
  7966. CROW_LOG_DEBUG << "Connection (" << this << ") freed, total: " << connectionCount;
  7967. #endif
  7968. }
  7969. /// The TCP socket on top of which the connection is established.
  7970. decltype(std::declval<Adaptor>().raw_socket())& socket()
  7971. {
  7972. return adaptor_.raw_socket();
  7973. }
  7974. void start()
  7975. {
  7976. auto self = this->shared_from_this();
  7977. adaptor_.start([self](const error_code& ec) {
  7978. if (!ec)
  7979. {
  7980. self->start_deadline();
  7981. self->parser_.clear();
  7982. self->do_read();
  7983. }
  7984. else
  7985. {
  7986. CROW_LOG_ERROR << "Could not start adaptor: " << ec.message();
  7987. }
  7988. });
  7989. }
  7990. void handle_url()
  7991. {
  7992. routing_handle_result_ = handler_->handle_initial(req_, res);
  7993. // if no route is found for the request method, return the response without parsing or processing anything further.
  7994. if (!routing_handle_result_->rule_index)
  7995. {
  7996. parser_.done();
  7997. need_to_call_after_handlers_ = true;
  7998. complete_request();
  7999. }
  8000. }
  8001. void handle_header()
  8002. {
  8003. // HTTP 1.1 Expect: 100-continue
  8004. if (req_.http_ver_major == 1 && req_.http_ver_minor == 1 && get_header_value(req_.headers, "expect") == "100-continue")
  8005. {
  8006. continue_requested = true;
  8007. buffers_.clear();
  8008. static std::string expect_100_continue = "HTTP/1.1 100 Continue\r\n\r\n";
  8009. buffers_.emplace_back(expect_100_continue.data(), expect_100_continue.size());
  8010. do_write();
  8011. }
  8012. }
  8013. void handle()
  8014. {
  8015. // TODO(EDev): cancel_deadline_timer should be looked into, it might be a good idea to add it to handle_url() and then restart the timer once everything passes
  8016. cancel_deadline_timer();
  8017. bool is_invalid_request = false;
  8018. add_keep_alive_ = false;
  8019. // Create context
  8020. ctx_ = detail::context<Middlewares...>();
  8021. req_.middleware_context = static_cast<void*>(&ctx_);
  8022. req_.middleware_container = static_cast<void*>(middlewares_);
  8023. req_.io_service = &adaptor_.get_io_service();
  8024. req_.remote_ip_address = adaptor_.remote_endpoint().address().to_string();
  8025. add_keep_alive_ = req_.keep_alive;
  8026. close_connection_ = req_.close_connection;
  8027. if (req_.check_version(1, 1)) // HTTP/1.1
  8028. {
  8029. if (!req_.headers.count("host"))
  8030. {
  8031. is_invalid_request = true;
  8032. res = response(400);
  8033. }
  8034. else if (req_.upgrade)
  8035. {
  8036. // h2 or h2c headers
  8037. if (req_.get_header_value("upgrade").substr(0, 2) == "h2")
  8038. {
  8039. // TODO(ipkn): HTTP/2
  8040. // currently, ignore upgrade header
  8041. }
  8042. else
  8043. {
  8044. detail::middleware_call_helper<detail::middleware_call_criteria_only_global,
  8045. 0, decltype(ctx_), decltype(*middlewares_)>({}, *middlewares_, req_, res, ctx_);
  8046. close_connection_ = true;
  8047. handler_->handle_upgrade(req_, res, std::move(adaptor_));
  8048. return;
  8049. }
  8050. }
  8051. }
  8052. CROW_LOG_INFO << "Request: " << utility::lexical_cast<std::string>(adaptor_.remote_endpoint()) << " " << this << " HTTP/" << (char)(req_.http_ver_major + '0') << "." << (char)(req_.http_ver_minor + '0') << ' ' << method_name(req_.method) << " " << req_.url;
  8053. need_to_call_after_handlers_ = false;
  8054. if (!is_invalid_request)
  8055. {
  8056. res.complete_request_handler_ = nullptr;
  8057. auto self = this->shared_from_this();
  8058. res.is_alive_helper_ = [self]() -> bool {
  8059. return self->adaptor_.is_open();
  8060. };
  8061. detail::middleware_call_helper<detail::middleware_call_criteria_only_global,
  8062. 0, decltype(ctx_), decltype(*middlewares_)>({}, *middlewares_, req_, res, ctx_);
  8063. if (!res.completed_)
  8064. {
  8065. auto self = this->shared_from_this();
  8066. res.complete_request_handler_ = [self] {
  8067. self->complete_request();
  8068. };
  8069. need_to_call_after_handlers_ = true;
  8070. handler_->handle(req_, res, routing_handle_result_);
  8071. if (add_keep_alive_)
  8072. res.set_header("connection", "Keep-Alive");
  8073. }
  8074. else
  8075. {
  8076. complete_request();
  8077. }
  8078. }
  8079. else
  8080. {
  8081. complete_request();
  8082. }
  8083. }
  8084. /// Call the after handle middleware and send the write the response to the connection.
  8085. void complete_request()
  8086. {
  8087. CROW_LOG_INFO << "Response: " << this << ' ' << req_.raw_url << ' ' << res.code << ' ' << close_connection_;
  8088. res.is_alive_helper_ = nullptr;
  8089. if (need_to_call_after_handlers_)
  8090. {
  8091. need_to_call_after_handlers_ = false;
  8092. // call all after_handler of middlewares
  8093. detail::after_handlers_call_helper<
  8094. detail::middleware_call_criteria_only_global,
  8095. (static_cast<int>(sizeof...(Middlewares)) - 1),
  8096. decltype(ctx_),
  8097. decltype(*middlewares_)>({}, *middlewares_, ctx_, req_, res);
  8098. }
  8099. #ifdef CROW_ENABLE_COMPRESSION
  8100. if (handler_->compression_used())
  8101. {
  8102. std::string accept_encoding = req_.get_header_value("Accept-Encoding");
  8103. if (!accept_encoding.empty() && res.compressed)
  8104. {
  8105. switch (handler_->compression_algorithm())
  8106. {
  8107. case compression::DEFLATE:
  8108. if (accept_encoding.find("deflate") != std::string::npos)
  8109. {
  8110. res.body = compression::compress_string(res.body, compression::algorithm::DEFLATE);
  8111. res.set_header("Content-Encoding", "deflate");
  8112. }
  8113. break;
  8114. case compression::GZIP:
  8115. if (accept_encoding.find("gzip") != std::string::npos)
  8116. {
  8117. res.body = compression::compress_string(res.body, compression::algorithm::GZIP);
  8118. res.set_header("Content-Encoding", "gzip");
  8119. }
  8120. break;
  8121. default:
  8122. break;
  8123. }
  8124. }
  8125. }
  8126. #endif
  8127. //if there is a redirection with a partial URL, treat the URL as a route.
  8128. std::string location = res.get_header_value("Location");
  8129. if (!location.empty() && location.find("://", 0) == std::string::npos)
  8130. {
  8131. #ifdef CROW_ENABLE_SSL
  8132. if (handler_->ssl_used())
  8133. location.insert(0, "https://" + req_.get_header_value("Host"));
  8134. else
  8135. #endif
  8136. location.insert(0, "http://" + req_.get_header_value("Host"));
  8137. res.set_header("location", location);
  8138. }
  8139. prepare_buffers();
  8140. if (res.is_static_type())
  8141. {
  8142. do_write_static();
  8143. }
  8144. else
  8145. {
  8146. do_write_general();
  8147. }
  8148. }
  8149. private:
  8150. void prepare_buffers()
  8151. {
  8152. res.complete_request_handler_ = nullptr;
  8153. res.is_alive_helper_ = nullptr;
  8154. if (!adaptor_.is_open())
  8155. {
  8156. //CROW_LOG_DEBUG << this << " delete (socket is closed) " << is_reading << ' ' << is_writing;
  8157. //delete this;
  8158. return;
  8159. }
  8160. // TODO(EDev): HTTP version in status codes should be dynamic
  8161. // Keep in sync with common.h/status
  8162. static std::unordered_map<int, std::string> statusCodes = {
  8163. {status::CONTINUE, "HTTP/1.1 100 Continue\r\n"},
  8164. {status::SWITCHING_PROTOCOLS, "HTTP/1.1 101 Switching Protocols\r\n"},
  8165. {status::OK, "HTTP/1.1 200 OK\r\n"},
  8166. {status::CREATED, "HTTP/1.1 201 Created\r\n"},
  8167. {status::ACCEPTED, "HTTP/1.1 202 Accepted\r\n"},
  8168. {status::NON_AUTHORITATIVE_INFORMATION, "HTTP/1.1 203 Non-Authoritative Information\r\n"},
  8169. {status::NO_CONTENT, "HTTP/1.1 204 No Content\r\n"},
  8170. {status::RESET_CONTENT, "HTTP/1.1 205 Reset Content\r\n"},
  8171. {status::PARTIAL_CONTENT, "HTTP/1.1 206 Partial Content\r\n"},
  8172. {status::MULTIPLE_CHOICES, "HTTP/1.1 300 Multiple Choices\r\n"},
  8173. {status::MOVED_PERMANENTLY, "HTTP/1.1 301 Moved Permanently\r\n"},
  8174. {status::FOUND, "HTTP/1.1 302 Found\r\n"},
  8175. {status::SEE_OTHER, "HTTP/1.1 303 See Other\r\n"},
  8176. {status::NOT_MODIFIED, "HTTP/1.1 304 Not Modified\r\n"},
  8177. {status::TEMPORARY_REDIRECT, "HTTP/1.1 307 Temporary Redirect\r\n"},
  8178. {status::PERMANENT_REDIRECT, "HTTP/1.1 308 Permanent Redirect\r\n"},
  8179. {status::BAD_REQUEST, "HTTP/1.1 400 Bad Request\r\n"},
  8180. {status::UNAUTHORIZED, "HTTP/1.1 401 Unauthorized\r\n"},
  8181. {status::FORBIDDEN, "HTTP/1.1 403 Forbidden\r\n"},
  8182. {status::NOT_FOUND, "HTTP/1.1 404 Not Found\r\n"},
  8183. {status::METHOD_NOT_ALLOWED, "HTTP/1.1 405 Method Not Allowed\r\n"},
  8184. {status::NOT_ACCEPTABLE, "HTTP/1.1 406 Not Acceptable\r\n"},
  8185. {status::PROXY_AUTHENTICATION_REQUIRED, "HTTP/1.1 407 Proxy Authentication Required\r\n"},
  8186. {status::CONFLICT, "HTTP/1.1 409 Conflict\r\n"},
  8187. {status::GONE, "HTTP/1.1 410 Gone\r\n"},
  8188. {status::PAYLOAD_TOO_LARGE, "HTTP/1.1 413 Payload Too Large\r\n"},
  8189. {status::UNSUPPORTED_MEDIA_TYPE, "HTTP/1.1 415 Unsupported Media Type\r\n"},
  8190. {status::RANGE_NOT_SATISFIABLE, "HTTP/1.1 416 Range Not Satisfiable\r\n"},
  8191. {status::EXPECTATION_FAILED, "HTTP/1.1 417 Expectation Failed\r\n"},
  8192. {status::PRECONDITION_REQUIRED, "HTTP/1.1 428 Precondition Required\r\n"},
  8193. {status::TOO_MANY_REQUESTS, "HTTP/1.1 429 Too Many Requests\r\n"},
  8194. {status::UNAVAILABLE_FOR_LEGAL_REASONS, "HTTP/1.1 451 Unavailable For Legal Reasons\r\n"},
  8195. {status::INTERNAL_SERVER_ERROR, "HTTP/1.1 500 Internal Server Error\r\n"},
  8196. {status::NOT_IMPLEMENTED, "HTTP/1.1 501 Not Implemented\r\n"},
  8197. {status::BAD_GATEWAY, "HTTP/1.1 502 Bad Gateway\r\n"},
  8198. {status::SERVICE_UNAVAILABLE, "HTTP/1.1 503 Service Unavailable\r\n"},
  8199. {status::GATEWAY_TIMEOUT, "HTTP/1.1 504 Gateway Timeout\r\n"},
  8200. {status::VARIANT_ALSO_NEGOTIATES, "HTTP/1.1 506 Variant Also Negotiates\r\n"},
  8201. };
  8202. static const std::string seperator = ": ";
  8203. buffers_.clear();
  8204. buffers_.reserve(4 * (res.headers.size() + 5) + 3);
  8205. if (!statusCodes.count(res.code))
  8206. {
  8207. CROW_LOG_WARNING << this << " status code "
  8208. << "(" << res.code << ")"
  8209. << " not defined, returning 500 instead";
  8210. res.code = 500;
  8211. }
  8212. auto& status = statusCodes.find(res.code)->second;
  8213. buffers_.emplace_back(status.data(), status.size());
  8214. if (res.code >= 400 && res.body.empty())
  8215. res.body = statusCodes[res.code].substr(9);
  8216. for (auto& kv : res.headers)
  8217. {
  8218. buffers_.emplace_back(kv.first.data(), kv.first.size());
  8219. buffers_.emplace_back(seperator.data(), seperator.size());
  8220. buffers_.emplace_back(kv.second.data(), kv.second.size());
  8221. buffers_.emplace_back(crlf.data(), crlf.size());
  8222. }
  8223. if (!res.manual_length_header && !res.headers.count("content-length"))
  8224. {
  8225. content_length_ = std::to_string(res.body.size());
  8226. static std::string content_length_tag = "Content-Length: ";
  8227. buffers_.emplace_back(content_length_tag.data(), content_length_tag.size());
  8228. buffers_.emplace_back(content_length_.data(), content_length_.size());
  8229. buffers_.emplace_back(crlf.data(), crlf.size());
  8230. }
  8231. if (!res.headers.count("server"))
  8232. {
  8233. static std::string server_tag = "Server: ";
  8234. buffers_.emplace_back(server_tag.data(), server_tag.size());
  8235. buffers_.emplace_back(server_name_.data(), server_name_.size());
  8236. buffers_.emplace_back(crlf.data(), crlf.size());
  8237. }
  8238. if (!res.headers.count("date"))
  8239. {
  8240. static std::string date_tag = "Date: ";
  8241. date_str_ = get_cached_date_str();
  8242. buffers_.emplace_back(date_tag.data(), date_tag.size());
  8243. buffers_.emplace_back(date_str_.data(), date_str_.size());
  8244. buffers_.emplace_back(crlf.data(), crlf.size());
  8245. }
  8246. if (add_keep_alive_)
  8247. {
  8248. static std::string keep_alive_tag = "Connection: Keep-Alive";
  8249. buffers_.emplace_back(keep_alive_tag.data(), keep_alive_tag.size());
  8250. buffers_.emplace_back(crlf.data(), crlf.size());
  8251. }
  8252. buffers_.emplace_back(crlf.data(), crlf.size());
  8253. }
  8254. void do_write_static()
  8255. {
  8256. asio::write(adaptor_.socket(), buffers_);
  8257. if (res.file_info.statResult == 0)
  8258. {
  8259. std::ifstream is(res.file_info.path.c_str(), std::ios::in | std::ios::binary);
  8260. std::vector<asio::const_buffer> buffers{1};
  8261. char buf[16384];
  8262. is.read(buf, sizeof(buf));
  8263. while (is.gcount() > 0)
  8264. {
  8265. buffers[0] = asio::buffer(buf, is.gcount());
  8266. do_write_sync(buffers);
  8267. is.read(buf, sizeof(buf));
  8268. }
  8269. }
  8270. if (close_connection_)
  8271. {
  8272. adaptor_.shutdown_readwrite();
  8273. adaptor_.close();
  8274. CROW_LOG_DEBUG << this << " from write (static)";
  8275. }
  8276. res.end();
  8277. res.clear();
  8278. buffers_.clear();
  8279. parser_.clear();
  8280. }
  8281. void do_write_general()
  8282. {
  8283. if (res.body.length() < res_stream_threshold_)
  8284. {
  8285. res_body_copy_.swap(res.body);
  8286. buffers_.emplace_back(res_body_copy_.data(), res_body_copy_.size());
  8287. do_write();
  8288. if (need_to_start_read_after_complete_)
  8289. {
  8290. need_to_start_read_after_complete_ = false;
  8291. start_deadline();
  8292. do_read();
  8293. }
  8294. }
  8295. else
  8296. {
  8297. asio::write(adaptor_.socket(), buffers_); // Write the response start / headers
  8298. cancel_deadline_timer();
  8299. if (res.body.length() > 0)
  8300. {
  8301. std::vector<asio::const_buffer> buffers{1};
  8302. const uint8_t *data = reinterpret_cast<const uint8_t*>(res.body.data());
  8303. size_t length = res.body.length();
  8304. for(size_t transferred = 0; transferred < length;)
  8305. {
  8306. size_t to_transfer = CROW_MIN(16384UL, length-transferred);
  8307. buffers[0] = asio::const_buffer(data+transferred, to_transfer);
  8308. do_write_sync(buffers);
  8309. transferred += to_transfer;
  8310. }
  8311. }
  8312. if (close_connection_)
  8313. {
  8314. adaptor_.shutdown_readwrite();
  8315. adaptor_.close();
  8316. CROW_LOG_DEBUG << this << " from write (res_stream)";
  8317. }
  8318. res.end();
  8319. res.clear();
  8320. buffers_.clear();
  8321. parser_.clear();
  8322. }
  8323. }
  8324. void do_read()
  8325. {
  8326. auto self = this->shared_from_this();
  8327. adaptor_.socket().async_read_some(
  8328. asio::buffer(buffer_),
  8329. [self](const error_code& ec, std::size_t bytes_transferred) {
  8330. bool error_while_reading = true;
  8331. if (!ec)
  8332. {
  8333. bool ret = self->parser_.feed(self->buffer_.data(), bytes_transferred);
  8334. if (ret && self->adaptor_.is_open())
  8335. {
  8336. error_while_reading = false;
  8337. }
  8338. }
  8339. if (error_while_reading)
  8340. {
  8341. self->cancel_deadline_timer();
  8342. self->parser_.done();
  8343. self->adaptor_.shutdown_read();
  8344. self->adaptor_.close();
  8345. CROW_LOG_DEBUG << self << " from read(1) with description: \"" << http_errno_description(static_cast<http_errno>(self->parser_.http_errno)) << '\"';
  8346. }
  8347. else if (self->close_connection_)
  8348. {
  8349. self->cancel_deadline_timer();
  8350. self->parser_.done();
  8351. // adaptor will close after write
  8352. }
  8353. else if (!self->need_to_call_after_handlers_)
  8354. {
  8355. self->start_deadline();
  8356. self->do_read();
  8357. }
  8358. else
  8359. {
  8360. // res will be completed later by user
  8361. self->need_to_start_read_after_complete_ = true;
  8362. }
  8363. });
  8364. }
  8365. void do_write()
  8366. {
  8367. auto self = this->shared_from_this();
  8368. asio::async_write(
  8369. adaptor_.socket(), buffers_,
  8370. [self](const error_code& ec, std::size_t /*bytes_transferred*/) {
  8371. self->res.clear();
  8372. self->res_body_copy_.clear();
  8373. if (!self->continue_requested)
  8374. {
  8375. self->parser_.clear();
  8376. }
  8377. else
  8378. {
  8379. self->continue_requested = false;
  8380. }
  8381. if (!ec)
  8382. {
  8383. if (self->close_connection_)
  8384. {
  8385. self->adaptor_.shutdown_write();
  8386. self->adaptor_.close();
  8387. CROW_LOG_DEBUG << self << " from write(1)";
  8388. }
  8389. }
  8390. else
  8391. {
  8392. CROW_LOG_DEBUG << self << " from write(2)";
  8393. }
  8394. });
  8395. }
  8396. inline void do_write_sync(std::vector<asio::const_buffer>& buffers)
  8397. {
  8398. asio::write(adaptor_.socket(), buffers, [&](error_code ec, std::size_t) {
  8399. if (!ec)
  8400. {
  8401. return false;
  8402. }
  8403. else
  8404. {
  8405. CROW_LOG_ERROR << ec << " - happened while sending buffers";
  8406. CROW_LOG_DEBUG << this << " from write (sync)(2)";
  8407. return true;
  8408. }
  8409. });
  8410. }
  8411. void cancel_deadline_timer()
  8412. {
  8413. CROW_LOG_DEBUG << this << " timer cancelled: " << &task_timer_ << ' ' << task_id_;
  8414. task_timer_.cancel(task_id_);
  8415. }
  8416. void start_deadline(/*int timeout = 5*/)
  8417. {
  8418. cancel_deadline_timer();
  8419. auto self = this->shared_from_this();
  8420. task_id_ = task_timer_.schedule([self] {
  8421. if (!self->adaptor_.is_open())
  8422. {
  8423. return;
  8424. }
  8425. self->adaptor_.shutdown_readwrite();
  8426. self->adaptor_.close();
  8427. });
  8428. CROW_LOG_DEBUG << this << " timer added: " << &task_timer_ << ' ' << task_id_;
  8429. }
  8430. private:
  8431. Adaptor adaptor_;
  8432. Handler* handler_;
  8433. std::array<char, 4096> buffer_;
  8434. HTTPParser<Connection> parser_;
  8435. std::unique_ptr<routing_handle_result> routing_handle_result_;
  8436. request& req_;
  8437. response res;
  8438. bool close_connection_ = false;
  8439. const std::string& server_name_;
  8440. std::vector<asio::const_buffer> buffers_;
  8441. std::string content_length_;
  8442. std::string date_str_;
  8443. std::string res_body_copy_;
  8444. detail::task_timer::identifier_type task_id_{};
  8445. bool continue_requested{};
  8446. bool need_to_call_after_handlers_{};
  8447. bool need_to_start_read_after_complete_{};
  8448. bool add_keep_alive_{};
  8449. std::tuple<Middlewares...>* middlewares_;
  8450. detail::context<Middlewares...> ctx_;
  8451. std::function<std::string()>& get_cached_date_str;
  8452. detail::task_timer& task_timer_;
  8453. size_t res_stream_threshold_;
  8454. std::atomic<unsigned int>& queue_length_;
  8455. };
  8456. } // namespace crow
  8457. #include <array>
  8458. namespace crow // NOTE: Already documented in "crow/app.h"
  8459. {
  8460. #ifdef CROW_USE_BOOST
  8461. namespace asio = boost::asio;
  8462. using error_code = boost::system::error_code;
  8463. #else
  8464. using error_code = asio::error_code;
  8465. #endif
  8466. /**
  8467. * \namespace crow::websocket
  8468. * \brief Namespace that includes the \ref Connection class
  8469. * and \ref connection struct. Useful for WebSockets connection.
  8470. *
  8471. * Used specially in crow/websocket.h, crow/app.h and crow/routing.h
  8472. */
  8473. namespace websocket
  8474. {
  8475. enum class WebSocketReadState
  8476. {
  8477. MiniHeader,
  8478. Len16,
  8479. Len64,
  8480. Mask,
  8481. Payload,
  8482. };
  8483. /// A base class for websocket connection.
  8484. struct connection
  8485. {
  8486. virtual void send_binary(std::string msg) = 0;
  8487. virtual void send_text(std::string msg) = 0;
  8488. virtual void send_ping(std::string msg) = 0;
  8489. virtual void send_pong(std::string msg) = 0;
  8490. virtual void close(std::string const& msg = "quit") = 0;
  8491. virtual std::string get_remote_ip() = 0;
  8492. virtual ~connection() = default;
  8493. void userdata(void* u) { userdata_ = u; }
  8494. void* userdata() { return userdata_; }
  8495. private:
  8496. void* userdata_;
  8497. };
  8498. // Modified version of the illustration in RFC6455 Section-5.2
  8499. //
  8500. //
  8501. // 0 1 2 3 -byte
  8502. // 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 -bit
  8503. // +-+-+-+-+-------+-+-------------+-------------------------------+
  8504. // |F|R|R|R| opcode|M| Payload len | Extended payload length |
  8505. // |I|S|S|S| (4) |A| (7) | (16/64) |
  8506. // |N|V|V|V| |S| | (if payload len==126/127) |
  8507. // | |1|2|3| |K| | |
  8508. // +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
  8509. // | Extended payload length continued, if payload len == 127 |
  8510. // + - - - - - - - - - - - - - - - +-------------------------------+
  8511. // | |Masking-key, if MASK set to 1 |
  8512. // +-------------------------------+-------------------------------+
  8513. // | Masking-key (continued) | Payload Data |
  8514. // +-------------------------------- - - - - - - - - - - - - - - - +
  8515. // : Payload Data continued ... :
  8516. // + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
  8517. // | Payload Data continued ... |
  8518. // +---------------------------------------------------------------+
  8519. //
  8520. /// A websocket connection.
  8521. template<typename Adaptor, typename Handler>
  8522. class Connection : public connection
  8523. {
  8524. public:
  8525. /// Constructor for a connection.
  8526. ///
  8527. /// Requires a request with an "Upgrade: websocket" header.<br>
  8528. /// Automatically handles the handshake.
  8529. Connection(const crow::request& req, Adaptor&& adaptor, Handler* handler, uint64_t max_payload,
  8530. std::function<void(crow::websocket::connection&)> open_handler,
  8531. std::function<void(crow::websocket::connection&, const std::string&, bool)> message_handler,
  8532. std::function<void(crow::websocket::connection&, const std::string&)> close_handler,
  8533. std::function<void(crow::websocket::connection&, const std::string&)> error_handler,
  8534. std::function<bool(const crow::request&, void**)> accept_handler):
  8535. adaptor_(std::move(adaptor)),
  8536. handler_(handler),
  8537. max_payload_bytes_(max_payload),
  8538. open_handler_(std::move(open_handler)),
  8539. message_handler_(std::move(message_handler)),
  8540. close_handler_(std::move(close_handler)),
  8541. error_handler_(std::move(error_handler)),
  8542. accept_handler_(std::move(accept_handler))
  8543. {
  8544. if (!utility::string_equals(req.get_header_value("upgrade"), "websocket"))
  8545. {
  8546. adaptor_.close();
  8547. handler_->remove_websocket(this);
  8548. delete this;
  8549. return;
  8550. }
  8551. if (accept_handler_)
  8552. {
  8553. void* ud = nullptr;
  8554. if (!accept_handler_(req, &ud))
  8555. {
  8556. adaptor_.close();
  8557. handler_->remove_websocket(this);
  8558. delete this;
  8559. return;
  8560. }
  8561. userdata(ud);
  8562. }
  8563. // Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
  8564. // Sec-WebSocket-Version: 13
  8565. std::string magic = req.get_header_value("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8566. sha1::SHA1 s;
  8567. s.processBytes(magic.data(), magic.size());
  8568. uint8_t digest[20];
  8569. s.getDigestBytes(digest);
  8570. start(crow::utility::base64encode((unsigned char*)digest, 20));
  8571. }
  8572. ~Connection() noexcept override
  8573. {
  8574. // Do not modify anchor_ here since writing shared_ptr is not atomic.
  8575. auto watch = std::weak_ptr<void>{anchor_};
  8576. // Wait until all unhandled asynchronous operations to join.
  8577. // As the deletion occurs inside 'check_destroy()', which already locks
  8578. // anchor, use count can be 1 on valid deletion context.
  8579. while (watch.use_count() > 2) // 1 for 'check_destroy() routine', 1 for 'this->anchor_'
  8580. {
  8581. std::this_thread::yield();
  8582. }
  8583. }
  8584. template<typename Callable>
  8585. struct WeakWrappedMessage
  8586. {
  8587. Callable callable;
  8588. std::weak_ptr<void> watch;
  8589. void operator()()
  8590. {
  8591. if (auto anchor = watch.lock())
  8592. {
  8593. std::move(callable)();
  8594. }
  8595. }
  8596. };
  8597. /// Send data through the socket.
  8598. template<typename CompletionHandler>
  8599. void dispatch(CompletionHandler&& handler)
  8600. {
  8601. asio::dispatch(adaptor_.get_io_service(),
  8602. WeakWrappedMessage<typename std::decay<CompletionHandler>::type>{
  8603. std::forward<CompletionHandler>(handler), anchor_});
  8604. }
  8605. /// Send data through the socket and return immediately.
  8606. template<typename CompletionHandler>
  8607. void post(CompletionHandler&& handler)
  8608. {
  8609. asio::post(adaptor_.get_io_service(),
  8610. WeakWrappedMessage<typename std::decay<CompletionHandler>::type>{
  8611. std::forward<CompletionHandler>(handler), anchor_});
  8612. }
  8613. /// Send a "Ping" message.
  8614. ///
  8615. /// Usually invoked to check if the other point is still online.
  8616. void send_ping(std::string msg) override
  8617. {
  8618. send_data(0x9, std::move(msg));
  8619. }
  8620. /// Send a "Pong" message.
  8621. ///
  8622. /// Usually automatically invoked as a response to a "Ping" message.
  8623. void send_pong(std::string msg) override
  8624. {
  8625. send_data(0xA, std::move(msg));
  8626. }
  8627. /// Send a binary encoded message.
  8628. void send_binary(std::string msg) override
  8629. {
  8630. send_data(0x2, std::move(msg));
  8631. }
  8632. /// Send a plaintext message.
  8633. void send_text(std::string msg) override
  8634. {
  8635. send_data(0x1, std::move(msg));
  8636. }
  8637. /// Send a close signal.
  8638. ///
  8639. /// Sets a flag to destroy the object once the message is sent.
  8640. void close(std::string const& msg) override
  8641. {
  8642. dispatch([this, msg]() mutable {
  8643. has_sent_close_ = true;
  8644. if (has_recv_close_ && !is_close_handler_called_)
  8645. {
  8646. is_close_handler_called_ = true;
  8647. if (close_handler_)
  8648. close_handler_(*this, msg);
  8649. }
  8650. auto header = build_header(0x8, msg.size());
  8651. write_buffers_.emplace_back(std::move(header));
  8652. write_buffers_.emplace_back(msg);
  8653. do_write();
  8654. });
  8655. }
  8656. std::string get_remote_ip() override
  8657. {
  8658. return adaptor_.remote_endpoint().address().to_string();
  8659. }
  8660. void set_max_payload_size(uint64_t payload)
  8661. {
  8662. max_payload_bytes_ = payload;
  8663. }
  8664. protected:
  8665. /// Generate the websocket headers using an opcode and the message size (in bytes).
  8666. std::string build_header(int opcode, size_t size)
  8667. {
  8668. char buf[2 + 8] = "\x80\x00";
  8669. buf[0] += opcode;
  8670. if (size < 126)
  8671. {
  8672. buf[1] += static_cast<char>(size);
  8673. return {buf, buf + 2};
  8674. }
  8675. else if (size < 0x10000)
  8676. {
  8677. buf[1] += 126;
  8678. *(uint16_t*)(buf + 2) = htons(static_cast<uint16_t>(size));
  8679. return {buf, buf + 4};
  8680. }
  8681. else
  8682. {
  8683. buf[1] += 127;
  8684. *reinterpret_cast<uint64_t*>(buf + 2) = ((1 == htonl(1)) ? static_cast<uint64_t>(size) : (static_cast<uint64_t>(htonl((size)&0xFFFFFFFF)) << 32) | htonl(static_cast<uint64_t>(size) >> 32));
  8685. return {buf, buf + 10};
  8686. }
  8687. }
  8688. /// Send the HTTP upgrade response.
  8689. ///
  8690. /// Finishes the handshake process, then starts reading messages from the socket.
  8691. void start(std::string&& hello)
  8692. {
  8693. static const std::string header =
  8694. "HTTP/1.1 101 Switching Protocols\r\n"
  8695. "Upgrade: websocket\r\n"
  8696. "Connection: Upgrade\r\n"
  8697. "Sec-WebSocket-Accept: ";
  8698. write_buffers_.emplace_back(header);
  8699. write_buffers_.emplace_back(std::move(hello));
  8700. write_buffers_.emplace_back(crlf);
  8701. write_buffers_.emplace_back(crlf);
  8702. do_write();
  8703. if (open_handler_)
  8704. open_handler_(*this);
  8705. do_read();
  8706. }
  8707. /// Read a websocket message.
  8708. ///
  8709. /// Involves:<br>
  8710. /// Handling headers (opcodes, size).<br>
  8711. /// Unmasking the payload.<br>
  8712. /// Reading the actual payload.<br>
  8713. void do_read()
  8714. {
  8715. if (has_sent_close_ && has_recv_close_)
  8716. {
  8717. close_connection_ = true;
  8718. adaptor_.shutdown_readwrite();
  8719. adaptor_.close();
  8720. check_destroy();
  8721. return;
  8722. }
  8723. is_reading = true;
  8724. switch (state_)
  8725. {
  8726. case WebSocketReadState::MiniHeader:
  8727. {
  8728. mini_header_ = 0;
  8729. //asio::async_read(adaptor_.socket(), asio::buffer(&mini_header_, 1),
  8730. adaptor_.socket().async_read_some(
  8731. asio::buffer(&mini_header_, 2),
  8732. [this](const error_code& ec, std::size_t
  8733. #ifdef CROW_ENABLE_DEBUG
  8734. bytes_transferred
  8735. #endif
  8736. )
  8737. {
  8738. is_reading = false;
  8739. mini_header_ = ntohs(mini_header_);
  8740. #ifdef CROW_ENABLE_DEBUG
  8741. if (!ec && bytes_transferred != 2)
  8742. {
  8743. throw std::runtime_error("WebSocket:MiniHeader:async_read fail:asio bug?");
  8744. }
  8745. #endif
  8746. if (!ec)
  8747. {
  8748. if ((mini_header_ & 0x80) == 0x80)
  8749. has_mask_ = true;
  8750. else //if the websocket specification is enforced and the message isn't masked, terminate the connection
  8751. {
  8752. #ifndef CROW_ENFORCE_WS_SPEC
  8753. has_mask_ = false;
  8754. #else
  8755. close_connection_ = true;
  8756. adaptor_.shutdown_readwrite();
  8757. adaptor_.close();
  8758. if (error_handler_)
  8759. error_handler_(*this, "Client connection not masked.");
  8760. check_destroy();
  8761. #endif
  8762. }
  8763. if ((mini_header_ & 0x7f) == 127)
  8764. {
  8765. state_ = WebSocketReadState::Len64;
  8766. }
  8767. else if ((mini_header_ & 0x7f) == 126)
  8768. {
  8769. state_ = WebSocketReadState::Len16;
  8770. }
  8771. else
  8772. {
  8773. remaining_length_ = mini_header_ & 0x7f;
  8774. state_ = WebSocketReadState::Mask;
  8775. }
  8776. do_read();
  8777. }
  8778. else
  8779. {
  8780. close_connection_ = true;
  8781. adaptor_.shutdown_readwrite();
  8782. adaptor_.close();
  8783. if (error_handler_)
  8784. error_handler_(*this, ec.message());
  8785. check_destroy();
  8786. }
  8787. });
  8788. }
  8789. break;
  8790. case WebSocketReadState::Len16:
  8791. {
  8792. remaining_length_ = 0;
  8793. remaining_length16_ = 0;
  8794. asio::async_read(
  8795. adaptor_.socket(), asio::buffer(&remaining_length16_, 2),
  8796. [this](const error_code& ec, std::size_t
  8797. #ifdef CROW_ENABLE_DEBUG
  8798. bytes_transferred
  8799. #endif
  8800. ) {
  8801. is_reading = false;
  8802. remaining_length16_ = ntohs(remaining_length16_);
  8803. remaining_length_ = remaining_length16_;
  8804. #ifdef CROW_ENABLE_DEBUG
  8805. if (!ec && bytes_transferred != 2)
  8806. {
  8807. throw std::runtime_error("WebSocket:Len16:async_read fail:asio bug?");
  8808. }
  8809. #endif
  8810. if (!ec)
  8811. {
  8812. state_ = WebSocketReadState::Mask;
  8813. do_read();
  8814. }
  8815. else
  8816. {
  8817. close_connection_ = true;
  8818. adaptor_.shutdown_readwrite();
  8819. adaptor_.close();
  8820. if (error_handler_)
  8821. error_handler_(*this, ec.message());
  8822. check_destroy();
  8823. }
  8824. });
  8825. }
  8826. break;
  8827. case WebSocketReadState::Len64:
  8828. {
  8829. asio::async_read(
  8830. adaptor_.socket(), asio::buffer(&remaining_length_, 8),
  8831. [this](const error_code& ec, std::size_t
  8832. #ifdef CROW_ENABLE_DEBUG
  8833. bytes_transferred
  8834. #endif
  8835. ) {
  8836. is_reading = false;
  8837. remaining_length_ = ((1 == ntohl(1)) ? (remaining_length_) : (static_cast<uint64_t>(ntohl((remaining_length_)&0xFFFFFFFF)) << 32) | ntohl((remaining_length_) >> 32));
  8838. #ifdef CROW_ENABLE_DEBUG
  8839. if (!ec && bytes_transferred != 8)
  8840. {
  8841. throw std::runtime_error("WebSocket:Len16:async_read fail:asio bug?");
  8842. }
  8843. #endif
  8844. if (!ec)
  8845. {
  8846. state_ = WebSocketReadState::Mask;
  8847. do_read();
  8848. }
  8849. else
  8850. {
  8851. close_connection_ = true;
  8852. adaptor_.shutdown_readwrite();
  8853. adaptor_.close();
  8854. if (error_handler_)
  8855. error_handler_(*this, ec.message());
  8856. check_destroy();
  8857. }
  8858. });
  8859. }
  8860. break;
  8861. case WebSocketReadState::Mask:
  8862. if (remaining_length_ > max_payload_bytes_)
  8863. {
  8864. close_connection_ = true;
  8865. adaptor_.close();
  8866. if (error_handler_)
  8867. error_handler_(*this, "Message length exceeds maximum payload.");
  8868. check_destroy();
  8869. }
  8870. else if (has_mask_)
  8871. {
  8872. asio::async_read(
  8873. adaptor_.socket(), asio::buffer((char*)&mask_, 4),
  8874. [this](const error_code& ec, std::size_t
  8875. #ifdef CROW_ENABLE_DEBUG
  8876. bytes_transferred
  8877. #endif
  8878. ) {
  8879. is_reading = false;
  8880. #ifdef CROW_ENABLE_DEBUG
  8881. if (!ec && bytes_transferred != 4)
  8882. {
  8883. throw std::runtime_error("WebSocket:Mask:async_read fail:asio bug?");
  8884. }
  8885. #endif
  8886. if (!ec)
  8887. {
  8888. state_ = WebSocketReadState::Payload;
  8889. do_read();
  8890. }
  8891. else
  8892. {
  8893. close_connection_ = true;
  8894. if (error_handler_)
  8895. error_handler_(*this, ec.message());
  8896. adaptor_.shutdown_readwrite();
  8897. adaptor_.close();
  8898. check_destroy();
  8899. }
  8900. });
  8901. }
  8902. else
  8903. {
  8904. state_ = WebSocketReadState::Payload;
  8905. do_read();
  8906. }
  8907. break;
  8908. case WebSocketReadState::Payload:
  8909. {
  8910. auto to_read = static_cast<std::uint64_t>(buffer_.size());
  8911. if (remaining_length_ < to_read)
  8912. to_read = remaining_length_;
  8913. adaptor_.socket().async_read_some(
  8914. asio::buffer(buffer_, static_cast<std::size_t>(to_read)),
  8915. [this](const error_code& ec, std::size_t bytes_transferred) {
  8916. is_reading = false;
  8917. if (!ec)
  8918. {
  8919. fragment_.insert(fragment_.end(), buffer_.begin(), buffer_.begin() + bytes_transferred);
  8920. remaining_length_ -= bytes_transferred;
  8921. if (remaining_length_ == 0)
  8922. {
  8923. if (handle_fragment())
  8924. {
  8925. state_ = WebSocketReadState::MiniHeader;
  8926. do_read();
  8927. }
  8928. }
  8929. else
  8930. do_read();
  8931. }
  8932. else
  8933. {
  8934. close_connection_ = true;
  8935. if (error_handler_)
  8936. error_handler_(*this, ec.message());
  8937. adaptor_.shutdown_readwrite();
  8938. adaptor_.close();
  8939. check_destroy();
  8940. }
  8941. });
  8942. }
  8943. break;
  8944. }
  8945. }
  8946. /// Check if the FIN bit is set.
  8947. bool is_FIN()
  8948. {
  8949. return mini_header_ & 0x8000;
  8950. }
  8951. /// Extract the opcode from the header.
  8952. int opcode()
  8953. {
  8954. return (mini_header_ & 0x0f00) >> 8;
  8955. }
  8956. /// Process the payload fragment.
  8957. ///
  8958. /// Unmasks the fragment, checks the opcode, merges fragments into 1 message body, and calls the appropriate handler.
  8959. bool handle_fragment()
  8960. {
  8961. if (has_mask_)
  8962. {
  8963. for (decltype(fragment_.length()) i = 0; i < fragment_.length(); i++)
  8964. {
  8965. fragment_[i] ^= ((char*)&mask_)[i % 4];
  8966. }
  8967. }
  8968. switch (opcode())
  8969. {
  8970. case 0: // Continuation
  8971. {
  8972. message_ += fragment_;
  8973. if (is_FIN())
  8974. {
  8975. if (message_handler_)
  8976. message_handler_(*this, message_, is_binary_);
  8977. message_.clear();
  8978. }
  8979. }
  8980. break;
  8981. case 1: // Text
  8982. {
  8983. is_binary_ = false;
  8984. message_ += fragment_;
  8985. if (is_FIN())
  8986. {
  8987. if (message_handler_)
  8988. message_handler_(*this, message_, is_binary_);
  8989. message_.clear();
  8990. }
  8991. }
  8992. break;
  8993. case 2: // Binary
  8994. {
  8995. is_binary_ = true;
  8996. message_ += fragment_;
  8997. if (is_FIN())
  8998. {
  8999. if (message_handler_)
  9000. message_handler_(*this, message_, is_binary_);
  9001. message_.clear();
  9002. }
  9003. }
  9004. break;
  9005. case 0x8: // Close
  9006. {
  9007. has_recv_close_ = true;
  9008. if (!has_sent_close_)
  9009. {
  9010. close(fragment_);
  9011. }
  9012. else
  9013. {
  9014. adaptor_.shutdown_readwrite();
  9015. adaptor_.close();
  9016. close_connection_ = true;
  9017. if (!is_close_handler_called_)
  9018. {
  9019. if (close_handler_)
  9020. close_handler_(*this, fragment_);
  9021. is_close_handler_called_ = true;
  9022. }
  9023. check_destroy();
  9024. return false;
  9025. }
  9026. }
  9027. break;
  9028. case 0x9: // Ping
  9029. {
  9030. send_pong(fragment_);
  9031. }
  9032. break;
  9033. case 0xA: // Pong
  9034. {
  9035. pong_received_ = true;
  9036. }
  9037. break;
  9038. }
  9039. fragment_.clear();
  9040. return true;
  9041. }
  9042. /// Send the buffers' data through the socket.
  9043. ///
  9044. /// Also destroys the object if the Close flag is set.
  9045. void do_write()
  9046. {
  9047. if (sending_buffers_.empty())
  9048. {
  9049. sending_buffers_.swap(write_buffers_);
  9050. std::vector<asio::const_buffer> buffers;
  9051. buffers.reserve(sending_buffers_.size());
  9052. for (auto& s : sending_buffers_)
  9053. {
  9054. buffers.emplace_back(asio::buffer(s));
  9055. }
  9056. auto watch = std::weak_ptr<void>{anchor_};
  9057. asio::async_write(
  9058. adaptor_.socket(), buffers,
  9059. [&, watch](const error_code& ec, std::size_t /*bytes_transferred*/) {
  9060. if (!ec && !close_connection_)
  9061. {
  9062. sending_buffers_.clear();
  9063. if (!write_buffers_.empty())
  9064. do_write();
  9065. if (has_sent_close_)
  9066. close_connection_ = true;
  9067. }
  9068. else
  9069. {
  9070. auto anchor = watch.lock();
  9071. if (anchor == nullptr) { return; }
  9072. sending_buffers_.clear();
  9073. close_connection_ = true;
  9074. check_destroy();
  9075. }
  9076. });
  9077. }
  9078. }
  9079. /// Destroy the Connection.
  9080. void check_destroy()
  9081. {
  9082. //if (has_sent_close_ && has_recv_close_)
  9083. if (!is_close_handler_called_)
  9084. if (close_handler_)
  9085. close_handler_(*this, "uncleanly");
  9086. handler_->remove_websocket(this);
  9087. if (sending_buffers_.empty() && !is_reading)
  9088. delete this;
  9089. }
  9090. struct SendMessageType
  9091. {
  9092. std::string payload;
  9093. Connection* self;
  9094. int opcode;
  9095. void operator()()
  9096. {
  9097. self->send_data_impl(this);
  9098. }
  9099. };
  9100. void send_data_impl(SendMessageType* s)
  9101. {
  9102. auto header = build_header(s->opcode, s->payload.size());
  9103. write_buffers_.emplace_back(std::move(header));
  9104. write_buffers_.emplace_back(std::move(s->payload));
  9105. do_write();
  9106. }
  9107. void send_data(int opcode, std::string&& msg)
  9108. {
  9109. SendMessageType event_arg{
  9110. std::move(msg),
  9111. this,
  9112. opcode};
  9113. post(std::move(event_arg));
  9114. }
  9115. private:
  9116. Adaptor adaptor_;
  9117. Handler* handler_;
  9118. std::vector<std::string> sending_buffers_;
  9119. std::vector<std::string> write_buffers_;
  9120. std::array<char, 4096> buffer_;
  9121. bool is_binary_;
  9122. std::string message_;
  9123. std::string fragment_;
  9124. WebSocketReadState state_{WebSocketReadState::MiniHeader};
  9125. uint16_t remaining_length16_{0};
  9126. uint64_t remaining_length_{0};
  9127. uint64_t max_payload_bytes_{UINT64_MAX};
  9128. bool close_connection_{false};
  9129. bool is_reading{false};
  9130. bool has_mask_{false};
  9131. uint32_t mask_;
  9132. uint16_t mini_header_;
  9133. bool has_sent_close_{false};
  9134. bool has_recv_close_{false};
  9135. bool error_occurred_{false};
  9136. bool pong_received_{false};
  9137. bool is_close_handler_called_{false};
  9138. std::shared_ptr<void> anchor_ = std::make_shared<int>(); // Value is just for placeholding
  9139. std::function<void(crow::websocket::connection&)> open_handler_;
  9140. std::function<void(crow::websocket::connection&, const std::string&, bool)> message_handler_;
  9141. std::function<void(crow::websocket::connection&, const std::string&)> close_handler_;
  9142. std::function<void(crow::websocket::connection&, const std::string&)> error_handler_;
  9143. std::function<bool(const crow::request&, void**)> accept_handler_;
  9144. };
  9145. } // namespace websocket
  9146. } // namespace crow
  9147. namespace crow
  9148. {
  9149. constexpr const char VERSION[] = "master";
  9150. }
  9151. #ifdef CROW_USE_BOOST
  9152. #include <boost/asio.hpp>
  9153. #ifdef CROW_ENABLE_SSL
  9154. #include <boost/asio/ssl.hpp>
  9155. #endif
  9156. #else
  9157. #ifndef ASIO_STANDALONE
  9158. #define ASIO_STANDALONE
  9159. #endif
  9160. #include <asio.hpp>
  9161. #ifdef CROW_ENABLE_SSL
  9162. #include <asio/ssl.hpp>
  9163. #endif
  9164. #endif
  9165. #include <atomic>
  9166. #include <chrono>
  9167. #include <cstdint>
  9168. #include <future>
  9169. #include <memory>
  9170. #include <vector>
  9171. namespace crow // NOTE: Already documented in "crow/app.h"
  9172. {
  9173. #ifdef CROW_USE_BOOST
  9174. namespace asio = boost::asio;
  9175. using error_code = boost::system::error_code;
  9176. #else
  9177. using error_code = asio::error_code;
  9178. #endif
  9179. using tcp = asio::ip::tcp;
  9180. template<typename Handler, typename Adaptor = SocketAdaptor, typename... Middlewares>
  9181. class Server
  9182. {
  9183. public:
  9184. Server(Handler* handler, std::string bindaddr, uint16_t port, std::string server_name = std::string("Crow/") + VERSION, std::tuple<Middlewares...>* middlewares = nullptr, uint16_t concurrency = 1, uint8_t timeout = 5, typename Adaptor::context* adaptor_ctx = nullptr):
  9185. acceptor_(io_service_, tcp::endpoint(asio::ip::address::from_string(bindaddr), port)),
  9186. signals_(io_service_),
  9187. tick_timer_(io_service_),
  9188. handler_(handler),
  9189. concurrency_(concurrency),
  9190. timeout_(timeout),
  9191. server_name_(server_name),
  9192. port_(port),
  9193. bindaddr_(bindaddr),
  9194. task_queue_length_pool_(concurrency_ - 1),
  9195. middlewares_(middlewares),
  9196. adaptor_ctx_(adaptor_ctx)
  9197. {}
  9198. void set_tick_function(std::chrono::milliseconds d, std::function<void()> f)
  9199. {
  9200. tick_interval_ = d;
  9201. tick_function_ = f;
  9202. }
  9203. void on_tick()
  9204. {
  9205. tick_function_();
  9206. tick_timer_.expires_after(std::chrono::milliseconds(tick_interval_.count()));
  9207. tick_timer_.async_wait([this](const error_code& ec) {
  9208. if (ec)
  9209. return;
  9210. on_tick();
  9211. });
  9212. }
  9213. void run()
  9214. {
  9215. uint16_t worker_thread_count = concurrency_ - 1;
  9216. for (int i = 0; i < worker_thread_count; i++)
  9217. io_service_pool_.emplace_back(new asio::io_service());
  9218. get_cached_date_str_pool_.resize(worker_thread_count);
  9219. task_timer_pool_.resize(worker_thread_count);
  9220. std::vector<std::future<void>> v;
  9221. std::atomic<int> init_count(0);
  9222. for (uint16_t i = 0; i < worker_thread_count; i++)
  9223. v.push_back(
  9224. std::async(
  9225. std::launch::async, [this, i, &init_count] {
  9226. // thread local date string get function
  9227. auto last = std::chrono::steady_clock::now();
  9228. std::string date_str;
  9229. auto update_date_str = [&] {
  9230. auto last_time_t = time(0);
  9231. tm my_tm;
  9232. #if defined(_MSC_VER) || defined(__MINGW32__)
  9233. gmtime_s(&my_tm, &last_time_t);
  9234. #else
  9235. gmtime_r(&last_time_t, &my_tm);
  9236. #endif
  9237. date_str.resize(100);
  9238. size_t date_str_sz = strftime(&date_str[0], 99, "%a, %d %b %Y %H:%M:%S GMT", &my_tm);
  9239. date_str.resize(date_str_sz);
  9240. };
  9241. update_date_str();
  9242. get_cached_date_str_pool_[i] = [&]() -> std::string {
  9243. if (std::chrono::steady_clock::now() - last >= std::chrono::seconds(1))
  9244. {
  9245. last = std::chrono::steady_clock::now();
  9246. update_date_str();
  9247. }
  9248. return date_str;
  9249. };
  9250. // initializing task timers
  9251. detail::task_timer task_timer(*io_service_pool_[i]);
  9252. task_timer.set_default_timeout(timeout_);
  9253. task_timer_pool_[i] = &task_timer;
  9254. task_queue_length_pool_[i] = 0;
  9255. init_count++;
  9256. while (1)
  9257. {
  9258. try
  9259. {
  9260. if (io_service_pool_[i]->run() == 0)
  9261. {
  9262. // when io_service.run returns 0, there are no more works to do.
  9263. break;
  9264. }
  9265. }
  9266. catch (std::exception& e)
  9267. {
  9268. CROW_LOG_ERROR << "Worker Crash: An uncaught exception occurred: " << e.what();
  9269. }
  9270. }
  9271. }));
  9272. if (tick_function_ && tick_interval_.count() > 0)
  9273. {
  9274. tick_timer_.expires_after(std::chrono::milliseconds(tick_interval_.count()));
  9275. tick_timer_.async_wait(
  9276. [this](const error_code& ec) {
  9277. if (ec)
  9278. return;
  9279. on_tick();
  9280. });
  9281. }
  9282. port_ = acceptor_.local_endpoint().port();
  9283. handler_->port(port_);
  9284. CROW_LOG_INFO << server_name_ << " server is running at " << (handler_->ssl_used() ? "https://" : "http://") << bindaddr_ << ":" << acceptor_.local_endpoint().port() << " using " << concurrency_ << " threads";
  9285. CROW_LOG_INFO << "Call `app.loglevel(crow::LogLevel::Warning)` to hide Info level logs.";
  9286. signals_.async_wait(
  9287. [&](const error_code& /*error*/, int /*signal_number*/) {
  9288. stop();
  9289. });
  9290. while (worker_thread_count != init_count)
  9291. std::this_thread::yield();
  9292. do_accept();
  9293. std::thread(
  9294. [this] {
  9295. notify_start();
  9296. io_service_.run();
  9297. CROW_LOG_INFO << "Exiting.";
  9298. })
  9299. .join();
  9300. }
  9301. void stop()
  9302. {
  9303. shutting_down_ = true; // Prevent the acceptor from taking new connections
  9304. for (auto& io_service : io_service_pool_)
  9305. {
  9306. if (io_service != nullptr)
  9307. {
  9308. CROW_LOG_INFO << "Closing IO service " << &io_service;
  9309. io_service->stop(); // Close all io_services (and HTTP connections)
  9310. }
  9311. }
  9312. CROW_LOG_INFO << "Closing main IO service (" << &io_service_ << ')';
  9313. io_service_.stop(); // Close main io_service
  9314. }
  9315. /// Wait until the server has properly started
  9316. void wait_for_start()
  9317. {
  9318. std::unique_lock<std::mutex> lock(start_mutex_);
  9319. if (!server_started_)
  9320. cv_started_.wait(lock);
  9321. }
  9322. void signal_clear()
  9323. {
  9324. signals_.clear();
  9325. }
  9326. void signal_add(int signal_number)
  9327. {
  9328. signals_.add(signal_number);
  9329. }
  9330. private:
  9331. uint16_t pick_io_service_idx()
  9332. {
  9333. uint16_t min_queue_idx = 0;
  9334. // TODO improve load balancing
  9335. // size_t is used here to avoid the security issue https://codeql.github.com/codeql-query-help/cpp/cpp-comparison-with-wider-type/
  9336. // even though the max value of this can be only uint16_t as concurrency is uint16_t.
  9337. for (size_t i = 1; i < task_queue_length_pool_.size() && task_queue_length_pool_[min_queue_idx] > 0; i++)
  9338. // No need to check other io_services if the current one has no tasks
  9339. {
  9340. if (task_queue_length_pool_[i] < task_queue_length_pool_[min_queue_idx])
  9341. min_queue_idx = i;
  9342. }
  9343. return min_queue_idx;
  9344. }
  9345. void do_accept()
  9346. {
  9347. if (!shutting_down_)
  9348. {
  9349. uint16_t service_idx = pick_io_service_idx();
  9350. asio::io_service& is = *io_service_pool_[service_idx];
  9351. task_queue_length_pool_[service_idx]++;
  9352. CROW_LOG_DEBUG << &is << " {" << service_idx << "} queue length: " << task_queue_length_pool_[service_idx];
  9353. auto p = std::make_shared<Connection<Adaptor, Handler, Middlewares...>>(
  9354. is, handler_, server_name_, middlewares_,
  9355. get_cached_date_str_pool_[service_idx], *task_timer_pool_[service_idx], adaptor_ctx_, task_queue_length_pool_[service_idx]);
  9356. acceptor_.async_accept(
  9357. p->socket(),
  9358. [this, p, &is, service_idx](error_code ec) {
  9359. if (!ec)
  9360. {
  9361. is.post(
  9362. [p] {
  9363. p->start();
  9364. });
  9365. }
  9366. else
  9367. {
  9368. task_queue_length_pool_[service_idx]--;
  9369. CROW_LOG_DEBUG << &is << " {" << service_idx << "} queue length: " << task_queue_length_pool_[service_idx];
  9370. }
  9371. do_accept();
  9372. });
  9373. }
  9374. }
  9375. /// Notify anything using `wait_for_start()` to proceed
  9376. void notify_start()
  9377. {
  9378. std::unique_lock<std::mutex> lock(start_mutex_);
  9379. server_started_ = true;
  9380. cv_started_.notify_all();
  9381. }
  9382. private:
  9383. std::vector<std::unique_ptr<asio::io_service>> io_service_pool_;
  9384. asio::io_service io_service_;
  9385. std::vector<detail::task_timer*> task_timer_pool_;
  9386. std::vector<std::function<std::string()>> get_cached_date_str_pool_;
  9387. tcp::acceptor acceptor_;
  9388. bool shutting_down_ = false;
  9389. bool server_started_{false};
  9390. std::condition_variable cv_started_;
  9391. std::mutex start_mutex_;
  9392. asio::signal_set signals_;
  9393. asio::basic_waitable_timer<std::chrono::high_resolution_clock> tick_timer_;
  9394. Handler* handler_;
  9395. uint16_t concurrency_{2};
  9396. std::uint8_t timeout_;
  9397. std::string server_name_;
  9398. uint16_t port_;
  9399. std::string bindaddr_;
  9400. std::vector<std::atomic<unsigned int>> task_queue_length_pool_;
  9401. std::chrono::milliseconds tick_interval_;
  9402. std::function<void()> tick_function_;
  9403. std::tuple<Middlewares...>* middlewares_;
  9404. typename Adaptor::context* adaptor_ctx_;
  9405. };
  9406. } // namespace crow
  9407. #include <string>
  9408. #include <vector>
  9409. #include <fstream>
  9410. #include <iterator>
  9411. #include <functional>
  9412. namespace crow
  9413. {
  9414. namespace mustache
  9415. {
  9416. using context = json::wvalue;
  9417. template_t load(const std::string& filename);
  9418. class invalid_template_exception : public std::exception
  9419. {
  9420. public:
  9421. invalid_template_exception(const std::string& msg):
  9422. msg("crow::mustache error: " + msg)
  9423. {}
  9424. virtual const char* what() const throw()
  9425. {
  9426. return msg.c_str();
  9427. }
  9428. std::string msg;
  9429. };
  9430. struct rendered_template : returnable
  9431. {
  9432. rendered_template():
  9433. returnable("text/html") {}
  9434. rendered_template(std::string& body):
  9435. returnable("text/html"), body_(std::move(body)) {}
  9436. std::string body_;
  9437. std::string dump() const override
  9438. {
  9439. return body_;
  9440. }
  9441. };
  9442. enum class ActionType
  9443. {
  9444. Ignore,
  9445. Tag,
  9446. UnescapeTag,
  9447. OpenBlock,
  9448. CloseBlock,
  9449. ElseBlock,
  9450. Partial,
  9451. };
  9452. struct Action
  9453. {
  9454. int start;
  9455. int end;
  9456. int pos;
  9457. ActionType t;
  9458. Action(ActionType t, size_t start, size_t end, size_t pos = 0):
  9459. start(static_cast<int>(start)), end(static_cast<int>(end)), pos(static_cast<int>(pos)), t(t)
  9460. {
  9461. }
  9462. };
  9463. /// A mustache template object.
  9464. class template_t
  9465. {
  9466. public:
  9467. template_t(std::string body):
  9468. body_(std::move(body))
  9469. {
  9470. // {{ {{# {{/ {{^ {{! {{> {{=
  9471. parse();
  9472. }
  9473. private:
  9474. std::string tag_name(const Action& action) const
  9475. {
  9476. return body_.substr(action.start, action.end - action.start);
  9477. }
  9478. auto find_context(const std::string& name, const std::vector<const context*>& stack, bool shouldUseOnlyFirstStackValue = false) const -> std::pair<bool, const context&>
  9479. {
  9480. if (name == ".")
  9481. {
  9482. return {true, *stack.back()};
  9483. }
  9484. static json::wvalue empty_str;
  9485. empty_str = "";
  9486. int dotPosition = name.find(".");
  9487. if (dotPosition == static_cast<int>(name.npos))
  9488. {
  9489. for (auto it = stack.rbegin(); it != stack.rend(); ++it)
  9490. {
  9491. if ((*it)->t() == json::type::Object)
  9492. {
  9493. if ((*it)->count(name))
  9494. return {true, (**it)[name]};
  9495. }
  9496. }
  9497. }
  9498. else
  9499. {
  9500. std::vector<int> dotPositions;
  9501. dotPositions.push_back(-1);
  9502. while (dotPosition != static_cast<int>(name.npos))
  9503. {
  9504. dotPositions.push_back(dotPosition);
  9505. dotPosition = name.find(".", dotPosition + 1);
  9506. }
  9507. dotPositions.push_back(name.size());
  9508. std::vector<std::string> names;
  9509. names.reserve(dotPositions.size() - 1);
  9510. for (int i = 1; i < static_cast<int>(dotPositions.size()); i++)
  9511. names.emplace_back(name.substr(dotPositions[i - 1] + 1, dotPositions[i] - dotPositions[i - 1] - 1));
  9512. for (auto it = stack.rbegin(); it != stack.rend(); ++it)
  9513. {
  9514. const context* view = *it;
  9515. bool found = true;
  9516. for (auto jt = names.begin(); jt != names.end(); ++jt)
  9517. {
  9518. if (view->t() == json::type::Object &&
  9519. view->count(*jt))
  9520. {
  9521. view = &(*view)[*jt];
  9522. }
  9523. else
  9524. {
  9525. if (shouldUseOnlyFirstStackValue)
  9526. {
  9527. return {false, empty_str};
  9528. }
  9529. found = false;
  9530. break;
  9531. }
  9532. }
  9533. if (found)
  9534. return {true, *view};
  9535. }
  9536. }
  9537. return {false, empty_str};
  9538. }
  9539. void escape(const std::string& in, std::string& out) const
  9540. {
  9541. out.reserve(out.size() + in.size());
  9542. for (auto it = in.begin(); it != in.end(); ++it)
  9543. {
  9544. switch (*it)
  9545. {
  9546. case '&': out += "&amp;"; break;
  9547. case '<': out += "&lt;"; break;
  9548. case '>': out += "&gt;"; break;
  9549. case '"': out += "&quot;"; break;
  9550. case '\'': out += "&#39;"; break;
  9551. case '/': out += "&#x2F;"; break;
  9552. case '`': out += "&#x60;"; break;
  9553. case '=': out += "&#x3D;"; break;
  9554. default: out += *it; break;
  9555. }
  9556. }
  9557. }
  9558. bool isTagInsideObjectBlock(const int& current, const std::vector<const context*>& stack) const
  9559. {
  9560. int openedBlock = 0;
  9561. for (int i = current; i > 0; --i)
  9562. {
  9563. auto& action = actions_[i - 1];
  9564. if (action.t == ActionType::OpenBlock)
  9565. {
  9566. if (openedBlock == 0 && (*stack.rbegin())->t() == json::type::Object)
  9567. {
  9568. return true;
  9569. }
  9570. --openedBlock;
  9571. }
  9572. else if (action.t == ActionType::CloseBlock)
  9573. {
  9574. ++openedBlock;
  9575. }
  9576. }
  9577. return false;
  9578. }
  9579. void render_internal(int actionBegin, int actionEnd, std::vector<const context*>& stack, std::string& out, int indent) const
  9580. {
  9581. int current = actionBegin;
  9582. if (indent)
  9583. out.insert(out.size(), indent, ' ');
  9584. while (current < actionEnd)
  9585. {
  9586. auto& fragment = fragments_[current];
  9587. auto& action = actions_[current];
  9588. render_fragment(fragment, indent, out);
  9589. switch (action.t)
  9590. {
  9591. case ActionType::Ignore:
  9592. // do nothing
  9593. break;
  9594. case ActionType::Partial:
  9595. {
  9596. std::string partial_name = tag_name(action);
  9597. auto partial_templ = load(partial_name);
  9598. int partial_indent = action.pos;
  9599. partial_templ.render_internal(0, partial_templ.fragments_.size() - 1, stack, out, partial_indent ? indent + partial_indent : 0);
  9600. }
  9601. break;
  9602. case ActionType::UnescapeTag:
  9603. case ActionType::Tag:
  9604. {
  9605. bool shouldUseOnlyFirstStackValue = false;
  9606. if (isTagInsideObjectBlock(current, stack))
  9607. {
  9608. shouldUseOnlyFirstStackValue = true;
  9609. }
  9610. auto optional_ctx = find_context(tag_name(action), stack, shouldUseOnlyFirstStackValue);
  9611. auto& ctx = optional_ctx.second;
  9612. switch (ctx.t())
  9613. {
  9614. case json::type::False:
  9615. case json::type::True:
  9616. case json::type::Number:
  9617. out += ctx.dump();
  9618. break;
  9619. case json::type::String:
  9620. if (action.t == ActionType::Tag)
  9621. escape(ctx.s, out);
  9622. else
  9623. out += ctx.s;
  9624. break;
  9625. case json::type::Function:
  9626. {
  9627. std::string execute_result = ctx.execute();
  9628. while (execute_result.find("{{") != std::string::npos)
  9629. {
  9630. template_t result_plug(execute_result);
  9631. execute_result = result_plug.render_string(*(stack[0]));
  9632. }
  9633. if (action.t == ActionType::Tag)
  9634. escape(execute_result, out);
  9635. else
  9636. out += execute_result;
  9637. }
  9638. break;
  9639. default:
  9640. throw std::runtime_error("not implemented tag type" + utility::lexical_cast<std::string>(static_cast<int>(ctx.t())));
  9641. }
  9642. }
  9643. break;
  9644. case ActionType::ElseBlock:
  9645. {
  9646. static context nullContext;
  9647. auto optional_ctx = find_context(tag_name(action), stack);
  9648. if (!optional_ctx.first)
  9649. {
  9650. stack.emplace_back(&nullContext);
  9651. break;
  9652. }
  9653. auto& ctx = optional_ctx.second;
  9654. switch (ctx.t())
  9655. {
  9656. case json::type::List:
  9657. if (ctx.l && !ctx.l->empty())
  9658. current = action.pos;
  9659. else
  9660. stack.emplace_back(&nullContext);
  9661. break;
  9662. case json::type::False:
  9663. case json::type::Null:
  9664. stack.emplace_back(&nullContext);
  9665. break;
  9666. default:
  9667. current = action.pos;
  9668. break;
  9669. }
  9670. break;
  9671. }
  9672. case ActionType::OpenBlock:
  9673. {
  9674. auto optional_ctx = find_context(tag_name(action), stack);
  9675. if (!optional_ctx.first)
  9676. {
  9677. current = action.pos;
  9678. break;
  9679. }
  9680. auto& ctx = optional_ctx.second;
  9681. switch (ctx.t())
  9682. {
  9683. case json::type::List:
  9684. if (ctx.l)
  9685. for (auto it = ctx.l->begin(); it != ctx.l->end(); ++it)
  9686. {
  9687. stack.push_back(&*it);
  9688. render_internal(current + 1, action.pos, stack, out, indent);
  9689. stack.pop_back();
  9690. }
  9691. current = action.pos;
  9692. break;
  9693. case json::type::Number:
  9694. case json::type::String:
  9695. case json::type::Object:
  9696. case json::type::True:
  9697. stack.push_back(&ctx);
  9698. break;
  9699. case json::type::False:
  9700. case json::type::Null:
  9701. current = action.pos;
  9702. break;
  9703. default:
  9704. throw std::runtime_error("{{#: not implemented context type: " + utility::lexical_cast<std::string>(static_cast<int>(ctx.t())));
  9705. break;
  9706. }
  9707. break;
  9708. }
  9709. case ActionType::CloseBlock:
  9710. stack.pop_back();
  9711. break;
  9712. default:
  9713. throw std::runtime_error("not implemented " + utility::lexical_cast<std::string>(static_cast<int>(action.t)));
  9714. }
  9715. current++;
  9716. }
  9717. auto& fragment = fragments_[actionEnd];
  9718. render_fragment(fragment, indent, out);
  9719. }
  9720. void render_fragment(const std::pair<int, int> fragment, int indent, std::string& out) const
  9721. {
  9722. if (indent)
  9723. {
  9724. for (int i = fragment.first; i < fragment.second; i++)
  9725. {
  9726. out += body_[i];
  9727. if (body_[i] == '\n' && i + 1 != static_cast<int>(body_.size()))
  9728. out.insert(out.size(), indent, ' ');
  9729. }
  9730. }
  9731. else
  9732. out.insert(out.size(), body_, fragment.first, fragment.second - fragment.first);
  9733. }
  9734. public:
  9735. /// Output a returnable template from this mustache template
  9736. rendered_template render() const
  9737. {
  9738. context empty_ctx;
  9739. std::vector<const context*> stack;
  9740. stack.emplace_back(&empty_ctx);
  9741. std::string ret;
  9742. render_internal(0, fragments_.size() - 1, stack, ret, 0);
  9743. return rendered_template(ret);
  9744. }
  9745. /// Apply the values from the context provided and output a returnable template from this mustache template
  9746. rendered_template render(const context& ctx) const
  9747. {
  9748. std::vector<const context*> stack;
  9749. stack.emplace_back(&ctx);
  9750. std::string ret;
  9751. render_internal(0, fragments_.size() - 1, stack, ret, 0);
  9752. return rendered_template(ret);
  9753. }
  9754. /// Apply the values from the context provided and output a returnable template from this mustache template
  9755. rendered_template render(const context&& ctx) const
  9756. {
  9757. return render(ctx);
  9758. }
  9759. /// Output a returnable template from this mustache template
  9760. std::string render_string() const
  9761. {
  9762. context empty_ctx;
  9763. std::vector<const context*> stack;
  9764. stack.emplace_back(&empty_ctx);
  9765. std::string ret;
  9766. render_internal(0, fragments_.size() - 1, stack, ret, 0);
  9767. return ret;
  9768. }
  9769. /// Apply the values from the context provided and output a returnable template from this mustache template
  9770. std::string render_string(const context& ctx) const
  9771. {
  9772. std::vector<const context*> stack;
  9773. stack.emplace_back(&ctx);
  9774. std::string ret;
  9775. render_internal(0, fragments_.size() - 1, stack, ret, 0);
  9776. return ret;
  9777. }
  9778. private:
  9779. void parse()
  9780. {
  9781. std::string tag_open = "{{";
  9782. std::string tag_close = "}}";
  9783. std::vector<int> blockPositions;
  9784. size_t current = 0;
  9785. while (1)
  9786. {
  9787. size_t idx = body_.find(tag_open, current);
  9788. if (idx == body_.npos)
  9789. {
  9790. fragments_.emplace_back(static_cast<int>(current), static_cast<int>(body_.size()));
  9791. actions_.emplace_back(ActionType::Ignore, 0, 0);
  9792. break;
  9793. }
  9794. fragments_.emplace_back(static_cast<int>(current), static_cast<int>(idx));
  9795. idx += tag_open.size();
  9796. size_t endIdx = body_.find(tag_close, idx);
  9797. if (endIdx == idx)
  9798. {
  9799. throw invalid_template_exception("empty tag is not allowed");
  9800. }
  9801. if (endIdx == body_.npos)
  9802. {
  9803. // error, no matching tag
  9804. throw invalid_template_exception("not matched opening tag");
  9805. }
  9806. current = endIdx + tag_close.size();
  9807. switch (body_[idx])
  9808. {
  9809. case '#':
  9810. idx++;
  9811. while (body_[idx] == ' ')
  9812. idx++;
  9813. while (body_[endIdx - 1] == ' ')
  9814. endIdx--;
  9815. blockPositions.emplace_back(static_cast<int>(actions_.size()));
  9816. actions_.emplace_back(ActionType::OpenBlock, idx, endIdx);
  9817. break;
  9818. case '/':
  9819. idx++;
  9820. while (body_[idx] == ' ')
  9821. idx++;
  9822. while (body_[endIdx - 1] == ' ')
  9823. endIdx--;
  9824. {
  9825. auto& matched = actions_[blockPositions.back()];
  9826. if (body_.compare(idx, endIdx - idx,
  9827. body_, matched.start, matched.end - matched.start) != 0)
  9828. {
  9829. throw invalid_template_exception("not matched {{# {{/ pair: " +
  9830. body_.substr(matched.start, matched.end - matched.start) + ", " +
  9831. body_.substr(idx, endIdx - idx));
  9832. }
  9833. matched.pos = actions_.size();
  9834. }
  9835. actions_.emplace_back(ActionType::CloseBlock, idx, endIdx, blockPositions.back());
  9836. blockPositions.pop_back();
  9837. break;
  9838. case '^':
  9839. idx++;
  9840. while (body_[idx] == ' ')
  9841. idx++;
  9842. while (body_[endIdx - 1] == ' ')
  9843. endIdx--;
  9844. blockPositions.emplace_back(static_cast<int>(actions_.size()));
  9845. actions_.emplace_back(ActionType::ElseBlock, idx, endIdx);
  9846. break;
  9847. case '!':
  9848. // do nothing action
  9849. actions_.emplace_back(ActionType::Ignore, idx + 1, endIdx);
  9850. break;
  9851. case '>': // partial
  9852. idx++;
  9853. while (body_[idx] == ' ')
  9854. idx++;
  9855. while (body_[endIdx - 1] == ' ')
  9856. endIdx--;
  9857. actions_.emplace_back(ActionType::Partial, idx, endIdx);
  9858. break;
  9859. case '{':
  9860. if (tag_open != "{{" || tag_close != "}}")
  9861. throw invalid_template_exception("cannot use triple mustache when delimiter changed");
  9862. idx++;
  9863. if (body_[endIdx + 2] != '}')
  9864. {
  9865. throw invalid_template_exception("{{{: }}} not matched");
  9866. }
  9867. while (body_[idx] == ' ')
  9868. idx++;
  9869. while (body_[endIdx - 1] == ' ')
  9870. endIdx--;
  9871. actions_.emplace_back(ActionType::UnescapeTag, idx, endIdx);
  9872. current++;
  9873. break;
  9874. case '&':
  9875. idx++;
  9876. while (body_[idx] == ' ')
  9877. idx++;
  9878. while (body_[endIdx - 1] == ' ')
  9879. endIdx--;
  9880. actions_.emplace_back(ActionType::UnescapeTag, idx, endIdx);
  9881. break;
  9882. case '=':
  9883. // tag itself is no-op
  9884. idx++;
  9885. actions_.emplace_back(ActionType::Ignore, idx, endIdx);
  9886. endIdx--;
  9887. if (body_[endIdx] != '=')
  9888. throw invalid_template_exception("{{=: not matching = tag: " + body_.substr(idx, endIdx - idx));
  9889. endIdx--;
  9890. while (body_[idx] == ' ')
  9891. idx++;
  9892. while (body_[endIdx] == ' ')
  9893. endIdx--;
  9894. endIdx++;
  9895. {
  9896. bool succeeded = false;
  9897. for (size_t i = idx; i < endIdx; i++)
  9898. {
  9899. if (body_[i] == ' ')
  9900. {
  9901. tag_open = body_.substr(idx, i - idx);
  9902. while (body_[i] == ' ')
  9903. i++;
  9904. tag_close = body_.substr(i, endIdx - i);
  9905. if (tag_open.empty())
  9906. throw invalid_template_exception("{{=: empty open tag");
  9907. if (tag_close.empty())
  9908. throw invalid_template_exception("{{=: empty close tag");
  9909. if (tag_close.find(" ") != tag_close.npos)
  9910. throw invalid_template_exception("{{=: invalid open/close tag: " + tag_open + " " + tag_close);
  9911. succeeded = true;
  9912. break;
  9913. }
  9914. }
  9915. if (!succeeded)
  9916. throw invalid_template_exception("{{=: cannot find space between new open/close tags");
  9917. }
  9918. break;
  9919. default:
  9920. // normal tag case;
  9921. while (body_[idx] == ' ')
  9922. idx++;
  9923. while (body_[endIdx - 1] == ' ')
  9924. endIdx--;
  9925. actions_.emplace_back(ActionType::Tag, idx, endIdx);
  9926. break;
  9927. }
  9928. }
  9929. // removing standalones
  9930. for (int i = actions_.size() - 2; i >= 0; i--)
  9931. {
  9932. if (actions_[i].t == ActionType::Tag || actions_[i].t == ActionType::UnescapeTag)
  9933. continue;
  9934. auto& fragment_before = fragments_[i];
  9935. auto& fragment_after = fragments_[i + 1];
  9936. bool is_last_action = i == static_cast<int>(actions_.size()) - 2;
  9937. bool all_space_before = true;
  9938. int j, k;
  9939. for (j = fragment_before.second - 1; j >= fragment_before.first; j--)
  9940. {
  9941. if (body_[j] != ' ')
  9942. {
  9943. all_space_before = false;
  9944. break;
  9945. }
  9946. }
  9947. if (all_space_before && i > 0)
  9948. continue;
  9949. if (!all_space_before && body_[j] != '\n')
  9950. continue;
  9951. bool all_space_after = true;
  9952. for (k = fragment_after.first; k < static_cast<int>(body_.size()) && k < fragment_after.second; k++)
  9953. {
  9954. if (body_[k] != ' ')
  9955. {
  9956. all_space_after = false;
  9957. break;
  9958. }
  9959. }
  9960. if (all_space_after && !is_last_action)
  9961. continue;
  9962. if (!all_space_after &&
  9963. !(
  9964. body_[k] == '\n' ||
  9965. (body_[k] == '\r' &&
  9966. k + 1 < static_cast<int>(body_.size()) &&
  9967. body_[k + 1] == '\n')))
  9968. continue;
  9969. if (actions_[i].t == ActionType::Partial)
  9970. {
  9971. actions_[i].pos = fragment_before.second - j - 1;
  9972. }
  9973. fragment_before.second = j + 1;
  9974. if (!all_space_after)
  9975. {
  9976. if (body_[k] == '\n')
  9977. k++;
  9978. else
  9979. k += 2;
  9980. fragment_after.first = k;
  9981. }
  9982. }
  9983. }
  9984. std::vector<std::pair<int, int>> fragments_;
  9985. std::vector<Action> actions_;
  9986. std::string body_;
  9987. };
  9988. inline template_t compile(const std::string& body)
  9989. {
  9990. return template_t(body);
  9991. }
  9992. namespace detail
  9993. {
  9994. inline std::string& get_template_base_directory_ref()
  9995. {
  9996. static std::string template_base_directory = "templates";
  9997. return template_base_directory;
  9998. }
  9999. /// A base directory not related to any blueprint
  10000. inline std::string& get_global_template_base_directory_ref()
  10001. {
  10002. static std::string template_base_directory = "templates";
  10003. return template_base_directory;
  10004. }
  10005. } // namespace detail
  10006. inline std::string default_loader(const std::string& filename)
  10007. {
  10008. std::string path = detail::get_template_base_directory_ref();
  10009. std::ifstream inf(utility::join_path(path, filename));
  10010. if (!inf)
  10011. {
  10012. CROW_LOG_WARNING << "Template \"" << filename << "\" not found.";
  10013. return {};
  10014. }
  10015. return {std::istreambuf_iterator<char>(inf), std::istreambuf_iterator<char>()};
  10016. }
  10017. namespace detail
  10018. {
  10019. inline std::function<std::string(std::string)>& get_loader_ref()
  10020. {
  10021. static std::function<std::string(std::string)> loader = default_loader;
  10022. return loader;
  10023. }
  10024. } // namespace detail
  10025. inline void set_base(const std::string& path)
  10026. {
  10027. auto& base = detail::get_template_base_directory_ref();
  10028. base = path;
  10029. if (base.back() != '\\' &&
  10030. base.back() != '/')
  10031. {
  10032. base += '/';
  10033. }
  10034. }
  10035. inline void set_global_base(const std::string& path)
  10036. {
  10037. auto& base = detail::get_global_template_base_directory_ref();
  10038. base = path;
  10039. if (base.back() != '\\' &&
  10040. base.back() != '/')
  10041. {
  10042. base += '/';
  10043. }
  10044. }
  10045. inline void set_loader(std::function<std::string(std::string)> loader)
  10046. {
  10047. detail::get_loader_ref() = std::move(loader);
  10048. }
  10049. inline std::string load_text(const std::string& filename)
  10050. {
  10051. std::string filename_sanitized(filename);
  10052. utility::sanitize_filename(filename_sanitized);
  10053. return detail::get_loader_ref()(filename_sanitized);
  10054. }
  10055. inline std::string load_text_unsafe(const std::string& filename)
  10056. {
  10057. return detail::get_loader_ref()(filename);
  10058. }
  10059. inline template_t load(const std::string& filename)
  10060. {
  10061. std::string filename_sanitized(filename);
  10062. utility::sanitize_filename(filename_sanitized);
  10063. return compile(detail::get_loader_ref()(filename_sanitized));
  10064. }
  10065. inline template_t load_unsafe(const std::string& filename)
  10066. {
  10067. return compile(detail::get_loader_ref()(filename));
  10068. }
  10069. } // namespace mustache
  10070. } // namespace crow
  10071. #include <cstdint>
  10072. #include <utility>
  10073. #include <tuple>
  10074. #include <unordered_map>
  10075. #include <memory>
  10076. #include <vector>
  10077. #include <algorithm>
  10078. #include <type_traits>
  10079. namespace crow // NOTE: Already documented in "crow/app.h"
  10080. {
  10081. constexpr const uint16_t INVALID_BP_ID{((uint16_t)-1)};
  10082. namespace detail
  10083. {
  10084. /// Typesafe wrapper for storing lists of middleware as their indices in the App
  10085. struct middleware_indices
  10086. {
  10087. template<typename App>
  10088. void push()
  10089. {}
  10090. template<typename App, typename MW, typename... Middlewares>
  10091. void push()
  10092. {
  10093. using MwContainer = typename App::mw_container_t;
  10094. static_assert(black_magic::has_type<MW, MwContainer>::value, "Middleware must be present in app");
  10095. static_assert(std::is_base_of<crow::ILocalMiddleware, MW>::value, "Middleware must extend ILocalMiddleware");
  10096. int idx = black_magic::tuple_index<MW, MwContainer>::value;
  10097. indices_.push_back(idx);
  10098. push<App, Middlewares...>();
  10099. }
  10100. void merge_front(const detail::middleware_indices& other)
  10101. {
  10102. indices_.insert(indices_.begin(), other.indices_.cbegin(), other.indices_.cend());
  10103. }
  10104. void merge_back(const detail::middleware_indices& other)
  10105. {
  10106. indices_.insert(indices_.end(), other.indices_.cbegin(), other.indices_.cend());
  10107. }
  10108. void pop_back(const detail::middleware_indices& other)
  10109. {
  10110. indices_.resize(indices_.size() - other.indices_.size());
  10111. }
  10112. bool empty() const
  10113. {
  10114. return indices_.empty();
  10115. }
  10116. // Sorts indices and filters out duplicates to allow fast lookups with traversal
  10117. void pack()
  10118. {
  10119. std::sort(indices_.begin(), indices_.end());
  10120. indices_.erase(std::unique(indices_.begin(), indices_.end()), indices_.end());
  10121. }
  10122. const std::vector<int>& indices()
  10123. {
  10124. return indices_;
  10125. }
  10126. private:
  10127. std::vector<int> indices_;
  10128. };
  10129. } // namespace detail
  10130. /// A base class for all rules.
  10131. ///
  10132. /// Used to provide a common interface for code dealing with different types of rules.<br>
  10133. /// A Rule provides a URL, allowed HTTP methods, and handlers.
  10134. class BaseRule
  10135. {
  10136. public:
  10137. BaseRule(std::string rule):
  10138. rule_(std::move(rule))
  10139. {}
  10140. virtual ~BaseRule()
  10141. {}
  10142. virtual void validate() = 0;
  10143. void set_added() {
  10144. added_ = true;
  10145. }
  10146. bool is_added() {
  10147. return added_;
  10148. }
  10149. std::unique_ptr<BaseRule> upgrade()
  10150. {
  10151. if (rule_to_upgrade_)
  10152. return std::move(rule_to_upgrade_);
  10153. return {};
  10154. }
  10155. virtual void handle(request&, response&, const routing_params&) = 0;
  10156. virtual void handle_upgrade(const request&, response& res, SocketAdaptor&&)
  10157. {
  10158. res = response(404);
  10159. res.end();
  10160. }
  10161. #ifdef CROW_ENABLE_SSL
  10162. virtual void handle_upgrade(const request&, response& res, SSLAdaptor&&)
  10163. {
  10164. res = response(404);
  10165. res.end();
  10166. }
  10167. #endif
  10168. uint32_t get_methods()
  10169. {
  10170. return methods_;
  10171. }
  10172. template<typename F>
  10173. void foreach_method(F f)
  10174. {
  10175. for (uint32_t method = 0, method_bit = 1; method < static_cast<uint32_t>(HTTPMethod::InternalMethodCount); method++, method_bit <<= 1)
  10176. {
  10177. if (methods_ & method_bit)
  10178. f(method);
  10179. }
  10180. }
  10181. std::string custom_templates_base;
  10182. const std::string& rule() { return rule_; }
  10183. protected:
  10184. uint32_t methods_{1 << static_cast<int>(HTTPMethod::Get)};
  10185. std::string rule_;
  10186. std::string name_;
  10187. bool added_{false};
  10188. std::unique_ptr<BaseRule> rule_to_upgrade_;
  10189. detail::middleware_indices mw_indices_;
  10190. friend class Router;
  10191. friend class Blueprint;
  10192. template<typename T>
  10193. friend struct RuleParameterTraits;
  10194. };
  10195. namespace detail
  10196. {
  10197. namespace routing_handler_call_helper
  10198. {
  10199. template<typename T, int Pos>
  10200. struct call_pair
  10201. {
  10202. using type = T;
  10203. static const int pos = Pos;
  10204. };
  10205. template<typename H1>
  10206. struct call_params
  10207. {
  10208. H1& handler;
  10209. const routing_params& params;
  10210. request& req;
  10211. response& res;
  10212. };
  10213. template<typename F, int NInt, int NUint, int NDouble, int NString, typename S1, typename S2>
  10214. struct call
  10215. {};
  10216. template<typename F, int NInt, int NUint, int NDouble, int NString, typename... Args1, typename... Args2>
  10217. struct call<F, NInt, NUint, NDouble, NString, black_magic::S<int64_t, Args1...>, black_magic::S<Args2...>>
  10218. {
  10219. void operator()(F cparams)
  10220. {
  10221. using pushed = typename black_magic::S<Args2...>::template push_back<call_pair<int64_t, NInt>>;
  10222. call<F, NInt + 1, NUint, NDouble, NString, black_magic::S<Args1...>, pushed>()(cparams);
  10223. }
  10224. };
  10225. template<typename F, int NInt, int NUint, int NDouble, int NString, typename... Args1, typename... Args2>
  10226. struct call<F, NInt, NUint, NDouble, NString, black_magic::S<uint64_t, Args1...>, black_magic::S<Args2...>>
  10227. {
  10228. void operator()(F cparams)
  10229. {
  10230. using pushed = typename black_magic::S<Args2...>::template push_back<call_pair<uint64_t, NUint>>;
  10231. call<F, NInt, NUint + 1, NDouble, NString, black_magic::S<Args1...>, pushed>()(cparams);
  10232. }
  10233. };
  10234. template<typename F, int NInt, int NUint, int NDouble, int NString, typename... Args1, typename... Args2>
  10235. struct call<F, NInt, NUint, NDouble, NString, black_magic::S<double, Args1...>, black_magic::S<Args2...>>
  10236. {
  10237. void operator()(F cparams)
  10238. {
  10239. using pushed = typename black_magic::S<Args2...>::template push_back<call_pair<double, NDouble>>;
  10240. call<F, NInt, NUint, NDouble + 1, NString, black_magic::S<Args1...>, pushed>()(cparams);
  10241. }
  10242. };
  10243. template<typename F, int NInt, int NUint, int NDouble, int NString, typename... Args1, typename... Args2>
  10244. struct call<F, NInt, NUint, NDouble, NString, black_magic::S<std::string, Args1...>, black_magic::S<Args2...>>
  10245. {
  10246. void operator()(F cparams)
  10247. {
  10248. using pushed = typename black_magic::S<Args2...>::template push_back<call_pair<std::string, NString>>;
  10249. call<F, NInt, NUint, NDouble, NString + 1, black_magic::S<Args1...>, pushed>()(cparams);
  10250. }
  10251. };
  10252. template<typename F, int NInt, int NUint, int NDouble, int NString, typename... Args1>
  10253. struct call<F, NInt, NUint, NDouble, NString, black_magic::S<>, black_magic::S<Args1...>>
  10254. {
  10255. void operator()(F cparams)
  10256. {
  10257. cparams.handler(
  10258. cparams.req,
  10259. cparams.res,
  10260. cparams.params.template get<typename Args1::type>(Args1::pos)...);
  10261. }
  10262. };
  10263. template<typename Func, typename... ArgsWrapped>
  10264. struct Wrapped
  10265. {
  10266. template<typename... Args>
  10267. void set_(Func f, typename std::enable_if<!std::is_same<typename std::tuple_element<0, std::tuple<Args..., void>>::type, const request&>::value, int>::type = 0)
  10268. {
  10269. handler_ = (
  10270. #ifdef CROW_CAN_USE_CPP14
  10271. [f = std::move(f)]
  10272. #else
  10273. [f]
  10274. #endif
  10275. (const request&, response& res, Args... args) {
  10276. res = response(f(args...));
  10277. res.end();
  10278. });
  10279. }
  10280. template<typename Req, typename... Args>
  10281. struct req_handler_wrapper
  10282. {
  10283. req_handler_wrapper(Func f):
  10284. f(std::move(f))
  10285. {
  10286. }
  10287. void operator()(const request& req, response& res, Args... args)
  10288. {
  10289. res = response(f(req, args...));
  10290. res.end();
  10291. }
  10292. Func f;
  10293. };
  10294. template<typename... Args>
  10295. void set_(Func f, typename std::enable_if<
  10296. std::is_same<typename std::tuple_element<0, std::tuple<Args..., void>>::type, const request&>::value &&
  10297. !std::is_same<typename std::tuple_element<1, std::tuple<Args..., void, void>>::type, response&>::value,
  10298. int>::type = 0)
  10299. {
  10300. handler_ = req_handler_wrapper<Args...>(std::move(f));
  10301. /*handler_ = (
  10302. [f = std::move(f)]
  10303. (const request& req, response& res, Args... args){
  10304. res = response(f(req, args...));
  10305. res.end();
  10306. });*/
  10307. }
  10308. template<typename... Args>
  10309. void set_(Func f, typename std::enable_if<
  10310. std::is_same<typename std::tuple_element<0, std::tuple<Args..., void>>::type, const request&>::value &&
  10311. std::is_same<typename std::tuple_element<1, std::tuple<Args..., void, void>>::type, response&>::value,
  10312. int>::type = 0)
  10313. {
  10314. handler_ = std::move(f);
  10315. }
  10316. template<typename... Args>
  10317. struct handler_type_helper
  10318. {
  10319. using type = std::function<void(const crow::request&, crow::response&, Args...)>;
  10320. using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
  10321. };
  10322. template<typename... Args>
  10323. struct handler_type_helper<const request&, Args...>
  10324. {
  10325. using type = std::function<void(const crow::request&, crow::response&, Args...)>;
  10326. using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
  10327. };
  10328. template<typename... Args>
  10329. struct handler_type_helper<const request&, response&, Args...>
  10330. {
  10331. using type = std::function<void(const crow::request&, crow::response&, Args...)>;
  10332. using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
  10333. };
  10334. typename handler_type_helper<ArgsWrapped...>::type handler_;
  10335. void operator()(request& req, response& res, const routing_params& params)
  10336. {
  10337. detail::routing_handler_call_helper::call<
  10338. detail::routing_handler_call_helper::call_params<
  10339. decltype(handler_)>,
  10340. 0, 0, 0, 0,
  10341. typename handler_type_helper<ArgsWrapped...>::args_type,
  10342. black_magic::S<>>()(
  10343. detail::routing_handler_call_helper::call_params<
  10344. decltype(handler_)>{handler_, params, req, res});
  10345. }
  10346. };
  10347. } // namespace routing_handler_call_helper
  10348. } // namespace detail
  10349. class CatchallRule
  10350. {
  10351. public:
  10352. /// @cond SKIP
  10353. CatchallRule() {}
  10354. template<typename Func>
  10355. typename std::enable_if<black_magic::CallHelper<Func, black_magic::S<>>::value, void>::type
  10356. operator()(Func&& f)
  10357. {
  10358. static_assert(!std::is_same<void, decltype(f())>::value,
  10359. "Handler function cannot have void return type; valid return types: string, int, crow::response, crow::returnable");
  10360. handler_ = (
  10361. #ifdef CROW_CAN_USE_CPP14
  10362. [f = std::move(f)]
  10363. #else
  10364. [f]
  10365. #endif
  10366. (const request&, response& res) {
  10367. res = response(f());
  10368. res.end();
  10369. });
  10370. }
  10371. template<typename Func>
  10372. typename std::enable_if<
  10373. !black_magic::CallHelper<Func, black_magic::S<>>::value &&
  10374. black_magic::CallHelper<Func, black_magic::S<crow::request>>::value,
  10375. void>::type
  10376. operator()(Func&& f)
  10377. {
  10378. static_assert(!std::is_same<void, decltype(f(std::declval<crow::request>()))>::value,
  10379. "Handler function cannot have void return type; valid return types: string, int, crow::response, crow::returnable");
  10380. handler_ = (
  10381. #ifdef CROW_CAN_USE_CPP14
  10382. [f = std::move(f)]
  10383. #else
  10384. [f]
  10385. #endif
  10386. (const crow::request& req, crow::response& res) {
  10387. res = response(f(req));
  10388. res.end();
  10389. });
  10390. }
  10391. template<typename Func>
  10392. typename std::enable_if<
  10393. !black_magic::CallHelper<Func, black_magic::S<>>::value &&
  10394. !black_magic::CallHelper<Func, black_magic::S<crow::request>>::value &&
  10395. black_magic::CallHelper<Func, black_magic::S<crow::response&>>::value,
  10396. void>::type
  10397. operator()(Func&& f)
  10398. {
  10399. static_assert(std::is_same<void, decltype(f(std::declval<crow::response&>()))>::value,
  10400. "Handler function with response argument should have void return type");
  10401. handler_ = (
  10402. #ifdef CROW_CAN_USE_CPP14
  10403. [f = std::move(f)]
  10404. #else
  10405. [f]
  10406. #endif
  10407. (const crow::request&, crow::response& res) {
  10408. f(res);
  10409. });
  10410. }
  10411. template<typename Func>
  10412. typename std::enable_if<
  10413. !black_magic::CallHelper<Func, black_magic::S<>>::value &&
  10414. !black_magic::CallHelper<Func, black_magic::S<crow::request>>::value &&
  10415. !black_magic::CallHelper<Func, black_magic::S<crow::response&>>::value,
  10416. void>::type
  10417. operator()(Func&& f)
  10418. {
  10419. static_assert(std::is_same<void, decltype(f(std::declval<crow::request>(), std::declval<crow::response&>()))>::value,
  10420. "Handler function with response argument should have void return type");
  10421. handler_ = std::move(f);
  10422. }
  10423. /// @endcond
  10424. bool has_handler()
  10425. {
  10426. return (handler_ != nullptr);
  10427. }
  10428. protected:
  10429. friend class Router;
  10430. private:
  10431. std::function<void(const crow::request&, crow::response&)> handler_;
  10432. };
  10433. /// A rule dealing with websockets.
  10434. ///
  10435. /// Provides the interface for the user to put in the necessary handlers for a websocket to work.
  10436. template<typename App>
  10437. class WebSocketRule : public BaseRule
  10438. {
  10439. using self_t = WebSocketRule;
  10440. public:
  10441. WebSocketRule(std::string rule, App* app):
  10442. BaseRule(std::move(rule)),
  10443. app_(app),
  10444. max_payload_(UINT64_MAX)
  10445. {}
  10446. void validate() override
  10447. {}
  10448. void handle(request&, response& res, const routing_params&) override
  10449. {
  10450. res = response(404);
  10451. res.end();
  10452. }
  10453. void handle_upgrade(const request& req, response&, SocketAdaptor&& adaptor) override
  10454. {
  10455. max_payload_ = max_payload_override_ ? max_payload_ : app_->websocket_max_payload();
  10456. new crow::websocket::Connection<SocketAdaptor, App>(req, std::move(adaptor), app_, max_payload_, open_handler_, message_handler_, close_handler_, error_handler_, accept_handler_);
  10457. }
  10458. #ifdef CROW_ENABLE_SSL
  10459. void handle_upgrade(const request& req, response&, SSLAdaptor&& adaptor) override
  10460. {
  10461. new crow::websocket::Connection<SSLAdaptor, App>(req, std::move(adaptor), app_, max_payload_, open_handler_, message_handler_, close_handler_, error_handler_, accept_handler_);
  10462. }
  10463. #endif
  10464. /// Override the global payload limit for this single WebSocket rule
  10465. self_t& max_payload(uint64_t max_payload)
  10466. {
  10467. max_payload_ = max_payload;
  10468. max_payload_override_ = true;
  10469. return *this;
  10470. }
  10471. template<typename Func>
  10472. self_t& onopen(Func f)
  10473. {
  10474. open_handler_ = f;
  10475. return *this;
  10476. }
  10477. template<typename Func>
  10478. self_t& onmessage(Func f)
  10479. {
  10480. message_handler_ = f;
  10481. return *this;
  10482. }
  10483. template<typename Func>
  10484. self_t& onclose(Func f)
  10485. {
  10486. close_handler_ = f;
  10487. return *this;
  10488. }
  10489. template<typename Func>
  10490. self_t& onerror(Func f)
  10491. {
  10492. error_handler_ = f;
  10493. return *this;
  10494. }
  10495. template<typename Func>
  10496. self_t& onaccept(Func f)
  10497. {
  10498. accept_handler_ = f;
  10499. return *this;
  10500. }
  10501. protected:
  10502. App* app_;
  10503. std::function<void(crow::websocket::connection&)> open_handler_;
  10504. std::function<void(crow::websocket::connection&, const std::string&, bool)> message_handler_;
  10505. std::function<void(crow::websocket::connection&, const std::string&)> close_handler_;
  10506. std::function<void(crow::websocket::connection&, const std::string&)> error_handler_;
  10507. std::function<bool(const crow::request&, void**)> accept_handler_;
  10508. uint64_t max_payload_;
  10509. bool max_payload_override_ = false;
  10510. };
  10511. /// Allows the user to assign parameters using functions.
  10512. ///
  10513. /// `rule.name("name").methods(HTTPMethod::POST)`
  10514. template<typename T>
  10515. struct RuleParameterTraits
  10516. {
  10517. using self_t = T;
  10518. template<typename App>
  10519. WebSocketRule<App>& websocket(App* app)
  10520. {
  10521. auto p = new WebSocketRule<App>(static_cast<self_t*>(this)->rule_, app);
  10522. static_cast<self_t*>(this)->rule_to_upgrade_.reset(p);
  10523. return *p;
  10524. }
  10525. self_t& name(std::string name) noexcept
  10526. {
  10527. static_cast<self_t*>(this)->name_ = std::move(name);
  10528. return static_cast<self_t&>(*this);
  10529. }
  10530. self_t& methods(HTTPMethod method)
  10531. {
  10532. static_cast<self_t*>(this)->methods_ = 1 << static_cast<int>(method);
  10533. return static_cast<self_t&>(*this);
  10534. }
  10535. template<typename... MethodArgs>
  10536. self_t& methods(HTTPMethod method, MethodArgs... args_method)
  10537. {
  10538. methods(args_method...);
  10539. static_cast<self_t*>(this)->methods_ |= 1 << static_cast<int>(method);
  10540. return static_cast<self_t&>(*this);
  10541. }
  10542. /// Enable local middleware for this handler
  10543. template<typename App, typename... Middlewares>
  10544. self_t& middlewares()
  10545. {
  10546. static_cast<self_t*>(this)->mw_indices_.template push<App, Middlewares...>();
  10547. return static_cast<self_t&>(*this);
  10548. }
  10549. };
  10550. /// A rule that can change its parameters during runtime.
  10551. class DynamicRule : public BaseRule, public RuleParameterTraits<DynamicRule>
  10552. {
  10553. public:
  10554. DynamicRule(std::string rule):
  10555. BaseRule(std::move(rule))
  10556. {}
  10557. void validate() override
  10558. {
  10559. if (!erased_handler_)
  10560. {
  10561. throw std::runtime_error(name_ + (!name_.empty() ? ": " : "") + "no handler for url " + rule_);
  10562. }
  10563. }
  10564. void handle(request& req, response& res, const routing_params& params) override
  10565. {
  10566. if (!custom_templates_base.empty())
  10567. mustache::set_base(custom_templates_base);
  10568. else if (mustache::detail::get_template_base_directory_ref() != "templates")
  10569. mustache::set_base("templates");
  10570. erased_handler_(req, res, params);
  10571. }
  10572. template<typename Func>
  10573. void operator()(Func f)
  10574. {
  10575. #ifdef CROW_MSVC_WORKAROUND
  10576. using function_t = utility::function_traits<decltype(&Func::operator())>;
  10577. #else
  10578. using function_t = utility::function_traits<Func>;
  10579. #endif
  10580. erased_handler_ = wrap(std::move(f), black_magic::gen_seq<function_t::arity>());
  10581. }
  10582. // enable_if Arg1 == request && Arg2 == response
  10583. // enable_if Arg1 == request && Arg2 != resposne
  10584. // enable_if Arg1 != request
  10585. #ifdef CROW_MSVC_WORKAROUND
  10586. template<typename Func, size_t... Indices>
  10587. #else
  10588. template<typename Func, unsigned... Indices>
  10589. #endif
  10590. std::function<void(request&, response&, const routing_params&)>
  10591. wrap(Func f, black_magic::seq<Indices...>)
  10592. {
  10593. #ifdef CROW_MSVC_WORKAROUND
  10594. using function_t = utility::function_traits<decltype(&Func::operator())>;
  10595. #else
  10596. using function_t = utility::function_traits<Func>;
  10597. #endif
  10598. if (!black_magic::is_parameter_tag_compatible(
  10599. black_magic::get_parameter_tag_runtime(rule_.c_str()),
  10600. black_magic::compute_parameter_tag_from_args_list<
  10601. typename function_t::template arg<Indices>...>::value))
  10602. {
  10603. throw std::runtime_error("route_dynamic: Handler type is mismatched with URL parameters: " + rule_);
  10604. }
  10605. auto ret = detail::routing_handler_call_helper::Wrapped<Func, typename function_t::template arg<Indices>...>();
  10606. ret.template set_<
  10607. typename function_t::template arg<Indices>...>(std::move(f));
  10608. return ret;
  10609. }
  10610. template<typename Func>
  10611. void operator()(std::string name, Func&& f)
  10612. {
  10613. name_ = std::move(name);
  10614. (*this).template operator()<Func>(std::forward(f));
  10615. }
  10616. private:
  10617. std::function<void(request&, response&, const routing_params&)> erased_handler_;
  10618. };
  10619. /// Default rule created when CROW_ROUTE is called.
  10620. template<typename... Args>
  10621. class TaggedRule : public BaseRule, public RuleParameterTraits<TaggedRule<Args...>>
  10622. {
  10623. public:
  10624. using self_t = TaggedRule<Args...>;
  10625. TaggedRule(std::string rule):
  10626. BaseRule(std::move(rule))
  10627. {}
  10628. void validate() override
  10629. {
  10630. if (rule_.at(0) != '/')
  10631. throw std::runtime_error("Internal error: Routes must start with a '/'");
  10632. if (!handler_)
  10633. {
  10634. throw std::runtime_error(name_ + (!name_.empty() ? ": " : "") + "no handler for url " + rule_);
  10635. }
  10636. }
  10637. template<typename Func>
  10638. void operator()(Func&& f)
  10639. {
  10640. handler_ = (
  10641. #ifdef CROW_CAN_USE_CPP14
  10642. [f = std::move(f)]
  10643. #else
  10644. [f]
  10645. #endif
  10646. (crow::request& req, crow::response& res, Args... args) {
  10647. detail::wrapped_handler_call(req, res, f, std::forward<Args>(args)...);
  10648. });
  10649. }
  10650. template<typename Func>
  10651. void operator()(std::string name, Func&& f)
  10652. {
  10653. name_ = std::move(name);
  10654. (*this).template operator()<Func>(std::forward(f));
  10655. }
  10656. void handle(request& req, response& res, const routing_params& params) override
  10657. {
  10658. if (!custom_templates_base.empty())
  10659. mustache::set_base(custom_templates_base);
  10660. else if (mustache::detail::get_template_base_directory_ref() != mustache::detail::get_global_template_base_directory_ref())
  10661. mustache::set_base(mustache::detail::get_global_template_base_directory_ref());
  10662. detail::routing_handler_call_helper::call<
  10663. detail::routing_handler_call_helper::call_params<decltype(handler_)>,
  10664. 0, 0, 0, 0,
  10665. black_magic::S<Args...>,
  10666. black_magic::S<>>()(
  10667. detail::routing_handler_call_helper::call_params<decltype(handler_)>{handler_, params, req, res});
  10668. }
  10669. private:
  10670. std::function<void(crow::request&, crow::response&, Args...)> handler_;
  10671. };
  10672. const int RULE_SPECIAL_REDIRECT_SLASH = 1;
  10673. /// A search tree.
  10674. class Trie
  10675. {
  10676. public:
  10677. struct Node
  10678. {
  10679. uint16_t rule_index{};
  10680. // Assign the index to the maximum 32 unsigned integer value by default so that any other number (specifically 0) is a valid BP id.
  10681. uint16_t blueprint_index{INVALID_BP_ID};
  10682. std::string key;
  10683. ParamType param = ParamType::MAX; // MAX = No param.
  10684. std::vector<Node> children;
  10685. bool IsSimpleNode() const
  10686. {
  10687. return !rule_index &&
  10688. blueprint_index == INVALID_BP_ID &&
  10689. children.size() < 2 &&
  10690. param == ParamType::MAX &&
  10691. std::all_of(std::begin(children), std::end(children), [](const Node& x) {
  10692. return x.param == ParamType::MAX;
  10693. });
  10694. }
  10695. Node& add_child_node()
  10696. {
  10697. children.emplace_back();
  10698. return children.back();
  10699. }
  10700. };
  10701. Trie()
  10702. {}
  10703. /// Check whether or not the trie is empty.
  10704. bool is_empty()
  10705. {
  10706. return head_.children.empty();
  10707. }
  10708. void optimize()
  10709. {
  10710. for (auto& child : head_.children)
  10711. {
  10712. optimizeNode(child);
  10713. }
  10714. }
  10715. private:
  10716. void optimizeNode(Node& node)
  10717. {
  10718. if (node.children.empty())
  10719. return;
  10720. if (node.IsSimpleNode())
  10721. {
  10722. auto children_temp = std::move(node.children);
  10723. auto& child_temp = children_temp[0];
  10724. node.key += child_temp.key;
  10725. node.rule_index = child_temp.rule_index;
  10726. node.blueprint_index = child_temp.blueprint_index;
  10727. node.children = std::move(child_temp.children);
  10728. optimizeNode(node);
  10729. }
  10730. else
  10731. {
  10732. for (auto& child : node.children)
  10733. {
  10734. optimizeNode(child);
  10735. }
  10736. }
  10737. }
  10738. void debug_node_print(const Node& node, int level)
  10739. {
  10740. if (node.param != ParamType::MAX)
  10741. {
  10742. switch (node.param)
  10743. {
  10744. case ParamType::INT:
  10745. CROW_LOG_DEBUG << std::string(3 * level, ' ') << "└➝ "
  10746. << "<int>";
  10747. break;
  10748. case ParamType::UINT:
  10749. CROW_LOG_DEBUG << std::string(3 * level, ' ') << "└➝ "
  10750. << "<uint>";
  10751. break;
  10752. case ParamType::DOUBLE:
  10753. CROW_LOG_DEBUG << std::string(3 * level, ' ') << "└➝ "
  10754. << "<double>";
  10755. break;
  10756. case ParamType::STRING:
  10757. CROW_LOG_DEBUG << std::string(3 * level, ' ') << "└➝ "
  10758. << "<string>";
  10759. break;
  10760. case ParamType::PATH:
  10761. CROW_LOG_DEBUG << std::string(3 * level, ' ') << "└➝ "
  10762. << "<path>";
  10763. break;
  10764. default:
  10765. CROW_LOG_DEBUG << std::string(3 * level, ' ') << "└➝ "
  10766. << "<ERROR>";
  10767. break;
  10768. }
  10769. }
  10770. else
  10771. CROW_LOG_DEBUG << std::string(3 * level, ' ') << "└➝ " << node.key;
  10772. for (const auto& child : node.children)
  10773. {
  10774. debug_node_print(child, level + 1);
  10775. }
  10776. }
  10777. public:
  10778. void debug_print()
  10779. {
  10780. CROW_LOG_DEBUG << "└➙ ROOT";
  10781. for (const auto& child : head_.children)
  10782. debug_node_print(child, 1);
  10783. }
  10784. void validate()
  10785. {
  10786. if (!head_.IsSimpleNode())
  10787. throw std::runtime_error("Internal error: Trie header should be simple!");
  10788. optimize();
  10789. }
  10790. //Rule_index, Blueprint_index, routing_params
  10791. routing_handle_result find(const std::string& req_url, const Node& node, unsigned pos = 0, routing_params* params = nullptr, std::vector<uint16_t>* blueprints = nullptr) const
  10792. {
  10793. //start params as an empty struct
  10794. routing_params empty;
  10795. if (params == nullptr)
  10796. params = &empty;
  10797. //same for blueprint vector
  10798. std::vector<uint16_t> MT;
  10799. if (blueprints == nullptr)
  10800. blueprints = &MT;
  10801. uint16_t found{}; //The rule index to be found
  10802. std::vector<uint16_t> found_BP; //The Blueprint indices to be found
  10803. routing_params match_params; //supposedly the final matched parameters
  10804. auto update_found = [&found, &found_BP, &match_params](routing_handle_result& ret) {
  10805. found_BP = std::move(ret.blueprint_indices);
  10806. if (ret.rule_index && (!found || found > ret.rule_index))
  10807. {
  10808. found = ret.rule_index;
  10809. match_params = std::move(ret.r_params);
  10810. }
  10811. };
  10812. //if the function was called on a node at the end of the string (the last recursion), return the nodes rule index, and whatever params were passed to the function
  10813. if (pos == req_url.size())
  10814. {
  10815. found_BP = std::move(*blueprints);
  10816. return routing_handle_result{node.rule_index, *blueprints, *params};
  10817. }
  10818. bool found_fragment = false;
  10819. for (const auto& child : node.children)
  10820. {
  10821. if (child.param != ParamType::MAX)
  10822. {
  10823. if (child.param == ParamType::INT)
  10824. {
  10825. char c = req_url[pos];
  10826. if ((c >= '0' && c <= '9') || c == '+' || c == '-')
  10827. {
  10828. char* eptr;
  10829. errno = 0;
  10830. long long int value = strtoll(req_url.data() + pos, &eptr, 10);
  10831. if (errno != ERANGE && eptr != req_url.data() + pos)
  10832. {
  10833. found_fragment = true;
  10834. params->int_params.push_back(value);
  10835. if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
  10836. auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
  10837. update_found(ret);
  10838. params->int_params.pop_back();
  10839. if (!blueprints->empty()) blueprints->pop_back();
  10840. }
  10841. }
  10842. }
  10843. else if (child.param == ParamType::UINT)
  10844. {
  10845. char c = req_url[pos];
  10846. if ((c >= '0' && c <= '9') || c == '+')
  10847. {
  10848. char* eptr;
  10849. errno = 0;
  10850. unsigned long long int value = strtoull(req_url.data() + pos, &eptr, 10);
  10851. if (errno != ERANGE && eptr != req_url.data() + pos)
  10852. {
  10853. found_fragment = true;
  10854. params->uint_params.push_back(value);
  10855. if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
  10856. auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
  10857. update_found(ret);
  10858. params->uint_params.pop_back();
  10859. if (!blueprints->empty()) blueprints->pop_back();
  10860. }
  10861. }
  10862. }
  10863. else if (child.param == ParamType::DOUBLE)
  10864. {
  10865. char c = req_url[pos];
  10866. if ((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.')
  10867. {
  10868. char* eptr;
  10869. errno = 0;
  10870. double value = strtod(req_url.data() + pos, &eptr);
  10871. if (errno != ERANGE && eptr != req_url.data() + pos)
  10872. {
  10873. found_fragment = true;
  10874. params->double_params.push_back(value);
  10875. if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
  10876. auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
  10877. update_found(ret);
  10878. params->double_params.pop_back();
  10879. if (!blueprints->empty()) blueprints->pop_back();
  10880. }
  10881. }
  10882. }
  10883. else if (child.param == ParamType::STRING)
  10884. {
  10885. size_t epos = pos;
  10886. for (; epos < req_url.size(); epos++)
  10887. {
  10888. if (req_url[epos] == '/')
  10889. break;
  10890. }
  10891. if (epos != pos)
  10892. {
  10893. found_fragment = true;
  10894. params->string_params.push_back(req_url.substr(pos, epos - pos));
  10895. if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
  10896. auto ret = find(req_url, child, epos, params, blueprints);
  10897. update_found(ret);
  10898. params->string_params.pop_back();
  10899. if (!blueprints->empty()) blueprints->pop_back();
  10900. }
  10901. }
  10902. else if (child.param == ParamType::PATH)
  10903. {
  10904. size_t epos = req_url.size();
  10905. if (epos != pos)
  10906. {
  10907. found_fragment = true;
  10908. params->string_params.push_back(req_url.substr(pos, epos - pos));
  10909. if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
  10910. auto ret = find(req_url, child, epos, params, blueprints);
  10911. update_found(ret);
  10912. params->string_params.pop_back();
  10913. if (!blueprints->empty()) blueprints->pop_back();
  10914. }
  10915. }
  10916. }
  10917. else
  10918. {
  10919. const std::string& fragment = child.key;
  10920. if (req_url.compare(pos, fragment.size(), fragment) == 0)
  10921. {
  10922. found_fragment = true;
  10923. if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
  10924. auto ret = find(req_url, child, pos + fragment.size(), params, blueprints);
  10925. update_found(ret);
  10926. if (!blueprints->empty()) blueprints->pop_back();
  10927. }
  10928. }
  10929. }
  10930. if (!found_fragment)
  10931. found_BP = std::move(*blueprints);
  10932. return routing_handle_result{found, found_BP, match_params}; //Called after all the recursions have been done
  10933. }
  10934. routing_handle_result find(const std::string& req_url) const
  10935. {
  10936. return find(req_url, head_);
  10937. }
  10938. //This functions assumes any blueprint info passed is valid
  10939. void add(const std::string& url, uint16_t rule_index, unsigned bp_prefix_length = 0, uint16_t blueprint_index = INVALID_BP_ID)
  10940. {
  10941. auto idx = &head_;
  10942. bool has_blueprint = bp_prefix_length != 0 && blueprint_index != INVALID_BP_ID;
  10943. for (unsigned i = 0; i < url.size(); i++)
  10944. {
  10945. char c = url[i];
  10946. if (c == '<')
  10947. {
  10948. static struct ParamTraits
  10949. {
  10950. ParamType type;
  10951. std::string name;
  10952. } paramTraits[] =
  10953. {
  10954. {ParamType::INT, "<int>"},
  10955. {ParamType::UINT, "<uint>"},
  10956. {ParamType::DOUBLE, "<float>"},
  10957. {ParamType::DOUBLE, "<double>"},
  10958. {ParamType::STRING, "<str>"},
  10959. {ParamType::STRING, "<string>"},
  10960. {ParamType::PATH, "<path>"},
  10961. };
  10962. for (const auto& x : paramTraits)
  10963. {
  10964. if (url.compare(i, x.name.size(), x.name) == 0)
  10965. {
  10966. bool found = false;
  10967. for (auto& child : idx->children)
  10968. {
  10969. if (child.param == x.type)
  10970. {
  10971. idx = &child;
  10972. i += x.name.size();
  10973. found = true;
  10974. break;
  10975. }
  10976. }
  10977. if (found)
  10978. break;
  10979. auto new_node_idx = &idx->add_child_node();
  10980. new_node_idx->param = x.type;
  10981. idx = new_node_idx;
  10982. i += x.name.size();
  10983. break;
  10984. }
  10985. }
  10986. i--;
  10987. }
  10988. else
  10989. {
  10990. //This part assumes the tree is unoptimized (every node has a max 1 character key)
  10991. bool piece_found = false;
  10992. for (auto& child : idx->children)
  10993. {
  10994. if (child.key[0] == c)
  10995. {
  10996. idx = &child;
  10997. piece_found = true;
  10998. break;
  10999. }
  11000. }
  11001. if (!piece_found)
  11002. {
  11003. auto new_node_idx = &idx->add_child_node();
  11004. new_node_idx->key = c;
  11005. //The assumption here is that you'd only need to add a blueprint index if the tree didn't have the BP prefix.
  11006. if (has_blueprint && i == bp_prefix_length)
  11007. new_node_idx->blueprint_index = blueprint_index;
  11008. idx = new_node_idx;
  11009. }
  11010. }
  11011. }
  11012. //check if the last node already has a value (exact url already in Trie)
  11013. if (idx->rule_index)
  11014. throw std::runtime_error("handler already exists for " + url);
  11015. idx->rule_index = rule_index;
  11016. }
  11017. private:
  11018. Node head_;
  11019. };
  11020. /// A blueprint can be considered a smaller section of a Crow app, specifically where the router is conecerned.
  11021. ///
  11022. /// You can use blueprints to assign a common prefix to rules' prefix, set custom static and template folders, and set a custom catchall route.
  11023. /// You can also assign nest blueprints for maximum Compartmentalization.
  11024. class Blueprint
  11025. {
  11026. public:
  11027. Blueprint(const std::string& prefix):
  11028. prefix_(prefix){};
  11029. Blueprint(const std::string& prefix, const std::string& static_dir):
  11030. prefix_(prefix), static_dir_(static_dir){};
  11031. Blueprint(const std::string& prefix, const std::string& static_dir, const std::string& templates_dir):
  11032. prefix_(prefix), static_dir_(static_dir), templates_dir_(templates_dir){};
  11033. /*
  11034. Blueprint(Blueprint& other)
  11035. {
  11036. prefix_ = std::move(other.prefix_);
  11037. all_rules_ = std::move(other.all_rules_);
  11038. }
  11039. Blueprint(const Blueprint& other)
  11040. {
  11041. prefix_ = other.prefix_;
  11042. all_rules_ = other.all_rules_;
  11043. }
  11044. */
  11045. Blueprint(Blueprint&& value)
  11046. {
  11047. *this = std::move(value);
  11048. }
  11049. Blueprint& operator=(const Blueprint& value) = delete;
  11050. Blueprint& operator=(Blueprint&& value) noexcept
  11051. {
  11052. prefix_ = std::move(value.prefix_);
  11053. static_dir_ = std::move(value.static_dir_);
  11054. templates_dir_ = std::move(value.templates_dir_);
  11055. all_rules_ = std::move(value.all_rules_);
  11056. catchall_rule_ = std::move(value.catchall_rule_);
  11057. blueprints_ = std::move(value.blueprints_);
  11058. mw_indices_ = std::move(value.mw_indices_);
  11059. return *this;
  11060. }
  11061. bool operator==(const Blueprint& value)
  11062. {
  11063. return value.prefix() == prefix_;
  11064. }
  11065. bool operator!=(const Blueprint& value)
  11066. {
  11067. return value.prefix() != prefix_;
  11068. }
  11069. std::string prefix() const
  11070. {
  11071. return prefix_;
  11072. }
  11073. std::string static_dir() const
  11074. {
  11075. return static_dir_;
  11076. }
  11077. void set_added() {
  11078. added_ = true;
  11079. }
  11080. bool is_added() {
  11081. return added_;
  11082. }
  11083. DynamicRule& new_rule_dynamic(const std::string& rule)
  11084. {
  11085. std::string new_rule = '/' + prefix_ + rule;
  11086. auto ruleObject = new DynamicRule(std::move(new_rule));
  11087. ruleObject->custom_templates_base = templates_dir_;
  11088. all_rules_.emplace_back(ruleObject);
  11089. return *ruleObject;
  11090. }
  11091. template<uint64_t N>
  11092. typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(const std::string& rule)
  11093. {
  11094. std::string new_rule = '/' + prefix_ + rule;
  11095. using RuleT = typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
  11096. auto ruleObject = new RuleT(std::move(new_rule));
  11097. ruleObject->custom_templates_base = templates_dir_;
  11098. all_rules_.emplace_back(ruleObject);
  11099. return *ruleObject;
  11100. }
  11101. void register_blueprint(Blueprint& blueprint)
  11102. {
  11103. if (blueprints_.empty() || std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
  11104. {
  11105. apply_blueprint(blueprint);
  11106. blueprints_.emplace_back(&blueprint);
  11107. }
  11108. else
  11109. throw std::runtime_error("blueprint \"" + blueprint.prefix_ + "\" already exists in blueprint \"" + prefix_ + '\"');
  11110. }
  11111. CatchallRule& catchall_rule()
  11112. {
  11113. return catchall_rule_;
  11114. }
  11115. template<typename App, typename... Middlewares>
  11116. void middlewares()
  11117. {
  11118. mw_indices_.push<App, Middlewares...>();
  11119. }
  11120. private:
  11121. void apply_blueprint(Blueprint& blueprint)
  11122. {
  11123. blueprint.prefix_ = prefix_ + '/' + blueprint.prefix_;
  11124. blueprint.static_dir_ = static_dir_ + '/' + blueprint.static_dir_;
  11125. blueprint.templates_dir_ = templates_dir_ + '/' + blueprint.templates_dir_;
  11126. for (auto& rule : blueprint.all_rules_)
  11127. {
  11128. std::string new_rule = '/' + prefix_ + rule->rule_;
  11129. rule->rule_ = new_rule;
  11130. }
  11131. for (Blueprint* bp_child : blueprint.blueprints_)
  11132. {
  11133. Blueprint& bp_ref = *bp_child;
  11134. apply_blueprint(bp_ref);
  11135. }
  11136. }
  11137. std::string prefix_;
  11138. std::string static_dir_;
  11139. std::string templates_dir_;
  11140. std::vector<std::unique_ptr<BaseRule>> all_rules_;
  11141. CatchallRule catchall_rule_;
  11142. std::vector<Blueprint*> blueprints_;
  11143. detail::middleware_indices mw_indices_;
  11144. bool added_{false};
  11145. friend class Router;
  11146. };
  11147. /// Handles matching requests to existing rules and upgrade requests.
  11148. class Router
  11149. {
  11150. public:
  11151. Router()
  11152. {}
  11153. DynamicRule& new_rule_dynamic(const std::string& rule)
  11154. {
  11155. auto ruleObject = new DynamicRule(rule);
  11156. all_rules_.emplace_back(ruleObject);
  11157. return *ruleObject;
  11158. }
  11159. template<uint64_t N>
  11160. typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(const std::string& rule)
  11161. {
  11162. using RuleT = typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
  11163. auto ruleObject = new RuleT(rule);
  11164. all_rules_.emplace_back(ruleObject);
  11165. return *ruleObject;
  11166. }
  11167. CatchallRule& catchall_rule()
  11168. {
  11169. return catchall_rule_;
  11170. }
  11171. void internal_add_rule_object(const std::string& rule, BaseRule* ruleObject)
  11172. {
  11173. internal_add_rule_object(rule, ruleObject, INVALID_BP_ID, blueprints_);
  11174. }
  11175. void internal_add_rule_object(const std::string& rule, BaseRule* ruleObject, const uint16_t& BP_index, std::vector<Blueprint*>& blueprints)
  11176. {
  11177. bool has_trailing_slash = false;
  11178. std::string rule_without_trailing_slash;
  11179. if (rule.size() > 1 && rule.back() == '/')
  11180. {
  11181. has_trailing_slash = true;
  11182. rule_without_trailing_slash = rule;
  11183. rule_without_trailing_slash.pop_back();
  11184. }
  11185. ruleObject->mw_indices_.pack();
  11186. ruleObject->foreach_method([&](int method) {
  11187. per_methods_[method].rules.emplace_back(ruleObject);
  11188. per_methods_[method].trie.add(rule, per_methods_[method].rules.size() - 1, BP_index != INVALID_BP_ID ? blueprints[BP_index]->prefix().length() : 0, BP_index);
  11189. // directory case:
  11190. // request to '/about' url matches '/about/' rule
  11191. if (has_trailing_slash)
  11192. {
  11193. per_methods_[method].trie.add(rule_without_trailing_slash, RULE_SPECIAL_REDIRECT_SLASH, BP_index != INVALID_BP_ID ? blueprints[BP_index]->prefix().length() : 0, BP_index);
  11194. }
  11195. });
  11196. ruleObject->set_added();
  11197. }
  11198. void register_blueprint(Blueprint& blueprint)
  11199. {
  11200. if (std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
  11201. {
  11202. blueprints_.emplace_back(&blueprint);
  11203. }
  11204. else
  11205. throw std::runtime_error("blueprint \"" + blueprint.prefix_ + "\" already exists in router");
  11206. }
  11207. void get_recursive_child_methods(Blueprint* blueprint, std::vector<HTTPMethod>& methods)
  11208. {
  11209. //we only need to deal with children if the blueprint has absolutely no methods (meaning its index won't be added to the trie)
  11210. if (blueprint->static_dir_.empty() && blueprint->all_rules_.empty())
  11211. {
  11212. for (Blueprint* bp : blueprint->blueprints_)
  11213. {
  11214. get_recursive_child_methods(bp, methods);
  11215. }
  11216. }
  11217. else if (!blueprint->static_dir_.empty())
  11218. methods.emplace_back(HTTPMethod::Get);
  11219. for (auto& rule : blueprint->all_rules_)
  11220. {
  11221. rule->foreach_method([&methods](unsigned method) {
  11222. HTTPMethod method_final = static_cast<HTTPMethod>(method);
  11223. if (std::find(methods.begin(), methods.end(), method_final) == methods.end())
  11224. methods.emplace_back(method_final);
  11225. });
  11226. }
  11227. }
  11228. void validate_bp() {
  11229. //Take all the routes from the registered blueprints and add them to `all_rules_` to be processed.
  11230. detail::middleware_indices blueprint_mw;
  11231. validate_bp(blueprints_, blueprint_mw);
  11232. }
  11233. void validate_bp(std::vector<Blueprint*> blueprints, detail::middleware_indices& current_mw)
  11234. {
  11235. for (unsigned i = 0; i < blueprints.size(); i++)
  11236. {
  11237. Blueprint* blueprint = blueprints[i];
  11238. if (blueprint->is_added()) continue;
  11239. if (blueprint->static_dir_ == "" && blueprint->all_rules_.empty())
  11240. {
  11241. std::vector<HTTPMethod> methods;
  11242. get_recursive_child_methods(blueprint, methods);
  11243. for (HTTPMethod x : methods)
  11244. {
  11245. int i = static_cast<int>(x);
  11246. per_methods_[i].trie.add(blueprint->prefix(), 0, blueprint->prefix().length(), i);
  11247. }
  11248. }
  11249. current_mw.merge_back(blueprint->mw_indices_);
  11250. for (auto& rule : blueprint->all_rules_)
  11251. {
  11252. if (rule && !rule->is_added())
  11253. {
  11254. auto upgraded = rule->upgrade();
  11255. if (upgraded)
  11256. rule = std::move(upgraded);
  11257. rule->validate();
  11258. rule->mw_indices_.merge_front(current_mw);
  11259. internal_add_rule_object(rule->rule(), rule.get(), i, blueprints);
  11260. }
  11261. }
  11262. validate_bp(blueprint->blueprints_, current_mw);
  11263. current_mw.pop_back(blueprint->mw_indices_);
  11264. blueprint->set_added();
  11265. }
  11266. }
  11267. void validate()
  11268. {
  11269. for (auto& rule : all_rules_)
  11270. {
  11271. if (rule && !rule->is_added())
  11272. {
  11273. auto upgraded = rule->upgrade();
  11274. if (upgraded)
  11275. rule = std::move(upgraded);
  11276. rule->validate();
  11277. internal_add_rule_object(rule->rule(), rule.get());
  11278. }
  11279. }
  11280. for (auto& per_method : per_methods_)
  11281. {
  11282. per_method.trie.validate();
  11283. }
  11284. }
  11285. // TODO maybe add actual_method
  11286. template<typename Adaptor>
  11287. void handle_upgrade(const request& req, response& res, Adaptor&& adaptor)
  11288. {
  11289. if (req.method >= HTTPMethod::InternalMethodCount)
  11290. return;
  11291. auto& per_method = per_methods_[static_cast<int>(req.method)];
  11292. auto& rules = per_method.rules;
  11293. unsigned rule_index = per_method.trie.find(req.url).rule_index;
  11294. if (!rule_index)
  11295. {
  11296. for (auto& per_method : per_methods_)
  11297. {
  11298. if (per_method.trie.find(req.url).rule_index)
  11299. {
  11300. CROW_LOG_DEBUG << "Cannot match method " << req.url << " " << method_name(req.method);
  11301. res = response(405);
  11302. res.end();
  11303. return;
  11304. }
  11305. }
  11306. CROW_LOG_INFO << "Cannot match rules " << req.url;
  11307. res = response(404);
  11308. res.end();
  11309. return;
  11310. }
  11311. if (rule_index >= rules.size())
  11312. throw std::runtime_error("Trie internal structure corrupted!");
  11313. if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
  11314. {
  11315. CROW_LOG_INFO << "Redirecting to a url with trailing slash: " << req.url;
  11316. res = response(301);
  11317. // TODO(ipkn) absolute url building
  11318. if (req.get_header_value("Host").empty())
  11319. {
  11320. res.add_header("Location", req.url + "/");
  11321. }
  11322. else
  11323. {
  11324. res.add_header("Location", "http://" + req.get_header_value("Host") + req.url + "/");
  11325. }
  11326. res.end();
  11327. return;
  11328. }
  11329. CROW_LOG_DEBUG << "Matched rule (upgrade) '" << rules[rule_index]->rule_ << "' " << static_cast<uint32_t>(req.method) << " / " << rules[rule_index]->get_methods();
  11330. try
  11331. {
  11332. rules[rule_index]->handle_upgrade(req, res, std::move(adaptor));
  11333. }
  11334. catch (...)
  11335. {
  11336. exception_handler_(res);
  11337. res.end();
  11338. return;
  11339. }
  11340. }
  11341. void get_found_bp(std::vector<uint16_t>& bp_i, std::vector<Blueprint*>& blueprints, std::vector<Blueprint*>& found_bps, uint16_t index = 0)
  11342. {
  11343. // This statement makes 3 assertions:
  11344. // 1. The index is above 0.
  11345. // 2. The index does not lie outside the given blueprint list.
  11346. // 3. The next blueprint we're adding has a prefix that starts the same as the already added blueprint + a slash (the rest is irrelevant).
  11347. //
  11348. // This is done to prevent a blueprint that has a prefix of "bp_prefix2" to be assumed as a child of one that has "bp_prefix".
  11349. //
  11350. // If any of the assertions is untrue, we delete the last item added, and continue using the blueprint list of the blueprint found before, the topmost being the router's list
  11351. auto verify_prefix = [&bp_i, &index, &blueprints, &found_bps]() {
  11352. return index > 0 &&
  11353. bp_i[index] < blueprints.size() &&
  11354. blueprints[bp_i[index]]->prefix().substr(0, found_bps[index - 1]->prefix().length() + 1).compare(std::string(found_bps[index - 1]->prefix() + '/')) == 0;
  11355. };
  11356. if (index < bp_i.size())
  11357. {
  11358. if (verify_prefix())
  11359. {
  11360. found_bps.push_back(blueprints[bp_i[index]]);
  11361. get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
  11362. }
  11363. else
  11364. {
  11365. if (found_bps.size() < 2)
  11366. {
  11367. found_bps.clear();
  11368. found_bps.push_back(blueprints_[bp_i[index]]);
  11369. }
  11370. else
  11371. {
  11372. found_bps.pop_back();
  11373. Blueprint* last_element = found_bps.back();
  11374. found_bps.push_back(last_element->blueprints_[bp_i[index]]);
  11375. }
  11376. get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
  11377. }
  11378. }
  11379. }
  11380. /// Is used to handle errors, you insert the error code, found route, request, and response. and it'll either call the appropriate catchall route (considering the blueprint system) and send you a status string (which is mainly used for debug messages), or just set the response code to the proper error code.
  11381. std::string get_error(unsigned short code, routing_handle_result& found, const request& req, response& res)
  11382. {
  11383. res.code = code;
  11384. std::vector<Blueprint*> bps_found;
  11385. get_found_bp(found.blueprint_indices, blueprints_, bps_found);
  11386. for (int i = bps_found.size() - 1; i > 0; i--)
  11387. {
  11388. std::vector<uint16_t> bpi = found.blueprint_indices;
  11389. if (bps_found[i]->catchall_rule().has_handler())
  11390. {
  11391. try
  11392. {
  11393. bps_found[i]->catchall_rule().handler_(req, res);
  11394. }
  11395. catch (...)
  11396. {
  11397. exception_handler_(res);
  11398. }
  11399. #ifdef CROW_ENABLE_DEBUG
  11400. return std::string("Redirected to Blueprint \"" + bps_found[i]->prefix() + "\" Catchall rule");
  11401. #else
  11402. return std::string();
  11403. #endif
  11404. }
  11405. }
  11406. if (catchall_rule_.has_handler())
  11407. {
  11408. try
  11409. {
  11410. catchall_rule_.handler_(req, res);
  11411. }
  11412. catch (...)
  11413. {
  11414. exception_handler_(res);
  11415. }
  11416. #ifdef CROW_ENABLE_DEBUG
  11417. return std::string("Redirected to global Catchall rule");
  11418. #else
  11419. return std::string();
  11420. #endif
  11421. }
  11422. return std::string();
  11423. }
  11424. std::unique_ptr<routing_handle_result> handle_initial(request& req, response& res)
  11425. {
  11426. HTTPMethod method_actual = req.method;
  11427. std::unique_ptr<routing_handle_result> found{
  11428. new routing_handle_result(
  11429. 0,
  11430. std::vector<uint16_t>(),
  11431. routing_params(),
  11432. HTTPMethod::InternalMethodCount)}; // This is always returned to avoid a null pointer dereference.
  11433. // NOTE(EDev): This most likely will never run since the parser should handle this situation and close the connection before it gets here.
  11434. if (CROW_UNLIKELY(req.method >= HTTPMethod::InternalMethodCount))
  11435. return found;
  11436. else if (req.method == HTTPMethod::Head)
  11437. {
  11438. *found = per_methods_[static_cast<int>(method_actual)].trie.find(req.url);
  11439. // support HEAD requests using GET if not defined as method for the requested URL
  11440. if (!found->rule_index)
  11441. {
  11442. method_actual = HTTPMethod::Get;
  11443. *found = per_methods_[static_cast<int>(method_actual)].trie.find(req.url);
  11444. if (!found->rule_index) // If a route is still not found, return a 404 without executing the rest of the HEAD specific code.
  11445. {
  11446. CROW_LOG_DEBUG << "Cannot match rules " << req.url;
  11447. res = response(404); //TODO(EDev): Should this redirect to catchall?
  11448. res.end();
  11449. return found;
  11450. }
  11451. }
  11452. res.skip_body = true;
  11453. found->method = method_actual;
  11454. return found;
  11455. }
  11456. else if (req.method == HTTPMethod::Options)
  11457. {
  11458. std::string allow = "OPTIONS, HEAD, ";
  11459. if (req.url == "/*")
  11460. {
  11461. for (int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
  11462. {
  11463. if (static_cast<int>(HTTPMethod::Head) == i)
  11464. continue; // HEAD is always allowed
  11465. if (!per_methods_[i].trie.is_empty())
  11466. {
  11467. allow += method_name(static_cast<HTTPMethod>(i)) + ", ";
  11468. }
  11469. }
  11470. allow = allow.substr(0, allow.size() - 2);
  11471. res = response(204);
  11472. res.set_header("Allow", allow);
  11473. res.end();
  11474. found->method = method_actual;
  11475. return found;
  11476. }
  11477. else
  11478. {
  11479. bool rules_matched = false;
  11480. for (int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
  11481. {
  11482. if (per_methods_[i].trie.find(req.url).rule_index)
  11483. {
  11484. rules_matched = true;
  11485. if (static_cast<int>(HTTPMethod::Head) == i)
  11486. continue; // HEAD is always allowed
  11487. allow += method_name(static_cast<HTTPMethod>(i)) + ", ";
  11488. }
  11489. }
  11490. if (rules_matched)
  11491. {
  11492. allow = allow.substr(0, allow.size() - 2);
  11493. res = response(204);
  11494. res.set_header("Allow", allow);
  11495. res.end();
  11496. found->method = method_actual;
  11497. return found;
  11498. }
  11499. else
  11500. {
  11501. CROW_LOG_DEBUG << "Cannot match rules " << req.url;
  11502. res = response(404); //TODO(EDev): Should this redirect to catchall?
  11503. res.end();
  11504. return found;
  11505. }
  11506. }
  11507. }
  11508. else // Every request that isn't a HEAD or OPTIONS request
  11509. {
  11510. *found = per_methods_[static_cast<int>(method_actual)].trie.find(req.url);
  11511. // TODO(EDev): maybe ending the else here would allow the requests coming from above (after removing the return statement) to be checked on whether they actually point to a route
  11512. if (!found->rule_index)
  11513. {
  11514. for (auto& per_method : per_methods_)
  11515. {
  11516. if (per_method.trie.find(req.url).rule_index) //Route found, but in another method
  11517. {
  11518. const std::string error_message(get_error(405, *found, req, res));
  11519. CROW_LOG_DEBUG << "Cannot match method " << req.url << " " << method_name(method_actual) << ". " << error_message;
  11520. res.end();
  11521. return found;
  11522. }
  11523. }
  11524. //Route does not exist anywhere
  11525. const std::string error_message(get_error(404, *found, req, res));
  11526. CROW_LOG_DEBUG << "Cannot match rules " << req.url << ". " << error_message;
  11527. res.end();
  11528. return found;
  11529. }
  11530. found->method = method_actual;
  11531. return found;
  11532. }
  11533. }
  11534. template<typename App>
  11535. void handle(request& req, response& res, routing_handle_result found)
  11536. {
  11537. HTTPMethod method_actual = found.method;
  11538. auto& rules = per_methods_[static_cast<int>(method_actual)].rules;
  11539. unsigned rule_index = found.rule_index;
  11540. if (rule_index >= rules.size())
  11541. throw std::runtime_error("Trie internal structure corrupted!");
  11542. if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
  11543. {
  11544. CROW_LOG_INFO << "Redirecting to a url with trailing slash: " << req.url;
  11545. res = response(301);
  11546. // TODO(ipkn) absolute url building
  11547. if (req.get_header_value("Host").empty())
  11548. {
  11549. res.add_header("Location", req.url + "/");
  11550. }
  11551. else
  11552. {
  11553. res.add_header("Location", "http://" + req.get_header_value("Host") + req.url + "/");
  11554. }
  11555. res.end();
  11556. return;
  11557. }
  11558. CROW_LOG_DEBUG << "Matched rule '" << rules[rule_index]->rule_ << "' " << static_cast<uint32_t>(req.method) << " / " << rules[rule_index]->get_methods();
  11559. try
  11560. {
  11561. auto& rule = rules[rule_index];
  11562. handle_rule<App>(rule, req, res, found.r_params);
  11563. }
  11564. catch (...)
  11565. {
  11566. exception_handler_(res);
  11567. res.end();
  11568. return;
  11569. }
  11570. }
  11571. template<typename App>
  11572. typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value != 0, void>::type
  11573. handle_rule(BaseRule* rule, crow::request& req, crow::response& res, const crow::routing_params& rp)
  11574. {
  11575. if (!rule->mw_indices_.empty())
  11576. {
  11577. auto& ctx = *reinterpret_cast<typename App::context_t*>(req.middleware_context);
  11578. auto& container = *reinterpret_cast<typename App::mw_container_t*>(req.middleware_container);
  11579. detail::middleware_call_criteria_dynamic<false> crit_fwd(rule->mw_indices_.indices());
  11580. auto glob_completion_handler = std::move(res.complete_request_handler_);
  11581. res.complete_request_handler_ = [] {};
  11582. detail::middleware_call_helper<decltype(crit_fwd),
  11583. 0, typename App::context_t, typename App::mw_container_t>(crit_fwd, container, req, res, ctx);
  11584. if (res.completed_)
  11585. {
  11586. glob_completion_handler();
  11587. return;
  11588. }
  11589. res.complete_request_handler_ = [&rule, &ctx, &container, &req, &res, glob_completion_handler] {
  11590. detail::middleware_call_criteria_dynamic<true> crit_bwd(rule->mw_indices_.indices());
  11591. detail::after_handlers_call_helper<
  11592. decltype(crit_bwd),
  11593. std::tuple_size<typename App::mw_container_t>::value - 1,
  11594. typename App::context_t,
  11595. typename App::mw_container_t>(crit_bwd, container, ctx, req, res);
  11596. glob_completion_handler();
  11597. };
  11598. }
  11599. rule->handle(req, res, rp);
  11600. }
  11601. template<typename App>
  11602. typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value == 0, void>::type
  11603. handle_rule(BaseRule* rule, crow::request& req, crow::response& res, const crow::routing_params& rp)
  11604. {
  11605. rule->handle(req, res, rp);
  11606. }
  11607. void debug_print()
  11608. {
  11609. for (int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
  11610. {
  11611. Trie& trie_ = per_methods_[i].trie;
  11612. if (!trie_.is_empty())
  11613. {
  11614. CROW_LOG_DEBUG << method_name(static_cast<HTTPMethod>(i));
  11615. trie_.debug_print();
  11616. }
  11617. }
  11618. }
  11619. std::vector<Blueprint*>& blueprints()
  11620. {
  11621. return blueprints_;
  11622. }
  11623. std::function<void(crow::response&)>& exception_handler()
  11624. {
  11625. return exception_handler_;
  11626. }
  11627. static void default_exception_handler(response& res)
  11628. {
  11629. // any uncaught exceptions become 500s
  11630. res = response(500);
  11631. try
  11632. {
  11633. throw;
  11634. }
  11635. catch (const std::exception& e)
  11636. {
  11637. CROW_LOG_ERROR << "An uncaught exception occurred: " << e.what();
  11638. }
  11639. catch (...)
  11640. {
  11641. CROW_LOG_ERROR << "An uncaught exception occurred. The type was unknown so no information was available.";
  11642. }
  11643. }
  11644. private:
  11645. CatchallRule catchall_rule_;
  11646. struct PerMethod
  11647. {
  11648. std::vector<BaseRule*> rules;
  11649. Trie trie;
  11650. // rule index 0, 1 has special meaning; preallocate it to avoid duplication.
  11651. PerMethod():
  11652. rules(2) {}
  11653. };
  11654. std::array<PerMethod, static_cast<int>(HTTPMethod::InternalMethodCount)> per_methods_;
  11655. std::vector<std::unique_ptr<BaseRule>> all_rules_;
  11656. std::vector<Blueprint*> blueprints_;
  11657. std::function<void(crow::response&)> exception_handler_ = &default_exception_handler;
  11658. };
  11659. } // namespace crow
  11660. namespace crow
  11661. {
  11662. struct CORSHandler;
  11663. /// Used for tuning CORS policies
  11664. struct CORSRules
  11665. {
  11666. friend struct crow::CORSHandler;
  11667. /// Set Access-Control-Allow-Origin. Default is "*"
  11668. CORSRules& origin(const std::string& origin)
  11669. {
  11670. origin_ = origin;
  11671. return *this;
  11672. }
  11673. /// Set Access-Control-Allow-Methods. Default is "*"
  11674. CORSRules& methods(crow::HTTPMethod method)
  11675. {
  11676. add_list_item(methods_, crow::method_name(method));
  11677. return *this;
  11678. }
  11679. /// Set Access-Control-Allow-Methods. Default is "*"
  11680. template<typename... Methods>
  11681. CORSRules& methods(crow::HTTPMethod method, Methods... method_list)
  11682. {
  11683. add_list_item(methods_, crow::method_name(method));
  11684. methods(method_list...);
  11685. return *this;
  11686. }
  11687. /// Set Access-Control-Allow-Headers. Default is "*"
  11688. CORSRules& headers(const std::string& header)
  11689. {
  11690. add_list_item(headers_, header);
  11691. return *this;
  11692. }
  11693. /// Set Access-Control-Allow-Headers. Default is "*"
  11694. template<typename... Headers>
  11695. CORSRules& headers(const std::string& header, Headers... header_list)
  11696. {
  11697. add_list_item(headers_, header);
  11698. headers(header_list...);
  11699. return *this;
  11700. }
  11701. /// Set Access-Control-Max-Age. Default is none
  11702. CORSRules& max_age(int max_age)
  11703. {
  11704. max_age_ = std::to_string(max_age);
  11705. return *this;
  11706. }
  11707. /// Enable Access-Control-Allow-Credentials
  11708. CORSRules& allow_credentials()
  11709. {
  11710. allow_credentials_ = true;
  11711. return *this;
  11712. }
  11713. /// Ignore CORS and don't send any headers
  11714. void ignore()
  11715. {
  11716. ignore_ = true;
  11717. }
  11718. /// Handle CORS on specific prefix path
  11719. CORSRules& prefix(const std::string& prefix);
  11720. /// Handle CORS for specific blueprint
  11721. CORSRules& blueprint(const Blueprint& bp);
  11722. /// Global CORS policy
  11723. CORSRules& global();
  11724. private:
  11725. CORSRules() = delete;
  11726. CORSRules(CORSHandler* handler):
  11727. handler_(handler) {}
  11728. /// build comma separated list
  11729. void add_list_item(std::string& list, const std::string& val)
  11730. {
  11731. if (list == "*") list = "";
  11732. if (list.size() > 0) list += ", ";
  11733. list += val;
  11734. }
  11735. /// Set header `key` to `value` if it is not set
  11736. void set_header_no_override(const std::string& key, const std::string& value, crow::response& res)
  11737. {
  11738. if (value.size() == 0) return;
  11739. if (!get_header_value(res.headers, key).empty()) return;
  11740. res.add_header(key, value);
  11741. }
  11742. /// Set response headers
  11743. void apply(crow::response& res)
  11744. {
  11745. if (ignore_) return;
  11746. set_header_no_override("Access-Control-Allow-Origin", origin_, res);
  11747. set_header_no_override("Access-Control-Allow-Methods", methods_, res);
  11748. set_header_no_override("Access-Control-Allow-Headers", headers_, res);
  11749. set_header_no_override("Access-Control-Max-Age", max_age_, res);
  11750. if (allow_credentials_) set_header_no_override("Access-Control-Allow-Credentials", "true", res);
  11751. }
  11752. bool ignore_ = false;
  11753. // TODO: support multiple origins that are dynamically selected
  11754. std::string origin_ = "*";
  11755. std::string methods_ = "*";
  11756. std::string headers_ = "*";
  11757. std::string max_age_;
  11758. bool allow_credentials_ = false;
  11759. CORSHandler* handler_;
  11760. };
  11761. /// CORSHandler is a global middleware for setting CORS headers.
  11762. ///
  11763. /// By default, it sets Access-Control-Allow-Origin/Methods/Headers to "*".
  11764. /// The default behaviour can be changed with the `global()` cors rule.
  11765. /// Additional rules for prexies can be added with `prefix()`.
  11766. struct CORSHandler
  11767. {
  11768. struct context
  11769. {};
  11770. void before_handle(crow::request& /*req*/, crow::response& /*res*/, context& /*ctx*/)
  11771. {}
  11772. void after_handle(crow::request& req, crow::response& res, context& /*ctx*/)
  11773. {
  11774. auto& rule = find_rule(req.url);
  11775. rule.apply(res);
  11776. }
  11777. /// Handle CORS on a specific prefix path
  11778. CORSRules& prefix(const std::string& prefix)
  11779. {
  11780. rules.emplace_back(prefix, CORSRules(this));
  11781. return rules.back().second;
  11782. }
  11783. /// Handle CORS for a specific blueprint
  11784. CORSRules& blueprint(const Blueprint& bp)
  11785. {
  11786. rules.emplace_back(bp.prefix(), CORSRules(this));
  11787. return rules.back().second;
  11788. }
  11789. /// Get the global CORS policy
  11790. CORSRules& global()
  11791. {
  11792. return default_;
  11793. }
  11794. private:
  11795. CORSRules& find_rule(const std::string& path)
  11796. {
  11797. // TODO: use a trie in case of many rules
  11798. for (auto& rule : rules)
  11799. {
  11800. // Check if path starts with a rules prefix
  11801. if (path.rfind(rule.first, 0) == 0)
  11802. {
  11803. return rule.second;
  11804. }
  11805. }
  11806. return default_;
  11807. }
  11808. std::vector<std::pair<std::string, CORSRules>> rules;
  11809. CORSRules default_ = CORSRules(this);
  11810. };
  11811. inline CORSRules& CORSRules::prefix(const std::string& prefix)
  11812. {
  11813. return handler_->prefix(prefix);
  11814. }
  11815. inline CORSRules& CORSRules::blueprint(const Blueprint& bp)
  11816. {
  11817. return handler_->blueprint(bp);
  11818. }
  11819. inline CORSRules& CORSRules::global()
  11820. {
  11821. return handler_->global();
  11822. }
  11823. } // namespace crow
  11824. /**
  11825. * \file crow/app.h
  11826. * \brief This file includes the definition of the crow::Crow class,
  11827. * the crow::App and crow::SimpleApp aliases, and some macros.
  11828. *
  11829. * In this file are defined:
  11830. * - crow::Crow
  11831. * - crow::App
  11832. * - crow::SimpleApp
  11833. * - \ref CROW_ROUTE
  11834. * - \ref CROW_BP_ROUTE
  11835. * - \ref CROW_WEBSOCKET_ROUTE
  11836. * - \ref CROW_MIDDLEWARES
  11837. * - \ref CROW_CATCHALL_ROUTE
  11838. * - \ref CROW_BP_CATCHALL_ROUTE
  11839. */
  11840. #include <chrono>
  11841. #include <string>
  11842. #include <functional>
  11843. #include <memory>
  11844. #include <future>
  11845. #include <cstdint>
  11846. #include <type_traits>
  11847. #include <thread>
  11848. #include <condition_variable>
  11849. #ifdef CROW_ENABLE_COMPRESSION
  11850. #endif // #ifdef CROW_ENABLE_COMPRESSION
  11851. #ifdef CROW_MSVC_WORKAROUND
  11852. #define CROW_ROUTE(app, url) app.route_dynamic(url) // See the documentation in the comment below.
  11853. #define CROW_BP_ROUTE(blueprint, url) blueprint.new_rule_dynamic(url) // See the documentation in the comment below.
  11854. #else // #ifdef CROW_MSVC_WORKAROUND
  11855. /**
  11856. * \def CROW_ROUTE(app, url)
  11857. * \brief Creates a route for app using a rule.
  11858. *
  11859. * It use crow::Crow::route_dynamic or crow::Crow::route to define
  11860. * a rule for your application. It's usage is like this:
  11861. *
  11862. * ```cpp
  11863. * auto app = crow::SimpleApp(); // or crow::App()
  11864. * CROW_ROUTE(app, "/")
  11865. * ([](){
  11866. * return "<h1>Hello, world!</h1>";
  11867. * });
  11868. * ```
  11869. *
  11870. * This is the recommended way to define routes in a crow application.
  11871. * \see [Page of guide "Routes"](https://crowcpp.org/master/guides/routes/).
  11872. */
  11873. #define CROW_ROUTE(app, url) app.template route<crow::black_magic::get_parameter_tag(url)>(url)
  11874. /**
  11875. * \def CROW_BP_ROUTE(blueprint, url)
  11876. * \brief Creates a route for a blueprint using a rule.
  11877. *
  11878. * It may use crow::Blueprint::new_rule_dynamic or
  11879. * crow::Blueprint::new_rule_tagged to define a new rule for
  11880. * an given blueprint. It's usage is similar
  11881. * to CROW_ROUTE macro:
  11882. *
  11883. * ```cpp
  11884. * crow::Blueprint my_bp();
  11885. * CROW_BP_ROUTE(my_bp, "/")
  11886. * ([](){
  11887. * return "<h1>Hello, world!</h1>";
  11888. * });
  11889. * ```
  11890. *
  11891. * This is the recommended way to define routes in a crow blueprint
  11892. * because of its compile-time capabilities.
  11893. *
  11894. * \see [Page of the guide "Blueprints"](https://crowcpp.org/master/guides/blueprints/).
  11895. */
  11896. #define CROW_BP_ROUTE(blueprint, url) blueprint.new_rule_tagged<crow::black_magic::get_parameter_tag(url)>(url)
  11897. /**
  11898. * \def CROW_WEBSOCKET_ROUTE(app, url)
  11899. * \brief Defines WebSocket route for app.
  11900. *
  11901. * It binds a WebSocket route to app. Easy solution to implement
  11902. * WebSockets in your app. The usage syntax of this macro is
  11903. * like this:
  11904. *
  11905. * ```cpp
  11906. * auto app = crow::SimpleApp(); // or crow::App()
  11907. * CROW_WEBSOCKET_ROUTE(app, "/ws")
  11908. * .onopen([&](crow::websocket::connection& conn){
  11909. * do_something();
  11910. * })
  11911. * .onclose([&](crow::websocket::connection& conn, const std::string& reason){
  11912. * do_something();
  11913. * })
  11914. * .onmessage([&](crow::websocket::connection&, const std::string& data, bool is_binary){
  11915. * if (is_binary)
  11916. * do_something(data);
  11917. * else
  11918. * do_something_else(data);
  11919. * });
  11920. * ```
  11921. *
  11922. * \see [Page of the guide "WebSockets"](https://crowcpp.org/master/guides/websockets/).
  11923. */
  11924. #define CROW_WEBSOCKET_ROUTE(app, url) app.route<crow::black_magic::get_parameter_tag(url)>(url).websocket<std::remove_reference<decltype(app)>::type>(&app)
  11925. /**
  11926. * \def CROW_MIDDLEWARES(app, ...)
  11927. * \brief Enable a Middleware for an specific route in app
  11928. * or blueprint.
  11929. *
  11930. * It defines the usage of a Middleware in one route. And it
  11931. * can be used in both crow::SimpleApp (and crow::App) instances and
  11932. * crow::Blueprint. Its usage syntax is like this:
  11933. *
  11934. * ```cpp
  11935. * auto app = crow::SimpleApp(); // or crow::App()
  11936. * CROW_ROUTE(app, "/with_middleware")
  11937. * .CROW_MIDDLEWARES(app, LocalMiddleware) // Can be used more than one
  11938. * ([]() { // middleware.
  11939. * return "Hello world!";
  11940. * });
  11941. * ```
  11942. *
  11943. * \see [Page of the guide "Middlewares"](https://crowcpp.org/master/guides/middleware/).
  11944. */
  11945. #define CROW_MIDDLEWARES(app, ...) template middlewares<typename std::remove_reference<decltype(app)>::type, __VA_ARGS__>()
  11946. #endif // #ifdef CROW_MSVC_WORKAROUND
  11947. /**
  11948. * \def CROW_CATCHALL_ROUTE(app)
  11949. * \brief Defines a custom catchall route for app using a
  11950. * custom rule.
  11951. *
  11952. * It defines a handler when the client make a request for an
  11953. * undefined route. Instead of just reply with a `404` status
  11954. * code (default behavior), you can define a custom handler
  11955. * using this macro.
  11956. *
  11957. * \see [Page of the guide "Routes" (Catchall routes)](https://crowcpp.org/master/guides/routes/#catchall-routes).
  11958. */
  11959. #define CROW_CATCHALL_ROUTE(app) app.catchall_route()
  11960. /**
  11961. * \def CROW_BP_CATCHALL_ROUTE(blueprint)
  11962. * \brief Defines a custom catchall route for blueprint
  11963. * using a custom rule.
  11964. *
  11965. * It defines a handler when the client make a request for an
  11966. * undefined route in the blueprint.
  11967. *
  11968. * \see [Page of the guide "Blueprint" (Define a custom Catchall route)](https://crowcpp.org/master/guides/blueprints/#define-a-custom-catchall-route).
  11969. */
  11970. #define CROW_BP_CATCHALL_ROUTE(blueprint) blueprint.catchall_rule()
  11971. /**
  11972. * \namespace crow
  11973. * \brief The main namespace of the library. In this namespace
  11974. * is defined the most important classes and functions of the
  11975. * library.
  11976. *
  11977. * Within this namespace, the Crow class, Router class, Connection
  11978. * class, and other are defined.
  11979. */
  11980. namespace crow
  11981. {
  11982. #ifdef CROW_ENABLE_SSL
  11983. using ssl_context_t = asio::ssl::context;
  11984. #endif
  11985. /**
  11986. * \class Crow
  11987. * \brief The main server application class.
  11988. *
  11989. * Use crow::SimpleApp or crow::App<Middleware1, Middleware2, etc...> instead of
  11990. * directly instantiate this class.
  11991. */
  11992. template<typename... Middlewares>
  11993. class Crow
  11994. {
  11995. public:
  11996. /// \brief This is the crow application
  11997. using self_t = Crow;
  11998. /// \brief The HTTP server
  11999. using server_t = Server<Crow, SocketAdaptor, Middlewares...>;
  12000. #ifdef CROW_ENABLE_SSL
  12001. /// \brief An HTTP server that runs on SSL with an SSLAdaptor
  12002. using ssl_server_t = Server<Crow, SSLAdaptor, Middlewares...>;
  12003. #endif
  12004. Crow()
  12005. {}
  12006. /// \brief Construct Crow with a subset of middleware
  12007. template<typename... Ts>
  12008. Crow(Ts&&... ts):
  12009. middlewares_(make_middleware_tuple(std::forward<Ts>(ts)...))
  12010. {}
  12011. /// \brief Process an Upgrade request
  12012. ///
  12013. /// Currently used to upgrade an HTTP connection to a WebSocket connection
  12014. template<typename Adaptor>
  12015. void handle_upgrade(const request& req, response& res, Adaptor&& adaptor)
  12016. {
  12017. router_.handle_upgrade(req, res, adaptor);
  12018. }
  12019. /// \brief Process only the method and URL of a request and provide a route (or an error response)
  12020. std::unique_ptr<routing_handle_result> handle_initial(request& req, response& res)
  12021. {
  12022. return router_.handle_initial(req, res);
  12023. }
  12024. /// \brief Process the fully parsed request and generate a response for it
  12025. void handle(request& req, response& res, std::unique_ptr<routing_handle_result>& found)
  12026. {
  12027. router_.handle<self_t>(req, res, *found);
  12028. }
  12029. /// \brief Process a fully parsed request from start to finish (primarily used for debugging)
  12030. void handle_full(request& req, response& res)
  12031. {
  12032. auto found = handle_initial(req, res);
  12033. if (found->rule_index)
  12034. handle(req, res, found);
  12035. }
  12036. /// \brief Create a dynamic route using a rule (**Use CROW_ROUTE instead**)
  12037. DynamicRule& route_dynamic(const std::string& rule)
  12038. {
  12039. return router_.new_rule_dynamic(rule);
  12040. }
  12041. /// \brief Create a route using a rule (**Use CROW_ROUTE instead**)
  12042. template<uint64_t Tag>
  12043. #ifdef CROW_GCC83_WORKAROUND
  12044. auto& route(const std::string& rule)
  12045. #else
  12046. auto route(const std::string& rule)
  12047. #endif
  12048. #if defined CROW_CAN_USE_CPP17 && !defined CROW_GCC83_WORKAROUND
  12049. -> typename std::invoke_result<decltype(&Router::new_rule_tagged<Tag>), Router, const std::string&>::type
  12050. #elif !defined CROW_GCC83_WORKAROUND
  12051. -> typename std::result_of<decltype (&Router::new_rule_tagged<Tag>)(Router, const std::string&)>::type
  12052. #endif
  12053. {
  12054. return router_.new_rule_tagged<Tag>(rule);
  12055. }
  12056. /// \brief Create a route for any requests without a proper route (**Use CROW_CATCHALL_ROUTE instead**)
  12057. CatchallRule& catchall_route()
  12058. {
  12059. return router_.catchall_rule();
  12060. }
  12061. /// \brief Set the default max payload size for websockets
  12062. self_t& websocket_max_payload(uint64_t max_payload)
  12063. {
  12064. max_payload_ = max_payload;
  12065. return *this;
  12066. }
  12067. /// \brief Get the default max payload size for websockets
  12068. uint64_t websocket_max_payload()
  12069. {
  12070. return max_payload_;
  12071. }
  12072. self_t& signal_clear()
  12073. {
  12074. signals_.clear();
  12075. return *this;
  12076. }
  12077. self_t& signal_add(int signal_number)
  12078. {
  12079. signals_.push_back(signal_number);
  12080. return *this;
  12081. }
  12082. std::vector<int> signals()
  12083. {
  12084. return signals_;
  12085. }
  12086. /// \brief Set the port that Crow will handle requests on
  12087. self_t& port(std::uint16_t port)
  12088. {
  12089. port_ = port;
  12090. return *this;
  12091. }
  12092. /// \brief Get the port that Crow will handle requests on
  12093. std::uint16_t port()
  12094. {
  12095. return port_;
  12096. }
  12097. /// \brief Set the connection timeout in seconds (default is 5)
  12098. self_t& timeout(std::uint8_t timeout)
  12099. {
  12100. timeout_ = timeout;
  12101. return *this;
  12102. }
  12103. /// \brief Set the server name
  12104. self_t& server_name(std::string server_name)
  12105. {
  12106. server_name_ = server_name;
  12107. return *this;
  12108. }
  12109. /// \brief The IP address that Crow will handle requests on (default is 0.0.0.0)
  12110. self_t& bindaddr(std::string bindaddr)
  12111. {
  12112. bindaddr_ = bindaddr;
  12113. return *this;
  12114. }
  12115. /// \brief Get the address that Crow will handle requests on
  12116. std::string bindaddr()
  12117. {
  12118. return bindaddr_;
  12119. }
  12120. /// \brief Run the server on multiple threads using all available threads
  12121. self_t& multithreaded()
  12122. {
  12123. return concurrency(std::thread::hardware_concurrency());
  12124. }
  12125. /// \brief Run the server on multiple threads using a specific number
  12126. self_t& concurrency(std::uint16_t concurrency)
  12127. {
  12128. if (concurrency < 2) // Crow can have a minimum of 2 threads running
  12129. concurrency = 2;
  12130. concurrency_ = concurrency;
  12131. return *this;
  12132. }
  12133. /// \brief Get the number of threads that server is using
  12134. std::uint16_t concurrency()
  12135. {
  12136. return concurrency_;
  12137. }
  12138. /// \brief Set the server's log level
  12139. ///
  12140. /// Possible values are:
  12141. /// - crow::LogLevel::Debug (0)
  12142. /// - crow::LogLevel::Info (1)
  12143. /// - crow::LogLevel::Warning (2)
  12144. /// - crow::LogLevel::Error (3)
  12145. /// - crow::LogLevel::Critical (4)
  12146. self_t& loglevel(LogLevel level)
  12147. {
  12148. crow::logger::setLogLevel(level);
  12149. return *this;
  12150. }
  12151. /// \brief Set the response body size (in bytes) beyond which Crow automatically streams responses (Default is 1MiB)
  12152. ///
  12153. /// Any streamed response is unaffected by Crow's timer, and therefore won't timeout before a response is fully sent.
  12154. self_t& stream_threshold(size_t threshold)
  12155. {
  12156. res_stream_threshold_ = threshold;
  12157. return *this;
  12158. }
  12159. /// \brief Get the response body size (in bytes) beyond which Crow automatically streams responses
  12160. size_t& stream_threshold()
  12161. {
  12162. return res_stream_threshold_;
  12163. }
  12164. self_t& register_blueprint(Blueprint& blueprint)
  12165. {
  12166. router_.register_blueprint(blueprint);
  12167. return *this;
  12168. }
  12169. /// \brief Set the function to call to handle uncaught exceptions generated in routes (Default generates error 500).
  12170. ///
  12171. /// The function must have the following signature: void(crow::response&).
  12172. /// It must set the response passed in argument to the function, which will be sent back to the client.
  12173. /// See Router::default_exception_handler() for the default implementation.
  12174. template<typename Func>
  12175. self_t& exception_handler(Func&& f)
  12176. {
  12177. router_.exception_handler() = std::forward<Func>(f);
  12178. return *this;
  12179. }
  12180. std::function<void(crow::response&)>& exception_handler()
  12181. {
  12182. return router_.exception_handler();
  12183. }
  12184. /// \brief Set a custom duration and function to run on every tick
  12185. template<typename Duration, typename Func>
  12186. self_t& tick(Duration d, Func f)
  12187. {
  12188. tick_interval_ = std::chrono::duration_cast<std::chrono::milliseconds>(d);
  12189. tick_function_ = f;
  12190. return *this;
  12191. }
  12192. #ifdef CROW_ENABLE_COMPRESSION
  12193. self_t& use_compression(compression::algorithm algorithm)
  12194. {
  12195. comp_algorithm_ = algorithm;
  12196. compression_used_ = true;
  12197. return *this;
  12198. }
  12199. compression::algorithm compression_algorithm()
  12200. {
  12201. return comp_algorithm_;
  12202. }
  12203. bool compression_used() const
  12204. {
  12205. return compression_used_;
  12206. }
  12207. #endif
  12208. /// \brief Apply blueprints
  12209. void add_blueprint()
  12210. {
  12211. #if defined(__APPLE__) || defined(__MACH__)
  12212. if (router_.blueprints().empty()) return;
  12213. #endif
  12214. for (Blueprint* bp : router_.blueprints())
  12215. {
  12216. if (bp->static_dir().empty()) continue;
  12217. auto static_dir_ = crow::utility::normalize_path(bp->static_dir());
  12218. bp->new_rule_tagged<crow::black_magic::get_parameter_tag(CROW_STATIC_ENDPOINT)>(CROW_STATIC_ENDPOINT)([static_dir_](crow::response& res, std::string file_path_partial) {
  12219. utility::sanitize_filename(file_path_partial);
  12220. res.set_static_file_info_unsafe(static_dir_ + file_path_partial);
  12221. res.end();
  12222. });
  12223. }
  12224. router_.validate_bp();
  12225. }
  12226. /// \brief Go through the rules, upgrade them if possible, and add them to the list of rules
  12227. void add_static_dir()
  12228. {
  12229. if (are_static_routes_added()) return;
  12230. auto static_dir_ = crow::utility::normalize_path(CROW_STATIC_DIRECTORY);
  12231. route<crow::black_magic::get_parameter_tag(CROW_STATIC_ENDPOINT)>(CROW_STATIC_ENDPOINT)([static_dir_](crow::response& res, std::string file_path_partial) {
  12232. utility::sanitize_filename(file_path_partial);
  12233. res.set_static_file_info_unsafe(static_dir_ + file_path_partial);
  12234. res.end();
  12235. });
  12236. set_static_routes_added();
  12237. }
  12238. /// \brief A wrapper for `validate()` in the router
  12239. void validate()
  12240. {
  12241. router_.validate();
  12242. }
  12243. /// \brief Run the server
  12244. void run()
  12245. {
  12246. #ifndef CROW_DISABLE_STATIC_DIR
  12247. add_blueprint();
  12248. add_static_dir();
  12249. #endif
  12250. validate();
  12251. #ifdef CROW_ENABLE_SSL
  12252. if (ssl_used_)
  12253. {
  12254. ssl_server_ = std::move(std::unique_ptr<ssl_server_t>(new ssl_server_t(this, bindaddr_, port_, server_name_, &middlewares_, concurrency_, timeout_, &ssl_context_)));
  12255. ssl_server_->set_tick_function(tick_interval_, tick_function_);
  12256. ssl_server_->signal_clear();
  12257. for (auto snum : signals_)
  12258. {
  12259. ssl_server_->signal_add(snum);
  12260. }
  12261. notify_server_start();
  12262. ssl_server_->run();
  12263. }
  12264. else
  12265. #endif
  12266. {
  12267. server_ = std::move(std::unique_ptr<server_t>(new server_t(this, bindaddr_, port_, server_name_, &middlewares_, concurrency_, timeout_, nullptr)));
  12268. server_->set_tick_function(tick_interval_, tick_function_);
  12269. for (auto snum : signals_)
  12270. {
  12271. server_->signal_add(snum);
  12272. }
  12273. notify_server_start();
  12274. server_->run();
  12275. }
  12276. }
  12277. /// \brief Non-blocking version of \ref run()
  12278. ///
  12279. /// The output from this method needs to be saved into a variable!
  12280. /// Otherwise the call will be made on the same thread.
  12281. std::future<void> run_async()
  12282. {
  12283. return std::async(std::launch::async, [&] {
  12284. this->run();
  12285. });
  12286. }
  12287. /// \brief Stop the server
  12288. void stop()
  12289. {
  12290. #ifdef CROW_ENABLE_SSL
  12291. if (ssl_used_)
  12292. {
  12293. if (ssl_server_) { ssl_server_->stop(); }
  12294. }
  12295. else
  12296. #endif
  12297. {
  12298. // TODO(EDev): Move these 6 lines to a method in http_server.
  12299. std::vector<crow::websocket::connection*> websockets_to_close = websockets_;
  12300. for (auto websocket : websockets_to_close)
  12301. {
  12302. CROW_LOG_INFO << "Quitting Websocket: " << websocket;
  12303. websocket->close("Server Application Terminated");
  12304. }
  12305. if (server_) { server_->stop(); }
  12306. }
  12307. }
  12308. void add_websocket(crow::websocket::connection* conn)
  12309. {
  12310. websockets_.push_back(conn);
  12311. }
  12312. void remove_websocket(crow::websocket::connection* conn)
  12313. {
  12314. websockets_.erase(std::remove(websockets_.begin(), websockets_.end(), conn), websockets_.end());
  12315. }
  12316. /// \brief Print the routing paths defined for each HTTP method
  12317. void debug_print()
  12318. {
  12319. CROW_LOG_DEBUG << "Routing:";
  12320. router_.debug_print();
  12321. }
  12322. #ifdef CROW_ENABLE_SSL
  12323. /// \brief Use certificate and key files for SSL
  12324. self_t& ssl_file(const std::string& crt_filename, const std::string& key_filename)
  12325. {
  12326. ssl_used_ = true;
  12327. ssl_context_.set_verify_mode(asio::ssl::verify_peer);
  12328. ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
  12329. ssl_context_.use_certificate_file(crt_filename, ssl_context_t::pem);
  12330. ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
  12331. ssl_context_.set_options(
  12332. asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
  12333. return *this;
  12334. }
  12335. /// \brief Use `.pem` file for SSL
  12336. self_t& ssl_file(const std::string& pem_filename)
  12337. {
  12338. ssl_used_ = true;
  12339. ssl_context_.set_verify_mode(asio::ssl::verify_peer);
  12340. ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
  12341. ssl_context_.load_verify_file(pem_filename);
  12342. ssl_context_.set_options(
  12343. asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
  12344. return *this;
  12345. }
  12346. /// \brief Use certificate chain and key files for SSL
  12347. self_t& ssl_chainfile(const std::string& crt_filename, const std::string& key_filename)
  12348. {
  12349. ssl_used_ = true;
  12350. ssl_context_.set_verify_mode(asio::ssl::verify_peer);
  12351. ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
  12352. ssl_context_.use_certificate_chain_file(crt_filename);
  12353. ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
  12354. ssl_context_.set_options(
  12355. asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
  12356. return *this;
  12357. }
  12358. self_t& ssl(asio::ssl::context&& ctx)
  12359. {
  12360. ssl_used_ = true;
  12361. ssl_context_ = std::move(ctx);
  12362. return *this;
  12363. }
  12364. bool ssl_used() const
  12365. {
  12366. return ssl_used_;
  12367. }
  12368. #else
  12369. template<typename T, typename... Remain>
  12370. self_t& ssl_file(T&&, Remain&&...)
  12371. {
  12372. // We can't call .ssl() member function unless CROW_ENABLE_SSL is defined.
  12373. static_assert(
  12374. // make static_assert dependent to T; always false
  12375. std::is_base_of<T, void>::value,
  12376. "Define CROW_ENABLE_SSL to enable ssl support.");
  12377. return *this;
  12378. }
  12379. template<typename T, typename... Remain>
  12380. self_t& ssl_chainfile(T&&, Remain&&...)
  12381. {
  12382. // We can't call .ssl() member function unless CROW_ENABLE_SSL is defined.
  12383. static_assert(
  12384. // make static_assert dependent to T; always false
  12385. std::is_base_of<T, void>::value,
  12386. "Define CROW_ENABLE_SSL to enable ssl support.");
  12387. return *this;
  12388. }
  12389. template<typename T>
  12390. self_t& ssl(T&&)
  12391. {
  12392. // We can't call .ssl() member function unless CROW_ENABLE_SSL is defined.
  12393. static_assert(
  12394. // make static_assert dependent to T; always false
  12395. std::is_base_of<T, void>::value,
  12396. "Define CROW_ENABLE_SSL to enable ssl support.");
  12397. return *this;
  12398. }
  12399. bool ssl_used() const
  12400. {
  12401. return false;
  12402. }
  12403. #endif
  12404. // middleware
  12405. using context_t = detail::context<Middlewares...>;
  12406. using mw_container_t = std::tuple<Middlewares...>;
  12407. template<typename T>
  12408. typename T::context& get_context(const request& req)
  12409. {
  12410. static_assert(black_magic::contains<T, Middlewares...>::value, "App doesn't have the specified middleware type.");
  12411. auto& ctx = *reinterpret_cast<context_t*>(req.middleware_context);
  12412. return ctx.template get<T>();
  12413. }
  12414. template<typename T>
  12415. T& get_middleware()
  12416. {
  12417. return utility::get_element_by_type<T, Middlewares...>(middlewares_);
  12418. }
  12419. /// \brief Wait until the server has properly started
  12420. void wait_for_server_start()
  12421. {
  12422. {
  12423. std::unique_lock<std::mutex> lock(start_mutex_);
  12424. if (!server_started_)
  12425. cv_started_.wait(lock);
  12426. }
  12427. if (server_)
  12428. server_->wait_for_start();
  12429. #ifdef CROW_ENABLE_SSL
  12430. else if (ssl_server_)
  12431. ssl_server_->wait_for_start();
  12432. #endif
  12433. }
  12434. private:
  12435. template<typename... Ts>
  12436. std::tuple<Middlewares...> make_middleware_tuple(Ts&&... ts)
  12437. {
  12438. auto fwd = std::forward_as_tuple((ts)...);
  12439. return std::make_tuple(
  12440. std::forward<Middlewares>(
  12441. black_magic::tuple_extract<Middlewares, decltype(fwd)>(fwd))...);
  12442. }
  12443. /// \brief Notify anything using \ref wait_for_server_start() to proceed
  12444. void notify_server_start()
  12445. {
  12446. std::unique_lock<std::mutex> lock(start_mutex_);
  12447. server_started_ = true;
  12448. cv_started_.notify_all();
  12449. }
  12450. void set_static_routes_added() {
  12451. static_routes_added_ = true;
  12452. }
  12453. bool are_static_routes_added() {
  12454. return static_routes_added_;
  12455. }
  12456. private:
  12457. std::uint8_t timeout_{5};
  12458. uint16_t port_ = 80;
  12459. uint16_t concurrency_ = 2;
  12460. uint64_t max_payload_{UINT64_MAX};
  12461. std::string server_name_ = std::string("Crow/") + VERSION;
  12462. std::string bindaddr_ = "0.0.0.0";
  12463. size_t res_stream_threshold_ = 1048576;
  12464. Router router_;
  12465. bool static_routes_added_{false};
  12466. #ifdef CROW_ENABLE_COMPRESSION
  12467. compression::algorithm comp_algorithm_;
  12468. bool compression_used_{false};
  12469. #endif
  12470. std::chrono::milliseconds tick_interval_;
  12471. std::function<void()> tick_function_;
  12472. std::tuple<Middlewares...> middlewares_;
  12473. #ifdef CROW_ENABLE_SSL
  12474. std::unique_ptr<ssl_server_t> ssl_server_;
  12475. bool ssl_used_{false};
  12476. ssl_context_t ssl_context_{asio::ssl::context::sslv23};
  12477. #endif
  12478. std::unique_ptr<server_t> server_;
  12479. std::vector<int> signals_{SIGINT, SIGTERM};
  12480. bool server_started_{false};
  12481. std::condition_variable cv_started_;
  12482. std::mutex start_mutex_;
  12483. std::vector<crow::websocket::connection*> websockets_;
  12484. };
  12485. /// \brief Alias of Crow<Middlewares...>. Useful if you want
  12486. /// a instance of an Crow application that require Middlewares
  12487. template<typename... Middlewares>
  12488. using App = Crow<Middlewares...>;
  12489. /// \brief Alias of Crow<>. Useful if you want a instance of
  12490. /// an Crow application that doesn't require of Middlewares
  12491. using SimpleApp = Crow<>;
  12492. } // namespace crow