http.h 399 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014
  1. /*
  2. http.h -- Header for the Embedthis Http Library.
  3. The http program is a client to issue HTTP requests. It is also a test platform for loading and testing web servers.
  4. Do NOT use this program as a sample for creating a simple http client.
  5. Copyright (c) All Rights Reserved. See copyright notice at the bottom of the file.
  6. */
  7. #ifndef _h_HTTP
  8. #define _h_HTTP 1
  9. /********************************* Includes ***********************************/
  10. #include "mpr.h"
  11. /****************************** Forward Declarations **************************/
  12. #ifdef __cplusplus
  13. extern "C" {
  14. #endif
  15. #if !DOXYGEN
  16. struct Http;
  17. struct HttpAuth;
  18. struct HttpEndpoint;
  19. struct HttpHost;
  20. struct HttpLimits;
  21. struct HttpNet;
  22. struct HttpPacket;
  23. struct HttpQueue;
  24. struct HttpRoute;
  25. struct HttpRx;
  26. struct HttpSession;
  27. struct HttpStage;
  28. struct HttpStream;
  29. struct HttpTrace;
  30. struct HttpTx;
  31. struct HttpUri;
  32. struct HttpUser;
  33. struct HttpWebSocket;
  34. #endif
  35. /********************************** Tunables **********************************/
  36. #ifndef ME_HTTP_BASIC
  37. #define ME_HTTP_BASIC 0
  38. #endif
  39. #ifndef ME_HTTP_CACHE
  40. #define ME_HTTP_CACHE 0
  41. #endif
  42. #ifndef ME_HTTP_DEFENSE
  43. #define ME_HTTP_DEFENSE 0
  44. #endif
  45. #ifndef ME_HTTP_DIGEST
  46. #define ME_HTTP_DIGEST 0
  47. #endif
  48. #ifndef ME_HTTP_DIR
  49. #define ME_HTTP_DIR 0
  50. #endif
  51. #ifndef ME_HTTP_PAM
  52. #define ME_HTTP_PAM 0
  53. #endif
  54. #ifndef ME_HTTP_HTTP2
  55. #define ME_HTTP_HTTP2 0
  56. #endif
  57. #ifndef ME_HTTP_UPLOAD
  58. #define ME_HTTP_UPLOAD 0
  59. #endif
  60. #ifndef ME_HTTP_WEB_SOCKETS
  61. #define ME_HTTP_WEB_SOCKETS 0
  62. #endif
  63. #ifndef ME_HTTP_SENDFILE
  64. #define ME_HTTP_SENDFILE 1
  65. #endif
  66. /*
  67. Unlimited limit value
  68. */
  69. #define HTTP_UNLIMITED MAXINT64
  70. #if ME_TUNE_SIZE
  71. #ifndef ME_PACKET_SIZE
  72. #define ME_PACKET_SIZE (8 * 1024) /**< Default packet size for pipeline packets */
  73. #endif
  74. #ifndef ME_CHUNK_SIZE
  75. #define ME_CHUNK_SIZE (8 * 1024) /**< Maximum chunk size for transfer chunk encoding */
  76. #endif
  77. #ifndef ME_MAX_PACKET_COUNT
  78. #define ME_MAX_PACKET_COUNT 10 /**< Max packets in socketq */
  79. #endif
  80. #elif ME_TUNE_SPEED
  81. #ifndef ME_PACKET_SIZE
  82. #define ME_PACKET_SIZE (32 * 1024)
  83. #endif
  84. #ifndef ME_CHUNK_SIZE
  85. #define ME_CHUNK_SIZE (32 * 1024)
  86. #endif
  87. #ifndef ME_MAX_PACKET_COUNT
  88. #define ME_MAX_PACKET_COUNT 20
  89. #endif
  90. #else
  91. #ifndef ME_PACKET_SIZE
  92. #define ME_PACKET_SIZE (16 * 1024)
  93. #endif
  94. #ifndef ME_CHUNK_SIZE
  95. #define ME_CHUNK_SIZE (16 * 1024)
  96. #endif
  97. #ifndef ME_MAX_PACKET_COUNT
  98. #define ME_MAX_PACKET_COUNT 30
  99. #endif
  100. #endif
  101. #ifndef ME_SANITY_PACKET
  102. #define ME_SANITY_PACKET (128 * 1024)
  103. #endif
  104. #ifndef ME_HTTP_DEFAULT_METHODS
  105. #define ME_HTTP_DEFAULT_METHODS "GET,POST" /**< Default methods for routes */
  106. #endif
  107. #ifndef ME_HTTP_PORT
  108. #define ME_HTTP_PORT 80
  109. #endif
  110. #ifndef ME_HTTP_SOFTWARE
  111. #define ME_HTTP_SOFTWARE "Embedthis-http" /**< Default Http protocol name used in Http Server header */
  112. #endif
  113. #ifndef ME_HTTP_BAN_PERIOD
  114. #define ME_HTTP_BAN_PERIOD (5 * 60 * 1000) /**< Default ban IP period */
  115. #endif
  116. #ifndef ME_HTTP_DELAY_PERIOD
  117. #define ME_HTTP_DELAY_PERIOD (5 * 60 * 1000) /**< Default delay IP period */
  118. #endif
  119. #ifndef ME_HTTP_MONITOR_PERIOD
  120. #define ME_HTTP_MONITOR_PERIOD (60 * 1000) /**< Monitor prune period */
  121. #endif
  122. #ifndef ME_HTTP_REMEDY_TIMEOUT
  123. #define ME_HTTP_REMEDY_TIMEOUT (60 * 1000) /**< Default remedy command timeout */
  124. #endif
  125. #ifndef ME_HTTP_DELAY
  126. #define ME_HTTP_DELAY (2000) /**< 2 second delay per request - while delay enforced */
  127. #endif
  128. #ifndef ME_DIGEST_NONCE_DURATION
  129. #define ME_DIGEST_NONCE_DURATION 60 /**< Lifespan for Digest auth request nonce */
  130. #endif
  131. #ifndef ME_MAX_URI
  132. #define ME_MAX_URI 512 /**< Reasonable URI size */
  133. #endif
  134. #ifndef ME_MAX_IOVEC
  135. #define ME_MAX_IOVEC 16 /**< Number of fragments in a single socket write */
  136. #endif
  137. #ifndef ME_MAX_CLIENTS_HASH
  138. #define ME_MAX_CLIENTS_HASH 131 /**< Hash table for client IP addresses */
  139. #endif
  140. #ifndef ME_MAX_CACHE_ITEM
  141. #define ME_MAX_CACHE_ITEM (256 * 1024) /**< Maximum cachable item size */
  142. #endif
  143. #ifndef ME_MAX_CHUNK
  144. #define ME_MAX_CHUNK (8 * 1024) /**< Maximum chunk size for transfer chunk encoding */
  145. #endif
  146. #ifndef ME_MAX_CLIENTS
  147. #define ME_MAX_CLIENTS 32 /**< Maximum unique client IP addresses */
  148. #endif
  149. #ifndef ME_MAX_CONNECTIONS
  150. #define ME_MAX_CONNECTIONS 50 /**< Maximum concurrent connections (sockets) for whole server */
  151. #endif
  152. #ifndef ME_MAX_CONNECTIONS_PER_CLIENT
  153. #define ME_MAX_CONNECTIONS_PER_CLIENT 20 /**< Maximum concurrent connections per client (ip address) */
  154. #endif
  155. #ifndef ME_MAX_HPACK_SIZE
  156. #define ME_MAX_HPACK_SIZE 65536 /**< Maximum size of the hpack table */
  157. #endif
  158. #ifndef ME_MAX_HEADERS
  159. #define ME_MAX_HEADERS (512 * 1024) /**< Maximum size of the headers (Chrome HTTP/2 needs this) */
  160. #endif
  161. #ifndef ME_MAX_KEEP_ALIVE
  162. #define ME_MAX_KEEP_ALIVE 400 /**< Maximum requests per network */
  163. #endif
  164. #ifndef ME_MAX_NUM_HEADERS
  165. #define ME_MAX_NUM_HEADERS 64 /**< Maximum number of header lines */
  166. #endif
  167. #ifndef ME_QUEUE_MAX_FACTOR
  168. #define ME_QUEUE_MAX_FACTOR 4 /**< Queue max set to packetSize * factor */
  169. #endif
  170. #ifndef ME_MAX_PROCESSES
  171. #define ME_MAX_PROCESSES 10 /**< Maximum concurrent processes */
  172. #endif
  173. #ifndef ME_MAX_RX_BODY
  174. #define ME_MAX_RX_BODY (512 * 1024) /**< Maximum incoming body size (512K) */
  175. #endif
  176. #ifndef ME_MAX_RX_FORM
  177. #define ME_MAX_RX_FORM (512 * 1024) /**< Maximum incoming form size (512K) */
  178. #endif
  179. #ifndef ME_MAX_RX_FORM_FIELD
  180. #define ME_MAX_RX_FORM_FIELD HTTP_UNLIMITED /**< Maximum form field size for copied to */
  181. #endif
  182. /*
  183. These two are interrelated for HTTP/2
  184. */
  185. #ifndef ME_MAX_STREAMS
  186. #ifndef ME_MAX_REQUESTS_PER_CLIENT
  187. #define ME_MAX_STREAMS 200 /**< Default maximum concurrent streams per network */
  188. #else
  189. #define ME_MAX_STREAMS ME_MAX_REQUESTS_PER_CLIENT
  190. #endif
  191. #endif
  192. #ifndef ME_MAX_REQUESTS_PER_CLIENT
  193. #define ME_MAX_REQUESTS_PER_CLIENT ME_MAX_STREAMS /**< Maximum concurrent requests per client (ip address) */
  194. #endif
  195. #ifndef ME_MAX_REWRITE
  196. #define ME_MAX_REWRITE 20 /**< Maximum URI rewrites */
  197. #endif
  198. #ifndef ME_MAX_ROUTE_MATCHES
  199. #define ME_MAX_ROUTE_MATCHES 32 /**< Maximum number of submatches in routes */
  200. #endif
  201. #ifndef ME_MAX_ROUTE_MAP_HASH
  202. #define ME_MAX_ROUTE_MAP_HASH 17 /**< Size of the route mapping hash */
  203. #endif
  204. #ifndef ME_MAX_SESSIONS
  205. #define ME_MAX_SESSIONS 100 /**< Maximum concurrent sessions */
  206. #endif
  207. #ifndef ME_MAX_SESSION_HASH
  208. #define ME_MAX_SESSION_HASH 31 /**< Hash table for session data */
  209. #endif
  210. #ifndef ME_MAX_TX_BODY
  211. #define ME_MAX_TX_BODY HTTP_UNLIMITED /**< Maximum buffer for response data */
  212. #endif
  213. #ifndef ME_MAX_UPLOAD
  214. #define ME_MAX_UPLOAD HTTP_UNLIMITED /**< Maximum file upload size */
  215. #endif
  216. #ifndef ME_HTTP_UPLOAD_TIMEOUT
  217. #define ME_HTTP_UPLOAD_TIMEOUT 0
  218. #endif
  219. #ifndef ME_MAX_WSS_FRAME
  220. #define ME_MAX_WSS_FRAME (4 * 1024) /**< Default max WebSockets message frame size */
  221. #endif
  222. #ifndef ME_MAX_WSS_PACKET
  223. #define ME_MAX_WSS_PACKET (8 * 1024) /**< Default size to provide to application in one packet */
  224. #endif
  225. #ifndef ME_MAX_WSS_SOCKETS
  226. #define ME_MAX_WSS_SOCKETS 25 /**< Default max WebSockets */
  227. #endif
  228. #ifndef ME_MAX_WSS_MESSAGE
  229. #define ME_MAX_WSS_MESSAGE (2147483647) /**< Default max WebSockets message size (2GB) */
  230. #endif
  231. #ifndef ME_MAX_CACHE_DURATION
  232. #define ME_MAX_CACHE_DURATION (86400 * 1000) /**< Default cache lifespan to 1 day */
  233. #endif
  234. #ifndef ME_MAX_INACTIVITY_DURATION
  235. #define ME_MAX_INACTIVITY_DURATION (30 * 1000) /**< Default keep alive between requests timeout (30 sec) */
  236. #endif
  237. #ifndef ME_MAX_PARSE_DURATION
  238. #define ME_MAX_PARSE_DURATION (5 * 1000) /**< Default request parse header timeout (5 sec) */
  239. #endif
  240. #ifndef ME_MAX_REQUEST_DURATION
  241. #define ME_MAX_REQUEST_DURATION (5 * 60 * 1000) /**< Default request timeout (5 minutes) */
  242. #endif
  243. #ifndef ME_MAX_SESSION_DURATION
  244. #define ME_MAX_SESSION_DURATION (5 * 60 * 1000) /**< Default session inactivity timeout (5 mins) */
  245. #endif
  246. #ifndef ME_MAX_PING_DURATION
  247. #define ME_MAX_PING_DURATION (30 * 1000) /**< WSS ping defeat Keep-Alive timeouts (30 sec) */
  248. #endif
  249. #ifndef ME_XSRF_COOKIE
  250. #define ME_XSRF_COOKIE "XSRF-TOKEN" /**< CSRF token cookie name */
  251. #endif
  252. #ifndef ME_XSRF_HEADER
  253. #define ME_XSRF_HEADER "X-XSRF-TOKEN" /**< CSRF token name in Http headers */
  254. #endif
  255. #ifndef ME_XSRF_PARAM
  256. #define ME_XSRF_PARAM "-xsrf-" /**< CSRF parameter in form fields */
  257. #endif
  258. #ifndef ME_HTTP_LOG
  259. /* Host, "-" username time requeset-line response-status bytes-written local-host */
  260. #define ME_HTTP_LOG_FORMAT "%h %l %u %t \"%r\" %>s %b %n"
  261. #endif
  262. #define HTTP_DATE_FORMAT "%a, %d %b %Y %T GMT"
  263. #define HTTP_MAX_SECRET 16 /**< Size of secret data for auth */
  264. #define HTTP_SMALL_HASH_SIZE 31 /* Small hash (less than the alphabet) */
  265. #define HTTP_TIMER_PERIOD 1000 /**< HttpTimer checks ever 1 second */
  266. #define HTTP_PACKET_ALIGN(x) (((x) + 0x3FF) & ~0x3FF)
  267. /********************************** Defines ***********************************/
  268. /*
  269. Standard HTTP/1.1 status codes
  270. */
  271. #define HTTP_CODE_CONTINUE 100 /**< Continue with request, only partial content transmitted */
  272. #define HTTP_CODE_SWITCHING 101 /**< Switching protocols */
  273. #define HTTP_CODE_OK 200 /**< The request completed successfully */
  274. #define HTTP_CODE_CREATED 201 /**< The request has completed and a new resource was created */
  275. #define HTTP_CODE_ACCEPTED 202 /**< The request has been accepted and processing is continuing */
  276. #define HTTP_CODE_NOT_AUTHORITATIVE 203 /**< The request has completed but content may be from another source */
  277. #define HTTP_CODE_NO_CONTENT 204 /**< The request has completed and there is no response to send */
  278. #define HTTP_CODE_RESET 205 /**< The request has completed with no content. Client must reset view */
  279. #define HTTP_CODE_PARTIAL 206 /**< The request has completed and is returning partial content */
  280. #define HTTP_CODE_MOVED_PERMANENTLY 301 /**< The requested URI has moved permanently to a new location */
  281. #define HTTP_CODE_MOVED_TEMPORARILY 302 /**< The URI has moved temporarily to a new location */
  282. #define HTTP_CODE_SEE_OTHER 303 /**< The requested URI can be found at another URI location */
  283. #define HTTP_CODE_NOT_MODIFIED 304 /**< The requested resource has changed since the last request */
  284. #define HTTP_CODE_USE_PROXY 305 /**< The requested resource must be accessed via the location proxy */
  285. #define HTTP_CODE_TEMPORARY_REDIRECT 307 /**< The request should be repeated at another URI location */
  286. #define HTTP_CODE_BAD_REQUEST 400 /**< The request is malformed */
  287. #define HTTP_CODE_UNAUTHORIZED 401 /**< Authentication for the request has failed */
  288. #define HTTP_CODE_PAYMENT_REQUIRED 402 /**< Reserved for future use */
  289. #define HTTP_CODE_FORBIDDEN 403 /**< The request was legal, but the server refuses to process */
  290. #define HTTP_CODE_NOT_FOUND 404 /**< The requested resource was not found */
  291. #define HTTP_CODE_BAD_METHOD 405 /**< The request HTTP method was not supported by the resource */
  292. #define HTTP_CODE_NOT_ACCEPTABLE 406 /**< The requested resource cannot generate the required content */
  293. #define HTTP_CODE_REQUEST_TIMEOUT 408 /**< The server timed out waiting for the request to complete */
  294. #define HTTP_CODE_CONFLICT 409 /**< The request had a conflict in the request headers and URI */
  295. #define HTTP_CODE_GONE 410 /**< The requested resource is no longer available*/
  296. #define HTTP_CODE_LENGTH_REQUIRED 411 /**< The request did not specify a required content length*/
  297. #define HTTP_CODE_PRECOND_FAILED 412 /**< The server cannot satisfy one of the request preconditions */
  298. #define HTTP_CODE_REQUEST_TOO_LARGE 413 /**< The request is too large for the server to process */
  299. #define HTTP_CODE_REQUEST_URL_TOO_LARGE 414 /**< The request URI is too long for the server to process */
  300. #define HTTP_CODE_UNSUPPORTED_MEDIA_TYPE 415 /**< The request media type is not supported by the server or resource */
  301. #define HTTP_CODE_RANGE_NOT_SATISFIABLE 416 /**< The request content range does not exist for the resource */
  302. #define HTTP_CODE_EXPECTATION_FAILED 417 /**< The server cannot satisfy the Expect header requirements */
  303. #define HTTP_CODE_IM_A_TEAPOT 418 /**< Short and stout error code (RFC 2324) */
  304. #define HTTP_CODE_UNPROCESSABLE 422 /**< The request was well-formed but was unable process */
  305. #define HTTP_CODE_UPGRADE_REQUIRED 426 /**< The client should upgrade */
  306. #define HTTP_CODE_NO_RESPONSE 444 /**< The connection was closed with no response to the client */
  307. #define HTTP_CODE_INTERNAL_SERVER_ERROR 500 /**< Server processing or configuration error. No response generated */
  308. #define HTTP_CODE_NOT_IMPLEMENTED 501 /**< The server does not recognize the request or method */
  309. #define HTTP_CODE_BAD_GATEWAY 502 /**< The server cannot act as a gateway for the given request */
  310. #define HTTP_CODE_SERVICE_UNAVAILABLE 503 /**< The server is currently unavailable or overloaded */
  311. #define HTTP_CODE_GATEWAY_TIMEOUT 504 /**< The server gateway timed out waiting for the upstream server */
  312. #define HTTP_CODE_BAD_VERSION 505 /**< The server does not support the HTTP protocol version */
  313. #define HTTP_CODE_INSUFFICIENT_STORAGE 507 /**< The server has insufficient storage to complete the request */
  314. /*
  315. Custom error codes
  316. */
  317. #define HTTP_CODE_CERT_ERROR 495 /**< The peer provided certificate is unacceptable */
  318. /*
  319. Proprietary HTTP status codes
  320. */
  321. #define HTTP_CODE_START_LOCAL_ERRORS 550
  322. #define HTTP_CODE_COMMS_ERROR 550 /**< The server had a communications error responding to the client */
  323. #define HTTP_CODE_BAD_HANDSHAKE 551 /**< The server handsake response is unacceptable */
  324. #define HTTP_CODE_CLIENT_ERROR 552 /**< The server responded, but the response is unacceptable to the client */
  325. /*
  326. Flags that can be ored into the status code
  327. */
  328. #define HTTP_CODE_MASK 0xFFFF
  329. #define HTTP_ABORT 0x10000 /* Abort the request and network connection. Will try to emit a response first. */
  330. #define HTTP_CLOSE 0x20000 /* Close the stream (and connection on HTTP/1) at the completion of the request */
  331. /**
  332. HttpStream state change notification callback
  333. @description The notifier callback is invoked for state changes and I/O events. A user notifier function can
  334. respond to these events with any desired custom code.
  335. There are four valid event types:
  336. <ul>
  337. <li>HTTP_EVENT_STATE. The stream object has changed state. See stream->state.</li>
  338. <li>HTTP_EVENT_READABLE. The input queue has I/O to read. See stream->readq.
  339. Use #httpRead to read the data. For WebSockets, use #httpGetPacket.</li>
  340. <li>HTTP_EVENT_WRITABLE. The output queue is now writable.</li>
  341. <li>HTTP_EVENT_ERROR. The stream has an error. </li>
  342. <li>HTTP_EVENT_DESTROY. The stream is being destroyed. NOTE: this is not the network / socket.</li>
  343. </ul>
  344. @param stream HttpStream stream object created via #httpCreateStream
  345. @param event Http state
  346. @param arg Per-event information
  347. @ingroup HttpStream
  348. @stability Stable
  349. */
  350. typedef void (*HttpNotifier)(struct HttpStream *stream, int event, int arg);
  351. /**
  352. Set environment vars callback. Invoked per request to permit custom form var definition
  353. @ingroup HttpStream
  354. @stability Stable
  355. */
  356. typedef void (*HttpEnvCallback)(struct HttpStream *stream);
  357. /**
  358. Listen callback. Invoked after listening on a socket endpoint
  359. @return "Zero" if the listening endpoint can be opened for service. Otherwise, return a negative MPR error code.
  360. @ingroup HttpStream
  361. @stability Stable
  362. */
  363. typedef int (*HttpListenCallback)(struct HttpEndpoint *endpoint);
  364. /**
  365. Redirect callback. Invoked before processing redirects
  366. @return New target Uri and *code to contain the status
  367. @ingroup HttpStream
  368. @stability Evolving
  369. */
  370. typedef cchar *(*HttpRedirectCallback)(struct HttpStream *stream, int *code, cchar *uri);
  371. /**
  372. Network event callback
  373. @param net HttpNetwork object
  374. @ingroup HttpNet
  375. @stability Evolving
  376. */
  377. typedef void (*HttpNetCallback)(struct HttpNet *net, int event);
  378. /**
  379. Request completion callback
  380. @param stream HttpStream object
  381. @ingroup HttpRx
  382. @stability Evolving
  383. */
  384. typedef void (*HttpRequestCallback)(struct HttpStream *stream);
  385. /**
  386. Timeout callback
  387. @description The timeout callback for the request inactivity and duration timeouts
  388. @param stream HttpStream stream object created via #httpCreateStream
  389. @ingroup HttpStream
  390. @stability Stable
  391. */
  392. typedef void (*HttpTimeoutCallback)(struct HttpStream *stream);
  393. /**
  394. Set the fork callback.
  395. @param proc Fork callback procedure
  396. @param arg Argument to supply when the callback is invoked.
  397. @ingroup HttpStream
  398. @stability Evolving
  399. */
  400. PUBLIC void httpSetForkCallback(MprForkCallback proc, void *arg);
  401. /********************************* HttpMonitor ************************************/
  402. /*
  403. Monitored counters. These are per-client IP unless specified.
  404. */
  405. #define HTTP_COUNTER_ACTIVE_CLIENTS 0 /**< Active unique client IP addresses (global) */
  406. #define HTTP_COUNTER_ACTIVE_CONNECTIONS 1 /**< Active connections per client */
  407. #define HTTP_COUNTER_ACTIVE_REQUESTS 2 /**< Active requests per client */
  408. #define HTTP_COUNTER_ACTIVE_PROCESSES 3 /**< Total processes for server (global) */
  409. #define HTTP_COUNTER_BAD_REQUEST_ERRORS 4 /**< Bad request format errors */
  410. #define HTTP_COUNTER_ERRORS 5 /**< All errors */
  411. #define HTTP_COUNTER_LIMIT_ERRORS 6 /**< Limit violation errors */
  412. #define HTTP_COUNTER_MEMORY 7 /**< Total application memory for server (global) */
  413. #define HTTP_COUNTER_NETWORK_IO 8 /**< Network I/O */
  414. #define HTTP_COUNTER_NOT_FOUND_ERRORS 9 /**< URI not found errors */
  415. #define HTTP_COUNTER_REQUESTS 10 /**< Request count */
  416. #define HTTP_COUNTER_SSL_ERRORS 11 /**< SSL upgrade errors */
  417. #define HTTP_COUNTER_MAX 12 /**< Max standard counters */
  418. #define HTTP_MONITOR_MIN_PERIOD (5 * 1000)
  419. /**
  420. Monitoring counter
  421. @ingroup HttpMonitor
  422. @stability Internal
  423. */
  424. typedef struct HttpCounter {
  425. uint64 value; /**< Current counter value */
  426. } HttpCounter;
  427. /**
  428. Monitor control structure
  429. @defgroup HttpMonitor HttpMonitor
  430. @stability Internal
  431. */
  432. typedef struct HttpMonitor {
  433. cchar *counterName; /**< Name of counter to monitor */
  434. int counterIndex; /**< Counter item index to monitor */
  435. int expr; /**< Expression. Set to '<' or '>' */
  436. uint64 limit; /**< Comparison limit value */
  437. MprTicks period; /**< Frequence of comparison */
  438. MprList *defenses; /**< List of defensive measures */
  439. MprEvent *timer; /**< Monitor timer */
  440. struct Http *http;
  441. } HttpMonitor;
  442. /**
  443. Per-IP address structure that holds the monitor counters
  444. @ingroup HttpMonitor HttpMonitor
  445. @stability Internal
  446. */
  447. typedef struct HttpAddress {
  448. MprTicks updated; /**< When the address counters were last updated */
  449. MprTicks banUntil; /**< Ban IP address until this time */
  450. MprTicks delayUntil; /**< Delay (go-slow) servicing requests until this time */
  451. cchar *banMsg; /**< Ban response message */
  452. int banStatus; /**< Ban response status */
  453. int delay; /**< Delay per request */
  454. int ncounters; /**< Number of counters in ncounters */
  455. int seqno; /**< Unique client sequence number */
  456. HttpCounter counters[1]; /**< Counters allocated here */
  457. } HttpAddress;
  458. /**
  459. Defense remedy callback
  460. @param args Hash of configuration args for the callback
  461. @ingroup HttpMonitor
  462. @stability Evolving
  463. */
  464. typedef void (*HttpRemedyProc)(MprHash *args);
  465. /**
  466. Monitor defense configuration
  467. @ingroup HttpMonitor
  468. @stability Evolving
  469. */
  470. typedef struct HttpDefense {
  471. cchar *name; /**< Defense name */
  472. cchar *remedy; /**< Remedy name to invoke */
  473. MprHash *args; /**< Remedy arguments */
  474. MprHash *suppress; /**< Active defenses to suppress */
  475. MprTicks suppressPeriod; /**< Period to suppress defense */
  476. int suppressed; /**< Number of remedies suppressed */
  477. } HttpDefense;
  478. /**
  479. Monitor an event and validate against defined limits and monitored resources
  480. @description The Http library supports a suite of resource limits that restrict the impact of a request on
  481. the system. This call validates a processing event for the current request against the server's endpoint limits.
  482. @param stream HttpStream stream object
  483. @param counter The counter to adjust.
  484. @param adj Value to adjust the counter by. May be positive or negative.
  485. @return Monitor value after applying the adjustment.
  486. @ingroup HttpMonitor
  487. @stability Evolving
  488. */
  489. PUBLIC int64 httpMonitorEvent(struct HttpStream *stream, int counter, int64 adj);
  490. /**
  491. Monitor a network event and validate against defined limits and monitored resources
  492. @description The Http library supports a suite of resource limits that restrict the impact of a request on
  493. the system. This call validates a processing event for the current request against the server's endpoint limits.
  494. @param net Network object.
  495. @param counter The counter to adjust.
  496. @param adj Value to adjust the counter by. May be positive or negative.
  497. @return Monitor value after applying the adjustment.
  498. @ingroup HttpMonitor
  499. @stability Evolving
  500. */
  501. PUBLIC int64 httpMonitorNetEvent(struct HttpNet *net, int counter, int64 adj);
  502. /**
  503. Add a monitor
  504. @param counter Name of counter to monitor. Some of the standard counter names are:
  505. ActiveClients, ActiveConnections, ActiveRequests, ActiveProcesses, BadRequestErrors, LimitErrors, Memory,
  506. NotFoundErrors, NetworkIO, Requests, SSLErrors, TotalErrors
  507. @param expr Expression operator. Select from "<" or ">".
  508. @param limit Limit value to compare with the counter value.
  509. @param period Time period over which to determine the counter value.
  510. @param defenses List of defenses to invoke if the counter exceeds the limit value over the designated period.
  511. @return Zero if successful, otherwise a negative MPR error code.
  512. @ingroup HttpMonitor
  513. @stability Evolving
  514. */
  515. PUBLIC int httpAddMonitor(cchar *counter, cchar *expr, uint64 limit, MprTicks period, cchar *defenses);
  516. /**
  517. Add a defense
  518. @param name Name of defensive policy
  519. @param remedy Remedy action to invoke. Standard remedies include: ban, cmd, delay, email, http and log.
  520. This can be null and the remedy can be specified via REMEDY=remedy in the args.
  521. @param args Arguments to pass to the remedy. These may include ${tokens}.
  522. @return Zero if successful, otherwise a negative MPR error code.
  523. @ingroup HttpMonitor
  524. @stability Evolving
  525. */
  526. PUBLIC int httpAddDefense(cchar *name, cchar *remedy, cchar *args);
  527. /**
  528. Add a defense using JSON arguments
  529. @param name Name of defensive policy
  530. @param remedy Remedy action to invoke. Standard remedies include: ban, cmd, delay, email, http and log.
  531. This can be null and the remedy can be specified via REMEDY=remedy in the args.
  532. @param jargs Arguments to pass to the remedy as a JSON object. These may include ${tokens}.
  533. @return Zero if successful, otherwise a negative MPR error code.
  534. @ingroup HttpMonitor
  535. @stability Evolving
  536. */
  537. PUBLIC int httpAddDefenseFromJson(cchar *name, cchar *remedy, MprJson *jargs);
  538. /**
  539. Add a counter to be monitored
  540. @param name Name of the counter
  541. @return The counter index in HttpAddress.counters[] to use
  542. @ingroup HttpMonitor
  543. @stability Evolving
  544. */
  545. PUBLIC int httpAddCounter(cchar *name);
  546. /**
  547. Add a remedy
  548. @param name Name of the remedy
  549. @param remedy Remedy callback function
  550. @return Zero if successful, otherwise a negative MPR error code.
  551. @ingroup HttpMonitor
  552. @stability Evolving
  553. */
  554. PUBLIC int httpAddRemedy(cchar *name, HttpRemedyProc remedy);
  555. /**
  556. Ban a client IP from service
  557. @param ip Client IP address to ban
  558. @param period Period in milliseconds to ban the client
  559. @param status If non-zero, then return a HTTP response to the client with this HTTP status.
  560. @param msg If non-null, then return a HTTP response with this message. If both status and msg are zero and null respectively,
  561. then do not send a response to the client, rather immediately close the network connection.
  562. @ingroup HttpMonitor
  563. @stability Evolving
  564. */
  565. PUBLIC int httpBanClient(cchar *ip, MprTicks period, int status, cchar *msg);
  566. /**
  567. Print the monitor counters to the error log
  568. @ingroup HttpMonitor
  569. @stability Evolving
  570. */
  571. PUBLIC void httpDumpCounters(void);
  572. /*
  573. Internal
  574. */
  575. PUBLIC void httpAddCounters(void);
  576. PUBLIC int httpAddRemedies(void);
  577. PUBLIC MprTicks httpGetTicks(cchar *value);
  578. PUBLIC uint64 httpGetNumber(cchar *value);
  579. PUBLIC int httpGetInt(cchar *value);
  580. PUBLIC void httpPruneMonitors(void);
  581. PUBLIC HttpAddress *httpMonitorAddress(struct HttpNet *net, int counterIndex);
  582. /********************************** HttpTrace *********************************/
  583. #define HTTP_TRACE_MAX_SIZE (10 * 1024) /**< Default maximum body size to log */
  584. #define HTTP_TRACE_MIN_LOG_SIZE (10 * 1024) /**< Minimum log file size */
  585. /*
  586. Formatter flags
  587. */
  588. #define HTTP_TRACE_HEX 0x1 /**< Format content in hex with side ascii */
  589. #define HTTP_TRACE_RAW 0x2 /**< Emit raw trace - don't interpret key/value pairs */
  590. #define HTTP_TRACE_CONT 0x4 /**< Continuation trace. Don't flush and try to format with subsequent trace */
  591. /**
  592. Trace formatter callback
  593. @param trace Trace object
  594. @param stream Stream object
  595. @param event Event to trace
  596. @param type Type of event to trace
  597. @param values Formatted comma separated key=value pairs
  598. @param data Data buffer
  599. @param len Length of data. May be zero.
  600. @stability Evolving
  601. @ingroup HttpTrace
  602. */
  603. typedef void (*HttpTraceFormatter)(struct HttpTrace *trace, cchar *event, cchar *type, int flags, cchar *data, ssize len, cchar *fmt, va_list args);
  604. /**
  605. Trace logger callback
  606. @param trace Trace object
  607. @param data Data buffer to write.
  608. @param len Length of data. May be zero.
  609. @stability Evolving
  610. @ingroup HttpTrace
  611. */
  612. typedef void (*HttpTraceLogger)(struct HttpTrace *trace, cchar *data, ssize len);
  613. /**
  614. Trace management structure
  615. @stability Evolving
  616. @defgroup HttpTrace HttpTrace
  617. */
  618. typedef struct HttpTrace {
  619. cchar *format; /**< Output format (used by Common Log Format) */
  620. cchar *path; /**< Trace logger filename */
  621. cchar *lastTime; /**< Most recent time string */
  622. MprTime lastMark; /**< When lastTime was last updated */
  623. MprBuf *buf; /**< Output buffer */
  624. MprFile *file; /**< Trace logger file object */
  625. int backupCount; /**< Trace logger backup count */
  626. int flags; /**< Trace control flags (append|anew) */
  627. int level; /**< Trace level */
  628. MprOff size; /**< Max log size */
  629. ssize maxContent; /**< Maximum content size to trace */
  630. MprHash *events; /**< Configuration of events */
  631. HttpTraceFormatter formatter; /**< Trace formatter */
  632. HttpTraceLogger logger; /**< Trace logger */
  633. struct HttpTrace *parent; /**< Parent trace */
  634. MprMutex *mutex; /**< Multithread sync */
  635. } HttpTrace;
  636. /**
  637. Backup the request trace log if required
  638. @description If the log file is greater than the maximum configured, or MPR_ANEW was set via httpSetTraceLog,
  639. then archive the log.
  640. @param trace HttpTrace object
  641. @return Zero if successful, otherwise a negative MPR error code.
  642. @ingroup HttpTrace
  643. @stability Evolving
  644. */
  645. PUBLIC int httpBackupTraceLogFile(HttpTrace *trace);
  646. /**
  647. Common Log trace formatter
  648. @param trace HttpTrace object
  649. @param event Event to trace
  650. @param type Event type
  651. @param flags Formatting flags
  652. @param buf Data buffer to trace.
  653. @param len Length of the data buf.
  654. @param fmt Printf style formatted string
  655. @param args Varargs arguments for fmt
  656. @ingroup HttpTrace
  657. @stability Evolving
  658. */
  659. PUBLIC void httpCommonFormatter(HttpTrace *trace, cchar *event, cchar *type, int flags, cchar *buf, ssize len, cchar *fmt, va_list args);
  660. /**
  661. Create a trace object.
  662. @description If parent is defined, inherit default settings from the parent
  663. @param parent Parent trace object from which to inherit settings
  664. @ingroup HttpTrace
  665. @stability Evolving
  666. @internal
  667. */
  668. PUBLIC HttpTrace *httpCreateTrace(HttpTrace *parent);
  669. /**
  670. Detailed log trace formatter
  671. @param trace HttpTrace object
  672. @param event Event to trace
  673. @param type Event type to trace
  674. @param flags Formatting flags
  675. @param buf Data buffer to trace.
  676. @param len Length of the data buf.
  677. @param fmt Printf style formatted string
  678. @param args Varargs arguments for fmt
  679. @ingroup HttpTrace
  680. @stability Evolving
  681. */
  682. PUBLIC void httpDetailFormatter(HttpTrace *trace, cchar *event, cchar *type, int flags, cchar *buf, ssize len, cchar *fmt, va_list args);
  683. /**
  684. Convenience routine to format trace via the configured formatter
  685. @description The formatter will invoke the trace logger and actually write the trace mesage
  686. @param trace HttpTrace object
  687. @param type Event type to trace
  688. @param flags Formatting flags
  689. @param event Event name to trace
  690. @param buf Trace data buffer to write
  691. @param len Length of data buffer
  692. @param fmt Printf style formatted string
  693. @param args Varargs arguments for fmt
  694. @ingroup HttpTrace
  695. @stability Evolving
  696. */
  697. PUBLIC void httpFormatTrace(HttpTrace *trace, cchar *event, cchar *type, int flags, cchar *buf, ssize len, cchar *fmt, va_list args);
  698. /**
  699. Get the current tracing level
  700. @return The tracing level 0-5
  701. @ingroup HttpTrace
  702. @param trace Trace object
  703. @stability Evolving
  704. */
  705. PUBLIC int httpGetTraceLevel(HttpTrace *trace);
  706. #if DOXYGEN
  707. /**
  708. Log (trace) an event of interest
  709. @description The Http trace log is for operational request and server messages and should be used in preference to
  710. the MPR error log which should be used only for configuration and hard system-wide errors.
  711. @param trace HttpTrace object. Typically used via HttpStream.trace or HttpNet.trace.
  712. @param event Event name to trace. Typically dot separated module names.
  713. @param type Event type to trace. Events are grouped into types that are traced at the same level.
  714. The standard set of types and their default trace levels are:
  715. debug: 1, error: 1, request:2, result:2, headers: 3, context:4, packet:5, detail:6. Users can create custom types.
  716. The request type is used for the initial http request line. The result type is used for the request status.
  717. The context type is used for general information including http headers. The form type is used for POST form data.
  718. The body type is used for request body data.
  719. \n\n
  720. Context type events may include a "msg" value field. By convention, these messages should be aggregated by trace
  721. formatters so that subsequent context events do not overwrite prior msg values.
  722. \n\n
  723. Event types are orthogonal to event names.
  724. @param fmt Printf style format string. String should be comma separated key=value pairs
  725. @param ... Arguments for fmt
  726. @return True if the event was traced
  727. @ingroup HttpTrace
  728. @stability Evolving
  729. */
  730. PUBLIC bool httpLog(HttpTrace *trace, cchar *event, cchar *type, cchar *fmt, ...);
  731. #else
  732. #define httpLog(trace, event, type, ...) \
  733. if (trace && trace->level > 0) { \
  734. int __tlevel = PTOI(mprLookupKey(trace->events, type)); \
  735. if (__tlevel > 0 && __tlevel <= trace->level) { \
  736. httpLogProc(trace, event, type, 0, __VA_ARGS__); \
  737. } \
  738. } else
  739. #endif
  740. // Internal
  741. PUBLIC void httpLogProc(HttpTrace *trace, cchar *event, cchar *type, int flags, cchar *fmt, ...) PRINTF_ATTRIBUTE(5,6);
  742. /**
  743. Trace a packet received from the network
  744. @param net HttpNet object
  745. @param buf Data buffer to trace
  746. @param len Size of buffer
  747. @ingroup HttpTrace
  748. @stability Evolving
  749. */
  750. PUBLIC void httpLogRxPacket(struct HttpNet *net, cchar *buf, ssize len);
  751. /**
  752. Trace packets sent to the network
  753. @description This traces the packets referenced by net->socketq->iovec
  754. @param net HttpNet object
  755. @param len Length in bytes actually written
  756. @ingroup HttpTrace
  757. @stability Evolving
  758. */
  759. PUBLIC void httpLogTxPacket(struct HttpNet *net, ssize len);
  760. /**
  761. Trace the completion of a request
  762. @description This traces the request metrics
  763. @param stream HttpStream object
  764. @ingroup HttpTrace
  765. @stability Evolving
  766. */
  767. PUBLIC void httpLogCompleteRequest(struct HttpStream *stream);
  768. /**
  769. Pretty log trace formatter for debugging
  770. @param trace HttpTrace object
  771. @param event Event to trace
  772. @param type Event type to trace
  773. @param flags Formatting flags
  774. @param buf Data buffer to trace.
  775. @param len Length of the data buf.
  776. @param fmt Printf style formatted string
  777. @param args Varargs arguments for fmt
  778. @ingroup HttpTrace
  779. @stability Evolving
  780. */
  781. PUBLIC void httpPrettyFormatter(HttpTrace *trace, cchar *event, cchar *type, int flags, cchar *buf, ssize len, cchar *fmt, va_list args);
  782. /*
  783. Trace LogFile logger
  784. @description Open the trace log file defined in the HttpTrace object
  785. @param trace Trace object
  786. @stability Evolving
  787. @internal
  788. */
  789. PUBLIC int httpOpenTraceLogFile(HttpTrace *trace);
  790. /**
  791. Set the formatter callback to use with a trace object
  792. @description The trace formatter should
  793. @param trace Trace object to configure
  794. @param callback Formatter callback
  795. @return Prior trace formatter
  796. @ingroup HttpTrace
  797. @stability Evolving
  798. */
  799. PUBLIC HttpTraceFormatter httpSetTraceFormatter(HttpTrace *trace, HttpTraceFormatter callback);
  800. /**
  801. Set the logging format
  802. @description This is used by the Common log formatter to define the fields written to the log
  803. @param trace Trace object
  804. @param format The format string defaults to: "%h %l %u %t \"%r\" %>s %b %n".
  805. @ingroup HttpTrace
  806. @stability Evolving
  807. */
  808. PUBLIC void httpSetTraceFormat(HttpTrace *trace, cchar *format);
  809. /**
  810. Set the current tracing verbosity level.
  811. @description This call defines the maximum trace level of messages that will be
  812. traced. Trace events have an associated verbosity level at which they will be enabled.
  813. If the event level is greater than the defined tracing verbosity level, the event is ignored.
  814. @param level New tracing level. Must be 0-5 inclusive.
  815. @param trace Trace object
  816. @ingroup HttpTrace
  817. @stability Evolving.
  818. */
  819. PUBLIC void httpSetTraceLevel(HttpTrace *trace, int level);
  820. /**
  821. Configure the tracing level for an event type
  822. @param trace Tracing object
  823. @param type Event type to modify
  824. @param level Desired trace level (0-5)
  825. @ingroup HttpTrace
  826. @stability Evolving.
  827. @internal
  828. */
  829. PUBLIC void httpSetTraceEventLevel(HttpTrace *trace, cchar *type, int level);
  830. /**
  831. Set the maximum content size to trace
  832. @description Tracing will be suspended for files that are larger than this size.
  833. @param trace Tracing object
  834. @param size Maximum content size to trace
  835. @ingroup HttpTrace
  836. @stability Evolving.
  837. */
  838. PUBLIC void httpSetTraceContentSize(HttpTrace *trace, ssize size);
  839. /**
  840. Set the trace callback to use with a trace object
  841. @description The trace logger is responsible for taking formatted messages and writing to the log.
  842. @param trace Trace object to configure
  843. @param callback Trace logger callback
  844. @ingroup HttpTrace
  845. @stability Evolving
  846. */
  847. PUBLIC void httpSetTraceLogger(HttpTrace *trace, HttpTraceLogger callback);
  848. /**
  849. Configure the request trace log
  850. @param trace HttpTrace object
  851. @param path Path for request trace log file.
  852. @param size Maximum size of the log file before archiving
  853. @param backup Set to true to create a backup of the log file if archiving.
  854. @param format Log file format
  855. @param flags Set to MPR_LOG_ANEW to archive the log when the application reboots.
  856. @return Zero if successful, otherwise a negative MPR error code.
  857. @ingroup HttpTrace
  858. @stability Evolving
  859. */
  860. PUBLIC int httpSetTraceLogFile(HttpTrace *trace, cchar *path, ssize size, int backup, cchar *format, int flags);
  861. /**
  862. Define the trace formatter by name
  863. @param trace Tracing object
  864. @param name Formatter name. Set to "common" for the Common Log format or "detail" for the Appweb detailed trace format.
  865. @ingroup HttpTrace
  866. @stability Evolving.
  867. @internal
  868. */
  869. PUBLIC void httpSetTraceFormatterName(HttpTrace *trace, cchar *name);
  870. /**
  871. Should trace be emitted
  872. @param trace Tracing object
  873. @param type Event type to consider
  874. @ingroup HttpTrace
  875. @stability Evolving.
  876. @returns True if trace should be emitted
  877. */
  878. PUBLIC bool httpShouldTrace(HttpTrace *trace, cchar *type);
  879. #define httpTracing(net) (net->trace->level > 0)
  880. /**
  881. Start tracing for the given trace log file when instructed via a command line switch.
  882. @param traceSpec Set the trace log file name and level. The format is "pathName[:level]".
  883. The following levels are generally observed:
  884. <ul>
  885. <li>0 - Essential messages, fatal errors and critical warnings</li>
  886. <li>1 - Hard errors</li>
  887. <li>2 - Configuration setup and soft warnings</li>
  888. <li>3 - Useful informational messages</li>
  889. <li>4 - Debug information</li>
  890. <li>5 - Most verbose levels of messages useful for debugging</li>
  891. </ul>
  892. If the traceSpec is null, not tracing is enabled.
  893. @return Zero if successful, otherwise a negative Mpr error code. See the Appweb log for diagnostics.
  894. @ingroup HttpTrace
  895. @stability Evolving
  896. */
  897. PUBLIC int httpStartTracing(cchar *traceSpec);
  898. /**
  899. Convenience routine to write data to the trace logger. Should only be used by formatters.
  900. @param trace HttpTrace object
  901. @param buf Trace message to write
  902. @param len Length of message
  903. @ingroup HttpTrace
  904. @stability Evolving
  905. */
  906. PUBLIC void httpWriteTrace(HttpTrace *trace, cchar *buf, ssize len);
  907. /**
  908. Write a message to the trace file logger
  909. @param trace HttpTrace object
  910. @param buf Message to write
  911. @param len Length of message
  912. @ingroup HttpTrace
  913. @stability Evolving
  914. */
  915. PUBLIC void httpWriteTraceLogFile(HttpTrace *trace, cchar *buf, ssize len);
  916. /*
  917. Internal
  918. */
  919. PUBLIC cchar *httpMakePrintable(HttpTrace *trace, cchar *buf, bool *hex, ssize *lenp);
  920. /************************************ Http **********************************/
  921. /**
  922. Http service object
  923. @description Configuration is not thread safe and must occur at initialization time when the application is
  924. single threaded. If the configuration is modified when the application is multithreaded, all requests must be
  925. first be quiesced.
  926. @defgroup Http Http
  927. @see Http HttpStream HttpEndpoint gettGetDateString httpCreate httpGetContext httpGetDateString
  928. httpLookupEndpoint httpLookupStatus httpLooupHost httpSetContext httpSetDefaultClientHost
  929. httpSetDefaultClientPort httpSetDefaultPort httpSetForkCallback httpSetProxy httpSetSoftware httpConfigure
  930. @stability Internal
  931. */
  932. typedef struct Http {
  933. MprList *endpoints; /**< Currently configured listening endpoints */
  934. MprList *hosts; /**< List of host objects */
  935. MprList *networks; /**< Currently open network connections */
  936. MprHash *parsers; /**< Table config parser callbacks */
  937. MprHash *stages; /**< Possible stages in connection pipelines */
  938. MprCache *sessionCache; /**< Session state cache */
  939. MprHash *statusCodes; /**< Http status codes */
  940. MprHash *routeSets; /**< Http route sets functions */
  941. MprHash *routeTargets; /**< Http route target functions */
  942. MprHash *routeConditions; /**< Http route condition functions */
  943. MprHash *routeUpdates; /**< Http route update functions */
  944. MprHash *authTypes; /**< Available authentication protocol types */
  945. MprHash *authStores; /**< Available password stores */
  946. MprHash *dateCache; /**< Cache of date modified times */
  947. MprList *staticHeaders; /**< HTTP/2 static headers */
  948. MprList *counters; /**< List of counters */
  949. MprList *monitors; /**< List of monitors */
  950. MprHash *defenses; /**< List of Defenses */
  951. MprHash *remedies; /**< List of Defense Remedies */
  952. MprHash *addresses; /**< Monitored per-IP-address counters */
  953. /*
  954. Some standard pipeline stages
  955. */
  956. struct HttpStage *actionHandler; /**< Action handler */
  957. struct HttpStage *cacheFilter; /**< Cache filter */
  958. struct HttpStage *cacheHandler; /**< Cache filter */
  959. struct HttpStage *chunkFilter; /**< Chunked transfer encoding filter */
  960. struct HttpStage *httpFilter; /**< Http filter */
  961. struct HttpStage *cgiHandler; /**< CGI handler */
  962. struct HttpStage *cgiConnector; /**< CGI connector */
  963. struct HttpStage *dirHandler; /**< Directory listing handler */
  964. struct HttpStage *egiHandler; /**< Embedded Gateway Interface (EGI) handler */
  965. struct HttpStage *espHandler; /**< ESP Web Framework handler */
  966. struct HttpStage *fastHandler; /**< FastCGI handler */
  967. struct HttpStage *fastConnector; /**< FastCGI connector */
  968. struct HttpStage *fileHandler; /**< Static file handler */
  969. struct HttpStage *netConnector; /**< Default network connector */
  970. struct HttpStage *passHandler; /**< Pass through handler */
  971. struct HttpStage *phpHandler; /**< PHP through handler */
  972. struct HttpStage *proxyHandler; /**< Proxy handler */
  973. struct HttpStage *proxyConnector; /**< Proxy connector */
  974. struct HttpStage *queueHead; /**< Queue head stage */
  975. struct HttpStage *rangeFilter; /**< Ranged requests filter */
  976. struct HttpStage *tailFilter; /**< Tail filter */
  977. struct HttpStage *uploadFilter; /**< Upload filter */
  978. #if ME_HTTP_WEB_SOCKETS
  979. struct HttpStage *webSocketFilter; /**< WebSocket filter */
  980. #endif
  981. struct HttpStage *http1Filter; /**< Http/1 filter */
  982. #if ME_HTTP_HTTP2
  983. struct HttpStage *http2Filter; /**< Http/2 filter */
  984. #endif
  985. struct HttpLimits *clientLimits; /**< Client resource limits */
  986. struct HttpLimits *serverLimits; /**< Server resource limits */
  987. struct HttpRoute *clientRoute; /**< Default route for clients */
  988. MprEvent *timer; /**< Admin service timer */
  989. MprEvent *timestamp; /**< Timestamp timer */
  990. MprTime booted; /**< Time the server started */
  991. MprTicks now; /**< Current time in ticks */
  992. MprMutex *mutex; /**< Multithread sync */
  993. HttpTrace *trace; /**< Default tracing configuration */
  994. char *software; /**< Software name and version */
  995. void *forkData;
  996. int monitorsStarted; /**< Monitors are running */
  997. MprTicks monitorPeriod; /**< Minimum monitor period */
  998. int nextAuth; /**< Auth object version vector */
  999. int activeProcesses; /**< Count of active external processes */
  1000. uint64 totalConnections; /**< Total connections accepted */
  1001. uint64 totalRequests; /**< Total requests served */
  1002. uint64 totalStreams; /**< Total streams created */
  1003. int flags; /**< Open flags */
  1004. void *context; /**< Embedding context */
  1005. MprTicks currentTime; /**< When currentDate was last calculated (ticks) */
  1006. char *currentDate; /**< Date string for HTTP response headers */
  1007. char *secret; /**< Random bytes for authentication */
  1008. char *defaultClientHost; /**< Default ip address */
  1009. int defaultClientPort; /**< Default port */
  1010. char *proxyHost; /**< Proxy ip address */
  1011. int proxyPort; /**< Proxy port */
  1012. cchar *group; /**< O/S application group name */
  1013. cchar *localPlatform; /**< Local (dev) platform os-arch-profile (lower case) */
  1014. cchar *platform; /**< Target platform os-arch-profile (lower case) */
  1015. cchar *platformDir; /**< Path to platform directory containing binaries */
  1016. cchar *user; /**< O/S application user name */
  1017. cchar *jail; /**< Chroot jail path */
  1018. int uid; /**< User Id */
  1019. int gid; /**< Group Id */
  1020. int userChanged; /**< User name changed */
  1021. int groupChanged; /**< Group name changed */
  1022. int staticLink; /**< Target platform is using a static linking */
  1023. int startLevel; /**< Start endpoint trace level */
  1024. int http2; /**< Enable http 2 */
  1025. /*
  1026. Callbacks
  1027. */
  1028. HttpEnvCallback envCallback; /**< SetEnv callback */
  1029. MprForkCallback forkCallback; /**< Callback in child after fork() */
  1030. HttpListenCallback listenCallback; /**< Invoked when creating listeners */
  1031. HttpRedirectCallback redirectCallback; /**< Redirect callback */
  1032. HttpRequestCallback requestCallback; /**< Request completion callback */
  1033. HttpNetCallback netCallback; /**< Default network event callback */
  1034. #if DEPRECATED
  1035. struct HttpStage *ejsHandler; /**< Ejscript Web Framework handler */
  1036. #endif
  1037. } Http;
  1038. #if DOXYGEN
  1039. /**
  1040. Return the MPR control instance.
  1041. @description Return the MPR singleton control object.
  1042. @return Returns the MPR control object.
  1043. @ingroup Mpr
  1044. @stability Stable.
  1045. */
  1046. PUBLIC Http *HTTP;
  1047. #elif ME_WIN_LIKE
  1048. PUBLIC Http *httpGetHttp(void);
  1049. #define HTTP httpGetHttp()
  1050. #else
  1051. PUBLIC_DATA Http *HTTP;
  1052. #endif
  1053. /**
  1054. Callback procedure for HttpConfigure
  1055. @param arg User definable data. May be managed or unmanaged.
  1056. @ingroup Http
  1057. @stability Stable
  1058. */
  1059. typedef void (*HttpConfigureProc)(void *arg);
  1060. /**
  1061. Apply the changed group ID.
  1062. @description Apply configuration changes and actually change the group id
  1063. @return Zero if successful, otherwise a negative Mpr error code. See the Appweb log for diagnostics.
  1064. @ingroup Http
  1065. @stability Stable
  1066. */
  1067. PUBLIC int httpApplyChangedGroup(void);
  1068. /**
  1069. Apply the changed user ID
  1070. @description Apply configuration changes and actually change the user id
  1071. @ingroup Http
  1072. @stability Stable
  1073. */
  1074. PUBLIC int httpApplyChangedUser(void);
  1075. /**
  1076. Apply the changed user and group ID.
  1077. @description Apply configuration changes and actually change the user and group id
  1078. @return Zero if successful, otherwise a negative Mpr error code. See the Appweb log for diagnostics.
  1079. @ingroup Http
  1080. @stability Stable
  1081. */
  1082. PUBLIC int httpApplyUserGroup(void);
  1083. /*
  1084. Flags for httpCreate
  1085. */
  1086. #define HTTP_CLIENT_SIDE 0x1 /**< Initialize the client-side support */
  1087. #define HTTP_SERVER_SIDE 0x2 /**< Initialize the server-side support */
  1088. /**
  1089. Alter the configuration by first quiescing all Http activity. This waits until there are no open connections
  1090. and then invokes the configuration callback while blocking further connections. When the callback completes,
  1091. connections are resumed with the new configuration.
  1092. This callback is required because configuration of the Http engine must be done when single-threaded.
  1093. @param proc Function of the type HttpConfigureProc.
  1094. @param arg Reference argument to pass to the callback proc. Can be a managed or an unmanaged reference.
  1095. @param timeout Timeout in milliseconds to wait. Set to -1 to use the default server inactivity timeout. Set to zero
  1096. to wait forever.
  1097. @ingroup Http
  1098. @stability Evolving
  1099. */
  1100. PUBLIC bool httpConfigure(HttpConfigureProc proc, void *arg, MprTicks timeout);
  1101. /**
  1102. Create a Http service object
  1103. @description Create a http service object. One http service object should be created per application.
  1104. @param flags Set to zero to initialize bo Initialize the client-side support only.
  1105. @return The http service object.
  1106. @ingroup Http
  1107. @stability Stable
  1108. */
  1109. PUBLIC Http *httpCreate(int flags);
  1110. /**
  1111. Destroy the Http service.
  1112. @description This routine is invoked as the final stage in shutting down the http service.
  1113. It stops the request timeout timer and releases all http memory.
  1114. @ingroup Http
  1115. @stability Internal
  1116. */
  1117. PUBLIC void httpDestroy(void);
  1118. /*
  1119. Enable or disable HTTP/2 for the server at runtime.
  1120. @param enable Boolean. Set to 1 to enable and zero to disable.
  1121. @ingroup Http
  1122. @stability Evolving
  1123. */
  1124. PUBLIC void httpEnableHttp2(int enable);
  1125. /**
  1126. Get the http context object
  1127. @return The http context object defined via httpSetContext
  1128. @ingroup Http
  1129. @stability Stable
  1130. */
  1131. PUBLIC void *httpGetContext(void);
  1132. /**
  1133. Get the time as an ISO date string
  1134. @param sbuf Optional path buffer. If supplied, the modified time of the path is used. If NULL, then the current
  1135. time is used.
  1136. @return RFC822 formatted date string.
  1137. @ingroup Http
  1138. @stability Stable
  1139. */
  1140. PUBLIC char *httpGetDateString(MprPath *sbuf);
  1141. /**
  1142. Get the user group
  1143. @description Get the user and group ID for the process
  1144. @ingroup Http
  1145. @stability Internal
  1146. */
  1147. PUBLIC void httpGetUserGroup(void);
  1148. /**
  1149. Initialize the Http configuration parser
  1150. @return Zero if successful, otherwise a negative Mpr error code. See the Appweb log for diagnostics.
  1151. @ingroup Http
  1152. @stability Stable
  1153. */
  1154. PUBLIC int httpInitParser(void);
  1155. /**
  1156. Lookup a Http status code
  1157. @description Lookup the code and return the corresponding text message briefly expaining the status.
  1158. @param status Http status code
  1159. @return Text message corresponding to the status code
  1160. @ingroup Http
  1161. @stability Stable
  1162. */
  1163. PUBLIC cchar *httpLookupStatus(int status);
  1164. /**
  1165. Lookup a host by name
  1166. @param name The name of the host to find
  1167. @return The corresponding host object
  1168. @ingroup Http
  1169. @stability Stable
  1170. */
  1171. PUBLIC struct HttpHost *httpLookupHost(cchar *name);
  1172. /**
  1173. Lookup a listening endpoint
  1174. @param ip Listening IP address to look for
  1175. @param port Listening port number
  1176. @return HttpEndpoint object
  1177. @ingroup Http
  1178. @stability Stable
  1179. */
  1180. PUBLIC struct HttpEndpoint *httpLookupEndpoint(cchar *ip, int port);
  1181. /**
  1182. Parse a platform string
  1183. @param platform The platform string. Must be of the form: os-arch-profile
  1184. @param os Parsed O/S portion
  1185. @param arch Parsed architecture portion
  1186. @param profile Parsed profile portion
  1187. @return Zero if successful, otherwise a negative Mpr error code.
  1188. @ingroup Http
  1189. @stability Stable
  1190. */
  1191. PUBLIC int httpParsePlatform(cchar *platform, cchar **os, cchar **arch, cchar **profile);
  1192. /**
  1193. Set the http context object
  1194. @param context New context object
  1195. @ingroup Http
  1196. @stability Stable
  1197. */
  1198. PUBLIC void httpSetContext(void *context);
  1199. /**
  1200. Define a default client host
  1201. @description Define a default host to use for client connections if the URI does not specify a host
  1202. @param host Host or IP address
  1203. @ingroup Http
  1204. @stability Stable
  1205. */
  1206. PUBLIC void httpSetDefaultClientHost(cchar *host);
  1207. /**
  1208. Define a default client port
  1209. @description Define a default port to use for client connections if the URI does not define a port
  1210. @param port Integer port number
  1211. @ingroup Http
  1212. @stability Stable
  1213. */
  1214. PUBLIC void httpSetDefaultClientPort(int port);
  1215. /**
  1216. Define a callback to invoke after env vars have been defined
  1217. @param envCallback Callback to invoke
  1218. @ingroup Http
  1219. @stability Evolving
  1220. */
  1221. PUBLIC void httpSetEnvCallback(HttpEnvCallback envCallback);
  1222. /**
  1223. Set the group account
  1224. @description Define the group account name under which to run the process
  1225. @param group Group name. Must be defined in the system group database.
  1226. @return Zero if successful, otherwise a negative Mpr error code.
  1227. @ingroup Http
  1228. @stability Stable
  1229. */
  1230. PUBLIC int httpSetGroupAccount(cchar *group);
  1231. /**
  1232. Remember the Chroot jail path
  1233. @description Store the jail path in HTTP->jail
  1234. @param path Pathname to remember
  1235. @ingroup Http
  1236. @stability Internal
  1237. */
  1238. PUBLIC void httpSetJail(cchar *path);
  1239. /**
  1240. Set platform description
  1241. @description Some web frameworks need to recompile sources before serving requests (ESP).
  1242. These need access to the http libraries to link with.
  1243. @param platform Platform string of the form: OS-ARCH-PROFILE.
  1244. @return Zero if the platform string parses, otherwise a negative Mpr error code.
  1245. @ingroup Http
  1246. @stability Stable
  1247. */
  1248. PUBLIC int httpSetPlatform(cchar *platform);
  1249. /**
  1250. Set platform directory location
  1251. @description Set the platform directory location which contains libraries and headers for the application.
  1252. @param platform Path to the platform directory.
  1253. @return Zero if successful, otherwise a negative Mpr error code.
  1254. @ingroup Http
  1255. @stability Stable
  1256. */
  1257. PUBLIC int httpSetPlatformDir(cchar *platform);
  1258. /**
  1259. Define a Http proxy host to use for all client connect requests.
  1260. @description Define a http proxy host to communicate via when accessing the net.
  1261. @param host Proxy host name or IP address
  1262. @param port Proxy host port number.
  1263. @ingroup Http
  1264. @stability Stable
  1265. */
  1266. PUBLIC void httpSetProxy(cchar *host, int port);
  1267. /**
  1268. Define a callback to invoke on redirect requests
  1269. @param redirectCallback Callback to invoke
  1270. @ingroup Http
  1271. @stability Evolving
  1272. */
  1273. PUBLIC void httpSetRedirectCallback(HttpRedirectCallback redirectCallback);
  1274. /**
  1275. Set the software description
  1276. @param description String describing the Http software. By default, this is set to HTTP_NAME.
  1277. @ingroup Http
  1278. @stability Stable
  1279. */
  1280. PUBLIC void httpSetSoftware(cchar *description);
  1281. /**
  1282. Set the user account
  1283. @description Define the user account name under which to run the process
  1284. @param user User name. Must be defined in the system password database.
  1285. @return Zero if successful, otherwise a negative Mpr error code.
  1286. @ingroup Http
  1287. @stability Stable
  1288. */
  1289. PUBLIC int httpSetUserAccount(cchar *user);
  1290. /* Internal APIs */
  1291. PUBLIC void httpAddStream(struct HttpNet *net, struct HttpStream *stream);
  1292. PUBLIC void httpRemoveStream(struct HttpNet *net, struct HttpStream *stream);
  1293. PUBLIC void httpAddNet(struct HttpNet *net);
  1294. PUBLIC void httpRemoveNet(struct HttpNet *net);
  1295. PUBLIC struct HttpEndpoint *httpGetFirstEndpoint(void);
  1296. PUBLIC void httpAddEndpoint(struct HttpEndpoint *endpoint);
  1297. PUBLIC void httpRemoveEndpoint(struct HttpEndpoint *endpoint);
  1298. PUBLIC void httpAddHost(struct HttpHost *host);
  1299. PUBLIC void httpRemoveHost(struct HttpHost *host);
  1300. PUBLIC void httpDefineRouteBuiltins(void);
  1301. PUBLIC void httpSetInfoLevel(int level);
  1302. PUBLIC void httpStopNetworks(void *data);
  1303. /*********************************** HttpStats ********************************/
  1304. /**
  1305. HttpStats
  1306. @defgroup HttpStats HttpStats
  1307. @stability Internal
  1308. */
  1309. typedef struct HttpStats {
  1310. uint64 ram; /**< System total RAM */
  1311. uint64 mem; /**< Current application memory (includes code + data + heap) */
  1312. uint64 memRedline; /**< Memory heap warnHeap limit */
  1313. uint64 memMax; /**< Memory heap maximum permitted */
  1314. uint64 memSessions; /**< Memory used for sessions */
  1315. uint64 heap; /**< Current application heap memory */
  1316. uint64 heapPeak; /**< Peak heap memory usage */
  1317. uint64 heapUsed; /**< Current heap memory in use */
  1318. uint64 heapFree; /**< Current heap memory available */
  1319. uint heapRegions; /**< Count of heap memory regions */
  1320. int workersBusy; /**< Current busy worker threads */
  1321. int workersIdle; /**< Current idle worker threads */
  1322. int workersYielded; /**< Number of busy workers that are yielded for GC */
  1323. int workersMax; /**< Maximum number of workers in the thread pool */
  1324. int activeClients; /**< Current active client IPs */
  1325. int activeConnections; /**< Current active connections */
  1326. int activeProcesses; /**< Current active processes */
  1327. int activeRequests; /**< Current active requests */
  1328. int activeSessions; /**< Current active sessions */
  1329. uint64 totalSweeps; /**< Total GC sweeps */
  1330. uint64 totalRequests; /**< Total requests served */
  1331. uint64 totalConnections; /**< Total connections accepted */
  1332. uint64 cpuUsage; /**< Total process CPU usage in ticks */
  1333. int cpuCores;
  1334. } HttpStats;
  1335. #define HTTP_STATS_MEMORY 0x1
  1336. #define HTTP_STATS_ALL 0x1
  1337. /**
  1338. Get an Http performance report
  1339. @param flags reserved
  1340. @return String containing the report
  1341. @ingroup HttpStats
  1342. @stability Internal
  1343. */
  1344. PUBLIC char *httpStatsReport(int flags);
  1345. /**
  1346. Get the Http performance statistics
  1347. @param sp Reference to a HttpStats structure
  1348. @ingroup HttpStats
  1349. @stability Internal
  1350. */
  1351. PUBLIC void httpGetStats(HttpStats *sp);
  1352. /************************************* Limits *********************************/
  1353. /**
  1354. Http limits
  1355. @defgroup HttpLimits HttpLimits
  1356. @see HttpLimits httpInitLimits httpCreateLimits httpEaseLimits
  1357. @stability Internal
  1358. */
  1359. typedef struct HttpLimits {
  1360. int cacheItemSize; /**< Maximum size of a cachable item */
  1361. ssize chunkSize; /**< Maximum chunk size for transfer encoding */
  1362. int clientMax; /**< Maximum number of unique clients (ip addresses) */
  1363. int connectionsMax; /**< Maximum number of simultaneous connections (sockets) for whole server */
  1364. int connectionsPerClientMax; /**< Maximum number of simultaneous connections (sockets) per client (ip address) */
  1365. int headerMax; /**< Maximum number of header lines */
  1366. int headerSize; /**< Maximum size of the total header */
  1367. MprTicks inactivityTimeout; /**< Timeout for keep-alive and idle requests (msec) */
  1368. int keepAliveMax; /**< Maximum number of Keep-Alive requests to perform per socket */
  1369. int packetSize; /**< Maximum packet size for queues and stages */
  1370. int processMax; /**< Maximum number of processes (CGI) */
  1371. int requestMax; /**< Maximum number of simultaneous concurrent requests */
  1372. MprTicks requestTimeout; /**< Time a request can take (msec) */
  1373. MprTicks requestParseTimeout; /**< Time a request can take to parse the request headers (msec) */
  1374. int requestsPerClientMax; /**< Maximum number of requests per client (ip address) */
  1375. MprOff rxBodySize; /**< Maximum size of receive body data */
  1376. MprOff rxFormSize; /**< Maximum size of form data */
  1377. int sessionMax; /**< Maximum number of sessions */
  1378. MprTicks sessionTimeout; /**< Time a session can persist (msec) */
  1379. MprOff txBodySize; /**< Maximum size of transmission body content */
  1380. MprOff uploadSize; /**< Maximum size of an uploaded file */
  1381. int uriSize; /**< Maximum size of a uri */
  1382. #if ME_HTTP_WEB_SOCKETS || DOXYGEN
  1383. int webSocketsFrameSize; /**< Maximum size of sent WebSocket frames. Incoming frames have no limit
  1384. except message size. */
  1385. int webSocketsMax; /**< Maximum number of WebSockets */
  1386. int webSocketsMessageSize; /**< Maximum total size of a WebSocket message including all frames */
  1387. int webSocketsPacketSize; /**< Maximum size of a WebSocket packet exchanged with the user callback */
  1388. MprTicks webSocketsPing; /**< Time between pings */
  1389. #endif
  1390. #if ME_HTTP_HTTP2 || DOXYGEN
  1391. int frameSize; /**< HTTP/2 maximum frame size */
  1392. int hpackMax; /**< HTTP/2 maximum size of the hpack header table */
  1393. int streamsMax; /**< HTTP/2 maximum number of streams per connection (both peer and self initiated) */
  1394. int txStreamsMax; /**< HTTP/2 maximum number of streams the peer will permit per connection */
  1395. int window; /**< HTTP/2 Initial rx window size (size willing to receive) */
  1396. #endif
  1397. } HttpLimits;
  1398. /**
  1399. Initialize a limits object with default values
  1400. @param limits Limits object to modify
  1401. @param serverSide Set to "true" for server side limits. Set to "false" for client side default limits
  1402. @ingroup HttpLimits
  1403. @stability Stable
  1404. */
  1405. PUBLIC void httpInitLimits(HttpLimits *limits, bool serverSide);
  1406. /**
  1407. Clone a limits object
  1408. @description Clone the limits and allocate a new limits object
  1409. @return The allocated limits object
  1410. @ingroup HttpLimits
  1411. @stability Evolving
  1412. */
  1413. PUBLIC HttpLimits *httpCloneLimits(HttpLimits *base);
  1414. /**
  1415. Create a new limits object
  1416. @description Create and initialize a new limits object with default values
  1417. @param serverSide Set to "true" for server side limits. Set to "false" for client side default limits
  1418. @return The allocated limits object
  1419. @ingroup HttpLimits
  1420. @stability Stable
  1421. */
  1422. PUBLIC HttpLimits *httpCreateLimits(int serverSide);
  1423. /**
  1424. Ease the limits
  1425. @description This increases the receive body size, transmission body size and upload size to the maximum
  1426. sizes supported by the system. Client side limits are eased by default.
  1427. @param limits Limits object. This can be either HttpHost.limits HttpStream.limits or HttpEndpoint.limits
  1428. @ingroup HttpLimits
  1429. @stability Stable
  1430. */
  1431. PUBLIC void httpEaseLimits(HttpLimits *limits);
  1432. /************************************* URI Services ***************************/
  1433. /**
  1434. URI management
  1435. @description The HTTP provides routines for formatting and parsing URIs. Routines are also provided
  1436. to escape dangerous characters for URIs as well as HTML content and shell commands.
  1437. @see HttpStream httpCloneUri httpCompleteUri httpCreateUri httpCreateUriFromParts httpFormatUri httpGetRelativeUri
  1438. httpJoinUri httpJoinUriPath httpLookupMimeType httpMakeUriLocal httpNormalizeUriPath httpResolveUri
  1439. httpUriToString
  1440. @defgroup HttpUri HttpUri
  1441. @stability Internal
  1442. */
  1443. typedef struct HttpUri {
  1444. cchar *scheme; /**< URI scheme (http|https|...) */
  1445. cchar *host; /**< Host name */
  1446. cchar *path; /**< Uri path (without scheme, host, query or fragements) */
  1447. cchar *ext; /**< Document extension */
  1448. cchar *reference; /**< Reference fragment within the specified resource */
  1449. cchar *query; /**< Query string */
  1450. int port; /**< Port number */
  1451. int secure; /**< Using https */
  1452. int webSockets; /**< Using WebSockets */
  1453. int valid; /**< Uri was successfully created */
  1454. } HttpUri;
  1455. #define HTTP_COMPLETE_URI 0x1 /**< Complete all missing URI fields. Set from "http://localhost/" */
  1456. #define HTTP_COMPLETE_URI_PATH 0x2 /**< Complete missing URI path. Set to "/" */
  1457. /**
  1458. Clone a URI
  1459. @description This call copies the base URI and optionally completes missing fields in the URI
  1460. @param base Base URI to copy
  1461. @param flags Set to HTTP_COMPLETE_URI to add missing components. ie. Add scheme, host and port if not supplied.
  1462. @return A new URI object
  1463. @ingroup HttpUri
  1464. @stability Stable
  1465. */
  1466. PUBLIC HttpUri *httpCloneUri(HttpUri *base, int flags);
  1467. /**
  1468. Complete the given URI
  1469. @description Complete the URI supplying missing URI components from the other URI. This modifies the supplied URI and
  1470. does not allocate or create a new URI.
  1471. @param uri URI to complete
  1472. @param other Other URI to supply the missing components
  1473. @return The supplied URI.
  1474. @ingroup HttpUri
  1475. @stability Stable
  1476. */
  1477. PUBLIC HttpUri *httpCompleteUri(HttpUri *uri, HttpUri *other);
  1478. /**
  1479. Create and initialize a URI.
  1480. @description Parse a uri and return a tokenized HttpUri structure.
  1481. @param uri Uri string to parse
  1482. @param flags Set to HTTP_COMPLETE_URI to add missing components. ie. Add scheme, host and port if not supplied.
  1483. @return A newly allocated HttpUri structure.
  1484. @ingroup HttpUri
  1485. @stability Stable
  1486. */
  1487. PUBLIC HttpUri *httpCreateUri(cchar *uri, int flags);
  1488. /**
  1489. Create a URI from parts
  1490. @description This call constructs a URI from the given parts. Various URI parts can be omitted by setting to null.
  1491. The URI path is the only mandatory parameter.
  1492. @param scheme The URI scheme. This is typically "http" or "https".
  1493. @param host The URI host name portion. This can be a textual host and domain name or it can be an IP address.
  1494. @param port The URI port number. Set to zero to accept the default value for the selected scheme.
  1495. @param path The URI path to the requested document.
  1496. @param reference URI reference with an HTML document. This is the URI component after the "#" in the URI path.
  1497. @param query URI query component. This is the URI component after the "?" in the URI.
  1498. @param flags Set to HTTP_COMPLETE_URI to add missing components. ie. Add scheme, host and port if not supplied.
  1499. @return A new URI
  1500. @ingroup HttpUri
  1501. @stability Stable
  1502. */
  1503. PUBLIC HttpUri *httpCreateUriFromParts(cchar *scheme, cchar *host, int port, cchar *path, cchar *reference,
  1504. cchar *query, int flags);
  1505. /**
  1506. Format a URI
  1507. @description Format a URI string using the input components.
  1508. @param scheme Protocol string for the uri. Example: "http"
  1509. @param host Host or IP address
  1510. @param port TCP/IP port number
  1511. @param path URL path
  1512. @param ref URL reference fragment
  1513. @param query Additiona query parameters.
  1514. @param flags Set to HTTP_COMPLETE_URI to add missing components. ie. Add scheme, host and port if not supplied.
  1515. @return A newly allocated uri string
  1516. @ingroup HttpUri
  1517. @stability Stable
  1518. */
  1519. PUBLIC char *httpFormatUri(cchar *scheme, cchar *host, int port, cchar *path, cchar *ref, cchar *query, int flags);
  1520. /**
  1521. Join URIs
  1522. @param base Base URI to being with
  1523. @param argc Count of URIs in others
  1524. @param others Array of URIs to join to the base
  1525. @return The resulting, joined URI
  1526. @ingroup HttpUri
  1527. @stability Stable
  1528. */
  1529. PUBLIC HttpUri *httpJoinUri(HttpUri *base, int argc, HttpUri **others);
  1530. /**
  1531. Join a URI path
  1532. @param result URI that will be modified with a joined path
  1533. @param base URI supplying the base path
  1534. @param other Other URI whose path is joined to the base
  1535. @return The result URI
  1536. @ingroup HttpUri
  1537. @stability Stable
  1538. */
  1539. PUBLIC HttpUri *httpJoinUriPath(HttpUri *result, HttpUri *base, HttpUri *other);
  1540. /**
  1541. Get the mime type for an extension.
  1542. This call will return the mime type from a limited internal set of mime types for the given path or extension.
  1543. @param ext Path or extension to examine
  1544. @returns Mime type. This is a static string.
  1545. @ingroup HttpUri
  1546. @stability Stable
  1547. */
  1548. PUBLIC cchar *httpLookupMimeType(cchar *ext);
  1549. /**
  1550. Normalize a URI
  1551. @description Validate and canonicalize a URI. This invokes httpNormalizeUriPath to normalize the URI path.
  1552. This removes redundant ./ and ../ segments including leading ../ segments. It does not make the URI absolute.
  1553. @param uri URI object to normalize
  1554. @return The supplied uri so it can be used in chaining. Returns null if the URI cannot be normalized.
  1555. @ingroup HttpUri
  1556. @stability Stable
  1557. */
  1558. PUBLIC HttpUri *httpNormalizeUri(HttpUri *uri);
  1559. /**
  1560. Normalize a URI
  1561. @description Validate and canonicalize a URI path. This removes redundant "./" and "../dir"
  1562. sequences including leading "../" segments.
  1563. @param uri Uri path string to normalize. This is the URI path portion without scheme, host and port components.
  1564. @return A new validated uri string. Returns null if the URI cannot be normalized.
  1565. @ingroup HttpUri
  1566. @stability Stable
  1567. */
  1568. PUBLIC char *httpNormalizeUriPath(cchar *uri);
  1569. /**
  1570. Get a relative URI from the base to the target
  1571. @description This creates a URI relative from the base to the target. This may contain ".." segments. This API is
  1572. designed to create relative URIs for use in a browser web page.
  1573. \n\n
  1574. If the target is null, an absolute URI, or if a relative URI from the base cannot be constructed, then
  1575. the target will be returned. If clone is true, then a clone of the target will be returned.
  1576. @param base The base URI considered to be the current URI. Think of this as the current directory.
  1577. @param target The destination URI for which a relative URI will be crafted to reach.
  1578. @param clone If true, the target URI will be cloned if the target is an absolute URI or if a relative URI
  1579. cannot be constructed.
  1580. @ingroup HttpUri
  1581. @stability Stable
  1582. */
  1583. PUBLIC HttpUri *httpGetRelativeUri(HttpUri *base, HttpUri *target, int clone);
  1584. /**
  1585. Make a URI local
  1586. @description This routine removes the scheme, host and port portions of a URI
  1587. @param uri URI to modify
  1588. @return The given URI.
  1589. @ingroup HttpUri
  1590. @stability Stable
  1591. */
  1592. PUBLIC HttpUri *httpMakeUriLocal(HttpUri *uri);
  1593. /**
  1594. Resolve URIs relative to a base
  1595. @param [in] stream HttpStream stream object
  1596. @param base Base URI to begin with
  1597. @param target URI to resolve relative to the base
  1598. @ingroup HttpUri
  1599. @stability Stable
  1600. */
  1601. PUBLIC HttpUri *httpResolveUri(struct HttpStream *stream, HttpUri *base, HttpUri *target);
  1602. /**
  1603. Create a URI link
  1604. @description Create a URI link based on a given target relative to the current request.
  1605. This API expands embedded tokens based on the current request and route state. The target URI parameter
  1606. may contain partial or complete URI information. The missing parts are supplied using the current request
  1607. and route tables.
  1608. @param [in] stream HttpStream stream object
  1609. @param target The URI target. The target parameter can be a URI string or JSON style set of options.
  1610. The target will have any embedded "{tokens}" expanded by using token values from the request parameters.
  1611. If the target has an absolute URI path, that path is used directly after tokenization. If the target begins with
  1612. "~", that character will be replaced with the route prefix. This is a very convenient way to create application
  1613. top-level relative links.
  1614. \n\n
  1615. If the target is a string that begins with "{AT}" it will be interpreted as a service/action pair of the
  1616. form "{AT}Service/action". If the "service/" portion is absent, the current service is used. If
  1617. the action component is missing, the "list" action is used. A bare "{AT}" refers to the "list" action
  1618. of the current service.
  1619. \n\n
  1620. If the target starts with "{" it is interpreted as being a JSON style set of options that describe the link.
  1621. If the target is a relative URI path, it is appended to the current request URI path.
  1622. \n\n
  1623. If the is a JSON style of options, it can specify the URI components: scheme, host, port, path, reference and
  1624. query. If these component properties are supplied, these will be combined to create a URI.
  1625. \n\n
  1626. If the target specifies either a service/action or a JSON set of options, The URI will be created according
  1627. to the route URI template. The template may be explicitly specified
  1628. via a "route" target property. Otherwise, if an "action" property is specified, the route of the same
  1629. name will be used. If these don't result in a usable route, the "default" route will be used.
  1630. \n\n
  1631. These are the properties supported in a JSON style "{ ... }" target:
  1632. <ul>
  1633. <li>scheme String URI scheme portion</li>
  1634. <li>host String URI host portion</li>
  1635. <li>port Number URI port number</li>
  1636. <li>path String URI path portion</li>
  1637. <li>reference String URI path reference. Does not include "#"</li>
  1638. <li>query String URI query parameters. Does not include "?"</li>
  1639. <li>service String Service name if using a Service-based route. This can also be specified via
  1640. the action option.</li>
  1641. <li>action String Action to invoke. This can be a URI string or a Service action of the form
  1642. {AT}Service/action.</li>
  1643. <li>route String Route name to use for the URI template</li>
  1644. </ul>
  1645. @return A normalized Uri string.
  1646. @ingroup HttpUri
  1647. @stability Evolving
  1648. @remarks Examples:
  1649. <pre>
  1650. httpLink(stream, "http://example.com/index.html");
  1651. httpLink(stream, "/path/to/index.html");
  1652. httpLink(stream, "../images/splash.png");
  1653. httpLink(stream, "~/static/images/splash.png");
  1654. httpLink(stream, "${app}/static/images/splash.png");
  1655. httpLink(stream, "@service/checkout");
  1656. httpLink(stream, "@service/") // Service = Service, action = index
  1657. httpLink(stream, "@init") // Current service, action = init
  1658. httpLink(stream, "@") // Current service, action = index
  1659. httpLink(stream, "{ action: '@post/create' }");
  1660. httpLink(stream, "{ action: 'checkout' }");
  1661. httpLink(stream, "{ action: 'logout', service: 'admin' }");
  1662. httpLink(stream, "{ action: 'admin/logout'");
  1663. httpLink(stream, "{ product: 'candy', quantity: '10', template: '/cart/${product}/${quantity}' }");
  1664. httpLink(stream, "{ route: '~/STAR/edit', action: 'checkout', id: '99' }");
  1665. httpLink(stream, "{ template: '~/static/images/${theme}/background.jpg', theme: 'blue' }");
  1666. </pre>
  1667. */
  1668. PUBLIC char *httpLink(struct HttpStream *stream, cchar *target);
  1669. /**
  1670. Create an absolute link that includes scheme and host
  1671. @param stream HttpStream stream object
  1672. @param target The URI target. See #httpLink for details of the target parameter.
  1673. @return A normalized Uri string.
  1674. @ingroup HttpUri
  1675. @stability Evolving
  1676. */
  1677. PUBLIC char *httpLinkAbs(struct HttpStream *stream, cchar *target);
  1678. /**
  1679. Extended URI link creation.
  1680. @description Extended httpLink with custom options. This routine extends the #httpLink API with an options hash
  1681. of token values.
  1682. @param [in] stream HttpStream stream object
  1683. @param target The URI target. See #httpLink for details.
  1684. @param options Hash of option values for embedded tokens. This hash is blended with the route variables.
  1685. @return A normalized Uri string.
  1686. @ingroup HttpUri
  1687. @stability Evolving
  1688. */
  1689. PUBLIC char *httpLinkEx(struct HttpStream *stream, cchar *target, MprHash *options);
  1690. /*
  1691. Create a URI link and return a URI object.
  1692. @param [in] stream HttpStream stream object
  1693. @param target The URI target. See #httpLink for details.
  1694. @param options Hash of option values for embedded tokens. This hash is blended with the route variables.
  1695. @return A normalized Uri string.
  1696. @ingroup HttpUri
  1697. @stability Evolving
  1698. */
  1699. PUBLIC HttpUri *httpLinkUri(struct HttpStream *stream, cchar *target, MprHash *options);
  1700. /**
  1701. Convert a Uri to a string.
  1702. @description Convert the given Uri to a string, optionally completing missing parts such as the host, port and path.
  1703. @param uri A Uri object created via httpCreateUri
  1704. @param flags Set to HTTP_COMPLETE_URI to add missing components. ie. Add scheme, host and port if not supplied.
  1705. @return A newly allocated uri string.
  1706. @ingroup HttpUri
  1707. @stability Stable
  1708. */
  1709. PUBLIC char *httpUriToString(HttpUri *uri, int flags);
  1710. /**
  1711. Validate a URI path as expected in a HTTP request line
  1712. @description This expects a URI beginning with "/" and containing only valid URI characters.
  1713. The URI is decoded, and normalized removing "../" and "." segments.
  1714. The URI must begin with a "/" both before and after decoding and normalization.
  1715. @param uri URI to validate.
  1716. @return A validated, normalized URI path
  1717. @stability Evolving
  1718. @ingroup HttpUri
  1719. */
  1720. PUBLIC char *httpValidateUriPath(cchar *uri);
  1721. /**
  1722. Test if a URI is using only valid characters
  1723. Note this does not test if the URI is fully legal. Some components of the URI have restricted character sets
  1724. that this routine does not test. This tests if the URI has only characters valid to use in a URI before decoding.
  1725. i.e. It will permit %NN encodings. The set of valid characters is:
  1726. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%"
  1727. @param uri Uri to test
  1728. @return True if the URI string is comprised of legal URI characters.
  1729. @ingroup HttpUri
  1730. */
  1731. PUBLIC bool httpValidUriChars(cchar *uri);
  1732. /************************************* Range **********************************/
  1733. /**
  1734. Content range structure
  1735. @pre
  1736. Range: 0, 49 First 50 bytes
  1737. Range: -1, -50 Last 50 bytes
  1738. Range: 1, -1 Skip first byte then select content to the end
  1739. @defgroup HttpRange HttpRange
  1740. @see HttpRange
  1741. @stability Internal
  1742. */
  1743. typedef struct HttpRange {
  1744. MprOff start; /**< Start of range */
  1745. MprOff end; /**< End byte of range + 1 */
  1746. MprOff len; /**< Redundant range length */
  1747. struct HttpRange *next; /**< Next range */
  1748. } HttpRange;
  1749. /************************************* Packet *********************************/
  1750. /*
  1751. Packet flags
  1752. */
  1753. #define HTTP_PACKET_HEADER 0x1 /**< Packet contains HTTP headers */
  1754. #define HTTP_PACKET_RANGE 0x2 /**< Packet is a range boundary packet */
  1755. #define HTTP_PACKET_DATA 0x4 /**< Packet contains actual content data */
  1756. #define HTTP_PACKET_END 0x8 /**< End of stream packet */
  1757. #define HTTP_PACKET_SOLO 0x10 /**< Don't join this packet */
  1758. #define HTTP_PACKET_PROCESSED 0x20 /**< Packet data has already been processed */
  1759. /**
  1760. Callback procedure to fill a packet with data
  1761. @param q Queue owning the packet
  1762. @param packet The packet to fill
  1763. @param off Offset in the packet to fill with data
  1764. @param size Size of packet from the offset to fill.
  1765. @return The number of bytes copied into the packet.
  1766. @ingroup HttpPacket
  1767. @stability Stable
  1768. */
  1769. typedef ssize (*HttpFillProc)(struct HttpQueue *q, struct HttpPacket *packet, MprOff pos, ssize size);
  1770. /**
  1771. Packet object.
  1772. @description The request/response pipeline sends data and control information in HttpPacket objects. The output
  1773. stream typically consists of a HEADER packet followed by zero or more data packets and terminated by an END
  1774. packet. If the request has input data, the input stream consists of one or more data packets followed by
  1775. an END packet.
  1776. \n\n
  1777. Packets contain data and optional prefix or suffix headers. Packets can be split, joined, filled, or emptied.
  1778. The pipeline stages will fill or transform packet data as required.
  1779. @defgroup HttpPacket HttpPacket
  1780. @see HttpFillProc HttpPacket HttpQueue httpAdjustPacketEnd httpAdjustPacketStart httpClonePacket
  1781. httpCreateDataPacket httpCreateEndPacket httpCreateEntityPacket httpCreateHeaderPacket httpCreatePacket
  1782. httpGetPacket httpGetPacketLength httpIsLastPacket httpJoinPacket
  1783. httpPutBackPacket httpPutForService httpPutPacket httpPutPacketToNext httpSplitPacket
  1784. @stability Internal
  1785. */
  1786. typedef struct HttpPacket {
  1787. uint flags: 7; /**< Packet flags */
  1788. uint last: 1; /**< Last packet in a message */
  1789. uint type: 8; /**< Packet type extension */
  1790. uint fin: 1; /**< Web sockets frame fin bit */
  1791. uint reserved: 15; /**< Reserved */
  1792. struct HttpPacket *next; /**< Next packet in chain */
  1793. MprBuf *content; /**< Chunk content */
  1794. MprBuf *prefix; /**< Prefix message to be emitted before the content */
  1795. MprOff esize; /**< Data size in entity (file) */
  1796. MprOff epos; /**< Data position in entity (file) */
  1797. HttpFillProc fill; /**< Callback to fill packet with data */
  1798. struct HttpStream *stream; /**< Reference to owning stream */
  1799. void *data; /**< Managed data reference */
  1800. } HttpPacket;
  1801. /**
  1802. Adjust the packet starting position.
  1803. @description This adjusts the packet content by the given size. The packet position is incremented by start and the
  1804. packet length (size) is decremented. If the packet describes entity data, the given size amount to the Packet.epos and
  1805. decrements the Packet.esize fields. If the packet has actual data buffered in Packet.content, the content buffer
  1806. start is incremeneted by the size amount.
  1807. @param packet Packet to modify
  1808. @param size Size to add to the packet current position.
  1809. @ingroup HttpPacket
  1810. @stability Stable
  1811. */
  1812. PUBLIC void httpAdjustPacketStart(HttpPacket *packet, MprOff size);
  1813. /**
  1814. Adjust the packet end position.
  1815. @description This adjusts the packet content by the given size. The packet length (size) is decremented by the requested
  1816. amount. If the packet describes entity data, the Packet.esize field is reduced by the requested size amount. If the
  1817. packet has actual data buffered in Packet.content, the content buffer end position is reduced by
  1818. by the size amount.
  1819. @param packet Packet to modify
  1820. @param size Size to adjust packet end position.
  1821. @ingroup HttpPacket
  1822. @stability Stable
  1823. */
  1824. PUBLIC void httpAdjustPacketEnd(HttpPacket *packet, MprOff size);
  1825. /**
  1826. Clone a packet
  1827. @param orig Original packet to clone
  1828. @return A new packet equivalent to the original
  1829. @ingroup HttpPacket
  1830. @stability Stable
  1831. */
  1832. PUBLIC HttpPacket *httpClonePacket(HttpPacket *orig);
  1833. /**
  1834. Create a data packet
  1835. @description Create a packet and set the HTTP_PACKET_DATA flag
  1836. Data packets convey data through the response pipeline.
  1837. @param size Size of the package data storage.
  1838. @return HttpPacket object.
  1839. @ingroup HttpPacket
  1840. @stability Stable
  1841. */
  1842. PUBLIC HttpPacket *httpCreateDataPacket(ssize size);
  1843. /**
  1844. Create an end-of-stream packet
  1845. @description Create an end-of-stream packet and set the HTTP_PACKET_END flag. The end pack signifies the
  1846. end of data. It is used on both incoming and outgoing streams through the request/response pipeline.
  1847. @return HttpPacket object.
  1848. @ingroup HttpPacket
  1849. @stability Stable
  1850. */
  1851. PUBLIC HttpPacket *httpCreateEndPacket(void);
  1852. /**
  1853. Create an entity data packet
  1854. @description Create an entity packet and set the HTTP_PACKET_DATA flag.
  1855. Entity packets describe the resource (entity) to send to the client and provide a #HttpFillProc procedure
  1856. used to fill packets with data from the entity.
  1857. @param pos Position within the entity for packet data
  1858. @param size Size of the entity data
  1859. @param fill HttpFillProc callback to supply the entity data.
  1860. @return HttpPacket object.
  1861. @ingroup HttpPacket
  1862. @stability Stable
  1863. */
  1864. PUBLIC HttpPacket *httpCreateEntityPacket(MprOff pos, MprOff size, HttpFillProc fill);
  1865. /**
  1866. Create a response header packet
  1867. @description Create a response header packet and set the HTTP_PACKET_HEADER flag.
  1868. A header packet is used by the pipeline to hold the response headers.
  1869. @return HttpPacket object.
  1870. @ingroup HttpPacket
  1871. @stability Stable
  1872. */
  1873. PUBLIC HttpPacket *httpCreateHeaderPacket(void);
  1874. /**
  1875. Create a data packet
  1876. @description Create a packet of the required size.
  1877. @param size Size of the package data storage.
  1878. @return HttpPacket object.
  1879. @ingroup HttpPacket
  1880. @stability Stable
  1881. */
  1882. PUBLIC HttpPacket *httpCreatePacket(ssize size);
  1883. /**
  1884. Get the next packet from a queue
  1885. @description Get the next packet. This will remove the packet from the queue and adjust the queue counts
  1886. accordingly. If the queue is full and upstream queues are blocked, they will be enabled.
  1887. @param q Queue reference
  1888. @return The packet removed from the queue.
  1889. @ingroup HttpQueue
  1890. @stability Stable
  1891. */
  1892. PUBLIC HttpPacket *httpGetPacket(struct HttpQueue *q);
  1893. #if DOXYGEN
  1894. /**
  1895. Get the packet data contents.
  1896. @description Get the packet content reference. This is an MprBuf object.
  1897. @param packet Packet to examine.
  1898. @return MprBuf reference or zero if there are not contents.
  1899. @ingroup HttpPacket
  1900. @stability Stable
  1901. */
  1902. PUBLIC ssize httpGetPacketContents(HttpPacket *packet);
  1903. #else
  1904. #define httpGetPacketContents(p) ((p && p->content) ? p->content : 0)
  1905. #endif
  1906. #if DOXYGEN
  1907. /**
  1908. Get the length of the packet data contents.
  1909. @description Get the content length of a packet. This does not include the prefix or virtual data length -- just
  1910. the pure buffered data contents.
  1911. @param packet Packet to examine.
  1912. @return Count of bytes contained by the packet.
  1913. @ingroup HttpPacket
  1914. @stability Stable
  1915. */
  1916. PUBLIC ssize httpGetPacketLength(HttpPacket *packet);
  1917. #else
  1918. #define httpGetPacketLength(p) ((p && p->content) ? mprGetBufLength(p->content) : 0)
  1919. #endif
  1920. /**
  1921. Get the start of the packet data contents.
  1922. @param packet Packet to examine.
  1923. @return A reference to the start of the packet contents.
  1924. @ingroup HttpPacket
  1925. @stability Stable
  1926. */
  1927. PUBLIC char *httpGetPacketStart(HttpPacket *packet);
  1928. /**
  1929. Get the packet data contents as a string.
  1930. @description Get the packet content reference. The packet contents will be null terminated.
  1931. @param packet Packet to examine.
  1932. @return A reference to the start of the packet contents.
  1933. @ingroup HttpPacket
  1934. @stability Stable
  1935. */
  1936. PUBLIC char *httpGetPacketString(HttpPacket *packet);
  1937. /**
  1938. Test if the packet is the last in a logical message.
  1939. @description Useful for WebSockets to test if the packet is the last frame in a message
  1940. @param packet Packet to examine
  1941. @return True if the packet is the last in a message.
  1942. @ingroup HttpPacket
  1943. @stability Stable
  1944. */
  1945. PUBLIC bool httpIsLastPacket(HttpPacket *packet);
  1946. /**
  1947. Join two packets
  1948. @description Join the contents of one packet to another by copying the data from the \a other packet into
  1949. the first packet.
  1950. @param packet Destination packet
  1951. @param other Other packet to copy data from.
  1952. @return "Zero" if successful, otherwise a negative Mpr error code
  1953. @ingroup HttpPacket
  1954. @stability Stable
  1955. */
  1956. PUBLIC int httpJoinPacket(HttpPacket *packet, HttpPacket *other);
  1957. /**
  1958. Split a data packet
  1959. @description Split a data packet at the specified offset. Packets may need to be split so that downstream
  1960. stages can digest their contents. If a packet is too large for the queue maximum size, it should be split.
  1961. When the packet is split, a new packet is created containing the data after the offset. Any suffix headers
  1962. are moved to the new packet.
  1963. NOTE: when splitting packets, the HttpPacket.content reference may be modified.
  1964. @param packet Packet to split
  1965. @param offset Location in the original packet at which to split. This is an offset relative to the current
  1966. 'start' read position not the beginning of the packet content buffer.
  1967. @return New HttpPacket object containing the data after the offset. No need to free, unless you have a very long
  1968. running request. Otherwise the packet memory will be released automatically when the request completes.
  1969. @ingroup HttpPacket
  1970. @stability Stable
  1971. */
  1972. PUBLIC HttpPacket *httpSplitPacket(HttpPacket *packet, ssize offset);
  1973. /*
  1974. Internal
  1975. */
  1976. #define httpGetPacketEntityLength(p) (p->content ? mprGetBufLength(p->content) : packet->esize)
  1977. /************************************* Queue *********************************/
  1978. /*
  1979. Queue directions
  1980. */
  1981. #define HTTP_QUEUE_TX 0 /**< Send (transmit to client) queue */
  1982. #define HTTP_QUEUE_RX 1 /**< Receive (read from client) queue */
  1983. #define HTTP_MAX_QUEUE 2 /**< Number of queue types */
  1984. /*
  1985. Queue flags
  1986. */
  1987. #define HTTP_QUEUE_OPEN_TRIED 0x1 /**< Queue's open routine has been called */
  1988. #define HTTP_QUEUE_OPENED 0x2 /**< Queue's open routine has been called */
  1989. #define HTTP_QUEUE_SUSPENDED 0x4 /**< Queue's service routine is suspended due to flow control */
  1990. #define HTTP_QUEUE_ALL 0x8 /**< Queue has all the data there is and will be */
  1991. #define HTTP_QUEUE_SERVICED 0x10 /**< Queue has been serviced at least once */
  1992. #define HTTP_QUEUE_EOF 0x20 /**< Queue at end of data */
  1993. #define HTTP_QUEUE_STARTED 0x40 /**< Handler stage start routine called */
  1994. #define HTTP_QUEUE_READY 0x80 /**< Handler stage ready routine called */
  1995. #define HTTP_QUEUE_RESERVICE 0x100 /**< Queue requires reservicing */
  1996. #define HTTP_QUEUE_OUTGOING 0x200 /**< Queue is for outgoing traffic */
  1997. #define HTTP_QUEUE_REQUEST 0x400 /**< Queue is specific for this request */
  1998. #define HTTP_QUEUE_HEAD 0x800 /**< Queue header */
  1999. #define HTTP_QUEUE_REMOVED 0x1000 /**< Queue removed from pipeline */
  2000. /*
  2001. Queue optimizations
  2002. */
  2003. #define HTTP_QUEUE_ALLOW 32 /**< Let packets less than this size flow through */
  2004. #define HTTP_QUEUE_DONT_SPLIT 32 /**< Don't split packets less than 32 bytes */
  2005. /*
  2006. Queue callback prototypes
  2007. */
  2008. typedef int (*HttpQueueOpen)(struct HttpQueue *q);
  2009. typedef void (*HttpQueueClose)(struct HttpQueue *q);
  2010. typedef void (*HttpQueueStart)(struct HttpQueue *q);
  2011. typedef void (*HttpQueueData)(struct HttpQueue *q, HttpPacket *packet);
  2012. typedef void (*HttpQueueService)(struct HttpQueue *q);
  2013. /**
  2014. Queue object
  2015. @description The request pipeline consists of a full-duplex pipeline of stages. Each stage has two queues,
  2016. one for outgoing data and one for incoming. A HttpQueue object manages the data flow for a request stage
  2017. and has the ability to queue and process data, manage flow control, and schedule packets for service.
  2018. \n\n
  2019. Queue's provide open, close, put, and service methods. These methods manage and respond to incoming packets.
  2020. A queue can respond immediately to an incoming packet by processing or dispatching a packet in its put() method.
  2021. Alternatively, the queue can defer processing by queueing the packet on it's service queue and then waiting for
  2022. it's service() method to be invoked.
  2023. \n\n
  2024. If a queue does not define a put() method, the default put() method will
  2025. be used which queues data onto the service queue. The default incoming put() method joins incoming packets
  2026. into a single packet on the service queue.
  2027. \n\n
  2028. Data flows downstream from one queue to the next queue linked via the nextQ field.
  2029. @defgroup HttpQueue HttpQueue
  2030. @see HttpStream HttpPacket HttpQueue httpDiscardQueueData httpFlushQueue httpGetQueueRoom
  2031. httpIsEof httpIsPacketTooBig httpIsQueueEmpty httpIsQueueSuspended httpJoinPacketForService httpJoinPackets
  2032. httpPutBackPacket httpPutForService httpPutPacket httpPutPacketToNext httpRemoveQueue httpResizePacket
  2033. httpResumeQueue httpScheduleQueue httpSetQueueLimits httpSuspendQueue
  2034. httpWillQueueAcceptPacket httpWillNextQueueAcceptSize httpWrite httpWriteBlock httpWriteBody httpWriteString
  2035. @stability Internal
  2036. */
  2037. typedef struct HttpQueue {
  2038. /* Ordered for debugging */
  2039. cchar *name; /**< Queue name for debugging */
  2040. ssize count; /**< Bytes in queue (Does not include virt packet data) */
  2041. int flags; /**< Queue flags */
  2042. struct HttpQueue *nextQ; /**< Downstream queue for next stage */
  2043. struct HttpQueue *prevQ; /**< Upstream queue for prior stage */
  2044. HttpPacket *first; /**< First packet in queue (singly linked) */
  2045. HttpPacket *last; /**< Last packet in queue (tail pointer) */
  2046. struct HttpStream *stream; /**< Stream owning this queue may be null */
  2047. struct HttpNet *net; /**< Network connection owning this queue */
  2048. struct HttpStage *stage; /**< Stage owning this queue */
  2049. HttpQueueOpen open; /**< Open the queue */
  2050. HttpQueueClose close; /**< Close the queue */
  2051. HttpQueueStart start; /**< Start the queue */
  2052. HttpQueueData put; /**< Callback to receive a packet */
  2053. HttpQueueService service; /**< Service the queue */
  2054. struct HttpQueue *scheduleNext; /**< Next linkage when queue is on the service queue */
  2055. struct HttpQueue *schedulePrev; /**< Previous linkage when queue is on the service queue */
  2056. struct HttpQueue *pair; /**< Queue for the same stage in the opposite direction */
  2057. void *queueData; /**< Stage instance data - must be a managed reference */
  2058. void *staticData; /**< Stage instance data - must be an unmanaged reference */
  2059. ssize max; /**< Advisory maxiumum queue size */
  2060. ssize low; /**< Low water mark for flow control */
  2061. ssize packetSize; /**< Maximum acceptable packet size */
  2062. int servicing; /**< Currently being serviced */
  2063. int direction; /**< Flow direction */
  2064. #if ME_HTTP_HTTP2 || DOXYGEN
  2065. ssize window; /**< HTTP/2 flow control window size */
  2066. #endif
  2067. } HttpQueue;
  2068. /**
  2069. Discard all data from the queue
  2070. @description Discard data from the queue. If removePackets (not yet implemented) is "true", then remove the packets.
  2071. Oherwise, just discard the data and preserve the packets.
  2072. @param q Queue reference
  2073. @param removePackets If "true", the data packets will be removed from the queue.
  2074. @ingroup HttpQueue
  2075. @stability Stable
  2076. */
  2077. PUBLIC void httpDiscardQueueData(HttpQueue *q, bool removePackets);
  2078. /**
  2079. Flush queue data
  2080. @description This initiates writing buffered data (flushes) by scheduling the queue and servicing the queues.
  2081. \n\n
  2082. If blocking mode is selected, all queues will be immediately serviced and the call may block while output drains.
  2083. If non-blocking, the queues will be serviced but the call will not block nor yield.
  2084. In blocking mode, this routine may invoke mprYield before it blocks to consent for the garbage collector to trun. Callers must
  2085. ensure they have retained all required temporary memory before invoking this routine.
  2086. \n\n
  2087. This routine when used with HTTP_BLOCK should never be used in filters, connectors or by handlers outside their
  2088. open, close, ready, start and writable callbacks.
  2089. @param q Queue to flush
  2090. @param flags If set to HTTP_BLOCK, this call will block until the data has drained through the network connector.
  2091. @return "True" if there is room for more data in the queue after flushing.
  2092. @ingroup HttpQueue
  2093. @stability Stable
  2094. */
  2095. PUBLIC bool httpFlushQueue(HttpQueue *q, int flags);
  2096. /**
  2097. Get the room in the queue
  2098. @description Get the amount of data the queue can accept before being full.
  2099. @param q Queue reference
  2100. @return A count of bytes that can be written to the queue
  2101. @ingroup HttpQueue
  2102. @stability Stable
  2103. */
  2104. PUBLIC ssize httpGetQueueRoom(HttpQueue *q);
  2105. /**
  2106. Test if the connection has received all incoming content
  2107. @description This tests if the connection is at an "End of File condition.
  2108. @param stream HttpStream object created via #httpCreateStream
  2109. @return "True" if all Receive content has been received
  2110. @ingroup HttpQueue
  2111. @stability Stable
  2112. */
  2113. PUBLIC bool httpIsEof(struct HttpStream *stream);
  2114. /**
  2115. Test if a packet is too big
  2116. @description Test if a packet is too big to fit downstream. If the packet content exceeds the downstream queue's
  2117. maximum or exceeds the downstream queue's requested packet size -- then this routine will return "true".
  2118. @param q Queue reference
  2119. @param packet Packet to test
  2120. @return "True" if the packet is too big for the downstream queue
  2121. @ingroup HttpQueue
  2122. @stability Stable
  2123. */
  2124. PUBLIC bool httpIsPacketTooBig(struct HttpQueue *q, HttpPacket *packet);
  2125. /**
  2126. Determine if the queue is empty
  2127. @description Determine if the queue has no packets queued. This does not test if the queue has no data content.
  2128. @param q Queue reference
  2129. @return "True" if there are no packets queued.
  2130. @ingroup HttpQueue
  2131. @stability Stable
  2132. */
  2133. PUBLIC bool httpIsQueueEmpty(HttpQueue *q);
  2134. /**
  2135. Test if a queue is suspended.
  2136. @param q Queue reference
  2137. @return true if the queue is suspended.
  2138. @ingroup HttpQueue
  2139. @stability Stable
  2140. */
  2141. PUBLIC bool httpIsQueueSuspended(HttpQueue *q);
  2142. /**
  2143. Join packets together
  2144. @description This call joins data packets on the given queue into a single packet. The given size specifies the
  2145. maximum size of data to be joined. The maximum size may also limited by the downstream queue maximum packet size.
  2146. @param q Queue to examine
  2147. @param size The maximum-sized packet that will be created by joining queue packets is the minimum of the given size
  2148. and the downstream queues maximum packet size. Note: this routine will not split packets and so the
  2149. maximum is advisory only.
  2150. @ingroup HttpQueue
  2151. @stability Stable
  2152. */
  2153. PUBLIC void httpJoinPackets(HttpQueue *q, ssize size);
  2154. /**
  2155. Join a packet onto the service queue
  2156. @description Add a packet to the service queue. If the queue already has data, then this packet
  2157. will be joined (aggregated) into the existing packet. If serviceQ is true, the queue will be scheduled
  2158. for service.
  2159. @param q Queue reference
  2160. @param packet Packet to join to the queue
  2161. @param serviceQ If true, schedule the queue for service
  2162. @ingroup HttpQueue
  2163. @stability Stable
  2164. */
  2165. PUBLIC void httpJoinPacketForService(struct HttpQueue *q, HttpPacket *packet, bool serviceQ);
  2166. /**
  2167. Put a packet back onto a queue
  2168. @description Put the packet back onto the front of the queue. The queue's put() method is not called.
  2169. This is typically used by the queue's service routine when a packet cannot complete processing.
  2170. @param q Queue reference
  2171. @param packet Packet to put back
  2172. @ingroup HttpQueue
  2173. @stability Stable
  2174. */
  2175. PUBLIC void httpPutBackPacket(struct HttpQueue *q, HttpPacket *packet);
  2176. /*
  2177. Convenience flags for httpPutForService in the serviceQ argument
  2178. */
  2179. #define HTTP_DELAY_SERVICE 0 /**< Delay servicing the queue */
  2180. #define HTTP_SCHEDULE_QUEUE 1 /**< Schedule the queue for service */
  2181. /**
  2182. Put a packet into the service queue for deferred processing.
  2183. @description Add a packet to the service queue. If serviceQ is true, the queue will be scheduled for service.
  2184. @param q Queue reference
  2185. @param packet Packet to join to the queue
  2186. @param serviceQ If true, schedule the queue for service
  2187. @ingroup HttpQueue
  2188. @stability Stable
  2189. */
  2190. PUBLIC void httpPutForService(struct HttpQueue *q, HttpPacket *packet, bool serviceQ);
  2191. /**
  2192. Put a packet to the queue.
  2193. @description The packet is passed to the queue by invoking its put() callback.
  2194. Note the receiving queue may immediately process the packet or it may choose to defer processing by putting to
  2195. its service queue. @param q Queue reference
  2196. \n\n
  2197. Note: the garbage collector may run while calling httpSendBlock to reclaim unused packets. It is essential that all
  2198. required memory be retained by a relevant manager calling mprMark as required.
  2199. @param packet Packet to put
  2200. @ingroup HttpQueue
  2201. @stability Stable
  2202. */
  2203. PUBLIC void httpPutPacket(struct HttpQueue *q, HttpPacket *packet);
  2204. /**
  2205. Put a packet to the next queue downstream.
  2206. @description Put a packet onto the next downstream queue by calling the downstream queue's put() method.
  2207. Note the receiving queue may immediately process the packet or it may choose to defer processing by putting to
  2208. its service queue.
  2209. @param qp Queue reference. The packet will not be queued on this queue, but rather on the queue downstream.
  2210. @param packet Packet to put
  2211. @ingroup HttpQueue
  2212. @stability Stable
  2213. */
  2214. PUBLIC void httpPutPacketToNext(struct HttpQueue *qp, HttpPacket *packet);
  2215. /**
  2216. Remove a queue
  2217. @description Remove a queue from the request/response pipeline. This will remove a queue so that it does
  2218. not participate in the pipeline, effectively removing the processing stage from the pipeline. This is
  2219. useful to remove unwanted filters and to speed up pipeline processing
  2220. @param q Queue reference
  2221. @ingroup HttpQueue
  2222. @stability Stable
  2223. */
  2224. PUBLIC void httpRemoveQueue(HttpQueue *q);
  2225. /**
  2226. Resize a packet
  2227. @description Resize a packet, if required, so that it fits in the downstream queue. This may split the packet
  2228. if it is too big to fit in the downstream queue. If it is split, the tail portion is put back on the queue.
  2229. @param q Queue reference. The q->nextQ will be examined to see if the packet will fit.
  2230. @param packet Packet to put
  2231. @param size If size is > 0, then also ensure the packet is not larger than this size.
  2232. @return Zero if the packet is not resized. Otherwise return the tail packet that was put back onto the queue.
  2233. @ingroup HttpQueue
  2234. @stability Stable
  2235. */
  2236. PUBLIC HttpPacket *httpResizePacket(struct HttpQueue *q, HttpPacket *packet, ssize size);
  2237. /**
  2238. Resume a queue
  2239. @description Resume a queue for service and schedule it to run. This will cause the service routine
  2240. to run as soon as possible. This is normally called automatically called by the pipeline when downstream
  2241. congestion has cleared.
  2242. @param q Queue reference
  2243. @param force Force a queue to be scheduled regardless. Set to true to force.
  2244. @return True if the queue was resumed.
  2245. @ingroup HttpQueue
  2246. @stability Evolving
  2247. */
  2248. PUBLIC bool httpResumeQueue(HttpQueue *q, bool force);
  2249. /**
  2250. Schedule a queue
  2251. @description Schedule a queue by adding it to the schedule queue. Queues are serviced FIFO.
  2252. @param q Queue reference
  2253. @ingroup HttpQueue
  2254. @stability Stable
  2255. */
  2256. PUBLIC void httpScheduleQueue(HttpQueue *q);
  2257. /**
  2258. Set a queue's max packetSize and flow control low, max and window thresholds
  2259. @description If size parameters are set to -1, default values from the limits are used.
  2260. @param q Queue reference
  2261. @param limits Default limits to use if other arguments are not provided.
  2262. @param packetSize The default maximum packet size.
  2263. @param low The low water mark. Typically set to packet size by default.
  2264. @param max The high water mark. Set by default to packetSize * 4.
  2265. @param window HTTP/2 flow control window size. Must be at least HTTP_DEFAULT_WINDOW_SIZE.
  2266. @ingroup HttpQueue
  2267. @stability Stable
  2268. */
  2269. PUBLIC void httpSetQueueLimits(HttpQueue *q, HttpLimits *limits, ssize packetSize, ssize low, ssize max, ssize window);
  2270. /**
  2271. Suspend a queue.
  2272. @description Suspended a queue so that it will not be scheduled for service. The pipeline will
  2273. will automatically call httpResumeQueue when the downstream queues are less congested.
  2274. @param q Queue reference
  2275. @ingroup HttpQueue
  2276. @stability Stable
  2277. */
  2278. PUBLIC void httpSuspendQueue(HttpQueue *q);
  2279. /**
  2280. Transfer packets from one queue to another
  2281. @param inq Input q
  2282. @param outq Output q
  2283. @ingroup HttpQueue
  2284. @stability Evolving
  2285. */
  2286. PUBLIC void httpTransferPackets(HttpQueue *inq, HttpQueue *outq);
  2287. /**
  2288. Replay incoming packets through the pipeline.
  2289. @description This routine is used to process previously received packets once the pipeline
  2290. is configured. It transfers already received packets back through the new pipeline stages
  2291. for processing.
  2292. @param inq Input q
  2293. @param outq Output q
  2294. @ingroup HttpQueue
  2295. @stability Evolving
  2296. */
  2297. PUBLIC void httpReplayPackets(HttpQueue *inq, HttpQueue *outq);
  2298. #if ME_DEBUG
  2299. /**
  2300. Verify a queue
  2301. @param q Queue reference
  2302. @return "True" if the queue verifies
  2303. @internal
  2304. */
  2305. PUBLIC bool httpVerifyQueue(HttpQueue *q);
  2306. #define VERIFY_QUEUE(q) httpVerifyQueue(q)
  2307. #else
  2308. #define VERIFY_QUEUE(q)
  2309. #endif
  2310. /**
  2311. Determine if the downstream queue will accept this packet.
  2312. @description Test if the downstream queue will accept a packet. The packet will be resized, if required, in an
  2313. attempt to get the downstream queue to accept it. If the downstream queue is full, disable this queue
  2314. and mark the downstream queue as full, and service it immediately to try to relieve the congestion.
  2315. @param q Queue reference
  2316. @param packet Packet to put
  2317. @return "True" if the downstream queue will accept the packet. Use #httpPutPacketToNext to send the
  2318. packet downstream
  2319. @ingroup HttpQueue
  2320. @stability Stable
  2321. */
  2322. PUBLIC bool httpWillNextQueueAcceptPacket(HttpQueue *q, HttpPacket *packet);
  2323. // Internal
  2324. PUBLIC bool httpIsNextQueueSuspended(HttpQueue *q);
  2325. /**
  2326. Test if the next queue is full
  2327. @description Tests if the next queue count is over the queue maximum
  2328. @param q Queue reference
  2329. @return "True" if the next q->count > q->max
  2330. @ingroup HttpQueue
  2331. @stability Stable
  2332. */
  2333. PUBLIC bool httpNextQueueFull(HttpQueue *q);
  2334. /**
  2335. Determine if the given queue will accept this packet.
  2336. @description Test if the queue will accept a packet. The packet will be resized, if split is true, in an
  2337. attempt to get the downstream queue to accept it.
  2338. @param q Queue reference
  2339. @param nextQ Next (downstream) queue reference
  2340. @param packet Packet to put
  2341. @return "True" if the queue will accept the packet.
  2342. @ingroup HttpQueue
  2343. @stability Stable
  2344. */
  2345. PUBLIC bool httpWillQueueAcceptPacket(HttpQueue *q, HttpQueue *nextQ, HttpPacket *packet);
  2346. /**
  2347. Determine if the downstream queue will accept a certain amount of data.
  2348. @description Test if the downstream queue will accept data of a given size.
  2349. @param q Queue reference
  2350. @param size Size of data to test for
  2351. @return "True" if the downstream queue will accept the given sized data.
  2352. @ingroup HttpQueue
  2353. @stability Stable
  2354. */
  2355. PUBLIC bool httpWillNextQueueAcceptSize(HttpQueue *q, ssize size);
  2356. /**
  2357. Write a formatted string
  2358. @description Write a formatted string of data into packets onto the end of the queue. Data packets will be created
  2359. as required to store the write data. This call always accepts all the data and will buffer as required.
  2360. This call may block waiting for the downstream queue to drain if it is or becomes full.
  2361. Data written after #httpFinalizeOutput or #httpError is called will be ignored.
  2362. \n\n
  2363. Handlers may only call httpWrite in their open, close, ready, start and writable callbacks as these are the only
  2364. callbacks permitted to block. If a handler
  2365. needs to write in other callbacks, it should use #httpWriteBlock and use the HTTP_NON_BLOCK or HTTP_BUFFER flags.
  2366. \n\n
  2367. Filters and connectors must never call httpWrite as it may block.
  2368. @param q Queue reference
  2369. @param fmt Printf style formatted string
  2370. @param ... Arguments for fmt
  2371. @return A count of the bytes actually written
  2372. @ingroup HttpQueue
  2373. @stability Stable
  2374. */
  2375. PUBLIC ssize httpWrite(HttpQueue *q, cchar *fmt, ...) PRINTF_ATTRIBUTE(2,3);
  2376. /*
  2377. Set HTTP_BLOCK to 0x1 so that legacy calls to httpFlushQueue that supplied a boolean block value will function correctly
  2378. */
  2379. #define HTTP_BLOCK 0x1 /**< Flag for httpSendBlock and httpWriteBlock to indicate blocking operation */
  2380. #define HTTP_NON_BLOCK 0x2 /**< Flag for httpSendBlock and httpWriteBlock to indicate non-blocking operation */
  2381. #define HTTP_BUFFER 0x4 /**< Flag for httpSendBlock and httpWriteBlock to always absorb the data without blocking */
  2382. #define HTTP_CURRENT 0x8 /**< Flag to service current queued events only */
  2383. /**
  2384. Write a block of data to the queue
  2385. @description Write a block of data onto the end of the queue. This will queue the data and may initiaite writing
  2386. to the connection if the queue is full. Data will be appended to last packet in the queue if there is room.
  2387. Otherwise, data packets will be created as required to store the write data.
  2388. \n\n
  2389. This call operates in buffering mode by default unless either the HTTP_BLOCK OR HTTP_NON_BLOCK flag is specified.
  2390. When blocking, the call will either accept and write all the data or it will fail, it will never return "short"
  2391. with a partial write.
  2392. \n\n
  2393. In blocking mode (HTTP_BLOCK), it blocks for up to the inactivity timeout specified in the
  2394. stream->limits->inactivityTimeout value. In blocking mode, this routine may invoke mprYield before blocking to
  2395. consent for the garbage collector to run. Callers must ensure they have retained all required temporary memory
  2396. before invoking this routine.
  2397. \n\n
  2398. In non-blocking mode (HTTP_NON_BLOCK), the call may return having written fewer bytes than requested.
  2399. \n\n
  2400. In buffering mode (HTTP_BUFFER), the data is always absorbed without blocking and queue size limits are ignored.
  2401. In buffering mode, this routine may invoke mprYield if required to consent for the garbage collector to run.
  2402. Callers must ensure they have retained all required temporary memory before invoking this routine.
  2403. \n\n
  2404. Data written after calling #httpFinalize, #httpFinalizeOutput or #httpError will be discarded.
  2405. @param q Queue reference
  2406. @param buf Buffer containing the write data
  2407. @param size of the data in buf
  2408. @param flags Set to HTTP_BLOCK for blocking operation or HTTP_NON_BLOCK for non-blocking. Set to HTTP_BUFFER to
  2409. buffer the data if required and never block. Set to zero will default to HTTP_BUFFER.
  2410. This call may yield via mprYield if flags are set to HTTP_BLOCK.
  2411. @return The size value if successful or a negative MPR error code.
  2412. @ingroup HttpQueue
  2413. @stability Evolving
  2414. */
  2415. PUBLIC ssize httpWriteBlock(HttpQueue *q, cchar *buf, ssize size, int flags);
  2416. /**
  2417. Write a string of data to the queue
  2418. @description Write a string of data into packets onto the end of the queue. Data packets will be created
  2419. as required to store the write data. This call may block waiting for the downstream queue to drain if it is
  2420. or becomes full. Data written after #httpFinalizeOutput or #httpError is called will be ignored.
  2421. @param q Queue reference
  2422. @param s String containing the data to write
  2423. @return A count of the bytes actually written
  2424. @ingroup HttpQueue
  2425. @stability Stable
  2426. */
  2427. PUBLIC ssize httpWriteString(HttpQueue *q, cchar *s);
  2428. /* Internal */
  2429. PUBLIC HttpQueue *httpAppendQueue(HttpQueue *q, HttpQueue *prev);
  2430. PUBLIC void httpAssignQueueCallbacks(HttpQueue *q, struct HttpStage *stage, int dir);
  2431. PUBLIC HttpQueue *httpCreateQueue(struct HttpNet *net, struct HttpStream *stream, struct HttpStage *stage, int dir, HttpQueue *prev);
  2432. PUBLIC HttpQueue *httpCreateQueueHead(struct HttpNet *net, struct HttpStream *stream, cchar *name, int dir);
  2433. PUBLIC HttpQueue *httpFindNextQueue(HttpQueue *q);
  2434. PUBLIC HttpQueue *httpFindPreviousQueue(HttpQueue *q);
  2435. PUBLIC HttpQueue *httpGetNextQueueForService(HttpQueue *q);
  2436. PUBLIC void httpInitSchedulerQueue(HttpQueue *q);
  2437. PUBLIC void httpMarkQueueHead(HttpQueue *q);
  2438. PUBLIC void httpOpenQueues(struct HttpStream *stream);
  2439. PUBLIC void httpPairQueues(HttpQueue *q1, HttpQueue *q2);
  2440. PUBLIC void httpRemoveChunkFilter(HttpQueue *head);
  2441. PUBLIC void httpRemovePacket(HttpQueue *q, HttpPacket *prev, HttpPacket *packet);
  2442. PUBLIC cchar *httpTraceHeaders(MprHash *headers);
  2443. PUBLIC void httpTraceQueues(struct HttpStream *stream);
  2444. PUBLIC void httpServiceQueue(HttpQueue *q);
  2445. /******************************** Pipeline Stages *****************************/
  2446. /*
  2447. Stage Flags
  2448. */
  2449. #define HTTP_STAGE_CONNECTOR 0x1000 /**< Stage is a connector */
  2450. #define HTTP_STAGE_HANDLER 0x2000 /**< Stage is a handler */
  2451. #define HTTP_STAGE_FILTER 0x4000 /**< Stage is a filter */
  2452. #define HTTP_STAGE_MODULE 0x8000 /**< Stage is a module */
  2453. #define HTTP_STAGE_AUTO_DIR 0x10000 /**< Want auto directory redirection */
  2454. #define HTTP_STAGE_UNLOADED 0x20000 /**< Stage module library has been unloaded */
  2455. #define HTTP_STAGE_RX 0x40000 /**< Stage to be used in the Rx direction */
  2456. #define HTTP_STAGE_TX 0x80000 /**< Stage to be used in the Tx direction */
  2457. #define HTTP_STAGE_INTERNAL 0x100000 /**< Internal stage - hidden */
  2458. #define HTTP_STAGE_QHEAD 0x200000 /**< Queue Head */
  2459. typedef int (*HttpParse)(cchar *key, char *value, void *state);
  2460. /**
  2461. Pipeline Stages
  2462. @description The request pipeline consists of a full-duplex pipeline of stages.
  2463. Stages are used to process client HTTP requests in a modular fashion. Each stage either creates, filters or
  2464. consumes data packets. The HttpStage structure describes the stage capabilities and callbacks.
  2465. Each stage has two queues, one for outgoing data and one for incoming data.
  2466. \n\n
  2467. Stages provide callback methods for parsing configuration, matching requests, open/close, run and the
  2468. acceptance and service of incoming and outgoing data. The order of these callbacks will vary depending if
  2469. HttpRx.streaming is set. FileUpload requires streaming and the input callback for some stages in the
  2470. standard pipeline may be invoked before the request is routed.
  2471. Configuration is not thread safe and must occur at initialization time when the application is single threaded.
  2472. If the configuration is modified when the application is multithreaded, all requests must be first be quiesced.
  2473. @defgroup HttpStage HttpStage
  2474. @see HttpStream HttpQueue HttpStage httpCloneStage httpCreateConnector httpCreateFilter httpCreateHandler
  2475. httpCreateStage httpDefaultService httpGetStageData httpHandleOptionsTrace httpLookupStage
  2476. httpLookupStageData httpSetStageData
  2477. @stability Internal
  2478. */
  2479. typedef struct HttpStage {
  2480. char *name; /**< Stage name */
  2481. char *path; /**< Backing module path (from LoadModule) */
  2482. int flags; /**< Stage flags */
  2483. void *stageData; /**< Private stage data */
  2484. MprModule *module; /**< Backing module */
  2485. MprHash *extensions; /**< Matching extensions for this filter */
  2486. /* These callbacks apply to all stages */
  2487. /**
  2488. Match a request
  2489. @description This routine is invoked to see if the stage wishes to handle the request. For handlers,
  2490. the match callback is invoked when selecting the appropriate route for the request. For filters,
  2491. the callback is invoked subsequently when constructing the request pipeline.
  2492. If a filter declines to handle a request, the filter will be removed from the pipeline for the
  2493. specified direction. The direction argument should be ignored for handlers.
  2494. Handlers and filters must not actually handle the request in the match callback and must not call httpError.
  2495. Errors can be reported via mprError. Handlers can defer error reporting until their start callback.
  2496. @param stream HttpStream stream object
  2497. @param route Route object
  2498. @param dir Queue direction. Set to HTTP_QUEUE_TX or HTTP_QUEUE_RX. Always set to HTTP_QUEUE_TX for handlers.
  2499. @return HTTP_ROUTE_OK if the request is acceptable. Return HTTP_ROUTE_REROUTE if the request has been rewritten.
  2500. Return HTTP_ROUTE_REJECT it the request is not acceptable.
  2501. @ingroup HttpStage
  2502. @stability Evolving
  2503. */
  2504. int (*match)(struct HttpStream *stream, struct HttpRoute *route, int dir);
  2505. /**
  2506. Rewrite a request after matching.
  2507. @description This callback will be invoked for handlers after matching and selecting the handler.
  2508. @param stream HttpStream stream object
  2509. @return Zero for success. Otherwise a negative MPR error code.
  2510. @ingroup HttpStage
  2511. @stability Evolving
  2512. */
  2513. int (*rewrite)(struct HttpStream *stream);
  2514. /**
  2515. Open the stage
  2516. @description Open the stage for this request instance. A handler may service the request in the open routine
  2517. and may call #httpError if required.
  2518. Handlers may block or yield in this callback.
  2519. @param q Queue instance object
  2520. @return Zero for success. Otherwise a negative MPR error code.
  2521. @ingroup HttpStage
  2522. @stability Evolving
  2523. */
  2524. int (*open)(HttpQueue *q);
  2525. /**
  2526. Close the stage
  2527. @description Close the stage and cleanup any request resources.
  2528. Handlers may block or yield in this callback.
  2529. @param q Queue instance object
  2530. @ingroup HttpStage
  2531. @stability Evolving
  2532. */
  2533. void (*close)(HttpQueue *q);
  2534. /**
  2535. Process outgoing data.
  2536. @description Accept a packet as outgoing data. Not used by handlers as handler generate packets internally.
  2537. Filters will use this entry point to accept outgoing packets.
  2538. Filters can choose to immediately process or forward the packet, or they can queue the packet on their
  2539. queue and schedule their outgoingService callback for batch processing of all queued packets. This is
  2540. a common pattern where the outgoing routine is not used and packets are automatically queued and the
  2541. outgoingService callback is used to process data. Filters should not block or yield in this callback.
  2542. @param q Queue instance object
  2543. @param packet Packet of data
  2544. @ingroup HttpStage
  2545. @stability Evolving
  2546. */
  2547. void (*outgoing)(HttpQueue *q, HttpPacket *packet);
  2548. /**
  2549. Service the outgoing data queue
  2550. @description This callback should service packets on the queue and process or forward as appropriate.
  2551. A service routine should check downstream queues by calling #httpWillNextQueueAcceptPacket before forwarding
  2552. packets to ensure they do not overfow downstream queues. Stages should not block or yield in this callback.
  2553. @param q Queue instance object
  2554. @ingroup HttpStage
  2555. @stability Evolving
  2556. */
  2557. void (*outgoingService)(HttpQueue *q);
  2558. /**
  2559. Process incoming data.
  2560. @description Accept an incoming packet of data.
  2561. Filters and handlers recieve packets via their incoming callback. They can choose to immediately process or
  2562. forward the packet, or they can queue the packet on their queue and schedule their incomingService callback
  2563. for batch processing of all queued packets. This is a common pattern where the incoming routine is not
  2564. used and packets are automatically queued and the incomingService callback is used to process.
  2565. Not used by connectors. Stages should not block or yield in this callback.
  2566. @param q Queue instance object
  2567. @param packet Packet of data
  2568. @ingroup HttpStage
  2569. @stability Evolving
  2570. */
  2571. void (*incoming)(HttpQueue *q, HttpPacket *packet);
  2572. /**
  2573. Service the incoming data queue
  2574. @description This callback should service packets on the queue and process or forward as appropriate.
  2575. A service routine should check upstream queues by calling #httpWillNextQueueAcceptPacket before forwarding
  2576. packets to ensure they do not overfow upstream queues. Handlers may not block or yield in this callback.
  2577. @param q Queue instance object
  2578. @ingroup HttpStage
  2579. @stability Evolving
  2580. */
  2581. void (*incomingService)(HttpQueue *q);
  2582. /* These callbacks apply only to handlers */
  2583. /**
  2584. Start the handler
  2585. @description The start callback is primarily responsible for starting the request processing.
  2586. Depending on the request Content Type, the request will be started at different times.
  2587. Form requests with a Content-Type of "application/x-www-form-urlencoded", will be started after fully
  2588. receiving all input data. Other requests will be started immediately after the request headers have been
  2589. parsed and before receiving input data. This enables such requests to stream large quantities of input
  2590. data without buffering. The start callback should test the HTTP method in stream->rx->method and only
  2591. respond to supported HTTP methods. It should call httpError for unsupported methods. The start callback
  2592. will not be called if the request already has an error. Handlers may block or yield in this callback.
  2593. @param q Queue instance object
  2594. @ingroup HttpStage
  2595. @stability Evolving
  2596. */
  2597. void (*start)(HttpQueue *q);
  2598. /**
  2599. The request is now fully ready.
  2600. @description This callback will be invoked when all incoming data has been received.
  2601. The ready callback will not be called if the request already has an error.
  2602. If a handler finishes processing the request, it should call #httpFinalizeOutput in the ready routine.
  2603. Handlers may block or yield in this callback.
  2604. @param q Queue instance object
  2605. @ingroup HttpStage
  2606. @stability Evolving
  2607. */
  2608. void (*ready)(HttpQueue *q);
  2609. /**
  2610. The outgoing pipeline is writable and can accept more response data.
  2611. @description This callback will be invoked after all incoming data has been receeived and whenever the outgoing
  2612. pipeline can absorb more output data (writable). As such, it may be called multiple times and can be effectively
  2613. used for non-blocking generation of a response.
  2614. The writable callback will not be invoked if the request output has been finalized or if an error has occurred.
  2615. Handlers may block or yield in this callback.
  2616. @param q Queue instance object
  2617. @ingroup HttpStage
  2618. @stability Evolving
  2619. */
  2620. void (*writable)(HttpQueue *q);
  2621. } HttpStage;
  2622. /**
  2623. Create a clone of an existing state. This is used when creating filters configured to match certain extensions.
  2624. @param stage Stage object to clone
  2625. @return A new stage object
  2626. @ingroup HttpStage
  2627. @stability Stable
  2628. */
  2629. PUBLIC HttpStage *httpCloneStage(HttpStage *stage);
  2630. /**
  2631. Create a connector stage
  2632. @description Create a new connector. Connectors are the final stage for outgoing data. Their job is to transmit
  2633. outgoing data to the client.
  2634. @param name Name of connector stage
  2635. @param module Optional module object for loadable stages
  2636. @return A new stage object
  2637. @ingroup HttpStage
  2638. @stability Stable
  2639. */
  2640. PUBLIC HttpStage *httpCreateConnector(cchar *name, MprModule *module);
  2641. /**
  2642. Create a filter stage
  2643. @description Create a new filter. Filters transform data generated by handlers and before connectors transmit to
  2644. the client. Filters can apply transformations to incoming, outgoing or bi-directional data.
  2645. @param name Name of connector stage
  2646. @param module Optional module object for loadable stages
  2647. @return A new stage object
  2648. @ingroup HttpStage
  2649. @stability Stable
  2650. */
  2651. PUBLIC HttpStage *httpCreateFilter(cchar *name, MprModule *module);
  2652. /**
  2653. Create a request handler stage
  2654. @description Create a new handler. Handlers generate outgoing data and are the final stage for incoming data.
  2655. Their job is to process requests and send outgoing data downstream toward the client consumer.
  2656. There is ever only one handler for a request.
  2657. @param name Name of connector stage
  2658. @param module Optional module object for loadable stages
  2659. @return A new stage object
  2660. @ingroup HttpStage
  2661. @stability Stable
  2662. */
  2663. PUBLIC HttpStage *httpCreateHandler(cchar *name, MprModule *module);
  2664. /**
  2665. Create a connector stage
  2666. @description Create a new stage.
  2667. @param name Name of connector stage
  2668. @param flags Stage flags
  2669. @param module Optional module object for loadable stages
  2670. @return A new stage object
  2671. @ingroup HttpStage
  2672. @stability Stable
  2673. */
  2674. PUBLIC HttpStage *httpCreateStage(cchar *name, int flags, MprModule *module);
  2675. /**
  2676. Lookup a stage by name
  2677. @param name Name of stage to locate
  2678. @return Stage or NULL if not found
  2679. @ingroup HttpStage
  2680. @stability Stable
  2681. */
  2682. PUBLIC struct HttpStage *httpLookupStage(cchar *name);
  2683. /**
  2684. Default stage service routine handling
  2685. @description This routine provides default service handling of data for stages. It simply sends all packets
  2686. downstream. It handles flow control automatically.
  2687. @param q Queue object
  2688. @ingroup HttpStage
  2689. @stability Evolving
  2690. */
  2691. PUBLIC void httpDefaultService(HttpQueue *q);
  2692. /**
  2693. Stage service routine that discards packets
  2694. @param q Queue object
  2695. @ingroup HttpStage
  2696. @stability Evolving
  2697. */
  2698. PUBLIC void httpDiscardService(HttpQueue *q);
  2699. /**
  2700. Default stage incoming handling
  2701. @description This routine provides default incoming handling of data for stages.
  2702. It puts the packet to the next Stage's incoming service queue or incoming routine if there
  2703. is no service routine defined.
  2704. @param q Queue object
  2705. @param packet Packet object
  2706. @ingroup HttpStage
  2707. @stability Evolving
  2708. */
  2709. PUBLIC void httpDefaultIncoming(HttpQueue *q, HttpPacket *packet);
  2710. /**
  2711. Default stage outgoing handling
  2712. @description This routine provides default outgoing handling of data for stages. It puts the packet
  2713. to the next Stage's outgoing service queue or outgoing routine if there is no service routine defined.
  2714. @param q Queue object
  2715. @param packet Packet to send.
  2716. @ingroup HttpStage
  2717. @stability Evolving
  2718. */
  2719. PUBLIC void httpDefaultOutgoing(HttpQueue *q, HttpPacket *packet);
  2720. /**
  2721. Get stage data
  2722. @description Stages can store extra configuration information indexed by key. This is used by handlers, filters,
  2723. connectors and and handlers.
  2724. @param stream HttpStream stream object
  2725. @param key Key index into the stage data
  2726. @return A reference to the stage data. Otherwise return null if the route data for the given key was not found.
  2727. @ingroup HttpRx
  2728. @stability Stable
  2729. */
  2730. PUBLIC cvoid *httpGetStageData(struct HttpStream *stream, cchar *key);
  2731. /**
  2732. Handle a Http Options method request
  2733. @description Convenience routine to respond to an OPTIONS request.
  2734. @param stream HttpStream object created via #httpCreateStream
  2735. @ingroup HttpStage
  2736. @stability Stable
  2737. */
  2738. PUBLIC void httpHandleOptions(struct HttpStream *stream);
  2739. /**
  2740. Lookup stage data
  2741. @description This looks up the stage by name and returns the private stage data.
  2742. @param name Name of the stage concerned
  2743. @return Reference to the stage data block.
  2744. @ingroup HttpStage
  2745. @stability Stable
  2746. */
  2747. PUBLIC void *httpLookupStageData(cchar *name);
  2748. /**
  2749. Set stage data
  2750. @description Stages can store extra configuration information indexed by key. This is used by handlers, filters,
  2751. connectors and applications.
  2752. @param stream HttpStream stream object
  2753. @param key Key index into the stage data
  2754. @param data Reference to custom data allocated via mprAlloc.
  2755. @ingroup HttpRoute
  2756. @stability Stable
  2757. */
  2758. PUBLIC void httpSetStageData(struct HttpStream *stream, cchar *key, cvoid *data);
  2759. /* Internal APIs */
  2760. PUBLIC void httpAddStage(HttpStage *stage);
  2761. PUBLIC int httpOpenQueueHead(void);
  2762. PUBLIC ssize httpFilterChunkData(HttpQueue *q, HttpPacket *packet);
  2763. PUBLIC int httpOpenActionHandler(void);
  2764. PUBLIC int httpOpenChunkFilter(void);
  2765. PUBLIC int httpOpenCacheHandler(void);
  2766. PUBLIC int httpOpenDirHandler(void);
  2767. PUBLIC int httpOpenFileHandler(void);
  2768. PUBLIC int httpOpenPassHandler(void);
  2769. PUBLIC int httpOpenRangeFilter(void);
  2770. PUBLIC int httpOpenNetConnector(void);
  2771. PUBLIC int httpOpenUploadFilter(void);
  2772. PUBLIC int httpOpenWebSockFilter(void);
  2773. PUBLIC int httpSendOpen(HttpQueue *q);
  2774. PUBLIC void httpSendOutgoingService(HttpQueue *q);
  2775. PUBLIC int httpHandleDirectory(struct HttpStream *stream);
  2776. PUBLIC int httpOpenHttp1Filter(void);
  2777. PUBLIC int httpOpenHttp2Filter(void);
  2778. PUBLIC int httpOpenQueueHead(void);
  2779. PUBLIC int httpOpenTailFilter(void);
  2780. /********************************** Http2 **************************************/
  2781. #if ME_HTTP_HTTP2 || DOXYGEN
  2782. /*
  2783. HTTP/2 Frame format
  2784. Byte 0 Byte 1 Byte 2 Byte 3
  2785. 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
  2786. +------------------------------------------------+--------------+
  2787. | Length (24) | Type (8) |
  2788. +------------------------------------------------+--------------+
  2789. | Flags (8) |R| Stream Identifier (31) |
  2790. +------------------------------------------------+--------------+
  2791. | Stream Cont | Payload Data .... |
  2792. +------------------------------------------------+--------------+
  2793. */
  2794. /*
  2795. HTTP/2 Frame sizes
  2796. */
  2797. #define HTTP2_FRAME_OVERHEAD 9 /**< Minimum HTTP/2 frame size */
  2798. #define HTTP2_SETTINGS_SIZE 6 /**< Size of settings frame data */
  2799. #define HTTP2_WINDOW_SIZE 4 /**< Size of windows frame data */
  2800. #define HTTP2_RESET_SIZE 4 /**< Size of rest frame data */
  2801. #define HTTP2_GOAWAY_SIZE 8 /**< Size of goaway frame data */
  2802. #define HTTP2_PRIORITY_SIZE 5 /**< Size of priority frame data */
  2803. /*
  2804. HTTP/2 parameters
  2805. */
  2806. #define HTTP2_MAX_FRAME_SIZE ((1 << 24) - 1) /**< Maximum frame size by spec */
  2807. #define HTTP2_MAX_STREAM ((1U << 31) - 1) /**< Maximum stream number by spec */
  2808. #define HTTP2_MAX_WINDOW ((1U << 31) - 1) /**< Maximum window size by spec */
  2809. /*
  2810. Do not change these defaults. They are defined by the spec.
  2811. */
  2812. #define HTTP2_MIN_WINDOW 65535 /**< Initial default window size by spec */
  2813. #define HTTP2_MIN_FRAME_SIZE (16 * 1024) /**< Default and minimum frame size - modified by config */
  2814. #define HTTP2_DEFAULT_WEIGHT 16 /**< Unused */
  2815. /*
  2816. Misc flags and constants
  2817. */
  2818. #define HTTP2_PREFACE "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
  2819. #define HTTP2_PREFACE_SIZE 24
  2820. #define HTTP2_ENCODE_RAW 0
  2821. #define HTTP2_ENCODE_HUFF 0x80
  2822. #define HTTP2_TABLE_SIZE 4096
  2823. #define HTTP2_HEADER_OVERHEAD 32 /**< HPACK table overhead by spec */
  2824. #define HTTP_STREAM_MASK 0x7fffffff
  2825. /*
  2826. HTTP/2 Frame types
  2827. */
  2828. #define HTTP2_DATA_FRAME 0x0
  2829. #define HTTP2_HEADERS_FRAME 0x1
  2830. #define HTTP2_PRIORITY_FRAME 0x2
  2831. #define HTTP2_RESET_FRAME 0x3
  2832. #define HTTP2_SETTINGS_FRAME 0x4
  2833. #define HTTP2_PUSH_FRAME 0x5
  2834. #define HTTP2_PING_FRAME 0x6
  2835. #define HTTP2_GOAWAY_FRAME 0x7
  2836. #define HTTP2_WINDOW_FRAME 0x8
  2837. #define HTTP2_CONT_FRAME 0x9
  2838. #define HTTP2_MAX_FRAME 0xA
  2839. /*
  2840. HTTP/2 frame flags
  2841. */
  2842. #define HTTP2_ACK_FLAG 0x1
  2843. #define HTTP2_END_STREAM_FLAG 0x1
  2844. #define HTTP2_END_HEADERS_FLAG 0x4
  2845. #define HTTP2_PADDED_FLAG 0x8
  2846. #define HTTP2_PRIORITY_FLAG 0x20
  2847. /*
  2848. Settings fields
  2849. */
  2850. #define HTTP2_HEADER_TABLE_SIZE_SETTING 0x1
  2851. #define HTTP2_ENABLE_PUSH_SETTING 0x2
  2852. #define HTTP2_MAX_STREAMS_SETTING 0x3
  2853. #define HTTP2_INIT_WINDOW_SIZE_SETTING 0x4
  2854. #define HTTP2_MAX_FRAME_SIZE_SETTING 0x5
  2855. #define HTTP2_MAX_HEADER_SIZE_SETTING 0x6
  2856. /*
  2857. HTTP2 error codes
  2858. */
  2859. #define HTTP2_NO_ERROR 0x0
  2860. #define HTTP2_PROTOCOL_ERROR 0x1
  2861. #define HTTP2_INTERNAL_ERROR 0x2
  2862. #define HTTP2_FLOW_CONTROL_ERROR 0x3
  2863. #define HTTP2_SETTINGS_TIMEOUT 0x4
  2864. #define HTTP2_STREAM_CLOSED 0x5
  2865. #define HTTP2_FRAME_SIZE_ERROR 0x6
  2866. #define HTTP2_REFUSED_STREAM 0x7
  2867. #define HTTP2_CANCEL 0x8
  2868. #define HTTP2_COMP_ERROR 0x9
  2869. #define HTTP2_CONNECT_ERROR 0xa
  2870. #define HTTP2_ENHANCE_YOUR_CALM 0xb
  2871. #define HTTP2_INADEQUATE_SECURITY 0xc
  2872. #define HTTP2_HTTP_1_1_REQUIRED 0xd
  2873. /*
  2874. Hpack static string indexes
  2875. */
  2876. #define HTTP2_METHOD_GET 2
  2877. #define HTTP2_METHOD_POST 3
  2878. #define HTTP2_PATH_ROOT 4
  2879. #define HTTP2_PATH_INDEX 4
  2880. #define HTTP2_STATUS_200 8
  2881. #define HTTP2_STATUS_204 9
  2882. #define HTTP2_STATUS_206 10
  2883. #define HTTP2_STATUS_304 11
  2884. #define HTTP2_STATUS_400 12
  2885. #define HTTP2_STATUS_404 13
  2886. #define HTTP2_STATUS_500 14
  2887. /*
  2888. HTTP/2 States
  2889. */
  2890. #define HTTP2_STATE_IDLE 0
  2891. typedef struct HttpFrame {
  2892. struct HttpStream *stream;
  2893. int type; /**< Frame type */
  2894. int flags; /**< Flags */
  2895. int depend; /** Stream dependency */
  2896. int exclusive;
  2897. int weight; /**< Priority weight */
  2898. int streamID; /**< Current stream ID */
  2899. } HttpFrame;
  2900. /**
  2901. HTTP HPACK header table
  2902. */
  2903. typedef struct HttpHeaderTable {
  2904. MprList *list; /**< Header list */
  2905. ssize size;
  2906. ssize max;
  2907. } HttpHeaderTable;
  2908. /*
  2909. Internal
  2910. */
  2911. PUBLIC void httpCreatePackedHeaders(void);
  2912. PUBLIC int httpLookupPackedHeader(HttpHeaderTable *headers, cchar *key, cchar *value, bool *withValue);
  2913. PUBLIC MprKeyValue *httpGetPackedHeader(HttpHeaderTable *headers, int index);
  2914. PUBLIC int httpAddPackedHeader(HttpHeaderTable *headers, cchar *key, cchar *value);
  2915. PUBLIC int httpSetPackedHeadersMax(HttpHeaderTable *headers, int size);
  2916. PUBLIC ssize httpHuffEncode(cchar *src, ssize len, char *dst, uint lower);
  2917. PUBLIC cchar *httpHuffDecode(uchar *src, int len);
  2918. #endif /* ME_HTTP_HTTP2 */
  2919. /********************************* Network *************************************/
  2920. /**
  2921. I/O callback for network connections
  2922. @param stream HttpNet object created via #httpCreateStream
  2923. @param event Event object describing the I/O event
  2924. @ingroup HttpNet
  2925. @stability Evolving
  2926. */
  2927. typedef void (*HttpIOCallback)(struct HttpNet *net, MprEvent *event);
  2928. /*
  2929. HTTP protocol variants
  2930. */
  2931. #define HTTP_1_0 0
  2932. #define HTTP_1_1 1
  2933. #define HTTP_2 2
  2934. #define HTTP_NET_ASYNC 0x1
  2935. /*
  2936. Net callback defines
  2937. */
  2938. #define HTTP_NET_ACCEPT 1 /**< A network connection has just been accepted */
  2939. #define HTTP_NET_CONNECT 2 /**< The network has just connected to a peery (client side only) */
  2940. #define HTTP_NET_EOF 3 /**< The network peer has disconnected */
  2941. #define HTTP_NET_ERROR 4 /**< The network has an unrecoverable error */
  2942. #define HTTP_NET_DESTROY 5 /**< The network is about to be destroyed */
  2943. #define HTTP_NET_IO 6 /**< The network has an IO event */
  2944. /**
  2945. Control object for the network connection. A network connection may multiplex many HttpStream objects that represent
  2946. logical streams over the connection.
  2947. @defgroup HttpNet HttpNet
  2948. @see HttpNet httpCreateNet httpDestroyNet httpIOEvent httpNetError httpServiceNetQueues httpSetIOCallback httpSetNetContext httpEnableNetEvents httpNetTimeout httpGetProtocol httpGetAsync httpSetAsync httpConnectNet
  2949. @stability Internal
  2950. */
  2951. typedef struct HttpNet {
  2952. Http *http; /**< Http service object */
  2953. HttpLimits *limits; /**< Service limits */
  2954. MprSocket *sock; /**< Underlying socket handle */
  2955. MprList *streams; /**< List of streams */
  2956. struct HttpStream
  2957. *stream; /**< Single stream for HTTP/1 == streams[0] */
  2958. struct HttpEndpoint
  2959. *endpoint; /**< Endpoint object (if set - indicates server-side) */
  2960. int port; /**< Remote port */
  2961. char *ip; /**< Remote client IP address */
  2962. cchar *errorMsg; /**< Error message for the last request (if any) */
  2963. HttpTrace *trace; /**< Tracing configuration */
  2964. HttpIOCallback ioCallback; /**< I/O event callback */
  2965. HttpAddress *address; /**< Per-client IP address reference */
  2966. HttpQueue *holdq; /**< GC hold queue while scheduling */
  2967. HttpQueue *inputq; /**< Queue of packets received from the network (http-rx) */
  2968. HttpQueue *outputq; /**< Queue of packets to write to the network (http-tx) */
  2969. HttpQueue *serviceq; /**< List of queues that require service */
  2970. HttpQueue *socketq; /**< Queue of packets to write to the output socket (last queue) */
  2971. #if ME_HTTP_HTTP2 || DOXYGEN
  2972. HttpHeaderTable *rxHeaders; /**< Cache of HPACK rx headers */
  2973. HttpHeaderTable *txHeaders; /**< Cache of HPACK tx headers */
  2974. HttpFrame *frame; /**< Current frame being parsed */
  2975. #endif
  2976. MprDispatcher *dispatcher; /**< Event dispatcher */
  2977. MprDispatcher *newDispatcher; /**< New dispatcher if using a worker thread */
  2978. MprDispatcher *oldDispatcher; /**< Original dispatcher if using a worker thread */
  2979. MprEvent *timeoutEvent; /**< Connection or request timeout event */
  2980. MprEvent *workerEvent; /**< Event for running connection via a worker thread (used by ejs) */
  2981. MprTicks lastActivity; /**< Last activity on the connection */
  2982. MprOff bytesWritten; /**< Total bytes written */
  2983. HttpNetCallback callback; /**< Network event callback */
  2984. void *context; /**< Embedding context (EjsRequest) */
  2985. void *data; /**< Custom data */
  2986. uint64 seqno; /**< Unique network sequence number */
  2987. int delay; /**< Delay servicing requests due to defense strategy */
  2988. int nextStreamID; /**< Next stream ID */
  2989. int lastStreamID; /**< Last stream ID */
  2990. int protocol; /**< HTTP protocol: 0 for HTTP/1.0, 1 for HTTP/1.1 or 2+ */
  2991. int ownStreams; /**< Number of peer created streams */
  2992. int session; /**< Currently parsing frame for this session */
  2993. int timeout; /**< Network timeout indication */
  2994. int totalRequests; /**< Total number of requests serviced */
  2995. int window; /**< Default HTTP/2 flow control window size for streams tx */
  2996. bool active; /** Active httpIOEvent */
  2997. bool servicing; /**< Servicing net request (server side) */
  2998. bool async: 1; /**< Network is in async mode (non-blocking) */
  2999. bool autoDestroy: 1; /**< Destroy the network automatically after IO events if appropriate */
  3000. bool destroyed: 1; /**< Net object has been destroyed */
  3001. bool eof: 1; /**< Socket has been closed */
  3002. bool error: 1; /**< Hard network error - cannot continue */
  3003. uint eventMask: 3; /**< Last IO event mask */
  3004. bool http2: 1; /**< Enable http 2 */
  3005. bool init: 1; /**< Settings frame has been sent and network is ready to use */
  3006. bool ownDispatcher: 1; /**< Using own dispatcher and should destroy when closing */
  3007. bool parsingHeaders: 1; /**< Parsing HTTP/2 headers */
  3008. bool push: 1; /**< Receiver will accept push */
  3009. bool receivedGoaway: 1; /**< Received goaway frame */
  3010. bool secure: 1; /**< Using https */
  3011. bool sentGoaway: 1; /**< Sent goaway frame */
  3012. bool sharedDispatcher: 1; /**< Dispatcher is shared and should not be destroyed */
  3013. bool skipTrace: 1; /**< Omit trace from now on */
  3014. bool tracing: 1; /**< Network is tracing packets */
  3015. bool worker: 1; /**< Use worker */
  3016. bool writeBlocked: 1; /**< Transmission writing is blocked */
  3017. #if DEPRECATED || 1
  3018. /*
  3019. This will be removed in Appweb 10
  3020. */
  3021. bool borrowed: 1; /**< Socket has been borrowed */
  3022. #endif
  3023. /*
  3024. Network connector instance data
  3025. */
  3026. MprIOVec iovec[ME_MAX_IOVEC];
  3027. int ioIndex; /**< Next index into iovec */
  3028. MprOff ioCount; /**< Count of bytes in iovec including file I/O */
  3029. MprOff ioPos; /**< Position in file */
  3030. //MprOff ioFileSize; /**< Size of file */
  3031. MprFile *ioFile; /**< File to send */
  3032. #if DEPRECATED
  3033. void *ejs; /**< Embedding VM */
  3034. void *pool; /**< Pool of VMs */
  3035. #endif
  3036. } HttpNet;
  3037. #if DEPRECATED
  3038. /**
  3039. Borrow a network connection
  3040. @description Borrow the network from Http. This effectively gains an exclusive loan of the network so that it
  3041. cannot be destroyed while the loan is active. After the loan is complete, you must call return the network
  3042. by calling #httpReturnNet. Otherwise the network will not be freed and memory will leak.
  3043. \n\n
  3044. The httpBorrowNet routine is used to stabilize a network while interacting with some outside service.
  3045. Without this routine, the network could be destroyed while waiting. Many things can happen while waiting.
  3046. For example: the client could disconnect or the network connection could timeout. These events will still be
  3047. serviced while the network is borrowed, but the network object will not be destroyed.
  3048. \n\n
  3049. While borrowed, you must not access the network object using foreign / non-MPR threads. If you need to do this,
  3050. use #mprCreateEvent to schedule an event to run on the networks's event dispatcher.
  3051. This is essential to serialize access to the network object.
  3052. \n\n
  3053. Before returning from the event callback, you must call #httpReturnNet to end the exclusive loan.
  3054. This restores normal processing of the connection and enables any required I/O events.
  3055. \n\n
  3056. @param net HttpNet object created via #httpCreateNet
  3057. @ingroup HttpNet
  3058. @stability Deprecated
  3059. */
  3060. PUBLIC void httpBorrowNet(HttpNet *net);
  3061. #endif
  3062. /**
  3063. Connect the network to a remote peer.
  3064. @param net HttpNet Network object created via #httpCreateNet
  3065. @param ip Remote IP address to connect to
  3066. @param port TCP/IP port to connect to
  3067. @param ssl MprSsl object that defines the SSL context
  3068. @return Zero if successful, otherwise a negative MPR error code.
  3069. @ingroup HttpNet
  3070. @stability Evolving
  3071. */
  3072. PUBLIC int httpConnectNet(HttpNet *net, cchar *ip, int port, MprSsl *ssl);
  3073. /**
  3074. Create a network object.
  3075. @description The network object defines the underlying network connection over which HttpStream connection streams will
  3076. be multiplexed.
  3077. @param dispatcher Event MprDispatcher object to serialize events for the network.
  3078. @param endpoint Server-side HttpEndpoint object. Set to NULL for client-side.
  3079. @param protocol HTTP protocol to use by default. Set to 1 for HTTP/1 and 2 for HTTP/2.
  3080. @param flags Set to HTTP_NET_ASYNC if you wish to use async I/O. Otherwise set to zero.
  3081. @returns A new network object
  3082. @ingroup HttpNet
  3083. @stability Evolving
  3084. */
  3085. PUBLIC HttpNet *httpCreateNet(MprDispatcher *dispatcher, struct HttpEndpoint *endpoint, int protocol, int flags);
  3086. /**
  3087. Destroy the network object
  3088. @description This call closes the network socket, destroys the connection dispatcher, disconnects the HttpStream
  3089. objects and removes the network from the HttpHost list of networks. All active stream connections
  3090. (HttpStream) will also be destroyed. Thereafter, the garbage collector can reclaim all memory. It may be called by
  3091. client connections at any time from a top-level event running on the connection's dispatcher. Server-side code
  3092. should not explicitly destroy the connection as it will be done automatically via httpIOEvent.
  3093. @param net HttpNet object created via #httpCreateNet
  3094. @ingroup HttpNet
  3095. @stability Internal
  3096. */
  3097. PUBLIC void httpDestroyNet(HttpNet *net);
  3098. /**
  3099. Enable network events
  3100. @description Network events are automatically disabled upon receipt of an I/O event on a network connection. This
  3101. permits a network to process the I/O without fear of interruption by another I/O event. At the completion
  3102. of processing of the I/O request, the network should be re-enabled via httpEnableNetEvents. This call is
  3103. made for requests in #httpIOEvent. Client-side networks may need to enable network events if they are
  3104. running in async mode and encounter a blocking condition.
  3105. @param net HttpNet Network object created via #httpCreateNet
  3106. @ingroup HttpNet
  3107. @stability Evolving
  3108. */
  3109. PUBLIC void httpEnableNetEvents(HttpNet *net);
  3110. /**
  3111. Get the Http protocol variant for this network connection
  3112. @param net HttpNet Network object created via #httpCreateNet
  3113. @return HTTP/1.0, HTTP/1.1 or HTTP/2.
  3114. @ingroup HttpNet
  3115. @stability Evolving
  3116. */
  3117. PUBLIC cchar *httpGetProtocol(HttpNet *net);
  3118. /**
  3119. Get the async mode value for the network
  3120. @param net HttpNet object created via #httpCreateNet
  3121. @return True if the Network is in async mode
  3122. @ingroup HttpNet
  3123. @stability Evolving
  3124. */
  3125. PUBLIC bool httpGetAsync(HttpNet *net);
  3126. /**
  3127. Respond to a HTTP I/O event
  3128. @description This routine responds to I/O events. If any readable data is present, it allocates a standard sized
  3129. packet and reads data into this packet and passes to the input queue pipeline.
  3130. @param net HttpNet object created via #httpCreateNet
  3131. @param event Event structure
  3132. @ingroup HttpNet
  3133. @stability Internal
  3134. */
  3135. PUBLIC void httpIOEvent(struct HttpNet *net, MprEvent *event);
  3136. // Internal
  3137. PUBLIC void httpServiceNet(struct HttpNet *net);
  3138. /**
  3139. Read input from a HTTP connected socket
  3140. @description This routine reads I/O events. It allocates a standard sized
  3141. packet and reads data into this packet and passes to the input queue pipeline.
  3142. @param net HttpNet object created via #httpCreateNet
  3143. @ingroup HttpNet
  3144. @stability Internal
  3145. */
  3146. PUBLIC bool httpReadIO(HttpNet *net);
  3147. /**
  3148. Test if the network is a client-side network
  3149. @param net HttpNet Network object created via #httpCreateNet
  3150. @return true if the network is client-side
  3151. @ingroup HttpNet
  3152. @stability Evolving
  3153. */
  3154. #define httpIsClient(net) (net && !net->endpoint)
  3155. /**
  3156. Test if the network is a server-side network
  3157. @param net HttpNet Network object created via #httpCreateNet
  3158. @return true if the network is server-side
  3159. @ingroup HttpNet
  3160. @stability Evolving
  3161. */
  3162. #define httpIsServer(net) (net && net->endpoint)
  3163. /**
  3164. Error handling for the network.
  3165. @description The httpNetError call is used to flag the current network as failed. If httpNetError is called multiple
  3166. times, those calls are ignored and only the first call to httpNetError has effect.
  3167. This call will close all network streams and discard all data in output pipeline queues.
  3168. @param net HttpNet object created via #httpCreateNet
  3169. @param fmt Printf style formatted string
  3170. @param ... Arguments for fmt
  3171. @ingroup HttpNet
  3172. @stability Evolving
  3173. */
  3174. PUBLIC void httpNetError(HttpNet *net, cchar *fmt, ...);
  3175. /**
  3176. Schedule a network connection timeout event on a network
  3177. @description This call schedules a timeout event to run serialized on the network's dispatcher. When run, it will
  3178. cancel all current requests on the network, disconnect the socket and issue an error to the error log.
  3179. This call is normally invoked by the httpTimer which runs regularly to check for timed out requests.
  3180. @param net HttpNet Network object created via #httpCreateNet
  3181. @ingroup HttpNet
  3182. @stability Internal
  3183. */
  3184. PUBLIC void httpNetTimeout(HttpNet *net);
  3185. #if DEPRECATED
  3186. /**
  3187. Return a borrowed a network connection
  3188. @description Returns a borrowed network object back to the Http engine. This ends the exclusive loan of the
  3189. network so that the current request can be completed. It also enables I/O events based on the
  3190. current state of the network.
  3191. \n\n
  3192. While the network is borrowed, you must not access the network using foreign / non-MPR threads.
  3193. Use #mprCreateEvent to schedule an event to run on the network's event dispatcher. This is
  3194. essential to serialize access to the network object.
  3195. \n\n
  3196. You should only call this routine (once) after calling #httpBorrowNet.
  3197. \n\n
  3198. @param net HttpNet object created via #httpCreateNet
  3199. @ingroup HttpNet
  3200. @stability Deprecated
  3201. */
  3202. PUBLIC void httpReturnNet(HttpNet *net);
  3203. #endif
  3204. /**
  3205. Service pipeline queues to flow data.
  3206. @description This routine should not be called by handlers, filters or user applications. It should only be called
  3207. by the http pipeline and support routines.
  3208. @param net HttpNet object created via #httpCreateNet
  3209. @param flags Set to HTTP_BLOCK to yield for GC if due
  3210. @ingroup HttpNet
  3211. @stability Evolving
  3212. */
  3213. PUBLIC void httpServiceNetQueues(HttpNet *net, int flags);
  3214. /**
  3215. Define an I/O callback for network connections
  3216. @description The I/O callback is invoked when I/O events are detected on the network. The default I/O callback
  3217. is #httpIOEvent.
  3218. @param net HttpNet object created via #httpCreateNet
  3219. @param fn Callback function to invoke
  3220. @ingroup HttpNet
  3221. @stability Evolving
  3222. */
  3223. PUBLIC void httpSetIOCallback(struct HttpNet *net, HttpIOCallback fn);
  3224. /**
  3225. Test if the network queues need service
  3226. @param net HttpNet object created via #httpCreateNet
  3227. @return True if there are queues that require servicing
  3228. @ingroup HttpNet
  3229. @stability Evolving
  3230. */
  3231. PUBLIC bool httpQueuesNeedService(HttpNet *net);
  3232. /**
  3233. Set the async mode value for the network
  3234. @param net HttpNet object created via #httpCreateNet
  3235. @param async Set to 1 to enable async mode
  3236. @return True if the network is in async mode
  3237. @ingroup HttpNet
  3238. @stability Evolving
  3239. */
  3240. PUBLIC void httpSetAsync(HttpNet *net, bool async);
  3241. /**
  3242. Define a network event callback
  3243. @description This callback is invoked when networks closed or receive a peer disconnect.
  3244. @param net If defined, set the callback on the net object. Otherwise update the default net callback for
  3245. future network objects.
  3246. @param callback The callback is invoked with the signature: void callback(HttpNet *net).
  3247. @ingroup HttpNet
  3248. @stability Evolving
  3249. */
  3250. PUBLIC void httpSetNetCallback(HttpNet *net, HttpNetCallback callback);
  3251. /**
  3252. Set the network context object
  3253. @param net HttpNet object created via #httpCreateNet
  3254. @param context New context object. Must be a managed memory reference.
  3255. @ingroup HttpNet
  3256. @stability Evolving
  3257. */
  3258. PUBLIC void httpSetNetContext(HttpNet *net, void *context);
  3259. /**
  3260. Set the EOF flag in the network to indicate a peer disconnect
  3261. @param net HttpNet Network object created via #httpCreateNet
  3262. @ingroup HttpNet
  3263. @stability Evolving
  3264. */
  3265. PUBLIC void httpSetNetEof(HttpNet *net);
  3266. /**
  3267. Set the error flag in the network to indicate a peer disconnect
  3268. @param net HttpNet Network object created via #httpCreateNet
  3269. @ingroup HttpNet
  3270. @stability Evolving
  3271. */
  3272. PUBLIC void httpSetNetError(HttpNet *net);
  3273. /**
  3274. Set the Http protocol variant for this network connection
  3275. @description Set the Http protocol variant to use.
  3276. @param net HttpNet Network object created via #httpCreateNet
  3277. @param protocol Integer representing the protocol variant. Valid values are: 0 for HTTP/1.0, 1 for HTTP/1.1 and 2 for HTTP/2.
  3278. @ingroup HttpNet
  3279. @stability Evolving
  3280. */
  3281. PUBLIC void httpSetNetProtocol(HttpNet *net, int protocol);
  3282. #if DEPRECATE
  3283. /**
  3284. Steal a socket from a network
  3285. @description Steal the MprSocket object from a network so the caller can assume total responsibility for the socket.
  3286. This routine returns a clone of the networks's socket object with the socket O/S handle. The handle is removed from the
  3287. networks's socket object. The network retains ownership of the original MprSocket object -- sans the socket handle.
  3288. This is done to preserve the HttpNetwork.sock object but remove the socket handle from its management.
  3289. \n\n
  3290. Note: All current streams are aborted and queue data is discarded.
  3291. After calling, the normal Appweb request and inactivity timeouts will not apply to the returned socket object.
  3292. It is the callers responsibility to call mprCloseSocket on the returned MprSocket when ready.
  3293. @param net HttpNet object created via #httpCreateNet
  3294. @return A clone of the network's MprSocket object with the socket handle.
  3295. @ingroup HttpNet
  3296. @stability Deprecated
  3297. */
  3298. PUBLIC MprSocket *httpStealSocket(HttpNet *net);
  3299. #endif
  3300. /**
  3301. Steal the O/S socket handle from the network socket object.
  3302. @description This removes the O/S socket handle from active management by the network. After calling,
  3303. normal request and inactivity timeouts will apply to the network, but will not disturb the underlying
  3304. actual socket handle. It is the callers responsibility to call close() on the socket handle when ready.
  3305. @param net HttpNet object created via #httpCreateNet
  3306. @return The O/S Socket handle.
  3307. @ingroup HttpNet
  3308. @stability Deprecated
  3309. */
  3310. PUBLIC Socket httpStealSocketHandle(HttpNet *net);
  3311. /*
  3312. Internal
  3313. */
  3314. PUBLIC int httpGetNetEventMask(HttpNet *net);
  3315. PUBLIC void httpGetUriAddress(HttpUri *uri, cchar **ip, int *port);
  3316. PUBLIC void httpSetNetTimeout(HttpNet *net, MprTicks inactivityTimeout);
  3317. PUBLIC void httpSendGoAway(struct HttpNet *net, int status, cchar *fmt, ...);
  3318. PUBLIC void httpBindSocket(HttpNet *net, MprSocket *sock);
  3319. PUBLIC void httpNetClosed(HttpNet *net);
  3320. PUBLIC void httpUsePrimary(HttpNet *net);
  3321. PUBLIC void httpUseWorker(HttpNet *net, MprDispatcher *dispatcher, MprEvent *event);
  3322. PUBLIC void httpSetupWaitHandler(HttpNet *net, int eventMask);
  3323. /********************************** HttpStream *********************************/
  3324. /**
  3325. Notifier events
  3326. */
  3327. #define HTTP_EVENT_STATE 1 /**< The request is changing state */
  3328. #define HTTP_EVENT_READABLE 2 /**< The request has data available for reading */
  3329. #define HTTP_EVENT_WRITABLE 3 /**< The request is now writable (post / put data) */
  3330. #define HTTP_EVENT_ERROR 4 /**< The request has an error */
  3331. #define HTTP_EVENT_DONE 5 /**< Request is done (all states complete) */
  3332. #define HTTP_EVENT_TIMEOUT 6 /**< Request has timed out */
  3333. #define HTTP_EVENT_DESTROY 7 /**< The HttpStream object is being closed and destroyed */
  3334. /*
  3335. Application level events
  3336. */
  3337. #define HTTP_EVENT_APP_CLOSE 8 /**< The request is now closed */
  3338. /*
  3339. Internal hidden events. Not exposed by the Http notifier.
  3340. */
  3341. #define HTTP_EVENT_APP_OPEN 9 /**< The request is now open */
  3342. #define HTTP_EVENT_MAX 10 /**< Maximum event plus one */
  3343. /*
  3344. Stream states
  3345. It is critical that the states be ordered and the values be contiguous. The httpSetState relies on this.
  3346. The http notifier is called when transitioning to these states.
  3347. */
  3348. #define HTTP_STATE_BEGIN 1 /**< Ready for a new request */
  3349. #define HTTP_STATE_CONNECTED 2 /**< Connection received or made */
  3350. #define HTTP_STATE_FIRST 3 /**< First request line has been parsed */
  3351. #define HTTP_STATE_PARSED 4 /**< Headers have been parsed, handler can start */
  3352. #define HTTP_STATE_CONTENT 5 /**< Reading posted content */
  3353. #define HTTP_STATE_READY 6 /**< Handler ready - all body data received */
  3354. #define HTTP_STATE_RUNNING 7 /**< Handler running */
  3355. #define HTTP_STATE_FINALIZED 8 /**< Input received, request processed and response transmitted */
  3356. #define HTTP_STATE_COMPLETE 9 /**< Request complete */
  3357. /**
  3358. Event callback function for httpCreateEvent
  3359. @ingroup HttpStream
  3360. @stability Evolving
  3361. */
  3362. typedef void (*HttpEventProc)(struct HttpStream *stream, void *data);
  3363. /**
  3364. Callback to fill headers
  3365. @description If defined, the headers callback will run before the standard response headers are generated. This gives an
  3366. opportunity to pre-populate the response headers.
  3367. @param arg Argument provided to httpSetHeadersCallback when the callback was established.
  3368. @ingroup HttpStream
  3369. @stability Evolving
  3370. */
  3371. typedef int (*HttpHeadersCallback)(void *arg);
  3372. /**
  3373. Define a headers callback
  3374. @description The headers callback will run before the standard response headers are generated. This gives an
  3375. opportunity to pre-populate the response headers.
  3376. @param stream HttpStream object created via #httpCreateStream
  3377. @param fn Callback function to invoke
  3378. @param arg Argument to provide when invoking the headers callback
  3379. @ingroup HttpStream
  3380. @stability Evolving
  3381. */
  3382. PUBLIC void httpSetHeadersCallback(struct HttpStream *stream, HttpHeadersCallback fn, void *arg);
  3383. /**
  3384. Http request stream
  3385. @description The HttpStream object represents a logical request stream to a peer.
  3386. A stream object is created for each request transaction. A stream object uses the underlying HttpNet network object. If using HTTP/2 there may be multiple HttpStream objects multiplexed over a single HttpNet object.
  3387. If using HTTP/1, a single HttpStream object may service many Http requests due to HTTP/1.1 keep-alive.
  3388. \n\n
  3389. In prior versions before HTTP/2, this was called the HttpConn (connection) object. For compatibility, a macro define will redefine
  3390. HttpConn references to HttpStream.
  3391. \n\n
  3392. Each connection has a request timeout and inactivity timeout. These can be set via #httpSetTimeout.
  3393. The set of APIs that block and yield to the garbage collector are:
  3394. <ul>
  3395. <li>httpFlushQueue(, HTTP_BLOCK)</li>
  3396. <li>httpWriteBlock(, HTTP_BLOCK)</li>
  3397. <li>httpSendBlock(, HTTP_BLOCK)</li>
  3398. <li>httpRead() when in sync mode</li>
  3399. <li>httpReadBlock(, HTTP_BLOCK)</li>
  3400. <li>httpWait()</li>
  3401. <li>httpWriteUploadData</li>
  3402. </ul>
  3403. When these APIs block and yield, the garbage collector may reclaim allocated memory that does not have a
  3404. managed reference. Read Appweb memory allocation at https://embedthis.com/appweb/doc/ref/memory.html.
  3405. \n\n
  3406. Some of the HttpStream fields are replicated from the HttpNet object for API compatibility.
  3407. @defgroup HttpStream HttpStream
  3408. @see HttpStream HttpEnvCallback HttpGetPassword HttpListenCallback HttpNotifier HttpQueue HttpRedirectCallback
  3409. HttpRx HttpStage HttpTx HtttpListenCallback httpCallEvent httpFinalizeConnector httpStreamTimeout
  3410. httpCreateStream httpCreateRxPipeline httpCreateTxPipeline httpDestroyStream httpClosePipeline httpDiscardData
  3411. httpDisconnect httpEnableUpload httpError httpGetChunkSize httpGetStreamContext
  3412. httpGetStreamHost httpGetError httpGetExt httpGetKeepAliveCount httpGetWriteQueueCount httpMatchHost httpMemoryError httpResetClientConn httpResetCredentials httpRouteRequest httpRunHandlerReady httpService
  3413. httpSetChunkSize httpSetStreamContext httpSetStreamHost httpSetStreamNotifier httpSetCredentials
  3414. httpSetFileHandler httpSetKeepAliveCount httpSetNetProtocol httpSetRetries httpSetState
  3415. httpSetTimeout httpSetTimestamp httpStartPipeline
  3416. @stability Internal
  3417. */
  3418. typedef struct HttpStream {
  3419. HttpNet *net;
  3420. int state; /**< Stream state */
  3421. int targetState; /**< Ultimate target state */
  3422. int h2State; /**< HTTP/2 stream state */
  3423. struct HttpRx *rx; /**< Rx object for HTTP/1 */
  3424. struct HttpTx *tx; /**< Tx object for HTTP/1 */
  3425. HttpQueue *rxHead; /**< Receive queue head */
  3426. HttpQueue *txHead; /**< Transmit queue head */
  3427. HttpQueue *inputq; /**< Start of the read pipeline (tailFilter-rx) */
  3428. HttpQueue *outputq; /**< End of the write pipeline (tailFilter-tx) */
  3429. HttpQueue *readq; /**< Application queue reading (qhead) */
  3430. HttpQueue *writeq; /**< Application queue to write outgoing data (handler) */
  3431. HttpQueue *transferq; /**< After routing, transfer already read packets to this queue for processing */
  3432. MprSocket *sock; /**< Underlying socket handle */
  3433. HttpLimits *limits; /**< Service limits. Alias to HttpRoute.limits for this request */
  3434. Http *http; /**< Http service object */
  3435. MprDispatcher *dispatcher; /**< Event dispatcher */
  3436. HttpNotifier notifier; /**< Http state change notification callback */
  3437. struct HttpEndpoint *endpoint; /**< Endpoint object (if set - indicates server-side) */
  3438. struct HttpHost *host; /**< Host object (if relevant) */
  3439. MprTicks started; /**< When the request started (ticks) */
  3440. MprTicks lastActivity; /**< Last activity on the connection */
  3441. MprEvent *timeoutEvent; /**< Connection or request timeout event */
  3442. HttpTrace *trace; /**< Tracing configuration */
  3443. uint64 startMark; /**< High resolution tick time of request */
  3444. uint64 seqno; /**< Unique monotonically increasing sequence number */
  3445. char *boundary; /**< File upload boundary */
  3446. void *context; /**< Embedding context (EjsRequest) */
  3447. void *data; /**< Custom data for request - must be a managed reference */
  3448. cchar *errorMsg; /**< Error message for the last request (if any) */
  3449. void *grid; /**< Current request database grid for MVC apps */
  3450. char *ip; /**< Remote client IP address */
  3451. char *protocol; /**< Default client protocol: HTTP/1.0 or HTTP/1.1 */
  3452. void *mark; /**< Reference for GC marking */
  3453. void *pool; /**< Pool of VMs */
  3454. char *protocols; /**< Supported WebSocket protocols (clients) */
  3455. void *reqData; /**< Extended request data for use by web frameworks */
  3456. void *record; /**< Current request database record for MVC apps */
  3457. void *staticData; /**< Custom data for request - must be an unmanaged reference */
  3458. int keepAliveCount; /**< Count of remaining Keep-Alive requests for this connection */
  3459. int port; /**< Remote port */
  3460. int streamID; /**< Http/2 stream */
  3461. int timeout; /**< Timeout indication */
  3462. bool active; /**< httpProcess active on this stack */
  3463. bool authRequested: 1; /**< Authorization requested based on user credentials */
  3464. bool completed: 1; /**< Request complete and completeRequest schedule */
  3465. bool counted: 1; /**< Request counted by/ monitor event */
  3466. bool destroyed: 1; /**< Stream has been destroyed */
  3467. bool disconnect; /**< Must disconnect/reset the connection - can not continue */
  3468. bool encoded: 1; /**< True if the password is MD5(username:realm:password) */
  3469. bool error; /**< An error has occurred and the request cannot be completed */
  3470. bool followRedirects: 1; /**< Follow redirects for client requests */
  3471. bool peerCreated: 1; /**< Stream created by peer */
  3472. bool proxied: 1; /**< Stream carried by a proxy connection */
  3473. bool ownDispatcher: 1; /**< Own the dispatcher and should destroy when closing connection */
  3474. bool secure: 1; /**< Using https */
  3475. int settingState; /**< Running httpSetState */
  3476. bool suppressTrace: 1; /**< Do not trace this connection */
  3477. bool upgraded: 1; /**< Request protocol upgraded */
  3478. /*
  3479. Authentication
  3480. */
  3481. char *authType; /**< Type of authentication: set to basic, digest, post or a custom name */
  3482. void *authData; /**< Authorization state data */
  3483. cchar *username; /**< Supplied user name */
  3484. cchar *password; /**< Password for client requests (only) */
  3485. struct HttpUser *user; /**< Authorized User record for access checking */
  3486. HttpTimeoutCallback timeoutCallback; /**< Request and inactivity timeout callback */
  3487. HttpIOCallback ioCallback; /**< I/O event callback */
  3488. HttpHeadersCallback headersCallback; /**< Callback to fill headers */
  3489. void *headersCallbackArg; /**< Arg to fillHeaders */
  3490. #if DEPRECATED
  3491. void *ejs; /**< Embedding VM */
  3492. #endif
  3493. } HttpStream;
  3494. /**
  3495. Add an END packet to the input queue
  3496. @param stream HttpStream stream object created via #httpCreateStream
  3497. @param q Queue to receive the packet
  3498. @ingroup HttpStream
  3499. @stability Evolving
  3500. */
  3501. PUBLIC void httpAddInputEndPacket(HttpStream *stream, HttpQueue *q);
  3502. /**
  3503. Emit an error message for a badly formatted request
  3504. @param stream HttpStream stream object created via #httpCreateStream
  3505. @param status Http status code. The status code can be ored with the flags HTTP_ABORT to immediately abort
  3506. the connection or HTTP_CLOSE to close the connection at the completion of the request.
  3507. @param fmt Printf style formatted string
  3508. @ingroup HttpStream
  3509. @stability Evolving
  3510. */
  3511. PUBLIC void httpBadRequestError(HttpStream *stream, int status, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  3512. /**
  3513. Destroy the request pipeline.
  3514. @description This is called at the conclusion of a request.
  3515. @param stream HttpStream object created via #httpCreateStream
  3516. @ingroup HttpStream
  3517. @stability Internal
  3518. */
  3519. PUBLIC void httpClosePipeline(HttpStream *stream);
  3520. #define HTTP_REQUEST_TIMEOUT 1
  3521. #define HTTP_INACTIVITY_TIMEOUT 2
  3522. #define HTTP_PARSE_TIMEOUT 3
  3523. /**
  3524. Create the pipeline.
  3525. @description Create the processing pipeline.
  3526. @param stream HttpStream object created via #httpCreateStream
  3527. @ingroup HttpStream
  3528. @stability Internal
  3529. */
  3530. PUBLIC void httpCreatePipeline(HttpStream *stream);
  3531. /**
  3532. Create a stream object.
  3533. @description Most interactions with the Http library are via a stream object. It is used for server-side
  3534. communications when responding to client requests and it is used to initiate outbound client requests.
  3535. In HTTP/2 networks, connections are multiplexed onto HttpNet objects.
  3536. @param net Network object owning the connection. Can be NULL and a HttpNetwork object will be transparently
  3537. created and defined as HttpStream.net.
  3538. @param peerCreated Set to true if the connection is being created in response to an incoming peer request.
  3539. @returns A new stream object
  3540. @ingroup HttpStream
  3541. @stability Internal
  3542. */
  3543. PUBLIC HttpStream *httpCreateStream(HttpNet *net, bool peerCreated);
  3544. /**
  3545. Create the receive request pipeline
  3546. @param stream HttpStream object created via #httpCreateStream
  3547. @param route Route object controlling how the pipeline is configured for the request
  3548. @ingroup HttpStream
  3549. @stability Internal
  3550. */
  3551. PUBLIC void httpCreateRxPipeline(HttpStream *stream, struct HttpRoute *route);
  3552. /**
  3553. Create the transmit request pipeline
  3554. @param stream HttpStream object created via #httpCreateStream
  3555. @param route Route object controlling how the pipeline is configured for the request
  3556. @ingroup HttpStream
  3557. @stability Internal
  3558. */
  3559. PUBLIC void httpCreateTxPipeline(HttpStream *stream, struct HttpRoute *route);
  3560. /**
  3561. Destroy the stream object
  3562. @description This call closes the connection socket, destroys the connection dispatcher, disconnects the HttpTx and
  3563. HttpRx property objects and removes the connection from the HttpHost list of connections. Thereafter, the
  3564. garbage collector can reclaim all memory. It may be called by client connections at any time from a
  3565. top-level event running on the connection's dispatcher. Server-side code should not need to explicitly
  3566. destroy the connection as it will be done automatically via httpIOEvent. This routine should not be called
  3567. deep within the stack as it will zero the HttpStream.http property to signify the connection is destroyed.
  3568. @param stream HttpStream object created via #httpCreateStream
  3569. @ingroup HttpStream
  3570. @stability Internal
  3571. */
  3572. PUBLIC void httpDestroyStream(HttpStream *stream);
  3573. /**
  3574. Discard buffered transmit pipeline data
  3575. @param stream HttpStream object created via #httpCreateStream
  3576. @param dir Queue direction. Either HTTP_QUEUE_TX or HTTP_QUEUE_RX.
  3577. @ingroup HttpStream
  3578. @stability Stable
  3579. */
  3580. PUBLIC void httpDiscardData(HttpStream *stream, int dir);
  3581. /**
  3582. Disconnect the connection's socket
  3583. @description This call will close the socket and signal a connection error by setting connError.
  3584. Subsequent use of the connection socket will not be possible. It will also set HttpRx.eof and will finalize
  3585. the request. Used internally when a connection times out and for abortive errors.
  3586. This should not be generally used. Rather, #httpDestroyStream and #httpError should be used in preference.
  3587. @param stream HttpStream stream object created via #httpCreateStream
  3588. @ingroup HttpStream
  3589. @stability Internal
  3590. */
  3591. PUBLIC void httpDisconnectStream(HttpStream *stream);
  3592. /**
  3593. Enable Multipart-Mime File Upload for this request. This will define a "Content-Type: multipart/form-data..."
  3594. header and will create a mime content boundary for use to delimit the various upload content files and fields.
  3595. @param stream HttpStream stream object
  3596. @ingroup HttpStream
  3597. @stability Stable
  3598. */
  3599. PUBLIC void httpEnableUpload(HttpStream *stream);
  3600. /**
  3601. Error handling for the connection.
  3602. @description The httpError call is used to flag the current request as failed. If httpError is called multiple
  3603. times, those calls are ignored and only the first call to httpError has effect.
  3604. This call will discard all data in the output pipeline queues. If some data has already been written to the
  3605. client the connection will be aborted so the client can get some indication that an error has occurred after the
  3606. headers have been transmitted.
  3607. @param stream HttpStream stream object created via #httpCreateStream
  3608. @param status Http status code. The status code can be ored with the flags HTTP_ABORT to immediately abort
  3609. the connection or HTTP_CLOSE to close the connection at the completion of the request.
  3610. @param fmt Printf style formatted string
  3611. @param ... Arguments for fmt
  3612. @ingroup HttpStream
  3613. @stability Stable
  3614. */
  3615. PUBLIC void httpError(HttpStream *stream, int status, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  3616. /**
  3617. Find a stream given a stream sequence number
  3618. @description Find a stream in a thread-safe manner given a stream sequence number. Each stream has a unique 64-bit
  3619. sequence number that can be used to retrieve a stream object. When using foreign threads, this is preferable
  3620. as another thread may disconnect and destroy the stream at any time.
  3621. \n\n
  3622. A callback may be provided which will be invoked if the stream is found before returning from the API. This
  3623. should be used if utilizing this API in a foreign thread. httpFindStream will lock the stream while the callback
  3624. is invoked.
  3625. @param seqno HttpStream stream sequence number retrieved from HttpStream.seqno
  3626. @param proc Callback function to invoke with the signature void (*HttpEventProc)(struct HttpStream *stream, void *data);
  3627. @param data Data to pass to the callback
  3628. @return The steam object reference. Returns NULL if the stream is not found. Only use this value if invoked in an
  3629. MPR thread. While foreign threads using this API may return a stream reference, the stream may be destroyed
  3630. before the reference can be used.
  3631. @ingroup HttpStream
  3632. @stability Evolving
  3633. */
  3634. PUBLIC HttpStream *httpFindStream(uint64 seqno, HttpEventProc proc, void *data);
  3635. /**
  3636. Emit an error message for limit violations
  3637. @param stream HttpStream stream object created via #httpCreateStream
  3638. @param status Http status code. The status code can be ored with the flags HTTP_ABORT to immediately abort the
  3639. connection or HTTP_CLOSE to close the connection at the completion of the request.
  3640. @param fmt Printf style formatted string
  3641. @ingroup HttpStream
  3642. @stability Evolving
  3643. */
  3644. PUBLIC void httpLimitError(HttpStream *stream, int status, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  3645. /**
  3646. Get the preferred chunked size for transfer chunk encoding.
  3647. @param stream HttpStream stream object created via #httpCreateStream
  3648. @return Chunk size. Returns "zero" if not yet defined.
  3649. @ingroup HttpStream
  3650. @stability Stable
  3651. */
  3652. PUBLIC ssize httpGetChunkSize(HttpStream *stream);
  3653. /**
  3654. Get the connection context object
  3655. @param stream HttpStream object created via #httpCreateStream
  3656. @return The connection context object defined via httpSetStreamContext
  3657. @ingroup HttpStream
  3658. @stability Stable
  3659. */
  3660. PUBLIC void *httpGetStreamContext(HttpStream *stream);
  3661. /**
  3662. Get an IO event mask for events of interest to the connection
  3663. @param stream HttpStream object created via #httpCreateStream
  3664. @return Mask of MPR_READABLE and MPR_WRITABLE events.
  3665. @ingroup HttpStream
  3666. @stability Evolving
  3667. */
  3668. PUBLIC int httpGetStreamEventMask(HttpStream *stream);
  3669. /**
  3670. Get the connection host object
  3671. @param stream HttpStream object created via #httpCreateStream
  3672. @return The connection host object defined via httpSetstreamHost
  3673. @ingroup HttpStream
  3674. @stability Stable
  3675. */
  3676. PUBLIC void *httpGetStreamHost(HttpStream *stream);
  3677. /**
  3678. Get the error message associated with the last request.
  3679. @description Error messages may be generated for internal or client side errors.
  3680. @param stream HttpStream stream object created via #httpCreateStream
  3681. @return A error string. The caller must not free this reference.
  3682. @ingroup HttpStream
  3683. @stability Stable
  3684. */
  3685. PUBLIC cchar *httpGetError(HttpStream *stream);
  3686. /**
  3687. Get a URI extension
  3688. @description If the URI has no extension and the response content filename (HttpTx.filename) has been calculated,
  3689. it will be tested for an extension.
  3690. @param stream HttpStream stream object created via #httpCreateStream
  3691. @return The URI extension without the leading period.
  3692. @ingroup HttpStream
  3693. @stability Stable
  3694. */
  3695. PUBLIC char *httpGetExt(HttpStream *stream);
  3696. /**
  3697. Get the count of Keep-Alive requests that will be used for this stream object.
  3698. @description Http Keep-Alive means that the TCP/IP connection is preserved accross multiple requests. This
  3699. typically means much higher performance and better response. Http Keep-Alive is enabled by default
  3700. for Http/1.1 (the default). Disable Keep-Alive when talking to old, broken HTTP servers.
  3701. @param stream HttpStream stream object created via #httpCreateStream
  3702. @return The maximum count of Keep-Alive requests.
  3703. @ingroup HttpStream
  3704. @stability Stable
  3705. */
  3706. PUBLIC int httpGetKeepAliveCount(HttpStream *stream);
  3707. /**
  3708. Get the count of bytes buffered on the write queue.
  3709. @param stream HttpStream stream object created via #httpCreateStream
  3710. @return The number of bytes buffered.
  3711. @ingroup HttpStream
  3712. @stability Stable
  3713. */
  3714. PUBLIC ssize httpGetWriteQueueCount(HttpStream *stream);
  3715. /**
  3716. Match the HttpHost object that should serve this request
  3717. @description This selects the appropriate host object for this request. If no suitable host can be found, #httpError
  3718. will be called and stream->error will be set.
  3719. @param net Network object created via #httpCreateNet
  3720. @param hostname Host name to select.
  3721. @return Host object to serve the request. Also sets stream->host.
  3722. @ingroup HttpStream
  3723. @stability Internal
  3724. */
  3725. PUBLIC struct HttpHost *httpMatchHost(HttpNet *net, cchar *hostname);
  3726. /**
  3727. Match the HttpHost object that should serve this request
  3728. @description This selects the appropriate SSL configuration for the request.
  3729. @param sp Socket object
  3730. @param hostname Host name to select.
  3731. @return SSL configuration object.
  3732. @ingroup HttpStream
  3733. @stability Internal
  3734. */
  3735. PUBLIC MprSsl *httpMatchSsl(MprSocket *sp, cchar *hostname);
  3736. /**
  3737. Signal a memory allocation error in a response to the peer
  3738. @param stream HttpStream stream object created via #httpCreateStream
  3739. @ingroup HttpStream
  3740. @stability Stable
  3741. */
  3742. PUBLIC void httpMemoryError(HttpStream *stream);
  3743. /**
  3744. Inform notifiers of a connection event or state change.
  3745. @description This is an internal API and should not be called by handler or user code.
  3746. @param stream HttpStream object created via #httpCreateStream
  3747. @param event Event to issue
  3748. @param arg Argument to event
  3749. @ingroup HttpStream
  3750. @stability Stable
  3751. */
  3752. PUBLIC void httpNotify(HttpStream *stream, int event, int arg);
  3753. #define HTTP_NOTIFY(stream, event, arg) \
  3754. if (1) { \
  3755. if (stream && stream->notifier) { \
  3756. httpNotify(stream, event, arg); \
  3757. } \
  3758. } else
  3759. /**
  3760. Prepare a client connection for a new request.
  3761. @param stream HttpStream object created via #httpCreateStream
  3762. @param keepHeaders If true, keep the headers already defined on the stream object
  3763. @ingroup HttpStream
  3764. @stability Internal
  3765. */
  3766. PUBLIC void httpResetClientStream(HttpStream *stream, bool keepHeaders);
  3767. #define httpPrepClientStream(stream, keepHeaders) httpResetClientStream(stream, keepHeaders)
  3768. /**
  3769. Run the handler ready callback.
  3770. @description This will be called when all incoming data for the request has been fully received.
  3771. @param stream HttpStream object created via #httpCreateStream
  3772. @ingroup HttpStream
  3773. @stability Internal
  3774. */
  3775. PUBLIC void httpReadyHandler(HttpStream *stream);
  3776. /**
  3777. Test if a request has exceeded its timeout limits
  3778. @description This tests the request against the HttpLimits.requestTimeout and HttpLimits.inactivityTimeout limits.
  3779. It uses the HttpStream.started and HttpStream.lastActivity time markers.
  3780. @param stream HttpStream object created via #httpCreateStream
  3781. @param timeout Overriding timeout in milliseconds. If timeout is zero, override default limits and wait forever.
  3782. If timeout is < 0, use default connection inactivity and duration timeouts. If timeout is > 0, then use this
  3783. timeout as an additional timeout.
  3784. @ingroup HttpStream
  3785. @stability Stable
  3786. */
  3787. PUBLIC bool httpRequestExpired(HttpStream *stream, MprTicks timeout);
  3788. /**
  3789. Reset the current security credentials
  3790. @description Remove any existing security credentials.
  3791. @param stream HttpStream stream object created via #httpCreateStream
  3792. @ingroup HttpStream
  3793. @stability Stable
  3794. */
  3795. PUBLIC void httpResetCredentials(HttpStream *stream);
  3796. /**
  3797. Route the request and select that matching route and handle to process the request.
  3798. @param stream HttpStream stream object created via #httpCreateStream
  3799. @ingroup HttpStream
  3800. @stability Internal
  3801. */
  3802. PUBLIC void httpRouteRequest(HttpStream *stream);
  3803. #if DOXYGEN
  3804. /**
  3805. Test if the connection is a server-side connection
  3806. @param stream HttpStream stream object created via #httpCreateStream
  3807. @return true if the connection is server-side
  3808. @ingroup HttpStream
  3809. @stability Stable
  3810. */
  3811. PUBLIC bool httpServerStream(HttpStream *stream);
  3812. /**
  3813. Test if the connection is a client-side connection
  3814. @param stream HttpStream stream object created via #httpCreateStream
  3815. @return true if the connection is client-side
  3816. @ingroup HttpStream
  3817. @stability Stable
  3818. */
  3819. PUBLIC bool httpClientStream(HttpStream *stream);
  3820. #else
  3821. #define httpServerStream(stream) (stream && stream->net && stream->net->endpoint)
  3822. #define httpClientStream(stream) (stream && stream->net && !stream->net->endpoint)
  3823. #endif
  3824. /**
  3825. Test if a directory listing should be rendered for the request.
  3826. @param stream Stream object
  3827. @return True if a directory listing is configured to be rendered for this request.
  3828. @ingroup HttpStream
  3829. @stability Internal
  3830. @internal
  3831. */
  3832. PUBLIC bool httpShouldRenderDirListing(HttpStream *stream);
  3833. /**
  3834. Schedule a connection timeout event on a connection
  3835. @description This call schedules an event to run serialized on the connection dispatcher. When run, it will
  3836. cancels the current request, disconnects the socket and issues an error to the error log.
  3837. This call is normally invoked by the httpTimer which runs regularly to check for timed out requests.
  3838. @param stream HttpStream stream object created via #httpCreateStream
  3839. @ingroup HttpStream
  3840. @stability Internal
  3841. */
  3842. PUBLIC void httpStreamTimeout(HttpStream *stream);
  3843. /**
  3844. Set the chunk size for transfer chunked encoding. When set, a "Transfer-Encoding: Chunked" header will
  3845. be added to the request, and all write data will be broken into chunks of the requested size.
  3846. @param stream HttpStream stream object created via #httpCreateStream
  3847. @param size Requested chunk size.
  3848. @ingroup HttpStream
  3849. @stability Stable
  3850. */
  3851. PUBLIC void httpSetChunkSize(HttpStream *stream, ssize size);
  3852. /**
  3853. Set the connection context object
  3854. @param stream HttpStream object created via #httpCreateStream
  3855. @param context New context object. Must be a managed memory reference.
  3856. @ingroup HttpStream
  3857. @stability Stable
  3858. */
  3859. PUBLIC void httpSetStreamContext(HttpStream *stream, void *context);
  3860. /**
  3861. Set the connection data field
  3862. @description The HttpStream.data field is a managed reference that applications can use to retain their
  3863. own per connection state. It will be marked for GC retention by Http.
  3864. See also HttpStream.reqData and HttpQueue.stageData;
  3865. @param stream HttpStream object created via #httpCreateStream
  3866. @param data Data object to associate with the connection. Must be a managed memory reference.
  3867. @stability Stable
  3868. */
  3869. PUBLIC void httpSetStreamData(HttpStream *stream, void *data);
  3870. /**
  3871. Set the connection host object
  3872. @param stream HttpStream object created via #httpCreateStream
  3873. @param host New context host
  3874. @ingroup HttpStream
  3875. @stability Stable
  3876. */
  3877. PUBLIC void httpSetStreamHost(HttpStream *stream, void *host);
  3878. /**
  3879. Define a notifier callback for this connection.
  3880. @description The notifier callback will be invoked for state changes and I/O events as Http requests are processed.
  3881. The notifier is invoked when transitioning to these states. i.e. the activities for these states may not yet be complete.
  3882. The supported events are:
  3883. <ul>
  3884. <li>HTTP_EVENT_STATE &mdash; The request is changing state. Valid states are:
  3885. HTTP_STATE_BEGIN, HTTP_STATE_CONNECTED, HTTP_STATE_FIRST, HTTP_STATE_CONTENT, HTTP_STATE_READY,
  3886. HTTP_STATE_RUNNING, HTTP_STATE_FINALIZED and HTTP_STATE_COMPLETE. A request will always visit all states and the
  3887. notifier will be invoked for each and every state. This is true even if the request has no content, the
  3888. HTTP_STATE_CONTENT will still be visited.</li>
  3889. <li>HTTP_EVENT_READABLE &mdash; There is data available to read</li>
  3890. <li>HTTP_EVENT_WRITABLE &mdash; The outgoing pipeline can absorb more data. The WRITABLE event is issued when the
  3891. outgoing pipeline is empties and can absorb more data.</li>
  3892. <li>HTTP_EVENT_ERROR &mdash; The request has encountered an error</li>
  3893. <li>HTTP_EVENT_DESTROY &mdash; The HttpStream object is about to be destoyed</li>
  3894. <li>HTTP_EVENT_APP_OPEN &mdash; The application layer is now open</li>
  3895. <li>HTTP_EVENT_APP_CLOSE &mdash; The application layer is now closed</li>
  3896. </ul>
  3897. @param stream HttpStream stream object created via #httpCreateStream
  3898. @param notifier Notifier function.
  3899. @ingroup HttpStream
  3900. @stability Stable
  3901. */
  3902. PUBLIC void httpSetStreamNotifier(HttpStream *stream, HttpNotifier notifier);
  3903. /**
  3904. Set the logged in user associated with the connection
  3905. @param stream HttpStream stream object created via #httpCreateStream
  3906. @param user User object
  3907. @ingroup HttpStream
  3908. @stability Stable
  3909. */
  3910. PUBLIC void httpSetStreamUser(HttpStream *stream, struct HttpUser *user);
  3911. /**
  3912. Set the Http credentials
  3913. @description Define a user and password to use with Http authentication for sites that require it. This will
  3914. be used for the next client connection.
  3915. @param stream HttpStream stream object created via #httpCreateStream
  3916. @param user String user
  3917. @param password Decrypted password string
  3918. @param authType Authentication type. Set to basic or digest. Defaults to nothing.
  3919. @ingroup HttpStream
  3920. @stability Stable
  3921. */
  3922. PUBLIC void httpSetCredentials(HttpStream *stream, cchar *user, cchar *password, cchar *authType);
  3923. /**
  3924. Set the "fileHandler" to process the request
  3925. @description This is used by handlers to relay file requests to the file handler. Should be called from the other
  3926. handlers start entry point.
  3927. @param stream HttpStream stream object created via #httpCreateStream
  3928. @param path Optional filename to serve. If null, use HttpTx.filename.
  3929. @ingroup HttpStream
  3930. @stability Evolving
  3931. */
  3932. PUBLIC void httpSetFileHandler(HttpStream *stream, cchar *path);
  3933. /**
  3934. Control Http Keep-Alive for the connection.
  3935. @description Http Keep-Alive means that the TCP/IP connection is preserved accross multiple requests. This
  3936. typically means much higher performance and better response. Http Keep-Alive is enabled by default
  3937. for Http/1.1 (the default). Disable Keep-Alive when talking to old, broken HTTP servers.
  3938. @param stream HttpStream stream object created via #httpCreateStream
  3939. @param count Count of Keep-Alive transactions to use before closing the connection. Set to zero to disable keep-alive.
  3940. @ingroup HttpStream
  3941. @stability Stable
  3942. */
  3943. PUBLIC void httpSetKeepAliveCount(HttpStream *stream, int count);
  3944. /**
  3945. Set the connection state and invoke notifiers.
  3946. @description The connection states are, in order : HTTP_STATE_BEGIN HTTP_STATE_CONNECTED HTTP_STATE_FIRST
  3947. HTTP_STATE_PARSED HTTP_STATE_CONTENT HTTP_STATE_READY HTTP_STATE_RUNNING HTTP_STATE_FINALIZED HTTP_STATE_COMPLETE.
  3948. When httpSetState advances the state it will invoke any registered #HttpNotifier. If the state is set to a state beyond
  3949. the next intermediate state, the HttpNotifier will be invoked for all intervening states.
  3950. This is true even if the request has no content, the HTTP_STATE_CONTENT will still be visited..
  3951. @param stream HttpStream object created via #httpCreateStream
  3952. @param state New state to enter
  3953. @ingroup HttpStream
  3954. @stability Internal
  3955. */
  3956. PUBLIC void httpSetState(HttpStream *stream, int state);
  3957. /**
  3958. Set the Http inactivity timeout
  3959. @description Define an inactivity timeout after which the Http connection will be closed.
  3960. @param stream HttpStream object created via #httpCreateStream
  3961. @param requestTimeout Request timeout in msec. This is the total time for the request. Set to -1 to preserve the
  3962. existing value.
  3963. @param inactivityTimeout Inactivity timeout in msec. This is maximum connection idle time. Set to -1 to preserve the
  3964. existing value.
  3965. @ingroup HttpStream
  3966. @stability Stable
  3967. */
  3968. PUBLIC void httpSetTimeout(HttpStream *stream, MprTicks requestTimeout, MprTicks inactivityTimeout);
  3969. /**
  3970. Define a timestamp in the MPR log file.
  3971. @description This routine initiates the writing of a timestamp in the MPR log file
  3972. @param period Time in milliseconds between timestamps
  3973. @ingroup HttpStream
  3974. @stability Stable
  3975. */
  3976. PUBLIC void httpSetTimestamp(MprTicks period);
  3977. /**
  3978. Start the pipeline. This starts the request handler.
  3979. @param stream HttpStream object created via #httpCreateStream
  3980. @ingroup HttpStream
  3981. @stability Internal
  3982. */
  3983. PUBLIC void httpStartPipeline(HttpStream *stream);
  3984. PUBLIC void httpStartHandler(HttpStream *stream);
  3985. /**
  3986. Verify the server handshake
  3987. @param stream HttpStream stream object created via #httpCreateStream
  3988. @return True if the handshake is valid
  3989. @ingroup HttpStream
  3990. @stability Evolving
  3991. */
  3992. PUBLIC bool httpVerifyWebSocketsHandshake(HttpStream *stream);
  3993. /* Internal APIs */
  3994. PUBLIC void httpParseMethod(HttpStream *stream);
  3995. PUBLIC void httpResetServerStream(HttpStream *stream);
  3996. PUBLIC HttpLimits *httpSetUniqueStreamLimits(HttpStream *stream);
  3997. PUBLIC void httpInitChunking(HttpStream *stream);
  3998. PUBLIC void httpServiceQueues(HttpStream *stream, int flags);
  3999. /********************************** HttpAuthStore *********************************/
  4000. /**
  4001. AuthStore callback Verify the user credentials
  4002. @param stream HttpStream stream object
  4003. @param username Users login name
  4004. @param password Actual user password
  4005. @return True if the user credentials can validate
  4006. @ingroup HttpAuth
  4007. @stability Stable
  4008. */
  4009. typedef bool (*HttpVerifyUser)(HttpStream *stream, cchar *username, cchar *password);
  4010. /**
  4011. Password backend store. Support stores are: system, file
  4012. @ingroup HttpAuth
  4013. @stability Evolving
  4014. @see HttpAskLogin HttpParseAuth httpSetAuthStoreVerify HttpVerifyUser
  4015. httpCreateAuthStore httpGetAuthStore httpSetAuthStore httpSetAuthStoreSessions httpSetAuthStoreVerifyByName
  4016. */
  4017. typedef struct HttpAuthStore {
  4018. char *name; /**< Authentication password store name: 'system', 'file' */
  4019. int noSession; /**< Do not create a session after login */
  4020. HttpVerifyUser verifyUser; /**< Default user verification routine */
  4021. } HttpAuthStore;
  4022. /**
  4023. Add an authorization store for password validation. The pre-supplied types are "config" and "system".
  4024. @description This creates an AuthStore object with the defined name and callbacks.
  4025. @param name Unique authorization store name
  4026. @param verifyUser Callback to verify the username and password contained in the HttpStream object passed to the callback.
  4027. @return Auth store if successful, otherwise NULL.
  4028. @ingroup HttpAuth
  4029. @stability Stable
  4030. */
  4031. PUBLIC HttpAuthStore *httpCreateAuthStore(cchar *name, HttpVerifyUser verifyUser);
  4032. /**
  4033. Lookup an authentication store
  4034. @description This returns a auth store object
  4035. @param name Unique authorization store name
  4036. @return Auth store if successful, otherwise NULL.
  4037. @ingroup HttpAuth
  4038. @stability Evolving
  4039. */
  4040. PUBLIC HttpAuthStore *httpGetAuthStore(cchar *name);
  4041. /**
  4042. Control whether sessions and session cookies are created for user logins
  4043. @description By default, a session and response cookie are created when a user is authenticated via #httpLogin.
  4044. This boosts performance because subsequent requests can supply the cookie and bypass authentication for each
  4045. subseqent request. This API permits the default behavior to be suppressed and thus no cookie or session will be created.
  4046. @param store AuthStore object created via #httpCreateAuthStore.
  4047. @param noSession Set to true to suppress creation of sessions or cookies.
  4048. @ingroup HttpAuth
  4049. @stability Evolving
  4050. */
  4051. PUBLIC void httpSetAuthStoreSessions(HttpAuthStore *store, bool noSession);
  4052. /**
  4053. Set the global verify callback for an authentication store
  4054. @description The verification callback is invoked to verify user credentials when authentication is required.
  4055. The callback has the signature: typedef bool (*HttpVerifyUser)(HttpStream *stream, cchar *username, cchar *password);
  4056. @param store AuthStore object allocated by #httpCreateAuthStore.
  4057. @param verifyUser Verification callback
  4058. @ingroup HttpAuth
  4059. @stability Evolving
  4060. @see httpSetAuthVerify httpSetAuthStoreVerifyByName httpGetAuthStore
  4061. */
  4062. PUBLIC void httpSetAuthStoreVerify(HttpAuthStore *store, HttpVerifyUser verifyUser);
  4063. /**
  4064. Set the global verify callback for an authentication store
  4065. @description The verification callback is invoked to verify user credentials when authentication is required.
  4066. The callback has the signature: typedef bool (*HttpVerifyUser)(HttpStream *stream, cchar *username, cchar *password);
  4067. @param storeName String name of the store
  4068. @param verifyUser Verification callback
  4069. @ingroup HttpAuth
  4070. @stability Evolving
  4071. @see httpSetAuthVerify httpSetAuthStoreVerify httpGetAuthStore
  4072. */
  4073. PUBLIC void httpSetAuthStoreVerifyByName(cchar *storeName, HttpVerifyUser verifyUser);
  4074. /********************************** HttpAuth *********************************/
  4075. /*
  4076. Authorization flags for HttpAuth.flags
  4077. */
  4078. #define HTTP_ALLOW_DENY 0x1 /**< Run allow checks before deny checks */
  4079. #define HTTP_DENY_ALLOW 0x2 /**< Run deny checks before allow checks */
  4080. #define HTTP_AUTH_NO_SESSION 0x4 /**< Do not create a session when authenticated */
  4081. #define HTTP_BLOW_ROUNDS 16 /***< Cipher rounds for blowfish encryption */
  4082. #define HTTP_BLOW_SALT 16 /***< Bytes of salt for blowfish encryption */
  4083. /**
  4084. AuthType callback to generate a response requesting the user login
  4085. This should call httpError if such a response cannot be generated.
  4086. @param stream HttpStream stream object
  4087. @ingroup HttpAuth
  4088. @stability Evolving
  4089. */
  4090. typedef void (*HttpAskLogin)(HttpStream *stream);
  4091. /**
  4092. AuthType callback to parse the HTTP 'Authorize' (client) and 'www-authenticate' (server) headers
  4093. @description This callback must extract the username and password. The username is set on HttpStream.username.
  4094. The password is returned by this call.
  4095. @param stream HttpStream stream object
  4096. @return The password if successful, otherwise NULL.
  4097. @ingroup HttpAuth
  4098. @stability Evolving
  4099. */
  4100. typedef int (*HttpParseAuth)(HttpStream *stream, cchar **username, cchar **password);
  4101. /**
  4102. AuthType callback to set the necessary HTTP authorization headers for a client request
  4103. @param stream HttpStream stream object
  4104. @return True if the authorization headers can be set.
  4105. @ingroup HttpAuth
  4106. @stability Evolving
  4107. */
  4108. typedef bool (*HttpSetAuth)(HttpStream *stream, cchar *username, cchar *password);
  4109. /*
  4110. Flags for AuthType
  4111. */
  4112. #define HTTP_AUTH_TYPE_CONDITION 0x1 /**< Use auth condition */
  4113. /**
  4114. Authentication Protocol. Supported protocols are: basic, digest, form.
  4115. @ingroup HttpAuth
  4116. @stability Internal
  4117. */
  4118. typedef struct HttpAuthType {
  4119. char *name; /**< Authentication protocol name: 'basic', 'digest', 'form' */
  4120. HttpAskLogin askLogin; /**< Callback to generate a client login response */
  4121. HttpParseAuth parseAuth; /**< Callback to parse request auth details */
  4122. HttpSetAuth setAuth; /**< Callback to set the HTTP response authentication headers */
  4123. int flags;
  4124. } HttpAuthType;
  4125. /**
  4126. Authorization
  4127. @description HttpAuth is the foundation authorization object and is used by HttpRoute.
  4128. It stores the authorization configuration information required to determine if a client request should be permitted
  4129. access to a given resource.
  4130. @defgroup HttpAuth HttpAuth
  4131. @see HttpAskLogin HttpAuth HttpAuthType HttpGetCredentials HttpRole HttpSetAuth HttpVerifyUser HttpUser
  4132. HttpVerifyUser httpAddAuthType httpAddRole httpAddUser httpCanUser httpAuthenticate
  4133. httpComputeAllUserAbilities httpComputeUserAbilities httpCreateRole httpCreateAuth httpAdduser
  4134. httpIsAuthenticated httpLogin httpRemoveRole httpRemoveUser httpSetAuthAllow httpSetAuthAnyValidUser
  4135. httpSetAuthUsername httpSetAuthDeny httpSetAuthOrder httpSetAuthPermittedUsers httpSetAuthLogin httpSetAuthQop
  4136. httpSetAuthRealm httpSetAuthRequiredAbilities httpSetAuthType
  4137. @stability Internal
  4138. */
  4139. typedef struct HttpAuth {
  4140. struct HttpAuth *parent; /**< Parent auth */
  4141. char *cipher; /**< Encryption cipher */
  4142. char *realm; /**< Realm of access */
  4143. int flags; /**< Authorization flags */
  4144. MprHash *allow; /**< Clients to allow */
  4145. MprHash *deny; /**< Clients to deny */
  4146. MprHash *userCache; /**< Cache of authenticated users */
  4147. MprHash *roles; /**< Hash of roles */
  4148. MprHash *abilities; /**< Set of required abilities (all are required) */
  4149. MprHash *permittedUsers; /**< Set of valid users */
  4150. char *loginPage; /**< Web page for user login for 'form' type */
  4151. char *loggedInPage; /**< Target URI after logging in */
  4152. char *loggedOutPage; /**< Target URI after logging out */
  4153. char *username; /**< Automatic login username. Password not required if defined */
  4154. char *qop; /**< Quality of service */
  4155. HttpAuthType *type; /**< Authorization protocol type (basic|digest|form|custom)*/
  4156. HttpAuthStore *store; /**< Authorization password backend (system|file|custom)*/
  4157. HttpVerifyUser verifyUser; /**< Password verification */
  4158. } HttpAuth;
  4159. /**
  4160. Create an authentication object
  4161. @return An empty authentiction object
  4162. @ingroup HttpAuth
  4163. @stability Stable
  4164. @internal
  4165. */
  4166. PUBLIC HttpAuth *httpCreateAuth(void);
  4167. /**
  4168. Create an authorization protocol type. The pre-supplied types are 'basic', 'digest' and 'form'.
  4169. @description This creates an AuthType with the defined name and callbacks. The basic and digest types are
  4170. supported by most browsers. The form type is implemented via web form requests over HTTP.
  4171. @param name Unique authorization type name
  4172. @param askLogin Callback to generate a client login response
  4173. @param parse Callback to parse the HTTP authentication headers
  4174. @param setAuth Callback to set the HTTP response authentication headers
  4175. @return Zero if successful, otherwise a negative MPR error code
  4176. @ingroup HttpAuth
  4177. @stability Stable
  4178. */
  4179. PUBLIC int httpCreateAuthType(cchar *name, HttpAskLogin askLogin, HttpParseAuth parse, HttpSetAuth setAuth);
  4180. /**
  4181. Control whether a session and session cookie will be created for user logins for this authentication route
  4182. @description By default, a session and response cookie are created when a user is authenticated via #httpLogin.
  4183. This boosts performance because subsequent requests can supply the cookie and bypass authentication for each
  4184. subseqent request. This API permits the default behavior to be suppressed and thus no cookie or session will be created.
  4185. @param auth Auth object created via #httpCreateAuth.
  4186. @param noSession Set to true to suppress creation of sessions or cookies.
  4187. @ingroup HttpAuth
  4188. @stability Evolving
  4189. */
  4190. PUBLIC void httpSetAuthSession(HttpAuth *auth, bool noSession);
  4191. /********************************* Users and Roles ***************************/
  4192. /**
  4193. User Authorization. A user has a name, password and a set of roles. These roles define a set of abilities.
  4194. @see HttpAuth
  4195. @ingroup HttpAuth
  4196. @stability Internal
  4197. */
  4198. typedef struct HttpUser {
  4199. char *name; /**< User name */
  4200. char *password; /**< User password for "internal" auth store - (actually the password hash */
  4201. MprHash *roles; /**< List of roles */
  4202. MprHash *abilities; /**< User abilities defined by roles */
  4203. void *data; /**< Unmanaged custom data */
  4204. } HttpUser;
  4205. /**
  4206. Authorization Roles. Roles are named sets of abilities.
  4207. @see HttpAuth
  4208. @ingroup HttpAuth
  4209. @stability Internal
  4210. */
  4211. typedef struct HttpRole {
  4212. char *name; /**< Role name */
  4213. MprHash *abilities; /**< Role's abilities */
  4214. } HttpRole;
  4215. /**
  4216. Add a role. If the role already exists, the role is updated.
  4217. @description This creates the role with given abilities. Ability words can also be other roles.
  4218. @param auth Auth object allocated by #httpCreateAuth.
  4219. @param role Role name to add
  4220. @param abilities Space separated list of abilities.
  4221. @return Allocated role object.
  4222. @ingroup HttpAuth
  4223. @stability Stable
  4224. */
  4225. PUBLIC HttpRole *httpAddRole(HttpAuth *auth, cchar *role, cchar *abilities);
  4226. /**
  4227. Add a user. If the user already exists, the user is updated.
  4228. @description This creates the user and adds the user to the authentication database.
  4229. @param auth Auth object allocated by #httpCreateAuth.
  4230. @param user User name to add
  4231. @param password User password. The password should not be encrypted. The backend will encrypt as required.
  4232. @param abilities Space separated list of abilities.
  4233. @return The User object allocated or NULL for an error.
  4234. @ingroup HttpAuth
  4235. @stability Stable
  4236. */
  4237. PUBLIC HttpUser *httpAddUser(HttpAuth *auth, cchar *user, cchar *password, cchar *abilities);
  4238. /**
  4239. Lookup a role by name
  4240. @param auth HttpAuth object. Stored in HttpStream.rx.route.auth
  4241. @param name Role name
  4242. @return Role object
  4243. @ingroup HttpAuth
  4244. @stability Evolving
  4245. */
  4246. PUBLIC HttpRole *httpLookupRole(HttpAuth *auth, cchar *name);
  4247. /**
  4248. Lookup a user by username
  4249. @description This looks up a user in the internal user store.
  4250. This is only used i
  4251. @param auth HttpAuth object. Stored in HttpStream.rx.route.auth
  4252. @param name Username
  4253. @return User object
  4254. @ingroup HttpAuth
  4255. @stability Evolving
  4256. */
  4257. PUBLIC HttpUser *httpLookupUser(HttpAuth *auth, cchar *name);
  4258. /**
  4259. Remove a role
  4260. @param auth Auth object allocated by #httpCreateAuth.
  4261. @param role Role name to remove
  4262. @return Zero if successful, otherwise a negative MPR error code
  4263. @ingroup HttpAuth
  4264. @stability Stable
  4265. @internal
  4266. */
  4267. PUBLIC int httpRemoveRole(HttpAuth *auth, cchar *role);
  4268. /**
  4269. Remove a user
  4270. @param auth Auth object allocated by #httpCreateAuth.
  4271. @param user User name to remove
  4272. @return Zero if successful, otherwise a negative MPR error code
  4273. @ingroup HttpAuth
  4274. @stability Stable
  4275. @internal
  4276. */
  4277. PUBLIC int httpRemoveUser(HttpAuth *auth, cchar *user);
  4278. /**
  4279. Compute all the user abilities for a route using the given auth
  4280. @param auth Auth object allocated by #httpCreateAuth
  4281. @ingroup HttpAuth
  4282. @stability Stable
  4283. */
  4284. PUBLIC void httpComputeAllUserAbilities(HttpAuth *auth);
  4285. /**
  4286. Compute the user abilities for a given user in a route using the given auth
  4287. @param auth Auth object allocated by #httpCreateAuth
  4288. @param user User object
  4289. @ingroup HttpAuth
  4290. @stability Stable
  4291. */
  4292. PUBLIC void httpComputeUserAbilities(HttpAuth *auth, HttpUser *user);
  4293. /*
  4294. Internal
  4295. */
  4296. PUBLIC char *httpRolesToAbilities(HttpAuth *auth, cchar *roles, cchar *separator);
  4297. /********************************* Login *************************************/
  4298. /**
  4299. Authenticate a user based on session data
  4300. @description This authenticates a user by testing the user supplied session cookie against login credentials
  4301. stored in the server-side session store. The httpAuthenticate call is not automatically performed by the
  4302. request pipeline. Web Frameworks should call this if required.
  4303. @param stream HttpStream stream object created via #httpCreateStream object.
  4304. @return True if the user is authenticated.
  4305. */
  4306. PUBLIC bool httpAuthenticate(HttpStream *stream);
  4307. /**
  4308. Test if a user has the required abilities
  4309. @param stream HttpStream stream object created via #httpCreateStream object.
  4310. @param abilities Comma separated list of abilities or roles to test for. If null, then use the required abilities defined
  4311. for the current request route.
  4312. @return True if the user has all the required abilities
  4313. @ingroup HttpAuth
  4314. @stability Stable
  4315. */
  4316. PUBLIC bool httpCanUser(HttpStream *stream, cchar *abilities);
  4317. /**
  4318. Test if the user is authenticated
  4319. @param stream HttpStream stream object
  4320. @return True if the username and password have been authenticated.
  4321. @ingroup HttpAuth
  4322. @stability Stable
  4323. */
  4324. PUBLIC bool httpIsAuthenticated(HttpStream *stream);
  4325. /**
  4326. Log the user in.
  4327. @description This will verify the supplied username and password. If the user is successfully logged in,
  4328. the user identity will be stored in session state for fast authentication on subsequent requests.
  4329. Note: this does not verify any user abilities.
  4330. @param stream HttpStream stream object
  4331. @param username User name to authenticate
  4332. @param password Password for the user
  4333. @return True if the username and password have been authenticated.
  4334. @ingroup HttpAuth
  4335. @stability Stable
  4336. */
  4337. PUBLIC bool httpLogin(HttpStream *stream, cchar *username, cchar *password);
  4338. /**
  4339. Logout the user.
  4340. @param stream HttpStream stream object
  4341. @ingroup HttpAuth
  4342. @stability Evolving
  4343. */
  4344. PUBLIC void httpLogout(HttpStream *stream);
  4345. /***************************** Auth Route ************************************/
  4346. /**
  4347. Allow access by a client IP IP address
  4348. @param auth Authorization object allocated by #httpCreateAuth.
  4349. @param ip Client IP address to allow.
  4350. @ingroup HttpAuth
  4351. @stability Stable
  4352. */
  4353. PUBLIC void httpSetAuthAllow(HttpAuth *auth, cchar *ip);
  4354. /**
  4355. Allow access by any valid user
  4356. @description This configures the basic or digest authentication for the authorization object
  4357. @param auth Authorization object allocated by #httpCreateAuth.
  4358. @ingroup HttpAuth
  4359. @stability Stable
  4360. */
  4361. PUBLIC void httpSetAuthAnyValidUser(HttpAuth *auth);
  4362. /**
  4363. Deny access by a client IP address
  4364. @param auth Authorization object allocated by #httpCreateAuth.
  4365. @param ip Client IP address to deny. This must be an IP address string.
  4366. @ingroup HttpAuth
  4367. @stability Stable
  4368. */
  4369. PUBLIC void httpSetAuthDeny(HttpAuth *auth, cchar *ip);
  4370. /**
  4371. Define login service URLs for use with "form" authentication.
  4372. @description This defines the login form URL and login/out service URLs.
  4373. Set arguments to null if they are not required because the application is implementing its own redirection
  4374. management during login. This API should not be used for web frameworks like ESP or PHP that define their own
  4375. login/out services.
  4376. @param route Route from which to inherit when creating a route for the login pages and services.
  4377. @param loginPage Web page URI for the user to enter username and password.
  4378. @param loginService URI to use for the internal login service. To use your own login URI, set to this the empty string.
  4379. @param logoutService URI to use to log the user out. To use your won logout URI, set this to the empty string.
  4380. @param loggedInPage The client is redirected to this URI once logged in. Use a "referrer:" prefix to the URI to
  4381. redirect the user to the referring URI before the loginPage. If the referrer cannot be determined, the base
  4382. URI is utilized.
  4383. @param loggedOutPage The client is redirected to this URI once logged in. Use a "referrer:" prefix to the URI to
  4384. redirect the user to the referring URI before the loginPage. If the referrer cannot be determined, the base
  4385. URI is utilized.
  4386. @ingroup HttpAuth
  4387. @stability Evolving
  4388. */
  4389. PUBLIC void httpSetAuthFormDetails(struct HttpRoute *route, cchar *loginPage, cchar *loginService, cchar *logoutService,
  4390. cchar *loggedInPage, cchar *loggedOutPage);
  4391. /**
  4392. Define the login page for use with authentication
  4393. @param auth Authorization object allocated by #httpCreateAuth.
  4394. @param uri URI for the login page. Can use "https:///page" to specify the SSL protocol with the current domain.
  4395. @ingroup HttpAuth
  4396. @stability Evolving
  4397. */
  4398. PUBLIC void httpSetAuthLogin(HttpAuth *auth, cchar *uri);
  4399. /**
  4400. Set the auth allow/deny order
  4401. @param auth Auth object allocated by #httpCreateAuth.
  4402. @param order Set to HTTP_ALLOW_DENY to run allow checks before deny checks. Set to HTTP_DENY_ALLOW to run deny
  4403. checks before allow.
  4404. @ingroup HttpAuth
  4405. @stability Stable
  4406. */
  4407. PUBLIC void httpSetAuthOrder(HttpAuth *auth, int order);
  4408. /**
  4409. Define the set of permitted users
  4410. @param auth Auth object allocated by #httpCreateAuth.
  4411. @param users Space separated list of acceptable users.
  4412. @ingroup HttpAuth
  4413. @stability Stable
  4414. */
  4415. PUBLIC void httpSetAuthPermittedUsers(HttpAuth *auth, cchar *users);
  4416. /**
  4417. Set the required quality of service for digest authentication
  4418. @description This configures the basic or digest authentication for the auth object
  4419. @param auth Auth object allocated by #httpCreateAuth.
  4420. @param qop Quality of service description.
  4421. @ingroup HttpAuth
  4422. @stability Stable
  4423. */
  4424. PUBLIC void httpSetAuthQop(HttpAuth *auth, cchar *qop);
  4425. /**
  4426. Set the required realm for basic or digest authentication
  4427. @description This configures the authentication realm. The realm is displayed to the user in the browser login
  4428. dialog box.
  4429. @param auth Auth object allocated by #httpCreateAuth.
  4430. @param realm Authentication realm
  4431. @ingroup HttpAuth
  4432. @stability Stable
  4433. */
  4434. PUBLIC void httpSetAuthRealm(HttpAuth *auth, cchar *realm);
  4435. /**
  4436. Set the required abilities for access
  4437. @param auth Auth object allocated by #httpCreateAuth.
  4438. @param abilities Space separated list of the required abilities. May supply roles in the abilities string.
  4439. @ingroup HttpAuth
  4440. @stability Stable
  4441. */
  4442. PUBLIC void httpSetAuthRequiredAbilities(HttpAuth *auth, cchar *abilities);
  4443. /**
  4444. Set the authentication password store to use
  4445. @param auth Auth object allocated by #httpCreateAuth.
  4446. @param store Password store to use. Select from: "app", "config" or "system"
  4447. @ingroup HttpAuth
  4448. @stability Stable
  4449. */
  4450. PUBLIC int httpSetAuthStore(HttpAuth *auth, cchar *store);
  4451. /**
  4452. Set the authentication protocol type to use
  4453. @param auth Auth object allocated by #httpCreateAuth.
  4454. @param proto Protocol name to use. Select from: 'basic', 'digest', 'form' or 'none'. Set to NULL or 'none' to disable
  4455. authentication.
  4456. @param details Extra protocol details.
  4457. @ingroup HttpAuth
  4458. @stability Stable
  4459. */
  4460. PUBLIC int httpSetAuthType(HttpAuth *auth, cchar *proto, cchar *details);
  4461. /**
  4462. Set an automatic login username
  4463. @description If defined, no password is required and the user will be automatically logged in as this username.
  4464. @param auth Auth object allocated by #httpCreateAuth.
  4465. @param username Username to automatically login with
  4466. @ingroup HttpAuth
  4467. @stability Stable
  4468. */
  4469. PUBLIC void httpSetAuthUsername(HttpAuth *auth, cchar *username);
  4470. /**
  4471. Set the verify callback for an authentication object that is part of a route.
  4472. @param auth Auth object allocated by #httpCreateAuth.
  4473. @param verifyUser Verification callback
  4474. @ingroup HttpAuth
  4475. @stability Evolving
  4476. @see httpSetAuthStoreVerify
  4477. */
  4478. PUBLIC void httpSetAuthVerify(HttpAuth *auth, HttpVerifyUser verifyUser);
  4479. /*
  4480. Internal
  4481. */
  4482. PUBLIC void httpBasicLogin(HttpStream *stream);
  4483. PUBLIC int httpBasicParse(HttpStream *stream, cchar **username, cchar **password);
  4484. PUBLIC bool httpBasicSetHeaders(HttpStream *stream, cchar *username, cchar *password);
  4485. PUBLIC void httpComputeRoleAbilities(HttpAuth *auth, MprHash *abilities, cchar *role);
  4486. PUBLIC HttpAuth *httpCreateInheritedAuth(HttpAuth *parent);
  4487. PUBLIC void httpDigestLogin(HttpStream *stream);
  4488. PUBLIC int httpDigestParse(HttpStream *stream, cchar **username, cchar **password);
  4489. PUBLIC bool httpDigestSetHeaders(HttpStream *stream, cchar *username, cchar *password);
  4490. PUBLIC bool httpGetCredentials(HttpStream *stream, cchar **username, cchar **password);
  4491. PUBLIC void httpInitAuth(void);
  4492. PUBLIC bool httpInternalVerifyUser(HttpStream *stream, cchar *username, cchar *password);
  4493. PUBLIC HttpAuthType *httpLookupAuthType(cchar *type);
  4494. PUBLIC bool httpPamVerifyUser(HttpStream *stream, cchar *username, cchar *password);
  4495. /********************************** HttpLang ********************************/
  4496. #define HTTP_LANG_BEFORE 0x1 /**< Insert suffix before extension */
  4497. #define HTTP_LANG_AFTER 0x2 /**< Insert suffix after extension */
  4498. /**
  4499. Language definition record for routes
  4500. @ingroup HttpRoute
  4501. @stability Internal
  4502. */
  4503. typedef struct HttpLang {
  4504. char *path; /**< Document directory for the language */
  4505. char *suffix; /**< Suffix to add to filenames */
  4506. int flags; /**< Control suffix position */
  4507. } HttpLang;
  4508. /********************************** HttpCache *********************************/
  4509. #define HTTP_CACHE_CLIENT 0x1 /**< Cache on the client side */
  4510. #define HTTP_CACHE_SERVER 0x2 /**< Cache on the server side */
  4511. #define HTTP_CACHE_MANUAL 0x4 /**< Cache manually. User must call httpWriteCache */
  4512. #define HTTP_CACHE_RESET 0x8 /**< Don't inherit cache config from outer routes */
  4513. #define HTTP_CACHE_UNIQUE 0x10 /**< Uniquely cache request with different params */
  4514. #define HTTP_CACHE_HAS_PARAMS 0x20 /**< Cache definition has params */
  4515. #define HTTP_CACHE_STATIC 0x40 /**< Cache extensions: css, gif, ico, jpg, js, html, pdf, ttf, txt, xml, woff */
  4516. /**
  4517. Cache Control
  4518. @description Configuration is not thread safe and must occur at initialization time when the application is
  4519. single threaded.
  4520. If the configuration is modified when the application is multithreaded, all requests must be first be quiesced.
  4521. @defgroup HttpCache HttpCache
  4522. @see HttpCache httpAddCache httpUpdateCache httpWriteCache
  4523. @stability Internal
  4524. */
  4525. typedef struct HttpCache {
  4526. MprHash *extensions; /**< Extensions to cache */
  4527. MprHash *methods; /**< Methods to cache */
  4528. MprHash *types; /**< MimeTypes to cache */
  4529. MprHash *uris; /**< URIs to cache */
  4530. MprTicks clientLifespan; /**< Lifespan for client cached content */
  4531. MprTicks serverLifespan; /**< Lifespan for server cached content */
  4532. int flags; /**< Cache control flags */
  4533. } HttpCache;
  4534. /**
  4535. Add caching for response content
  4536. @description This call configures caching for request responses. Caching may be used for any HTTP method,
  4537. though typically it is most useful for state-less GET requests. Output data may be uniquely cached for requests
  4538. with different request parameters (query, post, and route parameters).
  4539. \n\n
  4540. When server-side caching is requested and manual-mode is not enabled, the request response will be automatically
  4541. cached. Subsequent client requests will revalidate the cached content with the server. If the server-side cached
  4542. content has not expired, a HTTP Not-Modified (304) response will be sent and the client will use its client-side
  4543. cached content. This results in a very fast transaction with the client as no response data is sent.
  4544. Server-side caching will cache both the response headers and content.
  4545. \n\n
  4546. If manual server-side caching is requested, the response will be automatically cached, but subsequent requests will
  4547. require the handler to explicitly send cached content by calling #httpWriteCached.
  4548. \n\n
  4549. If client-side caching is requested, a 'Cache-Control' Http header will be sent to the client with the caching
  4550. 'max-age' set to the lifespan argument value (converted to seconds). This causes the client to serve client-cached
  4551. content and to not contact the server at all until the max-age expires.
  4552. Alternatively, you can use #httpSetHeader to explicitly set a 'Cache-Control' header. For your reference, here are
  4553. some keywords that can be used in the Cache-Control Http header.
  4554. \n\n
  4555. 'max-age' Maximum time in seconds the resource is considered fresh.
  4556. 's-maxage' Maximum time in seconds the resource is considered fresh from a shared cache.
  4557. 'public' marks authenticated responses as cacheable.
  4558. 'private' shared caches may not store the response.
  4559. 'no-cache' cache must re-submit request for validation before using cached copy.
  4560. 'no-store' response may not be stored in a cache.
  4561. 'must-revalidate' forces clients to revalidate the request with the server.
  4562. 'proxy-revalidate' similar to must-revalidate except only for proxy caches.
  4563. \n\n
  4564. Use client-side caching for static content that will rarely change or for content for which using 'reload' in
  4565. the browser is an adequate solution to force a refresh. Use manual server-side caching for situations where you need to
  4566. explicitly control when and how cached data is returned to the client. For most other situations, use server-side
  4567. caching.
  4568. @param route HttpRoute object
  4569. @param methods List of methods for which caching should be enabled. Set to a comma or space separated list
  4570. of method names. Method names can be any case. Set to null or '*' for all methods. Example:
  4571. 'GET, POST'.
  4572. @param uris Set of URIs to cache.
  4573. If the URI is set to '*' all URIs for that action are uniquely cached. If the request has POST data,
  4574. the URI may include such post data in a sorted query format. E.g. {uri: /buy?item=scarf&quantity=1}.
  4575. @param extensions List of document extensions for which caching should be enabled. Set to a comma or space
  4576. separated list of extensions. Extensions should not have a period prefix. Set to null, '' or '*' for all extensions.
  4577. Example: 'html, css, js'. The URI may include request parameters in sorted www-urlencoded format. For example:
  4578. /example.esp?hobby=sailing&name=john.
  4579. @param types List of document mime types for which caching should be enabled. Set to a comma or space
  4580. separated list of types. The mime types are those that correspond to the document extension and NOT the
  4581. content type defined by the handler serving the document. Set to null or '*' for all types.
  4582. Example: image/gif, application/x-php.
  4583. @param clientLifespan Lifespan of client cache items in milliseconds. If not set to positive integer,
  4584. the lifespan will default to the route lifespan.
  4585. @param serverLifespan Lifespan of server cache items in milliseconds. If not set to positive integer,
  4586. the lifespan will default to the route lifespan.
  4587. @param flags Cache control flags. Select HTTP_CACHE_MANUAL to enable manual mode. In manual mode, cached content
  4588. will not be automatically sent. Use #httpWriteCached in the request handler to write previously cached content.
  4589. \n\n
  4590. Select HTTP_CACHE_CLIENT to enable client-side caching. In this mode a 'Cache-Control' Http header will be
  4591. sent to the client with the caching 'max-age'. WARNING: the client will not send any request for this URI
  4592. until the max-age timeout has expired.
  4593. \n\n
  4594. Select HTTP_CACHE_RESET to first reset existing caching configuration for this route.
  4595. \n\n
  4596. Select HTTP_CACHE_SERVER to define the server-side caching mode.
  4597. \n\n
  4598. Select HTTP_CACHE_UNIQUE to uniquely cache requests with different request parameters.
  4599. @return A count of the bytes actually written
  4600. @ingroup HttpCache
  4601. @stability Evolving
  4602. */
  4603. PUBLIC void httpAddCache(struct HttpRoute *route, cchar *methods, cchar *uris, cchar *extensions, cchar *types,
  4604. MprTicks clientLifespan, MprTicks serverLifespan, int flags);
  4605. /**
  4606. Update the cached content for a URI
  4607. @param stream HttpStream stream object
  4608. @param uri The request URI for which to update the cache. The URI may
  4609. contain the request parameters in sorted www-urlencoded format.
  4610. The URI should include any route prefix.
  4611. @param data Data to cache for the URI. If you wish to cache response headers, include those at the start of the
  4612. data followed by an additional new line.
  4613. @param lifespan Lifespan in milliseconds for the cached content
  4614. @ingroup HttpCache
  4615. @stability Evolving
  4616. */
  4617. PUBLIC ssize httpUpdateCache(HttpStream *stream, cchar *uri, cchar *data, MprTicks lifespan);
  4618. /**
  4619. Write the cached content for a URI to the client
  4620. @description This call explicitly writes cached content to the client. It is useful when the caching is
  4621. configured in manual mode via the HTTP_CACHE_MANUAL flag to #httpAddCache.
  4622. @param stream HttpStream stream object
  4623. @ingroup HttpCache
  4624. @stability Evolving
  4625. */
  4626. PUBLIC ssize httpWriteCached(HttpStream *stream);
  4627. /******************************** Action Handler *************************************/
  4628. /**
  4629. Action handler callback signature
  4630. @description The Action Handler provides a simple mechanism to bind 'C' callback functions with URIs.
  4631. @param stream HttpStream stream object created via #httpCreateStream
  4632. @defgroup HttpStream HttpStream
  4633. @stability Stable
  4634. */
  4635. typedef void (*HttpAction)(HttpStream *stream);
  4636. /**
  4637. Define a function procedure to invoke when the specified URI is requested.
  4638. @description This creates the role with given abilities. Ability words can also be other roles.
  4639. @param uri URI to bind with. When this URI is requested, the callback will be invoked if the procHandler is
  4640. configured for the request route.
  4641. @param fun Callback function procedure
  4642. @ingroup HttpAction
  4643. @stability Stable
  4644. */
  4645. PUBLIC void httpDefineAction(cchar *uri, HttpAction fun);
  4646. /********************************** Streaming **********************************/
  4647. /**
  4648. Determine if input body content should be streamed or buffered for requests with content of a given mime type
  4649. @description The mime type and URI are used to match the request. If streaming is not defined true or false for
  4650. the mime and url, this routine return true if the request is not POST or PUT.
  4651. @param stream Current request stream
  4652. @return True if input should be streamed. False if it should be buffered.
  4653. @ingroup HttpHost
  4654. @stability Evolving
  4655. @internal
  4656. */
  4657. PUBLIC bool httpGetStreaming(struct HttpStream *stream);
  4658. /**
  4659. Control if input body content should be streamed or buffered for requests with content of a given mime type
  4660. and a URI path that starts with the specified URI prefix.
  4661. @param host Host to modify
  4662. @param mime Mime type to configure
  4663. @param uri URI prefix to match.
  4664. @param streaming Set to true to enable streaming for this mime type.
  4665. @ingroup HttpHost
  4666. @stability Evolving
  4667. @internal
  4668. */
  4669. PUBLIC void httpSetStreaming(struct HttpHost *host, cchar *mime, cchar *uri, bool streaming);
  4670. /********************************** HttpRoute *********************************/
  4671. /*
  4672. Misc route API flags
  4673. */
  4674. #define HTTP_ROUTE_NOT 0x1 /**< Negate the route pattern test result */
  4675. #define HTTP_ROUTE_FREE 0x2 /**< Free Route.mdata back to malloc when route is freed */
  4676. #define HTTP_ROUTE_FREE_PATTERN 0x4 /**< Free Route.patternCompiled back to malloc when route is freed */
  4677. #define HTTP_ROUTE_RAW 0x8 /**< Don't html encode the write data */
  4678. #define HTTP_ROUTE_STARTED 0x10 /**< Route initialized */
  4679. #define HTTP_ROUTE_XSRF 0x20 /**< Generate XSRF tokens */
  4680. #define HTTP_ROUTE_CORS 0x40 /**< Cross-Origin resource sharing */
  4681. #define HTTP_ROUTE_STEALTH 0x80 /**< Stealth mode */
  4682. #define HTTP_ROUTE_SHOW_ERRORS 0x100 /**< Show errors to the client */
  4683. #define HTTP_ROUTE_VISIBLE_SESSION 0x200 /**< Create a session cookie visible to client Javascript */
  4684. #define HTTP_ROUTE_PRESERVE_FRAMES 0x400 /**< Preserve WebSocket frame boundaries */
  4685. #define HTTP_ROUTE_HIDDEN 0x800 /**< Hide this route in route tables. */
  4686. #define HTTP_ROUTE_ENV_ESCAPE 0x1000 /**< Escape env vars */
  4687. #define HTTP_ROUTE_DOTNET_DIGEST_FIX 0x2000 /**< .NET digest auth omits query in MD5 */
  4688. #define HTTP_ROUTE_REDIRECT 0x4000 /**< Redirect secureCondition */
  4689. #define HTTP_ROUTE_STRICT_TLS 0x8000 /**< Emit Strict-Transport-Security header */
  4690. #define HTTP_ROUTE_HOSTED 0x10000 /**< Route being hosted (appweb) */
  4691. #define HTTP_ROUTE_NO_LISTEN 0x20000 /**< Not listening on endpoints */
  4692. #define HTTP_ROUTE_PERSIST_COOKIE 0x40000 /**< Persist session cookie to disk */
  4693. #define HTTP_ROUTE_OWN_LISTEN 0x80000 /**< Override listening endpoints */
  4694. #define HTTP_ROUTE_UTILITY 0x100000 /**< Route hosted by a utility */
  4695. #define HTTP_ROUTE_LAX_COOKIE 0x200000 /**< Session cookie is SameSite=lax */
  4696. #define HTTP_ROUTE_STRICT_COOKIE 0x400000 /**< Session cookie is SameSite=strict */
  4697. #define HTTP_ROUTE_NONE_COOKIE 0x800000 /**< Session cookie is SameSite=none */
  4698. /*
  4699. Route hook types
  4700. */
  4701. #define HTTP_ROUTE_HOOK_CGI 1
  4702. #define HTTP_ROUTE_HOOK_ERROR 2
  4703. typedef int (*HttpRouteCallback)(struct HttpStream *stream, int type, ...);
  4704. PUBLIC void httpSetRouteCallback(struct HttpRoute *route, HttpRouteCallback proc);
  4705. /**
  4706. Route Control
  4707. @description Configuration is not thread safe and must occur at initialization time when the application is
  4708. single threaded.
  4709. If the configuration is modified when the application is multithreaded, all requests must be first be quiesced.
  4710. @defgroup HttpRoute HttpRoute
  4711. @see HttpRoute httpAddRouteCondition httpAddRouteErrorDocument
  4712. httpAddRouteFilter httpAddRouteHandler httpAddRouteHeader httpAddRouteLanguageDir httpAddRouteLanguageSuffix
  4713. httpAddRouteLoad httpAddRouteQuery httpAddRouteUpdate httpClearRouteStages httpCreateAliasRoute
  4714. httpCreateDefaultRoute httpCreateInheritedRoute httpCreateRoute httpDefineRoute
  4715. httpDefineRouteCondition httpDefineRouteTarget httpDefineRouteUpdate httpFinalizeRoute httpGetRouteData
  4716. httpGetRouteDocuments httpLookupRouteErrorDocument httpMakePath httpResetRoutePipeline
  4717. httpSetRouteAuth httpSetRouteAutoDelete httpSetRouteAutoFinalize httpSetRouteConnector httpSetRouteData
  4718. httpSetRouteDefaultLanguage httpSetRouteDocuments httpSetRouteFlags httpSetRouteHandler httpSetRouteHost
  4719. httpSetRouteIndex httpSetRouteMethods httpSetRouteVar httpSetRoutePattern
  4720. httpSetRoutePrefix httpSetRouteScript httpSetRouteSource httpSetRouteTarget httpTemplate
  4721. httpTokenize httpTokenizev httpLink httpLinkEx
  4722. @stability Internal
  4723. */
  4724. typedef struct HttpRoute {
  4725. /* Ordered for debugging */
  4726. struct HttpRoute *parent; /**< Parent route */
  4727. char *pattern; /**< Original matching URI pattern for the route (includes prefix) */
  4728. char *startSegment; /**< First starting literal segment of pattern */
  4729. char *startWith; /**< Starting literal portion of pattern */
  4730. char *optimizedPattern; /**< Processed pattern (excludes prefix) */
  4731. char *prefix; /**< Application scriptName prefix. Set to '' for '/'. Always set */
  4732. char *tplate; /**< URI template for forming links based on this route (includes prefix) */
  4733. char *targetRule; /**< Target rule */
  4734. char *target; /**< Route target details */
  4735. cchar *documents; /**< Documents directory */
  4736. cchar *home; /**< Home directory for configuration files */
  4737. char *envPrefix; /**< Environment strings prefix */
  4738. MprList *indexes; /**< Directory index documents */
  4739. HttpStage *handler; /**< Fixed handler */
  4740. int nextGroup; /**< Next route with a different startWith */
  4741. int responseStatus; /**< Response status code */
  4742. ssize prefixLen; /**< Prefix length */
  4743. ssize startWithLen; /**< Length of startWith */
  4744. ssize startSegmentLen; /**< Prefix length */
  4745. MprJson *config; /**< Configuration file content */
  4746. cchar *mode; /**< Application run profile mode (debug|release) */
  4747. HttpUri *canonical; /**< Canonical host name (optional canonial public name for redirections) */
  4748. cchar *database; /**< Name of database for route */
  4749. cchar *responseFormat; /**< Client response format */
  4750. cchar *clientConfig; /**< Configuration to send to the client */
  4751. bool autoDelete: 1; /**< Automatically delete uploaded files */
  4752. bool autoFinalize: 1; /**< Auto finalize the request (ESP) */
  4753. bool debug: 1; /**< Application running in debug mode */
  4754. bool error: 1; /**< Parse or runtime error */
  4755. bool ignoreEncodingErrors: 1;/**< Ignore UTF8 encoding errors */
  4756. bool json: 1; /**< Response format is json */
  4757. MprList *caching; /**< Items to cache */
  4758. MprTicks lifespan; /**< Default lifespan for all cache items in route */
  4759. HttpAuth *auth; /**< Per route block authentication */
  4760. Http *http; /**< Http service object (copy of appweb->http) */
  4761. struct HttpHost *host; /**< Owning host */
  4762. HttpRouteCallback callback; /**< Route callback hook */
  4763. int flags; /**< Route flags */
  4764. char *defaultLanguage; /**< Default language */
  4765. MprHash *extensions; /**< Hash of handlers by extensions */
  4766. MprList *handlers; /**< List of handlers for this route */
  4767. HttpStage *connector; /**< Network connector to use */
  4768. MprHash *map; /**< Map of alternate extensions (gzip|minified) */
  4769. MprHash *data; /**< Hash of extra data configuration */
  4770. MprHash *vars; /**< Route variables. Used to expand Path ${token} refrerences */
  4771. MprHash *languages; /**< Languages supported */
  4772. MprList *inputStages; /**< Input stages */
  4773. MprList *outputStages; /**< Output stages */
  4774. MprHash *errorDocuments; /**< Set of error documents to use on errors */
  4775. void *context; /**< Hosting context (Appweb == EjsPool) */
  4776. void *eroute; /**< Extended route information for handler (only) */
  4777. int renameUploads; /**< Rename uploaded files */
  4778. HttpLimits *limits; /**< Host resource limits */
  4779. MprHash *mimeTypes; /**< Hash table of mime types (key is extension) */
  4780. cchar *charSet; /**< Character set to use with the Content-Type */
  4781. HttpTrace *trace; /**< Per-route tracing configuration */
  4782. cchar *cookie; /**< Cookie name for session data */
  4783. cchar *corsOrigin; /**< CORS permissible client origins */
  4784. cchar *corsHeaders; /**< Headers to add for Access-Control-Expose-Headers */
  4785. cchar *corsMethods; /**< Methods to add for Access-Control-Allow-Methods */
  4786. bool corsCredentials; /**< Whether to emit an Access-Control-Allow-Credentials */
  4787. int corsAge; /**< Age in seconds of the pre-flight authorization */
  4788. MprHash *methods; /**< Matching HTTP methods */
  4789. MprList *params; /**< Matching param field data */
  4790. MprList *requestHeaders; /**< Required request header values */
  4791. MprList *conditions; /**< Route conditions */
  4792. MprList *updates; /**< Route and request updates */
  4793. void *patternCompiled; /**< Compiled pattern regular expression (not alloced) */
  4794. cchar *source; /**< Final source for route target */
  4795. cchar *sourceName; /**< Source name for route target */
  4796. MprList *tokens; /**< Tokens in pattern, {name} */
  4797. MprList *headers; /**< Response header values */
  4798. struct MprSsl *ssl; /**< SSL configuration */
  4799. char *webSocketsProtocol; /**< WebSockets sub-protocol */
  4800. MprTicks webSocketsPingPeriod; /**< Time between pings (msec) */
  4801. #if DEPRECATED
  4802. /*
  4803. Used by Ejscript
  4804. */
  4805. char *script; /**< Startup script for handlers serving this route */
  4806. char *scriptPath; /**< Startup script path for handlers serving this route */
  4807. int workers; /**< Number of workers to use for this route */
  4808. #endif
  4809. } HttpRoute;
  4810. /**
  4811. Route operation record
  4812. @stability Internal
  4813. */
  4814. typedef struct HttpRouteOp {
  4815. char *name; /**< Name of route operation */
  4816. char *details; /**< General route operation details */
  4817. char *var; /**< Var to set */
  4818. char *value; /**< Value to assign to var */
  4819. void *mdata; /**< pcre_ data (unmanaged) */
  4820. int flags; /**< Route flags to control freeing mdata */
  4821. } HttpRouteOp;
  4822. /*
  4823. Route matching return codes
  4824. */
  4825. #define HTTP_ROUTE_OK 0 /**< The route matches the request */
  4826. #define HTTP_ROUTE_REJECT 1 /**< The route does not match the request */
  4827. #define HTTP_ROUTE_REROUTE 2 /**< Request has been modified and must be re-routed */
  4828. #define HTTP_ROUTE_OMIT_FILTER 1 /**< Omit filter. Same code as HTTP_ROUTE_REJECT for handlers */
  4829. /**
  4830. Http JSON configuration parse callback
  4831. @param route Current route
  4832. @param key Configuration file property key
  4833. @param child Key value as a JSON object
  4834. @ingroup HttpRoute
  4835. @stability Evolving
  4836. */
  4837. typedef void (*HttpParseCallback)(struct HttpRoute *route, cchar *key, MprJson *child);
  4838. /*
  4839. Emit a parse error message
  4840. @description This aborts processing further configuration.
  4841. @param route Current route
  4842. @fmt Printf style format string
  4843. @ingroup HttpRoute
  4844. @stability Evolving
  4845. */
  4846. PUBLIC void httpParseError(HttpRoute *route, cchar *fmt, ...);
  4847. /*
  4848. Emit a parse warning message
  4849. @param route Current route
  4850. @fmt Printf style format string
  4851. @ingroup HttpRoute
  4852. @stability Evolving
  4853. */
  4854. PUBLIC void httpParseWarn(HttpRoute *route, cchar *fmt, ...);
  4855. /**
  4856. General route procedure. Used by targets, conditions and updates.
  4857. @return Zero for success. Otherwise a negative MPR error code.
  4858. */
  4859. typedef int (HttpRouteProc)(HttpStream *stream, HttpRoute *route, HttpRouteOp *item);
  4860. /**
  4861. RouteSet callback
  4862. @param route Parent route for new routes
  4863. @param name Name of route set to add
  4864. @ingroup HttpRoute
  4865. @stability Evolving
  4866. */
  4867. typedef void (*HttpRouteSetProc)(HttpRoute *route, cchar *name);
  4868. /**
  4869. Add a configuration file callback for a property key
  4870. @param key Configuration file property key
  4871. @param callback Callback function of type #HttpParseCallback
  4872. @return Returns prior callback function. This should be invoked from the new callback to implemented multiple
  4873. callbacks per key.
  4874. @ingroup HttpRoute
  4875. @stability Evolving
  4876. */
  4877. PUBLIC HttpParseCallback httpAddConfig(cchar *key, HttpParseCallback callback);
  4878. /**
  4879. Define a route set callback
  4880. @param name Name of the route set
  4881. @param fn Callback function
  4882. @ingroup HttpRoute
  4883. @stability Evolving
  4884. */
  4885. PUBLIC HttpRouteSetProc httpDefineRouteSet(cchar *name, HttpRouteSetProc fn);
  4886. /**
  4887. Add a route set
  4888. @description This will add a set of routes. It will add a home route and optional routes depending on the route set.
  4889. <table>
  4890. <tr><td>Name</td><td>Method</td><td>Pattern</td><td>Target</td></tr>
  4891. <tr><td>home</td><td>GET,POST,PUT</td><td>^/$</td><td>index.esp</td></tr>
  4892. </table>
  4893. @param route Parent route from which to inherit configuration.
  4894. @param set Route set name to select.
  4895. @ingroup HttpRoute
  4896. @stability Evolving
  4897. */
  4898. PUBLIC void httpAddRouteSet(HttpRoute *route, cchar *set);
  4899. /**
  4900. Add routes for a resource
  4901. @description This routing adds a set of RESTful routes for a resource. It will add the following routes:
  4902. <table>
  4903. <tr><td>Name</td><td>Method</td><td>Pattern</td><td>Action</td></tr>
  4904. <tr><td>create</td><td>POST</td><td>/NAME(/)*$</td><td>create</td></tr>
  4905. <tr><td>edit</td><td>GET</td><td>/NAME/edit$</td><td>edit</td></tr>
  4906. <tr><td>get</td><td>GET</td><td>/NAME$</td><td>get</td></tr>
  4907. <tr><td>init</td><td>GET</td><td>/NAME/init$</td><td>init</td></tr>
  4908. <tr><td>update</td><td>PUT</td><td>/NAME$</td><td>update</td></tr>
  4909. <tr><td>remove</td><td>DELETE</td><td>/NAME$</td><td>remove</td></tr>
  4910. <tr><td>default</td><td>*</td><td>/NAME/{action}$</td><td>cmd-${action}</td></tr>
  4911. </tr>
  4912. </table>
  4913. @param parent Parent route from which to inherit configuration.
  4914. @param resource Resource name. This should be a lower case, single word, alphabetic resource name.
  4915. @ingroup HttpRoute
  4916. @stability Evolving
  4917. */
  4918. PUBLIC void httpAddResource(HttpRoute *parent, cchar *resource);
  4919. /**
  4920. Add routes for a permanent resource
  4921. @description This routing adds a set of RESTful routes for a resource. It will add the following routes:
  4922. <table>
  4923. <tr><td>Name</td><td>Method</td><td>Pattern</td><td>Action</td></tr>
  4924. <tr><td>get</td><td>GET</td><td>/NAME$</td><td>get</td></tr>
  4925. <tr><td>update</td><td>PUT</td><td>/NAME$</td><td>update</td></tr>
  4926. <tr><td>default</td><td>*</td><td>/NAME/{action}$</td><td>cmd-${action}</td></tr>
  4927. </tr>
  4928. </table>
  4929. @param parent Parent route from which to inherit configuration.
  4930. @param resource Resource name. This should be a lower case, single word, alphabetic resource name.
  4931. @ingroup HttpRoute
  4932. @stability Evolving
  4933. */
  4934. PUBLIC void httpAddPermResource(HttpRoute *parent, cchar *resource);
  4935. /**
  4936. Add routes for a group of resources
  4937. @description This routing adds a set of RESTful routes for a resource group. It will add the following routes:
  4938. <table>
  4939. <tr><td>Name</td><td>Method</td><td>Pattern</td><td>Action</td></tr>
  4940. <tr><td>create</td><td>POST</td><td>/NAME(/)*$</td><td>create</td></tr>
  4941. <tr><td>edit</td><td>GET</td><td>/NAME/{id=[0-9]+}/edit$</td><td>edit</td></tr>
  4942. <tr><td>get</td><td>GET</td><td>/NAME/{id=[0-9]+}$</td><td>get</td></tr>
  4943. <tr><td>init</td><td>GET</td><td>/NAME/init$</td><td>init</td></tr>
  4944. <tr><td>list</td><td>GET</td><td>/NAME(/)*$</td><td>list</td></tr>
  4945. <tr><td>remove</td><td>DELETE</td><td>/NAME/{id=[0-9]+}$</td><td>remove</td></tr>
  4946. <tr><td>update</td><td>PUT</td><td>/NAME/{id=[0-9]+}$</td><td>update</td></tr>
  4947. <tr><td>action</td><td>POST</td><td>/NAME/{action}/{id=[0-9]+}$</td><td>${action}</td></tr>
  4948. <tr><td>default</td><td>*</td><td>/NAME/{action}$</td><td>cmd-${action}</td></tr>
  4949. </tr>
  4950. </table>
  4951. @param parent Parent route from which to inherit configuration.
  4952. @param resource Resource name. This should be a lower case, single word, alphabetic resource name.
  4953. @ingroup HttpRoute
  4954. @stability Evolving
  4955. */
  4956. PUBLIC void httpAddResourceGroup(HttpRoute *parent, cchar *resource);
  4957. /**
  4958. Add routes that use POST methods to enable extra parameters to be included in the body.
  4959. Useful for a group of resources in a single page application. The resource ID is provided in the request POST body.
  4960. @description This routing adds a set of RESTful routes for a resource group. It will add the following routes:
  4961. <table>
  4962. <tr><td>Name</td><td>Method</td><td>Pattern</td><td>Action</td></tr>
  4963. <tr><td>create</td><td>POST</td><td>/NAME/create$</td><td>create</td></tr>
  4964. <tr><td>edit</td><td>GET</td><td>/NAME/edit$</td><td>edit</td></tr>
  4965. <tr><td>get</td><td>GET</td><td>/NAME/get$</td><td>get</td></tr>
  4966. <tr><td>init</td><td>GET</td><td>/NAME/init$</td><td>init</td></tr>
  4967. <tr><td>list</td><td>POST</td><td>/NAME/find$</td><td>find</td></tr>
  4968. <tr><td>remove</td><td>DELETE</td><td>/NAME/remove$</td><td>remove</td></tr>
  4969. <tr><td>update</td><td>PUT</td><td>/NAME/update$</td><td>update</td></tr>
  4970. <tr><td>action</td><td>POST</td><td>/NAME/{action}$</td><td>${action}</td></tr>
  4971. </tr>
  4972. </table>
  4973. @param parent Parent route from which to inherit configuration.
  4974. @param resource Resource name. This should be a lower case, single word, alphabetic resource name.
  4975. @ingroup HttpRoute
  4976. @stability Evolving
  4977. */
  4978. PUBLIC void httpAddPostGroup(HttpRoute *parent, cchar *resource);
  4979. /**
  4980. Add routes for a group of resources for use by a single page application
  4981. @description This routing adds a set of RESTful routes for a resource group. It will add the following routes:
  4982. <table>
  4983. <tr><td>Name</td><td>Method</td><td>Pattern</td><td>Action</td></tr>
  4984. <tr><td>create</td><td>POST</td><td>/NAME(/)*$</td><td>create</td></tr>
  4985. <tr><td>edit</td><td>GET</td><td>/NAME/{id=[0-9]+}/edit$</td><td>edit</td></tr>
  4986. <tr><td>get</td><td>GET</td><td>/NAME/{id=[0-9]+}$</td><td>get</td></tr>
  4987. <tr><td>init</td><td>GET</td><td>/NAME/init$</td><td>init</td></tr>
  4988. <tr><td>list</td><td>POST</td><td>/NAME/list$</td><td>list</td></tr>
  4989. <tr><td>remove</td><td>DELETE</td><td>/NAME/{id=[0-9]+}$</td><td>remove</td></tr>
  4990. <tr><td>update</td><td>PUT</td><td>/NAME/{id=[0-9]+}$</td><td>update</td></tr>
  4991. <tr><td>action</td><td>POST</td><td>/NAME/{action}/{id=[0-9]+}$</td><td>${action}</td></tr>
  4992. <tr><td>default</td><td>*</td><td>/NAME/{action}$</td><td>cmd-${action}</td></tr>
  4993. </tr>
  4994. </table>
  4995. @param parent Parent route from which to inherit configuration.
  4996. @param resource Resource name. This should be a lower case, single word, alphabetic resource name.
  4997. @ingroup HttpRoute
  4998. @stability Evolving
  4999. */
  5000. PUBLIC void httpAddSpaGroup(HttpRoute *parent, cchar *resource);
  5001. /**
  5002. Add a route condition
  5003. @description A route condition is run after matching the route pattern. For a route to be accepted, all conditions
  5004. must match. Route conditions are built-in rules that can be applied to routes.
  5005. @param route Route to modify
  5006. @param name Condition rule to add. Supported conditions are: "auth", "missing", "directory", "exists", and "match".
  5007. The "auth" rule is used internally to implement basic and digest authentication.
  5008. \n\n
  5009. The "missing" rule tests if the target filename is missing. The "missing" rule takes no arguments.
  5010. \n\n
  5011. The "directory" rule tests if the condition argument is a directory. The form of the "directory" rule is:
  5012. "directory pathString". For example: "directory /stuff/${request:pathInfo}.txt"
  5013. \n\n
  5014. The "exists" rule tests if the condition argument is present in the file system. The form of the "exists" rule is:
  5015. "exists pathString". For example: "exists ${request.filename}.gz",
  5016. \n\n
  5017. The match directory tests a regular expression pattern against the rest of the condition arguments. The form of
  5018. the match rule is: "match RegExp string". For example: "match https ${request.scheme}".
  5019. @param details Condition parameters.
  5020. See #httpSetRouteTarget for a list of the token values that can be included in the condition rule details.
  5021. @param flags Set to HTTP_ROUTE_NOT to negate the condition test
  5022. @return "Zero" if successful, otherwise a negative MPR error code.
  5023. @ingroup HttpRoute
  5024. @stability Evolving
  5025. */
  5026. PUBLIC int httpAddRouteCondition(HttpRoute *route, cchar *name, cchar *details, int flags);
  5027. /**
  5028. Add an error document
  5029. @description This defines an error document to be used when the requested document cannot be found.
  5030. This definition is used by some handlers for error processing.
  5031. @param route Route to modify
  5032. @param status The HTTP status code to use with the error document.
  5033. @param uri URL describing the error document
  5034. @ingroup HttpRoute
  5035. @stability Evolving
  5036. */
  5037. PUBLIC void httpAddRouteErrorDocument(HttpRoute *route, int status, cchar *uri);
  5038. /**
  5039. Add a route filter
  5040. @description This configures the route pipeline by adding processing filters for a request.
  5041. must match. Route conditions are built-in rules that can be applied to routes.
  5042. @param route Route to modify
  5043. @param name Filter name to add
  5044. @param extensions Request extensions for which the filter will be run. A request extension may come from the URI
  5045. if present or from the corresponding filename.
  5046. @param direction Set to HTTP_STAGE_TX for transmit direction and HTTP_STAGE_RX for receive data flow.
  5047. @return "Zero" if successful, otherwise a negative MPR error code.
  5048. @ingroup HttpRoute
  5049. @stability Stable
  5050. */
  5051. PUBLIC int httpAddRouteFilter(HttpRoute *route, cchar *name, cchar *extensions, int direction);
  5052. /**
  5053. Add a route handler
  5054. @description This configures the route pipeline by adding the given handler.
  5055. Must only be called at initialization time for the route.
  5056. @param route Route to modify
  5057. @param name Filter name to add
  5058. @param extensions Request extensions for which the handler will be selected. A request extension may come from the URI
  5059. if present or from the corresponding filename.
  5060. @return Zero if successful, otherwise a negative MPR error code.
  5061. @ingroup HttpRoute
  5062. @stability Stable
  5063. */
  5064. PUBLIC int httpAddRouteHandler(HttpRoute *route, cchar *name, cchar *extensions);
  5065. /**
  5066. Set the route index document
  5067. @description Set the name of the index document to serve. Index documents may be served when the request corresponds
  5068. to a directory on the file system.
  5069. @param route Route to modify
  5070. @param path Path name to the index document. If the path is a relative path, it may be joined to the route
  5071. directory to create an absolute path.
  5072. @return A reference to the route data. Otherwise return null if the route data for the given key was not found.
  5073. @ingroup HttpRoute
  5074. @stability Stable
  5075. */
  5076. PUBLIC void httpAddRouteIndex(HttpRoute *route, cchar *path);
  5077. /**
  5078. Add a route language directory
  5079. @description This configures the route pipeline by adding the given language content directory.
  5080. When creating filenames for matching requests, the language directory is prepended to the request filename.
  5081. @param route Route to modify
  5082. @param language Language symbolic name. For example: "en" for english.
  5083. @param path File system directory to contain content for matching requests.
  5084. @return Zero if successful, otherwise a negative MPR error code.
  5085. @ingroup HttpRoute
  5086. @stability Stable
  5087. */
  5088. PUBLIC int httpAddRouteLanguageDir(HttpRoute *route, cchar *language, cchar *path);
  5089. /**
  5090. Add a route language suffix
  5091. @description This configures the route pipeline by adding the given language for request processing.
  5092. The language definition includes a suffix which will be added to the request filename.
  5093. @param route Route to modify
  5094. @param language Language symbolic name. For example: "en" for english.
  5095. @param suffix Extension suffix to add when creating filenames for the request. For example: "fr" to add to "index.html"
  5096. could produce: "index.fr.html".
  5097. @param flags Set to HTTP_LANG_BEFORE to insert the suffix before the filename extension. Set to HTTP_LANG_AFTER to
  5098. append after the extension. For example: HTTP_LANG_AFTER would produce "index.html.fr".
  5099. @return "Zero" if successful, otherwise a negative MPR error code.
  5100. @ingroup HttpRoute
  5101. @stability Stable
  5102. */
  5103. PUBLIC int httpAddRouteLanguageSuffix(HttpRoute *route, cchar *language, cchar *suffix, int flags);
  5104. /**
  5105. Add a route mapping
  5106. @description Route mappings will map the request filename by changing the default extension to the mapped extension.
  5107. This is used primarily to select compressed content.
  5108. @param route Route to modify
  5109. @param extensions Comma separated list of extensions to map. For example: "css,html,js,less,txt,xml"
  5110. Set to "*" or the empty string to match all extensions.
  5111. @param mappings List of new file extensions to consider. This may include a "${1}" token to replace the
  5112. previous extension. The extensions are searched in order and the first matching extensions for which there is
  5113. an existing file will be selected. For example: "${1}.gz, min.${1}.gz, min.${1}".
  5114. @ingroup HttpRoute
  5115. @stability Stable
  5116. */
  5117. PUBLIC void httpAddRouteMapping(HttpRoute *route, cchar *extensions, cchar *mappings);
  5118. /**
  5119. Add HTTP methods for the route
  5120. @description This defines additional HTTP methods for requests to match this route
  5121. @param route Route to modify
  5122. @param methods Set to a comma or space separated list of methods. Can also set to "All" or "*" for all possible
  5123. methods. Typical methods include: "DELETE, GET, OPTIONS, POST, PUT, TRACE". Must be upper case.
  5124. @ingroup HttpRoute
  5125. @stability Stable
  5126. */
  5127. PUBLIC void httpAddRouteMethods(HttpRoute *route, cchar *methods);
  5128. /**
  5129. Add a route param check
  5130. @description This configures the route to match a request only if the specified param field matches a specific value.
  5131. @param route Route to modify
  5132. @param field Param field to interrogate
  5133. @param value Header value that will match
  5134. @param flags Set to HTTP_ROUTE_NOT to negate the query test
  5135. @ingroup HttpRoute
  5136. @stability Stable
  5137. */
  5138. PUBLIC void httpAddRouteParam(HttpRoute *route, cchar *field, cchar *value, int flags);
  5139. /**
  5140. Add a request header check
  5141. @description This configures the route to match a request only if the specified header field matches a specific value.
  5142. @param route Route to modify
  5143. @param header Header field to interrogate
  5144. @param value Header value that will match
  5145. @param flags Set to HTTP_ROUTE_NOT to negate the header test
  5146. @ingroup HttpRoute
  5147. @stability Stable
  5148. */
  5149. PUBLIC void httpAddRouteRequestHeaderCheck(HttpRoute *route, cchar *header, cchar *value, int flags);
  5150. /*
  5151. Commands for httpAddRouteResponseHeader
  5152. */
  5153. #define HTTP_ROUTE_ADD_HEADER 1
  5154. #define HTTP_ROUTE_APPEND_HEADER 2
  5155. #define HTTP_ROUTE_REMOVE_HEADER 3
  5156. #define HTTP_ROUTE_SET_HEADER 4
  5157. /**
  5158. Add a response header
  5159. @description This modifies the response header set
  5160. @param route Route to modify
  5161. @param cmd Set to HTTP_ROUTE_HEADER_ADD to add a header if it is not already present in the response header set.
  5162. Set to HTTP_ROUTE_HEADER_REMOVE to remove a header. Set to HTTP_ROUTE_HEADER_SET to define a header and overwrite any
  5163. prior values. Set to HTTP_ROUTE_HEADER_APPEND to append to an existing header value.
  5164. @param header Header field to interrogate
  5165. @param value Header value that will match
  5166. @ingroup HttpRoute
  5167. @stability Stable
  5168. */
  5169. PUBLIC void httpAddRouteResponseHeader(HttpRoute *route, int cmd, cchar *header, cchar *value);
  5170. /**
  5171. Add a route update rule
  5172. @description This configures the route pipeline by adding processing update rules for a request.
  5173. Updates are built-in rules that can be applied to routes.
  5174. @param route Route to modify
  5175. @param name Update rule to add. Supported update rules include: "cmd", "field" and "lang".
  5176. \n\n
  5177. The "cmd" rule is used to run external commands. For example: "cmd touch /tmp/filename".
  5178. \n\n
  5179. The "param" rule is used to set values in the request param fields. For example: "param priority high".
  5180. \n\n
  5181. The "lang" update rule is used internally to implement the various language options.
  5182. See #httpSetRouteTarget for a list of the token values that can be included in the condition rule details.
  5183. @param details Update rule parameters.
  5184. @param flags Reserved.
  5185. @return "Zero" if successful, otherwise a negative MPR error code.
  5186. @ingroup HttpRoute
  5187. @stability Stable
  5188. */
  5189. PUBLIC int httpAddRouteUpdate(HttpRoute *route, cchar *name, cchar *details, int flags);
  5190. /**
  5191. Add a route using the WebSockets filter
  5192. @param route Parent route from which to inherit configuration.
  5193. @param action Name of the action to invoke on the route
  5194. @return The new route object.
  5195. @ingroup HttpRoute
  5196. @stability Stable
  5197. */
  5198. PUBLIC HttpRoute *httpAddWebSocketsRoute(HttpRoute *route, cchar *action);
  5199. /**
  5200. Clear the pipeline stages for the route
  5201. @description This resets the configured pipeline stages for the route.
  5202. @param route Route to modify
  5203. @param direction Set to HTTP_STAGE_TX for transmit direction and HTTP_STAGE_RX for receive data flow.
  5204. @ingroup HttpRoute
  5205. @stability Stable
  5206. */
  5207. PUBLIC void httpClearRouteStages(HttpRoute *route, int direction);
  5208. /**
  5209. Create a route suitable for use as an alias
  5210. @description The parent supplies the owning host for the route. A route is not added to its owning host until it
  5211. is finalized by calling #httpFinalizeRoute
  5212. @param parent Parent route to inherit from
  5213. @param pattern Pattern to match URIs
  5214. @param path File system directory containing documents for this route
  5215. @param status Http redirect status for matching requests. Set to zero if not using redirects
  5216. @return Allocated HttpRoute object
  5217. @ingroup HttpRoute
  5218. @stability Stable
  5219. */
  5220. PUBLIC HttpRoute *httpCreateAliasRoute(HttpRoute *parent, cchar *pattern, cchar *path, int status);
  5221. /**
  5222. Create a configured route
  5223. @description This creates a route and configures the request pipeline with range, chunk and upload filters.
  5224. @param host HttpHost object owning the route
  5225. @param serverSide Set to "true" if this is a server side route. Set to "false" for client side.
  5226. @return Allocated HttpRoute object
  5227. @ingroup HttpRoute
  5228. @stability Stable
  5229. */
  5230. PUBLIC HttpRoute *httpCreateConfiguredRoute(struct HttpHost *host, int serverSide);
  5231. /**
  5232. Create a default route for a host
  5233. @description When the route is fully configured, it should be finalized which will add it to its owning host.
  5234. @param host HttpHost object owning the route
  5235. @return Allocated HttpRoute object
  5236. @ingroup HttpRoute
  5237. @stability Stable
  5238. */
  5239. PUBLIC HttpRoute *httpCreateDefaultRoute(struct HttpHost *host);
  5240. /**
  5241. Create a route inherited from a parent route
  5242. @description When the route is fully configured, it should be finalized which will add it to its owning host.
  5243. @param route Parent route from which to inherit
  5244. @return Allocated HttpRoute object
  5245. @ingroup HttpRoute
  5246. @stability Stable
  5247. */
  5248. PUBLIC HttpRoute *httpCreateInheritedRoute(HttpRoute *route);
  5249. /**
  5250. Create a route for use with the Action Handler
  5251. @description This call creates a route inheriting from a parent route. The new route is configured for use with the
  5252. actionHandler and the given callback procedure.
  5253. @param parent Parent route from which to inherit
  5254. @param pattern Pattern to match URIs
  5255. @param action Action to invoke
  5256. @return Newly created route
  5257. @ingroup HttpRoute
  5258. @stability Stable
  5259. */
  5260. PUBLIC HttpRoute *httpCreateActionRoute(HttpRoute *parent, cchar *pattern, HttpAction action);
  5261. /**
  5262. Create a route for a host
  5263. @description This call creates a bare route without inheriting from a parent route.
  5264. When the route is fully configured, it should be finalized which will add it to its owning host.
  5265. @param host HttpHost object owning the route
  5266. @return Allocated HttpRoute object
  5267. @ingroup HttpRoute
  5268. @stability Stable
  5269. */
  5270. PUBLIC HttpRoute *httpCreateRoute(struct HttpHost *host);
  5271. /**
  5272. Define a route
  5273. @description This creates a route and then configures it using the given parameters. The route is finalized and
  5274. added to the parent host.
  5275. @param parent Parent route from which to inherit configuration.
  5276. @param methods Http methods for which this route is active
  5277. @param pattern Matching URI pattern for which this route will qualify
  5278. @param target Route target string expression. This is used by handlers to determine the physical or virtual resource
  5279. to serve.
  5280. @param source Source file pattern containing the resource to activate or serve.
  5281. @return Created route.
  5282. @ingroup HttpRoute
  5283. @stability Stable
  5284. */
  5285. PUBLIC HttpRoute *httpDefineRoute(HttpRoute *parent, cchar *methods, cchar *pattern, cchar *target, cchar *source);
  5286. /**
  5287. Define a RESTful route
  5288. @description This creates a restful route and then configures it using the given parameters. The route is finalized and
  5289. added to the parent host.
  5290. @param parent Parent route from which to inherit configuration.
  5291. @param methods Http methods for which this route is active
  5292. @param pattern Matching URI pattern for which this route will qualify
  5293. @param target Route target string expression. This is used by handlers to determine the physical or virtual resource
  5294. to serve.
  5295. @param resource Resource basename to use when constructing a source file name.
  5296. @return Created route.
  5297. @ingroup HttpRoute
  5298. @stability Evolving
  5299. */
  5300. PUBLIC HttpRoute *httpAddRestfulRoute(HttpRoute *parent, cchar *methods, cchar *pattern, cchar * target, cchar *resource);
  5301. /**
  5302. Define a route condition rule
  5303. @description This creates a new condition rule.
  5304. @param name Condition name
  5305. @param proc Condition function to process the condition during route matching.
  5306. @ingroup HttpRoute
  5307. @stability Evolving
  5308. */
  5309. PUBLIC void httpDefineRouteCondition(cchar *name, HttpRouteProc *proc);
  5310. /**
  5311. Define a route target rule
  5312. @description This creates a new target rule.
  5313. @param name Target name
  5314. @param proc Target function to process the target during route matching.
  5315. @ingroup HttpRoute
  5316. @stability Stable
  5317. */
  5318. PUBLIC void httpDefineRouteTarget(cchar *name, HttpRouteProc *proc);
  5319. /**
  5320. Define a route update rule
  5321. @description This creates a new update rule.
  5322. @param name Update name
  5323. @param proc Update function to process the update during route matching.
  5324. @ingroup HttpRoute
  5325. @stability Stable
  5326. */
  5327. PUBLIC void httpDefineRouteUpdate(cchar *name, HttpRouteProc *proc);
  5328. /**
  5329. Expand route variables in a string
  5330. @param route Route to modify
  5331. @param str String to expand
  5332. @ingroup HttpRoute
  5333. @stability Stable
  5334. */
  5335. PUBLIC cchar *httpExpandRouteVars(HttpRoute *route, cchar *str);
  5336. /**
  5337. Finalize a route
  5338. @description A route must be finalized to add it to its owning hosts list of routes.
  5339. @param route Route to modify
  5340. @ingroup HttpRoute
  5341. @stability Stable
  5342. */
  5343. PUBLIC void httpFinalizeRoute(HttpRoute *route);
  5344. /**
  5345. Get a route directory variable
  5346. @description This looks up the value of the directory
  5347. @param route Route to modify
  5348. @param name Lower case name of the directory. This should not include the '_DIR' suffix.
  5349. @return Directory path
  5350. @ingroup HttpRoute
  5351. @stability Evolving
  5352. */
  5353. PUBLIC cchar *httpGetDir(HttpRoute *route, cchar *name);
  5354. /**
  5355. Parse a boolean token
  5356. @param tok Token to parse
  5357. @return True if tok is set to "yes", "on", "true" or "1"
  5358. @ingroup HttpRoute
  5359. @stability Stable
  5360. */
  5361. PUBLIC bool httpGetBoolToken(cchar *tok);
  5362. /**
  5363. Get extra route data
  5364. @description Routes can store extra configuration information indexed by key. This is used by handlers, filters,
  5365. connectors and updates to store additional information on a per-route basis.
  5366. @param route Route to modify
  5367. @param key Unique string key to identify the data.
  5368. @return A reference to the route data. Otherwise return null if the route data for the given key was not found.
  5369. @see httpGetRouteData
  5370. @ingroup HttpRoute
  5371. @stability Stable
  5372. */
  5373. PUBLIC void *httpGetRouteData(HttpRoute *route, cchar *key);
  5374. /**
  5375. Get the route documents directory
  5376. @description Routes can define a default directory for documents to serve. This value may be used by
  5377. target rules to calculate the response filename.
  5378. @param route Route to modify
  5379. @return The route documents directory pathname.
  5380. @ingroup HttpRoute
  5381. @stability Stable
  5382. */
  5383. PUBLIC cchar *httpGetRouteDocuments(HttpRoute *route);
  5384. /**
  5385. Get the route home directory
  5386. @description Routes can define a home directory for configuration files.
  5387. @param route Route to modify
  5388. @return The route home directory pathname.
  5389. @ingroup HttpRoute
  5390. @stability Stable
  5391. */
  5392. PUBLIC cchar *httpGetRouteHome(HttpRoute *route);
  5393. /**
  5394. Get the route method list
  5395. @param route Route to examine
  5396. @return The list of support methods. Return NULL if not method list is defined.
  5397. @ingroup HttpRoute
  5398. @stability Stable
  5399. */
  5400. PUBLIC cchar *httpGetRouteMethods(HttpRoute *route);
  5401. /**
  5402. Get a URL path to the top of the route from the current request (rx->pathInfo)
  5403. @param stream Current stream object
  5404. @return A relative URL path to the top of the route. This URL does not contain a trailing "/"
  5405. @ingroup HttpRoute
  5406. @stability Evolving
  5407. */
  5408. PUBLIC cchar *httpGetRouteTop(HttpStream *stream);
  5409. /**
  5410. Get a path token variable
  5411. @param route Route to get
  5412. @param key Token key value
  5413. @ingroup HttpRoute
  5414. @stability Stable
  5415. */
  5416. PUBLIC cchar *httpGetRouteVar(HttpRoute *route, cchar *key);
  5417. /**
  5418. Graduate the limits from the parent route.
  5419. @description This creates a unique limit structure for the route if it is currently inheriting its parents limits.
  5420. @param route Route to modify
  5421. @param limits Limits to use if graduating.
  5422. @ingroup HttpRoute
  5423. @stability Stable
  5424. */
  5425. PUBLIC HttpLimits *httpGraduateLimits(HttpRoute *route, HttpLimits *limits);
  5426. /**
  5427. Hide the route from route tables.
  5428. The route is still active, just not displayed in route tables. This is used to hide
  5429. parent routes that are used just for inheritance for child routes.
  5430. @param route Route to hide
  5431. @param on Set to true to hide the route
  5432. @stability Evolving
  5433. */
  5434. PUBLIC void httpHideRoute(HttpRoute *route, bool on);
  5435. /**
  5436. Initialize and prepare to load configuration files.
  5437. @ingroup HttpRoute
  5438. @stability Evolving
  5439. */
  5440. PUBLIC void httpInitConfig(HttpRoute *route);
  5441. /**
  5442. Load a JSON configuration file
  5443. @description This loads the JSON configuration file.
  5444. @param route Parent route to configure
  5445. @param path Filename of the JSON configuration file. If this is a relative path, it will be resolved relative
  5446. to the routes home directory.
  5447. @return 'Zero' if successful, otherwise a negative MPR error code.
  5448. @ingroup HttpRoute
  5449. @stability Evolving
  5450. */
  5451. PUBLIC int httpLoadConfig(HttpRoute *route, cchar *path);
  5452. /**
  5453. Lookup an error document by HTTP status code
  5454. @description This looks up error documents configured via #httpAddRouteErrorDocument
  5455. @param route Route to modify
  5456. @param status HTTP status code integer
  5457. @return URI associated with the error document for the requested status.
  5458. @ingroup HttpRoute
  5459. @stability Stable
  5460. */
  5461. PUBLIC cchar *httpLookupRouteErrorDocument(HttpRoute *route, int status);
  5462. /**
  5463. Make a filename path
  5464. @description This makes a filename by expanding the tokens "${token}" and then normalizing the path. Relative paths
  5465. are resolved relative to the optional dir parameter.
  5466. The supported tokens are:
  5467. <ul>
  5468. <li>DOCUMENTS_DIR - for the default directory containing documents to serve</li>
  5469. <li>HOME_DIR - for the directory containing the web server configuration files</li>
  5470. <li>BIN_DIR - for the shared library directory. E.g. /usr/local/lib/appweb/bin </li>
  5471. <li>OS - for the operating system name. E.g. LINUX, MACOSX, VXWORKS, or WIN</li>
  5472. <li>PRODUCT - for the product name</li>
  5473. <li>VERSION - for the product version. E.g. 4.0.2</li>
  5474. </ul>
  5475. Additional tokens can be defined via #httpSetRouteVar.
  5476. @param route Route to modify
  5477. @param dir Directory to use as a base directory for relative paths.
  5478. @param path Path name to examine
  5479. @return A resolved absolute path name.
  5480. @ingroup HttpRoute
  5481. @stability Stable
  5482. */
  5483. PUBLIC char *httpMakePath(HttpRoute *route, cchar *dir, cchar *path);
  5484. /**
  5485. Map a content filename
  5486. @description Test a filename for alternative extension mappings. This is used to server compressed or minified
  5487. content intead of "vanilla" files.
  5488. @param stream HttpStream stream object
  5489. @param filename Base filename.
  5490. @ingroup HttpRoute
  5491. @stability Internal
  5492. */
  5493. PUBLIC cchar *httpMapContent(HttpStream *stream, cchar *filename);
  5494. /**
  5495. Map the request URI to a filename in physical storage for a handler.
  5496. @description This routine is invoked by handlers to map the request URI to a filename and should be called by handlers
  5497. that serve physical documents. The request URI is resolved relative to the route documents directory.
  5498. If a route language directory is defined, that directory is prefixed to the filename after the route documents directory.
  5499. \n\n
  5500. If route maps have been defined, the filename may be mapped to a preferred compressed or minified filename to serve.
  5501. \n\n
  5502. After computing the filename, this routine calls #httpSetFilename to set the HttpTx.filename, ext, etag and fileInfo
  5503. fields. If a filename has already been defined by a prior call to httpMapFile or #httpSetFilename, this routine will
  5504. do nothing. To reset a prior filename, use #httpSetFilename with a null argument.
  5505. @param stream HttpStream stream object
  5506. @ingroup HttpRoute
  5507. @stability Stable
  5508. */
  5509. PUBLIC void httpMapFile(HttpStream *stream);
  5510. /**
  5511. Parse all the properties under the given key
  5512. @param route Parent route to configure
  5513. @param key Json property key
  5514. @param prop Json property value
  5515. @ingroup HttpRoute
  5516. @stability Evolving
  5517. */
  5518. PUBLIC void httpParseAll(HttpRoute *route, cchar *key, MprJson *prop);
  5519. /**
  5520. Remove HTTP methods for the route
  5521. @description This removes supported HTTP methods from this route
  5522. @param route Route to modify
  5523. @param methods Set to a comma or space separated list of methods.
  5524. @ingroup HttpRoute
  5525. @stability Stable
  5526. */
  5527. PUBLIC void httpRemoveRouteMethods(HttpRoute *route, cchar *methods);
  5528. /**
  5529. Reset all defined indexes
  5530. @ingroup HttpRoute
  5531. @stability Stable
  5532. */
  5533. PUBLIC void httpResetRouteIndexes(HttpRoute *route);
  5534. /**
  5535. Reset the route pipeline
  5536. @description This completely resets the pipeline and discards inherited pipeline configuration. This resets the
  5537. error documents, expiry cache values, extensions, handlers, input and output stage configuration.
  5538. @param route Route to modify
  5539. @ingroup HttpRoute
  5540. @stability Stable
  5541. */
  5542. PUBLIC void httpResetRoutePipeline(HttpRoute *route);
  5543. /**
  5544. Define a route directory path variable
  5545. @description This creates an upper case route variable with a _DIR suffix for the given name.
  5546. @param route Route to modify
  5547. @param name Name of the directory to define
  5548. @param value Directory path value.
  5549. @ingroup HttpRoute
  5550. @stability Evolving
  5551. */
  5552. PUBLIC void httpSetDir(HttpRoute *route, cchar *name, cchar *value);
  5553. /**
  5554. Set the route authentication
  5555. @description This defines the authentication configuration for basic and digest authentication for the route.
  5556. @param route Route to modify
  5557. @param auth Authentication object
  5558. @ingroup HttpRoute
  5559. @stability Stable
  5560. */
  5561. PUBLIC void httpSetRouteAuth(HttpRoute *route, HttpAuth *auth);
  5562. /**
  5563. Control file upload auto delete
  5564. @description This controls whether files are auto-deleted after the handler runs to service a request.
  5565. @param route Route to modify
  5566. @param on Set to true to enable auto-delete. Auto-delete is enabled by default.
  5567. @ingroup HttpRoute
  5568. @stability Stable
  5569. */
  5570. PUBLIC void httpSetRouteAutoDelete(HttpRoute *route, bool on);
  5571. /**
  5572. Control auto finalize for a route
  5573. @description This controls whether a request is auto-finalized after the handler runs to service a request.
  5574. @param route Route to modify
  5575. @param on Set to true to enable auto-finalize. Auto-finalize is enabled by default for frameworks that use it.
  5576. @ingroup HttpRoute
  5577. @stability Evolving
  5578. */
  5579. PUBLIC void httpSetRouteAutoFinalize(HttpRoute *route, bool on);
  5580. /**
  5581. Set the route canonical name
  5582. @description The route canonical name is the public perferred name to use for the server for this route. This is
  5583. used when redirecting client requests for directories.
  5584. @param route HttpRoute object
  5585. @param name Host canonical name to use
  5586. @return Zero if successful. May return a negative MPR error code if the name is a regular expression and cannot
  5587. be compiled.
  5588. @ingroup HttpHost
  5589. @stability Stable
  5590. */
  5591. PUBLIC int httpSetRouteCanonicalName(HttpRoute *route, cchar *name);
  5592. /**
  5593. Set the default route character set
  5594. @description Set the default character set used in response Content-Types
  5595. @param route HttpRoute object created via #httpCreateRoute
  5596. @param charSet Character set string
  5597. @ingroup HttpTx
  5598. @stability Stable
  5599. */
  5600. PUBLIC void httpSetRouteCharSet(HttpRoute *route, cchar *charSet);
  5601. /**
  5602. Define whether updating a request may compile from source
  5603. @param route Route to modify
  5604. @param on Set to true to enable
  5605. @ingroup HttpRoute
  5606. @stability Evolving
  5607. */
  5608. PUBLIC void httpSetRouteCompile(HttpRoute *route, bool on);
  5609. /**
  5610. Set the connector to use for a route
  5611. @param route Route to modify
  5612. @param name Connector name to use for this route
  5613. @return "Zero" if successful, otherwise a negative MPR error code.
  5614. @ingroup HttpRoute
  5615. @stability Stable
  5616. */
  5617. PUBLIC int httpSetRouteConnector(HttpRoute *route, cchar *name);
  5618. /**
  5619. Set route data
  5620. @description Routes can store extra configuration information indexed by key. This is used by handlers, filters,
  5621. connectors and updates to store additional information on a per-route basis.
  5622. @param route Route to modify
  5623. @param key Unique string to identify the data
  5624. @param data Data object. This must be allocated via mprAlloc.
  5625. @ingroup HttpRoute
  5626. @stability Stable
  5627. */
  5628. PUBLIC void httpSetRouteData(HttpRoute *route, cchar *key, void *data);
  5629. PUBLIC void httpSetRouteModuleData(HttpRoute *route, cchar *key, void *data);
  5630. /**
  5631. Set the default language for the route
  5632. @description This call defines the default language to serve if the client does not provide an Accept HTTP header
  5633. with language preference instructions.
  5634. @param route Route to modify
  5635. @param language Language symbolic name. For example: "en" for english.
  5636. @ingroup HttpRoute
  5637. @stability Stable
  5638. */
  5639. PUBLIC void httpSetRouteDefaultLanguage(HttpRoute *route, cchar *language);
  5640. /**
  5641. Set the route directory
  5642. @description Routes can define a default directory for documents to serve. This value may be used by
  5643. target rules to calculate the response filename.
  5644. @param route Route to modify
  5645. @param path Directory path name for the route content
  5646. @ingroup HttpRoute
  5647. @stability Stable
  5648. */
  5649. PUBLIC void httpSetRouteDocuments(HttpRoute *route, cchar *path);
  5650. /**
  5651. Define a prefix string for environment variables
  5652. @description When mapping URI query parameters and form variables to environment variables, it is
  5653. important to prevent important system variables like SHELL, PATH and IFS being overwritten or
  5654. corrupted. Defining a unique prefix for such parameters ensures they have their own namespace.
  5655. @param route Route to modify
  5656. @param prefix Prefix to use in front of environment variables for URI and form parameters.
  5657. @ingroup HttpRoute
  5658. @stability Stable
  5659. */
  5660. PUBLIC void httpSetRouteEnvPrefix(HttpRoute *route, cchar *prefix);
  5661. /**
  5662. Define whether shell special characters are escaped in environment variables
  5663. @description If using shell scripts as CGI programs, it is useful to escape all special shell characters
  5664. to make scripting easier. This will escape (with \) the following characters:
  5665. &;`'\"|*?~<>^()[]{}$\\\n and also on windows \\r%
  5666. @param route Route to modify
  5667. @param on Set to true to enable escaping shell special characters.
  5668. @ingroup HttpRoute
  5669. @stability Stable
  5670. */
  5671. PUBLIC void httpSetRouteEnvEscape(HttpRoute *route, bool on);
  5672. /**
  5673. Update the route flags
  5674. @description Low level routine to manipulate the route flags
  5675. @param route Route to modify
  5676. @param flags Flags mask
  5677. @ingroup HttpRoute
  5678. @stability Stable
  5679. @internal
  5680. */
  5681. PUBLIC void httpSetRouteFlags(HttpRoute *route, int flags);
  5682. /**
  5683. Set the handler to use for a route
  5684. @description This defines the stage handler to use in the request pipline for requests matching this route.
  5685. Note that you can also use httpAddRouteHandler which configures a set of handlers that will match by extension.
  5686. @param route Route to modify
  5687. @param name Handler name to define
  5688. @return "Zero" if successful, otherwise a negative MPR error code.
  5689. @ingroup HttpRoute
  5690. @stability Stable
  5691. */
  5692. PUBLIC int httpSetRouteHandler(HttpRoute *route, cchar *name);
  5693. /**
  5694. Set the route directory for configuration files
  5695. @description Routes can define a default directory for configuration files.
  5696. @param route Route to modify
  5697. @param home Directory path name for configuration files
  5698. @ingroup HttpRoute
  5699. @stability Stable
  5700. */
  5701. PUBLIC void httpSetRouteHome(HttpRoute *route, cchar *home);
  5702. /*
  5703. Define the owning host for a route.
  5704. @description WARNING: this should not be called by users.
  5705. @param route Route to modify
  5706. @param host HttpHost object
  5707. @ingroup HttpRoute
  5708. @stability Internal
  5709. @internal
  5710. */
  5711. PUBLIC void httpSetRouteHost(HttpRoute *route, struct HttpHost *host);
  5712. /**
  5713. Set the route to ignore UTF encoding errors for WebSocket connections
  5714. @param route Route to modify
  5715. @param on Set to true to ignore encoding errors
  5716. @ingroup HttpRoute
  5717. @stability Stable
  5718. */
  5719. PUBLIC void httpSetRouteIgnoreEncodingErrors(HttpRoute *route, bool on);
  5720. /**
  5721. Define the methods for the route
  5722. @description This defines the set of valid HTTP methods for requests to match this route
  5723. @param route Route to modify
  5724. @param methods Set to a comma or space separated list of methods. Can also set to "All" or "*" for all possible
  5725. methods. Typical methods include: "DELETE, GET, OPTIONS, POST, PUT, TRACE".
  5726. @ingroup HttpRoute
  5727. @stability Stable
  5728. */
  5729. PUBLIC void httpSetRouteMethods(HttpRoute *route, cchar *methods);
  5730. /**
  5731. Set the route session cookie
  5732. @param route Route to modify
  5733. @param cookie Session cookie name
  5734. @ingroup HttpRoute
  5735. @stability Stable
  5736. */
  5737. PUBLIC void httpSetRouteCookie(HttpRoute *route, cchar *cookie);
  5738. /**
  5739. Persist the cookie to disk
  5740. @description By default, browser session cookies are created so they are discarded when the browser exits.
  5741. If persistent cookies are created, they live despite browser restarts
  5742. @param route Route to modify
  5743. @param enable Set to true to enable
  5744. @ingroup HttpRoute
  5745. @stability Evolving
  5746. */
  5747. PUBLIC void httpSetRouteCookiePersist(HttpRoute *route, int enable);
  5748. /**
  5749. Set the session cookie SameSite property.
  5750. @param route Route to modify
  5751. @param value Set to "lax", "strict" or NULL/empty.
  5752. @ingroup HttpRoute
  5753. @stability Evolving
  5754. */
  5755. PUBLIC void httpSetRouteCookieSame(HttpRoute *route, cchar *value);
  5756. /**
  5757. Set the route pattern
  5758. @description This call defines the route regular expression pattern that is used to match against the request URI.
  5759. The route pattern is an enhanced JavaScript-compatibile regular expression. It is enhanced by optionally
  5760. embedding braced tokens "{name}" in the pattern. During request URI matching, these tokens are extracted and
  5761. defined in the request params and are available to the request. The normal regular expression repeat syntax
  5762. also uses "{}". To use the traditional (uncommon) repeat syntax, back quote with "\\".
  5763. Sub-expressions and token expressions are also available in various rules as numbered tokens "$1". For example:
  5764. the pattern "/app/(.*)(\.html)$" will permit a file target "$1.${request.Language=fr}.$2".
  5765. @param route Route to modify
  5766. @param pattern Route regular expression pattern
  5767. @param flags Set to HTTP_ROUTE_NOT to negate the pattern match result
  5768. @ingroup HttpRoute
  5769. @stability Stable
  5770. */
  5771. PUBLIC void httpSetRoutePattern(HttpRoute *route, cchar *pattern, int flags);
  5772. /**
  5773. Set the route prefix
  5774. @description Routes may have a prefix which will be stripped from the request URI if the request matches.
  5775. The prefix is made available as the "${request:prefix}" token and also as the ScriptName via some handlers.
  5776. @param route Route to modify
  5777. @param prefix URI prefix to define for the route.
  5778. @ingroup HttpRoute
  5779. @stability Stable
  5780. */
  5781. PUBLIC void httpSetRoutePrefix(HttpRoute *route, cchar *prefix);
  5782. /**
  5783. Set the route to preserve WebSocket frames boundaries
  5784. @description When enabled, the WebSocketFilter will not merge or fragment frames.
  5785. @param route Route to modify
  5786. @param on Set to true perserve frame boundaries
  5787. @ingroup HttpRoute
  5788. @stability Stable
  5789. */
  5790. PUBLIC void httpSetRoutePreserveFrames(HttpRoute *route, bool on);
  5791. /**
  5792. Control the renaming of uploaded filenames
  5793. @param route Route to modify
  5794. @param enable Set to true to enable renaming to the client specified filename. Renaming is disabled by default.
  5795. @ingroup HttpRoute
  5796. @stability Evolving
  5797. */
  5798. PUBLIC void httpSetRouteRenameUploads(HttpRoute *route, bool enable);
  5799. #if DEPRECATED
  5800. /**
  5801. Set the script to service the route.
  5802. @description This is used by handlers to add a per-route script for processing.
  5803. Either a literal script or a path to a script filename can be provided.
  5804. @param route Route to modify
  5805. @param script Literal script to execute.
  5806. @param scriptPath Pathname to the script file to execute
  5807. @ingroup HttpRoute
  5808. @stability Deprecated
  5809. @internal
  5810. */
  5811. PUBLIC void httpSetRouteScript(HttpRoute *route, cchar *script, cchar *scriptPath);
  5812. #endif
  5813. /**
  5814. Make session cookies that are visible to javascript.
  5815. @description If not visible, cookies will be created with httponly. This helps reduce the XSS risk as
  5816. Javascripts cannot read the session cookie.
  5817. @param route Route to modify
  5818. @param visible Set to true to create session cookies that are visible to Javascript.
  5819. @ingroup HttpRoute
  5820. @stability Evolving
  5821. */
  5822. PUBLIC void httpSetRouteSessionVisibility(HttpRoute *route, bool visible);
  5823. /**
  5824. Define whether to show errors to the client
  5825. @param route Route to modify
  5826. @param on Set to true to show errors to the client.
  5827. @ingroup HttpRoute
  5828. @stability Stable
  5829. */
  5830. PUBLIC void httpSetRouteShowErrors(HttpRoute *route, bool on);
  5831. /**
  5832. Set the source code module for the route
  5833. @description Some handlers can dynamically load web applications and services to serve requests.
  5834. @param route Route to modify
  5835. @param source Source path or description
  5836. @ingroup HttpRoute
  5837. @stability Stable
  5838. */
  5839. PUBLIC void httpSetRouteSource(HttpRoute *route, cchar *source);
  5840. /**
  5841. Set stealth mode for the route
  5842. @description Stealth mode tries to emit as little information as possible.
  5843. @param route Route to modify
  5844. @param on Set to True to enable stealth mode
  5845. @ingroup HttpRoute
  5846. @stability Stable
  5847. */
  5848. PUBLIC void httpSetRouteStealth(HttpRoute *route, bool on);
  5849. /**
  5850. Set a route target
  5851. @description This configures the route pipeline by defining a route target. The route target is interpreted by
  5852. the selected route handler to process the request.
  5853. Route targets can contain symbolic tokens that are expanded at run-time with their corresponding values. There are
  5854. three classes of tokens:
  5855. <ul>
  5856. <li>System and Route varibles - such as DOCUMENTS_DIR, HOME_DIR, BIN_DIR, PRODUCT, OS, VERSION.</li>
  5857. <li>Route URI tokens - these are the braced tokens in the route pattern.</li>
  5858. <li>Request fields - these are request state and property values.</li>
  5859. </ul>
  5860. System and URI tokens are of the form: "${token}" where "token" is the name of the variable or URI token.
  5861. Request fields are of the form: "${family:name=defaultValue}" where the family defines a set of values.
  5862. If the named field is not present, an optional default value "=defaultValue" will be used instead.
  5863. These supported request field families are:
  5864. <ul>
  5865. <li>header - for request HTTP header values</li>
  5866. <li>param - for request params</li>
  5867. <li>query - for request query field values</li>
  5868. <li>request - for request details</li>
  5869. <li>Any URI pattern token</li>
  5870. </ul>
  5871. For example: "run ${header:User-Agent}" to select the client's browser string passed in the HTTP headers.
  5872. For example: "run ${field:name}" to select the client's browser string passed in the HTTP headers.
  5873. For example: "run ${name}.html" where {name} was a token in the route pattern.
  5874. For example: "run ${name}.html" where {name} was a token in the route pattern.
  5875. The supported request key names are:
  5876. <ul>
  5877. <li>clientAddress - The client IP address</li>
  5878. <li>clientPort - The client port number</li>
  5879. <li>error - Any request or connection error message</li>
  5880. <li>ext - The request extension</li>
  5881. <li>extraPath - The request extra path after the script extension</li>
  5882. <li>filename - The mapped request filename in physical storage</li>
  5883. <li>language - The selected language for the request</li>
  5884. <li>languageDir - The langauge directory</li>
  5885. <li>host - The host name owning the route for the request</li>
  5886. <li>method - The request HTTP method</li>
  5887. <li>originalUri - The original, pre-decoded URI</li>
  5888. <li>pathInfo - The path portion of the URI after the host and port information</li>
  5889. <li>prefix - The route prefix</li>
  5890. <li>query - The request query information</li>
  5891. <li>reference - The request reference fragment. This is the URI portion after "#"</li>
  5892. <li>scheme - The request protocol scheme. E.g. "http"</li>
  5893. <li>scriptName - The request script or application name</li>
  5894. <li>serverAddress - The server IP address</li>
  5895. <li>serverPort - The server port number</li>
  5896. <li>uri - The full request URI. May be modified by routes, handlers and filters</li>
  5897. </ul>
  5898. Also see #httpMakePath for additional tokens (DOCUMENTS_DIR, HOME_DIR, BIN_DIR, PRODUCT, OS, VERSION).
  5899. @param route Route to modify
  5900. @param name Target rule to add. Supported update rules include:
  5901. "close", "redirect", "run" and "write".
  5902. \n\n
  5903. The "close" rule is used to do abortive closes for the request. This is useful for ward off known security attackers.
  5904. For example: "close immediate". The "close" rule takes no addition parameters.
  5905. \n\n
  5906. The "redirect" rule is used to redirect the request to a new resource. For example: "redirect 302 /tryAgain.html".
  5907. The "redirect" takes the form: "redirect status URI". The status code is used as the HTTP response
  5908. code. The URI can be a fully qualified URI beginning with "http" or it can be a relative URI.
  5909. \n\n
  5910. The "run" target is used to run the configured handler to respond to the request.
  5911. For example: "file ${DOCUMENTS}/${request.uri}.gz".
  5912. \n\n
  5913. The "write" rule is used to write literal data back to the client. For example: "write 200 Hello World\r\n".
  5914. The "write" rule takes the form: "write [-r] status message". Write data is by default HTML encoded to help
  5915. eliminate XSS security exposures. The "-r" option selects "raw" output and bypasses the HTML encoding of the
  5916. write data string.
  5917. \n\n
  5918. WARNING: Take great care when using raw writes with tokens. Write data is not HTML encoded and echoing back to
  5919. raw data to the client can cause XSS and other security issues.
  5920. The status field defines the HTTP status code to use in the response.
  5921. @param details Update rule parameters.
  5922. @return "Zero" if successful, otherwise a negative MPR error code.
  5923. @ingroup HttpRoute
  5924. @stability Stable
  5925. */
  5926. PUBLIC int httpSetRouteTarget(HttpRoute *route, cchar *name, cchar *details);
  5927. /**
  5928. Set the route template
  5929. @description Set the route URI template uses when constructing URIs via httpLink.
  5930. @param route Route to modify
  5931. @param tplate URI template to use. Templates may contain embedded tokens "{token}" where the token names correspond
  5932. to the token names in the route pattern.
  5933. @ingroup HttpRoute
  5934. @stability Stable
  5935. */
  5936. PUBLIC void httpSetRouteTemplate(HttpRoute *route, cchar *tplate);
  5937. /**
  5938. Define a route variable
  5939. @description This defines a route variable that will be used by #httpMakePath and route conditions,
  5940. updates, headers, fields and targets to expand tokenized expressions "${token}".
  5941. @param route Route to modify
  5942. @param token Name of the token to define
  5943. @param value Value of the token
  5944. @ingroup HttpRoute
  5945. @stability Stable
  5946. */
  5947. PUBLIC void httpSetRouteVar(HttpRoute *route, cchar *token, cchar *value);
  5948. /**
  5949. Define whether updating a cached request is required
  5950. @param route Route to modify
  5951. @param on Set to true to enable
  5952. @ingroup HttpRoute
  5953. @stability Evolving
  5954. */
  5955. PUBLIC void httpSetRouteUpdate(HttpRoute *route, bool on);
  5956. /**
  5957. Set the default upload directory for file uploads
  5958. @param route Route to modify
  5959. @param dir Directory path
  5960. @ingroup HttpRoute
  5961. @stability Evolving
  5962. */
  5963. PUBLIC void httpSetRouteUploadDir(HttpRoute *route, cchar *dir);
  5964. #if DEPRECATED
  5965. /**
  5966. Define the maximum number of workers for a route
  5967. @param route Route to modify
  5968. @param workers Maximum number of workers for this route
  5969. @ingroup HttpRoute
  5970. @stability Deprecated
  5971. @internal
  5972. */
  5973. PUBLIC void httpSetRouteWorkers(HttpRoute *route, int workers);
  5974. #endif
  5975. /**
  5976. Control whether an XSRF token will be emitted during a user login sequence.
  5977. @description The XSRF token is emitted in the HTTP response headers and may be used to match with a
  5978. session XSRF token to mitigate XSS security threats.
  5979. @param route Route to modify
  5980. @param enable Set to true to emit and XSRF header token
  5981. @ingroup HttpRoute
  5982. @stability Stable
  5983. */
  5984. PUBLIC void httpSetRouteXsrf(HttpRoute *route, bool enable);
  5985. /**
  5986. Expand a template string using given options
  5987. @description This expands a string with embedded tokens of the form "${token}" using values from the given options.
  5988. This routine also understands the leading aliases: "~" for the route prefix.
  5989. @param stream HttpStream stream object created via #httpCreateStream
  5990. @param tplate Template string to process
  5991. @param options Hash of option values for embedded tokens.
  5992. @ingroup HttpRoute
  5993. @stability Stable
  5994. */
  5995. PUBLIC char *httpTemplate(HttpStream *stream, cchar *tplate, MprHash *options);
  5996. /**
  5997. Tokenize a string based on route data
  5998. @description This is a utility routine to parse a string into tokens given a format specifier.
  5999. Mandatory tokens can be specified with "%" format specifier. Optional tokens are specified with "?" format.
  6000. Supported tokens:
  6001. <ul>
  6002. <li>%B - Boolean. Parses: on/off, true/false, yes/no.</li>
  6003. <li>%N - Number. Parses numbers in base 10.</li>
  6004. <li>%S - String. Removes quotes.</li>
  6005. <li>%P - Path string. Removes quotes and expands ${PathVars}. Resolved relative to host->dir (Home).</li>
  6006. <li>%W - Parse words into a list</li>
  6007. <li>%! - Optional negate. Set value to HTTP_ROUTE_NOT present, otherwise zero.</li>
  6008. </ul>
  6009. Values wrapped in quotes will have the outermost quotes trimmed.
  6010. @param route Route to modify
  6011. @param str String to expand
  6012. @param fmt Format string specifier
  6013. @return True if the string can be successfully parsed.
  6014. @ingroup HttpRoute
  6015. @stability Stable
  6016. */
  6017. PUBLIC bool httpTokenize(HttpRoute *route, cchar *str, cchar *fmt, ...);
  6018. /**
  6019. Tokenize a string based on route data
  6020. @description This is a utility routine to parse a string into tokens given a format specifier.
  6021. This call is similar to #httpTokenize but uses a va_list argument.
  6022. @param route Route to modify
  6023. @param str String to expand
  6024. @param fmt Format string specifier
  6025. @param args Varargs argument list
  6026. @return True if the string can be successfully parsed.
  6027. @ingroup HttpRoute
  6028. @stability Stable
  6029. */
  6030. PUBLIC bool httpTokenizev(HttpRoute *route, cchar *str, cchar *fmt, va_list args);
  6031. /*
  6032. Internal
  6033. */
  6034. PUBLIC int httpStartRoute(HttpRoute *route);
  6035. PUBLIC void httpStopRoute(HttpRoute *route);
  6036. PUBLIC char *httpExpandVars(HttpStream *stream, cchar *str);
  6037. /*********************************** Session ***************************************/
  6038. #define HTTP_SESSION_COOKIE "-http-session-" /**< Session cookie name */
  6039. #define HTTP_SESSION_USERNAME "__USERNAME__" /**< Username variable */
  6040. #define HTTP_SESSION_IP "__IP__" /**< Connection IP address - prevents session hijack */
  6041. /**
  6042. Session state object
  6043. @defgroup HttpSession HttpSession
  6044. @see httpAllocSession httpCreateSession httpDestroySession httpGetSession httpGetSessionObj
  6045. httpRemoveSessionVar httpGetSessionID httpSetSessionObj httpSetSessionVar
  6046. @stability Internal
  6047. */
  6048. typedef struct HttpSession {
  6049. char *id; /**< Session ID key */
  6050. MprCache *cache; /**< Cache store reference */
  6051. MprTicks lifespan; /**< Session inactivity timeout (msecs) */
  6052. MprHash *data; /**< Intermediate session data before writing to cache */
  6053. int dirty; /**< Session updated and needs saving */
  6054. int seqno; /**< Unique sequence number */
  6055. } HttpSession;
  6056. /**
  6057. Allocate a new session state object.
  6058. @param stream Http stream object
  6059. @param id Unique session state ID
  6060. @param lifespan Session lifespan in ticks
  6061. @return A session state object
  6062. @ingroup HttpSession
  6063. @stability Internal
  6064. */
  6065. PUBLIC HttpSession *httpAllocSession(HttpStream *stream, cchar *id, MprTicks lifespan);
  6066. /**
  6067. Create a session object.
  6068. @description This call creates a session object. If one already exists, it is destroyed and a fresh session
  6069. is created. Use httpGetSession to retrieve an existing session object.
  6070. @param stream Http stream object
  6071. @return A session state object
  6072. @ingroup HttpSession
  6073. @stability Internal
  6074. */
  6075. PUBLIC HttpSession *httpCreateSession(HttpStream *stream);
  6076. /**
  6077. Destroy a session state object.
  6078. This destroys a session. It will emit an expired cookie to force the client to remove the old session cookie.
  6079. @description
  6080. @param stream Http stream object.
  6081. @ingroup HttpSession
  6082. @stability Internal
  6083. */
  6084. PUBLIC void httpDestroySession(HttpStream *stream);
  6085. /**
  6086. Get a session state object.
  6087. This will optionally create a session if one does not already exist. It will not re-create a session that exists.
  6088. @description
  6089. @param stream Http stream object
  6090. @param create Set to "true" to create a session state object if one does not already exist for this client
  6091. @return A session state object
  6092. @ingroup HttpSession
  6093. @stability Stable
  6094. */
  6095. PUBLIC HttpSession *httpGetSession(HttpStream *stream, int create);
  6096. /**
  6097. Get the session ID.
  6098. @description
  6099. @param stream Http stream object
  6100. @return The session ID string
  6101. @ingroup HttpSession
  6102. @stability Stable
  6103. */
  6104. PUBLIC cchar *httpGetSessionID(HttpStream *stream);
  6105. /**
  6106. Get an object from the session state store.
  6107. @description Retrieve an object from the session state store by deserializing all properties.
  6108. @param stream Http stream object
  6109. @param key Session state key
  6110. @ingroup HttpSession
  6111. @stability Stable
  6112. */
  6113. PUBLIC MprHash *httpGetSessionObj(HttpStream *stream, cchar *key);
  6114. /**
  6115. Get a session state variable.
  6116. @param stream Http stream object
  6117. @param name Variable name to get
  6118. @param defaultValue If the variable does not exist, return the defaultValue.
  6119. @return The variable value or defaultValue if it does not exist.
  6120. @ingroup HttpSession
  6121. @stability Stable
  6122. */
  6123. PUBLIC cchar *httpGetSessionVar(HttpStream *stream, cchar *name, cchar *defaultValue);
  6124. /**
  6125. Lookup a session ID
  6126. @param id Session ID to lookup.
  6127. @return True if the ID is associated with a session
  6128. @ingroup HttpSession
  6129. @stability Stable
  6130. */
  6131. PUBLIC bool httpLookupSessionID(cchar *id);
  6132. /**
  6133. Remove a session state variable
  6134. @param stream Http stream object
  6135. @param name Variable name to remove
  6136. @return Zero if successful, otherwise a negative MPR error code.
  6137. @ingroup HttpSession
  6138. @stability Stable
  6139. */
  6140. PUBLIC int httpRemoveSessionVar(HttpStream *stream, cchar *name);
  6141. /**
  6142. Set a linked managed memory reference for a session.
  6143. @description When the session expires, the linked memory will be eligible for garbage collection.
  6144. This routine is useful to attach objects or memory to a session and have them be released together.
  6145. @param stream Http stream object
  6146. @param link Managed memory reference. May be NULL.
  6147. @ingroup MprCache
  6148. @stability Evolving
  6149. */
  6150. PUBLIC int httpSetCacheLink(HttpStream *stream, void *link);
  6151. /**
  6152. Set a notification callback to be invoked for session notification events.
  6153. WARNING: the callback may happen on any thread. Use careful locking to synchronize access to data. Take care
  6154. not to block the thread issuing the callback.
  6155. @param notifyProc MprCacheProc notification callback. Invoked for events of interest on cache items.
  6156. The event is set to MPR_CACHE_NOTIFY_REMOVE when items are removed from the cache. Invoked as:
  6157. \n\n
  6158. (*MprCacheProc)(MprCache *cache, cchar *key, cchar *data, int event);
  6159. @ingroup HttpSession
  6160. @stability Evolving
  6161. */
  6162. PUBLIC void httpSetSessionNotify(MprCacheProc notifyProc);
  6163. /**
  6164. Set an object into the session state store.
  6165. @description Store an object in the session state store by serializing all properties.
  6166. @param stream Http stream object
  6167. @param key Session state key
  6168. @param value Object to serialize. This must be an MprHash object.
  6169. @ingroup HttpSession
  6170. @stability Stable
  6171. */
  6172. PUBLIC int httpSetSessionObj(HttpStream *stream, cchar *key, MprHash *value);
  6173. /**
  6174. Set a session variable.
  6175. @description
  6176. @param stream Http stream object
  6177. @param name Variable name to set
  6178. @param value String variable value to use. This must point to a valid null terminated string.
  6179. @return A session state object
  6180. @ingroup HttpSession
  6181. @stability Stable
  6182. */
  6183. PUBLIC int httpSetSessionVar(HttpStream *stream, cchar *name, cchar *value);
  6184. /**
  6185. Write the session state to persistent data storage
  6186. @description This is called internally by the ESP handler at the completion of any processing.
  6187. @param stream Http stream object
  6188. @stability Evolving
  6189. @ingroup HttpSession
  6190. @internal
  6191. */
  6192. PUBLIC int httpWriteSession(HttpStream *stream);
  6193. /**
  6194. Check a security token.
  6195. @description Check the request security token against the security token defined in the session state.
  6196. @param stream Http stream object
  6197. @return True if the security token matches the session held token.
  6198. @ingroup HttpSession
  6199. @stability Stable
  6200. */
  6201. PUBLIC bool httpCheckSecurityToken(HttpStream *stream);
  6202. /**
  6203. Get a unique security token.
  6204. @description This will get an existing security token or create a new token if one does not exist.
  6205. If recreate is true, the security token will be recreated.
  6206. Use #httpAddSecurityToken to add the token to the response headers.
  6207. @param stream HttpStream stream object
  6208. @param recreate Set to true to recreate the security token.
  6209. @return The security token string
  6210. @ingroup HttpSession
  6211. @stability Stable
  6212. */
  6213. PUBLIC cchar *httpGetSecurityToken(HttpStream *stream, bool recreate);
  6214. /**
  6215. Add the security token to the response.
  6216. @description To minimize form replay attacks, a security token may be required for POST requests on a route.
  6217. This call will set a security token in the response as a response header and as a response cookie.
  6218. Client-side Javascript must then send this token as a request header in subsquent POST requests.
  6219. To configure a route to require security tokens, use #httpSetRouteXsrf.
  6220. @param stream Http stream object
  6221. @param recreate Set to true to recreate the security token.
  6222. @ingroup HttpSession
  6223. @stability Stable
  6224. */
  6225. PUBLIC int httpAddSecurityToken(HttpStream *stream, bool recreate);
  6226. /********************************** HttpUploadFile *********************************/
  6227. /**
  6228. Upload File
  6229. @description Each uploaded file has an HttpUploadedFile entry. This is managed by the upload handler.
  6230. @stability Stable
  6231. @defgroup HttpUploadFile HttpUploadFile
  6232. @see httpAddUploadFile httpRemoveAllUploadedFiles httpRemoveUploadFile
  6233. @stability Internal
  6234. */
  6235. typedef struct HttpUploadFile {
  6236. cchar *name; /**< Form field name */
  6237. cchar *filename; /**< Local (temp) name of the file */
  6238. cchar *clientFilename; /**< Client side name of the file */
  6239. cchar *contentType; /**< Content type */
  6240. ssize size; /**< Uploaded file size */
  6241. } HttpUploadFile;
  6242. /********************************** HttpRx *********************************/
  6243. /*
  6244. Rx flags
  6245. */
  6246. #define HTTP_DELETE 0x1 /**< DELETE method */
  6247. #define HTTP_GET 0x2 /**< GET method */
  6248. #define HTTP_HEAD 0x4 /**< HEAD method */
  6249. #define HTTP_OPTIONS 0x8 /**< OPTIONS method */
  6250. #define HTTP_POST 0x10 /**< Post method */
  6251. #define HTTP_PUT 0x20 /**< PUT method */
  6252. #define HTTP_TRACE 0x40 /**< TRACE method */
  6253. #define HTTP_CREATE_ENV 0x80 /**< Must create env for this request */
  6254. #define HTTP_IF_MODIFIED 0x100 /**< If-[un]modified-since supplied */
  6255. #define HTTP_CHUNKED 0x200 /**< Content is chunk encoded */
  6256. #define HTTP_ADDED_QUERY_PARAMS 0x400 /**< Query added to params */
  6257. #define HTTP_ADDED_BODY_PARAMS 0x800 /**< Body data added to params */
  6258. #define HTTP_EXPECT_CONTINUE 0x1000 /**< Client expects an HTTP 100 Continue response */
  6259. /*
  6260. Incoming chunk encoding states
  6261. */
  6262. #define HTTP_CHUNK_UNCHUNKED 0 /**< Data is not transfer-chunk encoded */
  6263. #define HTTP_CHUNK_START 1 /**< Start of a new chunk */
  6264. #define HTTP_CHUNK_DATA 2 /**< Start of chunk data */
  6265. #define HTTP_CHUNK_EOF 3 /**< End of last chunk */
  6266. /**
  6267. Http Rx
  6268. @description Most of the APIs in the rx group still take a HttpStream object as their first parameter. This is
  6269. to make the API easier to remember - APIs take a stream object rather than a rx or tx object.
  6270. @defgroup HttpRx HttpRx
  6271. @see HttpStream HttpRx HttpTx httpAddBodyVars httpAddParamsFromBuf httpContentNotModified
  6272. httpCreateCGIParams httpGetContentLength httpGetCookies httpGetParam httpGetParams httpGetHeader
  6273. httpGetHeaderHash httpGetHeaders httpGetIntParam httpGetLanguage httpGetQueryString httpGetReadCount httpGetStatus
  6274. httpGetStatusMessage httpMatchParam httpRead httpReadString httpSetParam httpSetIntParam httpSetUri
  6275. httpTestParam httpTrimExtraPath
  6276. @stability Internal
  6277. */
  6278. typedef struct HttpRx {
  6279. /* Ordered for debugging */
  6280. cchar *method; /**< Request method */
  6281. cchar *uri; /**< Current URI (not decoded, may be rewritten) */
  6282. cchar *pathInfo; /**< Path information after the scriptName (Decoded and normalized) */
  6283. cchar *scriptName; /**< ScriptName portion of the uri (Decoded). May be empty or start with "/" */
  6284. cchar *extraPath; /**< Extra path information (CGI|PHP) */
  6285. MprOff bytesUploaded; /**< Length of uploaded content by user */
  6286. MprOff bytesRead; /**< Length of content read by user (includes bytesUloaded) */
  6287. MprOff length; /**< Content length header value (ENV: CONTENT_LENGTH) */
  6288. MprOff remainingContent; /**< Remaining content data to read (in next chunk if chunked) */
  6289. MprOff dataFrameLength; /**< Size of HTTP/2 data frames read */
  6290. MprOff http2ContentLength; /**< Pre-parsed content-length header for http/2 */
  6291. HttpStream *stream; /**< HttpStream object */
  6292. HttpRoute *route; /**< Route for request */
  6293. HttpSession *session; /**< Session for request */
  6294. cchar *traceId; /**< Request trace id */
  6295. int seqno; /**< Unique request sequence number */
  6296. MprList *etags; /**< Document etag to uniquely identify the document version */
  6297. MprList *files; /**< List of uploaded files (HttpUploadFile objects) */
  6298. HttpPacket *headerPacket; /**< HTTP headers */
  6299. MprHash *headers; /**< Header variables */
  6300. MprList *inputPipeline; /**< Input processing */
  6301. HttpUri *parsedUri; /**< Parsed request uri */
  6302. MprHash *requestData; /**< General request data storage. Set via #httpSetStageData */
  6303. MprTime since; /**< If-Modified date */
  6304. int chunkState; /**< Chunk encoding state */
  6305. int flags; /**< Rx modifiers */
  6306. bool authenticateProbed: 1; /**< Request has been authenticated */
  6307. bool authenticated: 1; /**< Request has been authenticated */
  6308. bool autoDelete: 1; /**< Automatically delete uploaded files */
  6309. bool endStream: 1; /**< HTTP/2 end of input stream */
  6310. bool eof: 1; /**< All read data has been received by the protocol layer (http*Filter) */
  6311. bool errorDoc: 1; /**< Processing an error document */
  6312. bool form: 1; /**< Using mime-type application/x-www-form-urlencoded */
  6313. bool ifModified: 1; /**< If-Modified processing requested */
  6314. bool ifMatch: 1; /**< If-Match processing requested */
  6315. bool inputEnded: 1; /**< End packet appended to input stream */
  6316. bool json: 1; /**< Using a JSON body */
  6317. bool needInputPipeline: 1; /**< Input pipeline required to process received data */
  6318. bool ownParams: 1; /**< Do own parameter handling */
  6319. bool renameUploads: 1; /**< Rename uploaded files to the client specified filename */
  6320. bool seenRegularHeader: 1; /**< Seen a regular HTTP/2 header (non pseudo) */
  6321. bool sessionProbed: 1; /**< Session has been resolved */
  6322. bool streaming: 1; /**< Stream incoming content. Forms typically buffer and dont stream */
  6323. bool upload: 1; /**< Request is using file upload */
  6324. /*
  6325. Incoming response line if a client request
  6326. */
  6327. int status; /**< HTTP response status */
  6328. cchar *statusMessage; /**< HTTP Response status message */
  6329. /*
  6330. Header values
  6331. */
  6332. cchar *accept; /**< Accept header */
  6333. cchar *acceptCharset; /**< Accept-Charset header */
  6334. cchar *acceptEncoding; /**< Accept-Encoding header */
  6335. cchar *acceptLanguage; /**< Accept-Language header */
  6336. cchar *authDetails; /**< Header details: authorization|www-authenticate provided by peer */
  6337. cchar *authType; /**< Type of authentication: set to basic, digest, post or a custom name */
  6338. cchar *cookie; /**< Cookie header - may contain many cookies */
  6339. cchar *connection; /**< Connection header */
  6340. cchar *contentLength; /**< Content length string value */
  6341. cchar *hostHeader; /**< Client supplied host name header */
  6342. cchar *mimeType; /**< Mime type of the request payload (ENV: CONTENT_TYPE) */
  6343. cchar *originalMethod; /**< Original method from the client */
  6344. cchar *origin; /**< Origin header (not used) */
  6345. cchar *originalUri; /**< Original URI passed by the client */
  6346. cchar *paramString; /**< Cached param data as a string */
  6347. cchar *pragma; /**< Pragma header */
  6348. char *protocol; /**< Request protocol: HTTP/1.0 or HTTP/1.1 */
  6349. cchar *passwordDigest; /**< User password digest for authentication */
  6350. cchar *redirect; /**< Redirect route header */
  6351. cchar *referrer; /**< Refering URL */
  6352. cchar *securityToken; /**< Security form token */
  6353. cchar *scheme; /**< HTTP/2 request scheme */
  6354. cchar *upgrade; /**< Protocol upgrade header */
  6355. cchar *userAgent; /**< User-Agent header */
  6356. HttpLang *lang; /**< Selected language */
  6357. MprJson *params; /**< Request params (Query and post data variables) */
  6358. MprHash *svars; /**< Server variables */
  6359. HttpRange *inputRange; /**< Specified range for rx (post) data */
  6360. struct HttpWebSocket *webSocket; /**< WebSocket state */
  6361. /*
  6362. Routing info
  6363. */
  6364. char *target; /**< Route target */
  6365. int matches[ME_MAX_ROUTE_MATCHES * 2];
  6366. int matchCount;
  6367. } HttpRx;
  6368. /**
  6369. Add parameters from the request query string.
  6370. @description This adds query data to the request params
  6371. @param stream HttpStream stream object
  6372. @ingroup HttpRx
  6373. @stability Internal
  6374. @internal
  6375. */
  6376. PUBLIC void httpAddQueryParams(HttpStream *stream);
  6377. /**
  6378. Add parameters from the request body content.
  6379. @description This adds query data to the request params
  6380. @param stream HttpStream stream object
  6381. @return Zero if successful, otherwise a negative MPR error code.
  6382. @ingroup HttpRx
  6383. @stability Internal
  6384. @internal
  6385. */
  6386. PUBLIC int httpAddBodyParams(HttpStream *stream);
  6387. /**
  6388. Add parameters from a JSON body.
  6389. @description This adds query data and posted body data to the request params
  6390. @param stream HttpStream stream object
  6391. @ingroup HttpRx
  6392. @stability Internal
  6393. @internal
  6394. */
  6395. PUBLIC void httpAddJsonParams(HttpStream *stream);
  6396. /**
  6397. Test if the content has not been modified
  6398. @description This call tests if the file content to be served has been modified since the client last
  6399. requested this resource. The client must provide an Etag and Since or If-Modified headers.
  6400. @param stream HttpStream stream object
  6401. @return True if the content is current and has not been modified.
  6402. @ingroup HttpRx
  6403. @stability Stable
  6404. */
  6405. PUBLIC bool httpContentNotModified(HttpStream *stream);
  6406. /**
  6407. Create CGI parameters
  6408. @description This call creates request params corresponding to the standard CGI/1.1 environment variables.
  6409. This is used by the CGI and PHP handlers. It may also be useful to handlers that wish to expose CGI style
  6410. environment variables through the form vars interface.
  6411. @param stream HttpStream stream object
  6412. @ingroup HttpRx
  6413. @stability Stable
  6414. */
  6415. PUBLIC void httpCreateCGIParams(HttpStream *stream);
  6416. /**
  6417. Get the receive body content length
  6418. @description Get the length of the receive body content (if any). This is used in servers to get the length of posted
  6419. data and in clients to get the response body length.
  6420. @param stream HttpStream stream object created via #httpCreateStream
  6421. @return A count of the response content data in bytes.
  6422. @ingroup HttpRx
  6423. @stability Stable
  6424. */
  6425. PUBLIC MprOff httpGetContentLength(HttpStream *stream);
  6426. /**
  6427. Get a request cookie
  6428. @description Get a request cookie by name
  6429. @param stream HttpStream stream object created via #httpCreateStream
  6430. @param name Name of cookie retrieve
  6431. @return Return the cookie value. Return null if the cookie is not defined.
  6432. @ingroup HttpRx
  6433. @stability Stable
  6434. */
  6435. PUBLIC cchar *httpGetCookie(HttpStream *stream, cchar *name);
  6436. /**
  6437. Get the request cookies
  6438. @description Get the cookies defined in the current requeset
  6439. @param stream HttpStream stream object created via #httpCreateStream
  6440. @return Return a string containing the cookies sent in the Http header of the last request.
  6441. Return null if there are not cookies defined.
  6442. @ingroup HttpRx
  6443. @stability Stable
  6444. */
  6445. PUBLIC cchar *httpGetCookies(HttpStream *stream);
  6446. /**
  6447. Get a request param
  6448. @description Get the value of a named request param. Request parameters are define via POST data or
  6449. www-urlencoded query data.
  6450. @param stream HttpStream stream object
  6451. @param var Name of the request param to retrieve
  6452. @param defaultValue Default value to return if the variable is not defined. Can be null.
  6453. @return String containing a reference to the the request param's value. Caller should not mutate this value.
  6454. Returns defaultValue if not defined.
  6455. @ingroup HttpRx
  6456. @stability Stable
  6457. */
  6458. PUBLIC cchar *httpGetParam(HttpStream *stream, cchar *var, cchar *defaultValue);
  6459. /**
  6460. Get a request parm as an integer
  6461. @description Get the value of a named form variable as an integer. Request parameters are define via
  6462. www-urlencoded query or post data contained in the request and route parameters.
  6463. @param stream HttpStream stream object
  6464. @param var Name of the parameter to retrieve
  6465. @param defaultValue Default value to return if the variable is not defined. Can be null.
  6466. @return Integer containing the parameter variable's value
  6467. @ingroup HttpRx
  6468. @stability Stable
  6469. */
  6470. PUBLIC int httpGetIntParam(HttpStream *stream, cchar *var, int defaultValue);
  6471. /**
  6472. Get a parameter as a JSON object
  6473. @description Get a JSON subtree for a named parameter from the request parameters. Request parameters are define via
  6474. www-urlencoded query, post data contained in the request or route parameters.
  6475. @param stream HttpStream stream object
  6476. @param var Name of the parameter to retrieve
  6477. @return JSON object containing the selected subtree.
  6478. @ingroup HttpRx
  6479. @stability Stable
  6480. */
  6481. PUBLIC MprJson *httpGetParamObj(HttpStream *stream, cchar *var);
  6482. /**
  6483. Get the request params table
  6484. @description This call gets the form var table for the current request.
  6485. Query data and www-url encoded form data is entered into the table after decoding.
  6486. Use #mprLookupKey to retrieve data from the table.
  6487. @param stream HttpStream stream object
  6488. @return MprJson JSON object instance containing the form vars
  6489. @ingroup HttpRx
  6490. @stability Stable
  6491. */
  6492. PUBLIC MprJson *httpGetParams(HttpStream *stream);
  6493. /**
  6494. Get the request params table as a string
  6495. @description This call gets the request params encoded as a string. The params are always in the same order
  6496. regardless of the form parameter order. Request parameters include query parameters, form data and routing
  6497. parameters.
  6498. @param stream HttpStream stream object
  6499. @return A string representation in www-urlencoded format.
  6500. @ingroup HttpRx
  6501. @stability Stable
  6502. */
  6503. PUBLIC cchar *httpGetParamsString(HttpStream *stream);
  6504. /**
  6505. Get an rx http header.
  6506. @description Get a http request header value for a given header key.
  6507. @param stream HttpStream stream object created via #httpCreateStream
  6508. @param key Name of the header to retrieve.
  6509. @return Value associated with the header key or null if the key did not exist in the request.
  6510. @ingroup HttpRx
  6511. @stability Stable
  6512. */
  6513. PUBLIC cchar *httpGetHeader(HttpStream *stream, cchar *key);
  6514. /**
  6515. Get the hash table of rx Http headers
  6516. @description Get the internal hash table of rx headers
  6517. @param stream HttpStream stream object created via #httpCreateStream
  6518. @return Hash table. See MprHash for how to access the hash table.
  6519. @ingroup HttpRx
  6520. @stability Stable
  6521. */
  6522. PUBLIC MprHash *httpGetHeaderHash(HttpStream *stream);
  6523. /**
  6524. Get all the request http headers.
  6525. @description Get all the rx headers. The returned string formats all the headers in the form:
  6526. key: value\\nkey2: value2\\n...
  6527. @param stream HttpStream stream object created via #httpCreateStream
  6528. @return String containing all the headers. The caller must free this returned string.
  6529. @ingroup HttpRx
  6530. @stability Stable
  6531. */
  6532. PUBLIC char *httpGetHeaders(HttpStream *stream);
  6533. /**
  6534. Get a header string from the given hash.
  6535. @description This returns a set of "key: value" lines in HTTP header format.
  6536. @param hash Hash table to examine
  6537. @ingroup HttpRx
  6538. @stability Internal
  6539. @internal
  6540. */
  6541. PUBLIC char *httpGetHeadersFromHash(MprHash *hash);
  6542. /**
  6543. Get the language to use for the request
  6544. @description This call tests if the file content to be served has been modified since the client last
  6545. requested this resource. The client must provide an Etag and Since or If-Modified headers.
  6546. @param stream HttpStream stream object
  6547. @param spoken Hash table of HttpLang records. This is typically route->languages.
  6548. @param defaultLang Default language to use if none specified in the request Accept-Language header.
  6549. @return A HttpLang reference, or null if no language requested or no language found in the spoken table.
  6550. @ingroup HttpRx
  6551. @stability Stable
  6552. */
  6553. PUBLIC HttpLang *httpGetLanguage(HttpStream *stream, MprHash *spoken, cchar *defaultLang);
  6554. /**
  6555. Get a path extension
  6556. @param path File pathname to examine
  6557. @return The path extension sans "."
  6558. @ingroup HttpRx
  6559. @stability Stable
  6560. */
  6561. PUBLIC char *httpGetPathExt(cchar *path);
  6562. /**
  6563. Get the request query string
  6564. @description Get query string sent with the current request.
  6565. @param stream HttpStream stream object
  6566. @return String containing a reference to the request query string. Caller should not mutate this value.
  6567. @ingroup HttpRx
  6568. @stability Stable
  6569. */
  6570. PUBLIC cchar *httpGetQueryString(HttpStream *stream);
  6571. /**
  6572. Get the number of bytes that can be read from the read queue
  6573. @param stream HttpStream stream object
  6574. @return The number of bytes available in the read queue for the connection
  6575. @ingroup HttpRx
  6576. @stability Stable
  6577. */
  6578. PUBLIC ssize httpGetReadCount(HttpStream *stream);
  6579. /**
  6580. Get the response status
  6581. @param stream HttpStream stream object created via #httpCreateStream
  6582. @return An integer Http response code. Typically 200 is success.
  6583. @ingroup HttpRx
  6584. @stability Stable
  6585. */
  6586. PUBLIC int httpGetStatus(HttpStream *stream);
  6587. /**
  6588. Get the Http response status message. The Http status message is supplied on the first line of the Http response.
  6589. @param stream HttpStream stream object created via #httpCreateStream
  6590. @returns A Http status message.
  6591. @ingroup HttpRx
  6592. @stability Stable
  6593. */
  6594. PUBLIC cchar *httpGetStatusMessage(HttpStream *stream);
  6595. /**
  6596. Match a form variable with an expected value
  6597. @description Compare a form variable and return true if it exists and its value matches.
  6598. @param stream HttpStream stream object
  6599. @param var Name of the form variable
  6600. @param expected Expected value to match with
  6601. @return True if the value matches
  6602. @ingroup HttpRx
  6603. @stability Stable
  6604. */
  6605. PUBLIC bool httpMatchParam(HttpStream *stream, cchar *var, cchar *expected);
  6606. /**
  6607. Read rx body data.
  6608. @description This routine will read body data from the connection read queue (HttpStream.readq) which is at the head
  6609. of the response pipeline.
  6610. \n\n
  6611. This call will block depending on whether the connection is in async or sync mode. Sync mode is
  6612. the default for client connections and async for server connections.
  6613. \n\n
  6614. If in sync mode, this call may block to wait for data. If in async mode, the call will not block and will
  6615. return with whatever data is available.
  6616. \n\n
  6617. In sync mode, this routine may invoke mprYield before blocking to consent for the garbage collector to run. Callers must
  6618. ensure they have retained all required temporary memory before invoking this routine.
  6619. \n\n
  6620. This call will block for at most the timeout specified by the connection inactivity timeout defined in
  6621. HttpStream.limits.inactivityTimeout. Use #httpSetTimeout to change the timeout value.
  6622. \n\n
  6623. Server applications often prefer to access packets directly from the connection readq which offers a higher performance
  6624. interface.
  6625. @param stream HttpStream stream object created via #httpCreateStream
  6626. @param buffer Buffer to receive read data
  6627. @param size Size of buffer.
  6628. @return The number of bytes read. Returns zero for not data. EOF can be detected by testing #httpIsEof.
  6629. @ingroup HttpRx
  6630. @stability Stable
  6631. */
  6632. PUBLIC ssize httpRead(HttpStream *stream, char *buffer, ssize size);
  6633. /**
  6634. Read a block of rx body data.
  6635. @description This routine will read body data and provide control over blocking and call duration.
  6636. \n\n
  6637. If in blocking mode (the default for client connections), this call may block to wait for data. If in non-blocking
  6638. mode (the default for server connections), the call will not block and will return with whatever data is available.
  6639. The blocking mode is set via the flags parameter.
  6640. \n\n
  6641. In blocking mode, this routine may invoke mprYield before blocking to consent for the garbage collector to run.
  6642. Callers must ensure they have retained all required temporary memory before invoking this routine.
  6643. \n\n
  6644. This call will block for at most the timeout specified by the connection inactivity timeout defined in
  6645. HttpStream.limits.inactivityTimeout. Use #httpSetTimeout to change the timeout value.
  6646. \n\n
  6647. Server applications should not call httpReadBlock in blocking mode as it will consume a valuable thread.
  6648. Rather, server apps should perform non-blocking reads or access packets directly from the connection readq
  6649. which offers a higher performance interface.
  6650. @param stream HttpStream stream object created via #httpCreateStream
  6651. @param buffer Buffer to receive read data
  6652. @param size Size of buffer.
  6653. @param timeout Timeout in milliseconds to wait. Set to -1 to use the default inactivity timeout. Set to zero
  6654. to wait forever.
  6655. @param flags Set to HTTP_BLOCK to wait for data before returning. Set to HTTP_NON_BLOCK to read what is
  6656. available and return without blocking. If set to zero, it will default to HTTP_BLOCK for sync connections
  6657. and HTTP_NON_BLOCK for async connections.
  6658. @return The number of bytes read. Returns zero for not data. EOF can be detected by testing #httpIsEof.
  6659. @ingroup HttpRx
  6660. @stability Evolving
  6661. */
  6662. PUBLIC ssize httpReadBlock(HttpStream *stream, char *buffer, ssize size, MprTicks timeout, int flags);
  6663. /**
  6664. Get the receive body input
  6665. @description This will return all the body input. The request must have received all input (rx->eof == 1) and
  6666. must not be streaming (rx->streaming).
  6667. @param stream HttpStream stream object created via #httpCreateStream
  6668. @return A string containing the body input.
  6669. @stability Evolving
  6670. */
  6671. PUBLIC cchar *httpGetBodyInput(HttpStream *stream);
  6672. /**
  6673. Read response data as a string. This will read all rx body and return a string that the caller should free.
  6674. This will block and should not be used in async mode.
  6675. @param stream HttpStream stream object created via #httpCreateStream
  6676. @returns A string containing the rx body.
  6677. @ingroup HttpRx
  6678. @stability Stable
  6679. */
  6680. PUBLIC char *httpReadString(HttpStream *stream);
  6681. /**
  6682. Remove a request param
  6683. @description Remove the value of a named request param.
  6684. @param stream HttpStream stream object
  6685. @param var Name of the request param to retrieve
  6686. @ingroup HttpRx
  6687. @stability Stable
  6688. */
  6689. PUBLIC void httpRemoveParam(HttpStream *stream, cchar *var);
  6690. /**
  6691. Set the HttpRx eof condition
  6692. @description This routine should be called rather than setting HttpRx.eof manually. This is because it will advance
  6693. the HttpStream state to HTTP_STATE_FINALIZED if the request and connector have been finalized.
  6694. @param stream HttpStream stream object
  6695. @ingroup HttpRx
  6696. @stability Stable
  6697. */
  6698. PUBLIC void httpSetEof(HttpStream *stream);
  6699. /**
  6700. Set a request param value
  6701. @description Set the value of a named request param to a string value. Request parameters are define via
  6702. www-urlencoded query or post data contained in the request and route parameters.
  6703. @param stream HttpStream stream object
  6704. @param var Name of the request param to retrieve
  6705. @param value Default value to return if the variable is not defined. Can be null.
  6706. @ingroup HttpRx
  6707. @stability Stable
  6708. */
  6709. PUBLIC void httpSetParam(HttpStream *stream, cchar *var, cchar *value);
  6710. /**
  6711. Set an integer request param value
  6712. @description Set the value of a named request param to an integer value. Request parameters are define via
  6713. www-urlencoded query or post data contained in the request and route parameters.
  6714. @param stream HttpStream stream object
  6715. @param var Name of the request param to retrieve
  6716. @param value Default value to return if the variable is not defined. Can be null.
  6717. @ingroup HttpRx
  6718. @stability Stable
  6719. */
  6720. PUBLIC void httpSetIntParam(HttpStream *stream, cchar *var, int value);
  6721. /**
  6722. Set a new HTTP method for processing
  6723. @description This modifies the request method to alter request processing. The original method is preserved in
  6724. the HttpRx.originalMethod field. This is only useful to do before request routing has matched a route.
  6725. @param stream HttpStream stream object
  6726. @param method New method to use.
  6727. @ingroup HttpRx
  6728. @stability Stable
  6729. */
  6730. PUBLIC void httpSetMethod(HttpStream *stream, cchar *method);
  6731. /**
  6732. Define a request completion callback
  6733. @description This callback is invoked when the request is completed.
  6734. @param callback The callback is invoked with the signature: void callback(HttpStream *stream).
  6735. @ingroup HttpRx
  6736. @stability Evolving
  6737. */
  6738. PUBLIC void httpSetRequestCallback(HttpRequestCallback callback);
  6739. /**
  6740. Set a new URI for processing
  6741. @description This modifies the request URI to alter request processing. The original URI is preserved in
  6742. the HttpRx.originalUri field. This is only useful to do before request routing has matched a route.
  6743. @param stream HttpStream stream object
  6744. @param uri New URI to use. The URI can be fully qualified starting with a scheme ("http") or it can be
  6745. a partial/relative URI. Missing portions of the URI will be completed with equivalent portions from the
  6746. current URI. For example: if the current request URI was http://example.com:7777/index.html, then
  6747. a call to httpSetUri(stream, "/new.html", 0) will set the request URI to http://example.com:7777/new.html.
  6748. The request script name will be reset and the pathInfo will be set to the path portion of the URI.
  6749. @return "Zero" if successful, otherwise a negative MPR error code.
  6750. @ingroup HttpRx
  6751. @stability Stable
  6752. */
  6753. PUBLIC int httpSetUri(HttpStream *stream, cchar *uri);
  6754. /**
  6755. Test if a request param is defined
  6756. @param stream HttpStream stream object
  6757. @param var Name of the request param to retrieve
  6758. @return True if the request param is defined
  6759. @ingroup HttpRx
  6760. @stability Stable
  6761. */
  6762. PUBLIC int httpTestParam(HttpStream *stream, cchar *var);
  6763. /**
  6764. Trim extra path from the URI
  6765. @description This call trims extra path information after the uri extension. This is used by CGI and PHP.
  6766. The strategy is to heuristically find the script name in the uri. This is assumed to be the original uri
  6767. up to and including first path component containing a "." Any path information after that is regarded as
  6768. extra path. WARNING: Extra path is an old, unreliable, CGI specific technique. Do not use directories
  6769. with embedded periods.
  6770. @param stream HttpStream stream object
  6771. @ingroup HttpRx
  6772. @stability Stable
  6773. */
  6774. PUBLIC void httpTrimExtraPath(HttpStream *stream);
  6775. /**
  6776. Process http content
  6777. @description This will change the http state to HTTP_STATE_READY if all the body content has been received.
  6778. @param stream HttpStream Stream object
  6779. @ingroup HttpRx
  6780. @stability Evolving
  6781. */
  6782. PUBLIC int httpProcessContent(HttpStream *stream);
  6783. /**
  6784. Process Http headers
  6785. @description the httpProcessHeaders function drives the HTTP request and response state machine. Once a request is received from the peer and the HTTP headers have been parsed into HttpStream and HttpTx, the httpProcessHeaders() function should be called to drive parse the headers fields.
  6786. \n\n
  6787. The HTTP state machine should be in the HTTP_STATE_FIRST state. This routine will advance the state to HTTP_STATE_PARSED.
  6788. \n\n
  6789. httpProcessHeaders is invoked by the HTTP/1 and HTTP/2 filters after they have decoded input packets and whenever the network socket becomes newly writable and can absorb more output data.
  6790. @param q HttpQueue queue object
  6791. @ingroup HttpRx
  6792. @stability Evolving
  6793. */
  6794. PUBLIC bool httpProcessHeaders(HttpQueue *q);
  6795. /* Internal */
  6796. PUBLIC void httpCloseRx(struct HttpStream *stream);
  6797. PUBLIC HttpRange *httpCreateRange(HttpStream *stream, MprOff start, MprOff end);
  6798. PUBLIC HttpRx *httpCreateRx(HttpStream *stream);
  6799. PUBLIC void httpDestroyRx(HttpRx *rx);
  6800. PUBLIC bool httpMatchEtag(HttpStream *stream, char *requestedEtag);
  6801. PUBLIC bool httpMatchModified(HttpStream *stream, MprTime time);
  6802. PUBLIC bool httpProcessCompletion(HttpStream *stream);
  6803. PUBLIC int httpProcessState(HttpQueue *q);
  6804. PUBLIC void httpProcessWriteEvent(HttpStream *stream);
  6805. /********************************** HttpTx *********************************/
  6806. /*
  6807. Tx flags
  6808. */
  6809. #define HTTP_TX_NO_BODY 0x1 /**< No transmission body, only send headers */
  6810. #define HTTP_TX_HEADERS_CREATED 0x2 /**< Tx headers have been created */
  6811. #define HTTP_TX_USE_OWN_HEADERS 0x8 /**< Skip adding default headers */
  6812. #define HTTP_TX_NO_CHECK 0x10 /**< Do not check if the filename is inside the route documents directory */
  6813. #define HTTP_TX_NO_LENGTH 0x20 /**< Do not emit a content length (used for TRACE) */
  6814. #define HTTP_TX_NO_MAP 0x40 /**< Do not map the filename to compressed or minified alternatives */
  6815. #define HTTP_TX_PIPELINE 0x80 /**< Created Tx pipeline */
  6816. #define HTTP_TX_HAS_FILTERS 0x100 /**< Has output filters */
  6817. #define HTTP_TX_HEADERS_PREPARED 0x200 /**< Tx headers have been created */
  6818. /**
  6819. Http Tx
  6820. @description The tx object controls the transmission of data. This may be client requests or responses to
  6821. client requests. Most of the APIs in the Response group still take a HttpStream object as their first parameter.
  6822. This is to make the API easier to remember - APIs take a stream object rather than a rx or
  6823. transmission object.
  6824. @defgroup HttpTx HttpTx
  6825. @see HttpStream HttpRx HttpTx httpAddHeader httpAddHeaderString httpAppendHeader httpAppendHeaderString httpFinalize
  6826. httpConnect httpCreateTx httpDestroyTx httpFinalize httpFlush httpFollowRedirects httpFormatBody httpFormatError
  6827. httpFormatErrorV httpFormatResponse httpFormatResponseBody httpFormatResponsev httpGetQueueData
  6828. httpIsChunked httpIsComplete httpIsOutputFinalized httpNeedRetry httpOmitBody httpRedirect httpRemoveHeader
  6829. httpSetContentLength httpSetContentType httpSetCookie httpSetHeader httpSetHeaderString
  6830. httpSetResponded httpSetStatus httpWait httpWriteHeaders httpWriteUploadData
  6831. @stability Internal
  6832. */
  6833. typedef struct HttpTx {
  6834. /* Ordered for debugging */
  6835. HttpUri *parsedUri; /**< Client request uri */
  6836. cchar *filename; /**< Name of a real file being served (typically pathInfo mapped) */
  6837. int status; /**< HTTP response status */
  6838. bool allDataSent:1; /**< Processed the last data packet */
  6839. bool finalized:1; /**< Request response generated and handler processing is complete */
  6840. bool finalizedConnector:1; /**< Connector has finished sending the response */
  6841. bool finalizedInput:1; /**< Handler has finished processing all input */
  6842. bool finalizedOutput:1; /**< Handler or surrogate has finished writing output */
  6843. bool needChunking:1; /**< Use chunk encoding */
  6844. bool pendingFinalize:1; /**< Call httpFinalize again once the Tx pipeline is created */
  6845. bool putEndPacket:1; /**< Handler has manually put the END package (httpFinalizeOutput to skip) */
  6846. bool responded:1; /**< The handler has started to respond. Some output has been initiated. */
  6847. bool startedHeader: 1; /**< Already started sending at least one header packet in the output queue */
  6848. bool started:1; /**< Handler has been started */
  6849. uint flags:16; /**< Response flags */
  6850. MprOff bytesWritten; /**< Bytes written including headers */
  6851. ssize chunkSize; /**< Chunk size to use when using transfer encoding. Zero for unchunked. */
  6852. struct HttpStream *stream; /**< Current HttpStream object */
  6853. MprList *outputPipeline; /**< Output processing */
  6854. HttpStage *connector; /**< Network connector to send / receive socket data */
  6855. MprHash *cookies; /**< Browser cookies */
  6856. MprHash *headers; /**< Transmission headers */
  6857. HttpCache *cache; /**< Cache control entry (only set if this request is being cached) */
  6858. MprBuf *cacheBuffer; /**< Response caching buffer */
  6859. ssize cacheBufferLength; /**< Current size of the cache buffer data */
  6860. cchar *cachedContent; /**< Retrieved cached response to send */
  6861. MprOff entityLength; /**< Original content length before range subsetting */
  6862. cchar *errorDocument; /**< Error document to render */
  6863. cchar *ext; /**< Filename extension */
  6864. char *etag; /**< Unique identifier tag */
  6865. HttpStage *handler; /**< Final handler serving the request */
  6866. MprOff length; /**< Transmission content length */
  6867. cchar *method; /**< Client request method GET, HEAD, POST, DELETE, OPTIONS, PUT, TRACE */
  6868. cchar *mimeType; /**< Mime type of the request payload */
  6869. cchar *charSet; /**< Character set to use with the Content-Type */
  6870. uint simplePipeline; /**< Output pipeline doesn't use custom filters or HTTP/2, SSL or ranges */
  6871. /*
  6872. Range fields
  6873. */
  6874. HttpRange *outputRanges; /**< Data ranges for tx data */
  6875. HttpRange *currentRange; /**< Current range being fullfilled */
  6876. char *rangeBoundary; /**< Inter-range boundary */
  6877. MprOff rangePos; /**< Current range I/O position in response data */
  6878. MprOff filePos; /**< Position in file */
  6879. cchar *altBody; /**< Alternate transmission for errors */
  6880. int traceMethods; /**< Handler methods supported */
  6881. /* File information for file-based handlers */
  6882. MprFile *file; /**< File to be served */
  6883. MprPath fileInfo; /**< File information if there is a real file to serve */
  6884. ssize headerSize; /**< Size of the header written */
  6885. char *webSockKey; /**< Sec-WebSocket-Key header */
  6886. } HttpTx;
  6887. /**
  6888. Add a header to the transmission using a format string.
  6889. @description Add a header if it does not already exits.
  6890. @param stream HttpStream stream object created via #httpCreateStream
  6891. @param key Http response header key
  6892. @param fmt Printf style formatted string to use as the header key value
  6893. @param ... Arguments for fmt
  6894. @return "Zero" if successful, otherwise a negative MPR error code. Returns MPR_ERR_ALREADY_EXISTS if the header already
  6895. exists.
  6896. @ingroup HttpTx
  6897. @stability Stable
  6898. */
  6899. PUBLIC void httpAddHeader(HttpStream *stream, cchar *key, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  6900. /**
  6901. Add a header to the transmission
  6902. @description Add a header if it does not already exits.
  6903. @param stream HttpStream stream object created via #httpCreateStream
  6904. @param key Http response header key
  6905. @param value Value to set for the header
  6906. @return Zero if successful, otherwise a negative MPR error code. Returns MPR_ERR_ALREADY_EXISTS if the header already
  6907. exists.
  6908. @ingroup HttpTx
  6909. @stability Stable
  6910. */
  6911. PUBLIC void httpAddHeaderString(HttpStream *stream, cchar *key, cchar *value);
  6912. /**
  6913. Append a transmission header
  6914. @description Set the header if it does not already exists. Append with a ", " separator if the header already exists.
  6915. @param stream HttpStream stream object created via #httpCreateStream
  6916. @param key Http response header key
  6917. @param fmt Printf style formatted string to use as the header key value
  6918. @param ... Arguments for fmt
  6919. @ingroup HttpTx
  6920. @stability Stable
  6921. */
  6922. PUBLIC void httpAppendHeader(HttpStream *stream, cchar *key, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  6923. /**
  6924. Append a transmission header string
  6925. @description Set the header if it does not already exists. Append with a ", " separator if the header already exists.
  6926. @param stream HttpStream stream object created via #httpCreateStream
  6927. @param key Http response header key
  6928. @param value Value to set for the header
  6929. @ingroup HttpTx
  6930. @stability Stable
  6931. */
  6932. PUBLIC void httpAppendHeaderString(HttpStream *stream, cchar *key, cchar *value);
  6933. /**
  6934. Connect to a server and issue Http client request.
  6935. @description Start a new Http request on the http object and return. This routine does not block.
  6936. After starting the request, you can use #httpWait to wait for the request to achieve a certain state or to complete.
  6937. @param stream HttpStream stream object created via #httpCreateStream
  6938. @param method Http method to use. Valid methods include: "GET", "POST", "PUT", "DELETE", "OPTIONS" and "TRACE"
  6939. @param uri URI to fetch
  6940. @param ssl SSL configuration to use if a secure connection.
  6941. @return "Zero" if the request was successfully sent to the server. Otherwise a negative MPR error code is returned.
  6942. @ingroup HttpTx
  6943. @stability Stable
  6944. */
  6945. PUBLIC int httpConnect(HttpStream *stream, cchar *method, cchar *uri, struct MprSsl *ssl);
  6946. /**
  6947. Create the tx object. This is used internally by the http library.
  6948. @param stream HttpStream stream object created via #httpCreateStream
  6949. @param headers Optional headers to use for the transmission
  6950. @returns A tx object
  6951. @ingroup HttpTx
  6952. @stability Internal
  6953. */
  6954. PUBLIC HttpTx *httpCreateTx(HttpStream *stream, MprHash *headers);
  6955. /**
  6956. Destroy the tx object
  6957. @description This is called when the garbage collector frees a connection. It should not be called manually.
  6958. @param tx Tx object
  6959. @ingroup HttpTx
  6960. @stability Internal
  6961. */
  6962. PUBLIC void httpDestroyTx(HttpTx *tx);
  6963. /**
  6964. Indicate the request is finalized.
  6965. @description Calling this routine indicates that the handler has fully finished processing the request including
  6966. processing all input, generating a full response and any other required processing. This call will invoke
  6967. #httpFinalizeOutput and then set the request finalized flag. If the request is already finalized, this call
  6968. does nothing. A handler MUST call httpFinalize when it has completed processing a request.
  6969. As background: there are three finalize concepts: HttpTx.finalizedOutput means the handler has generated all
  6970. the response output but it may not yet be fully transmited through the pipeline and to the network by the
  6971. connector. HttpTx.finalizedConnector means the connector has sent all the output to the network. HttpTx.finalized
  6972. means the application has fully processed the request including reading all the input data it wishes to read
  6973. and has generated all the output that will be generated. A fully finalized request has both HttpTx.finalized
  6974. and HttpTx.finalizedConnector true.
  6975. @param stream HttpStream stream object
  6976. @ingroup HttpTx
  6977. @stability Stable
  6978. */
  6979. PUBLIC void httpFinalize(HttpStream *stream);
  6980. /**
  6981. Finalize connector output sending the response.
  6982. @description This should only be called by a connector.
  6983. @param stream HttpStream object created via #httpCreateStream
  6984. @ingroup HttpTx
  6985. @stability Internal
  6986. @internal
  6987. */
  6988. PUBLIC void httpFinalizeConnector(HttpStream *stream);
  6989. /**
  6990. Finalize a HTTP/2 stream when the connector output has sent the response.
  6991. @description This should only be called by httpFinalizeConnector
  6992. @param stream HttpStream object created via #httpCreateStream
  6993. @ingroup HttpTx
  6994. @stability Internal
  6995. @internal
  6996. */
  6997. PUBLIC void httpFinalizeHttp2Stream(HttpStream *stream);
  6998. /**
  6999. Finalize transmission of the http response
  7000. @description This routine should be called by applications and handlers to signify the end of the body content being sent with the request or response body. This call will force the transmission of buffered content to the peer. HttpFinalizeOutput will set the HttpTx.finalizedOutput flag and write a final chunk trailer if using chunked transfers. If the output is already finalized, this call does nothing. Note that after finalization, incoming content may continue to be processed. i.e. httpFinalizeOutput can be called before all incoming data has been received. Use httpFinalizeInput to signify that processing all input is complete.
  7001. \n\n
  7002. The difference between #httpFinalize and #httpFinalizeOutput is that #httpFinalize implies that all request processing is complete including both input and output. Whereas #httpFinalizeOutput implies that the output is generated. Note that while the output may be fully generated, it may not be fully transmitted by the pipeline and connector. When the output is fully transmitted, the connector will call #httpFinalizeConnector.
  7003. @param stream HttpStream Queue object.
  7004. @ingroup HttpTx
  7005. @stability Evolving
  7006. */
  7007. PUBLIC void httpFinalizeOutput(HttpStream *stream);
  7008. /**
  7009. Finalize receiption of the http content
  7010. @description This routine should be called by clients and Handlers to signify that all processing of the input is complete. the request or response body.
  7011. @param stream HttpStream Queue object.
  7012. @ingroup HttpTx
  7013. @stability Stable
  7014. */
  7015. PUBLIC void httpFinalizeInput(HttpStream *stream);
  7016. /**
  7017. Flush transmit data.
  7018. @description This call initiates writing buffered data an will not block.
  7019. If you need to wait until all the data has been written to the socket, use #httpFlushAll.
  7020. Handlers may only call this routine in their open, close, ready, start and writable callbacks.
  7021. @param stream HttpStream stream object created via #httpCreateStream
  7022. @ingroup HttpTx
  7023. @stability Stable
  7024. */
  7025. PUBLIC void httpFlush(HttpStream *stream);
  7026. /**
  7027. Flush transmit data and wait for all the data to be written to the socket.
  7028. @description This call initiates writing buffered data.
  7029. If in sync mode this call may block until the output queues drain.
  7030. In sync mode, this may invoke mprYield before blocking to consent for the garbage collector to run. Callers must
  7031. ensure they have retained all required temporary memory before invoking this routine.
  7032. Filters and connectors should not call this routine as it may block. Use #httpFlush in filters or connectors.
  7033. Handlers may only call this routine in their open, close, ready, start and writable callbacks.
  7034. See #httpFlush if you do need to wait for all the data to be written to the socket.
  7035. @param stream HttpStream stream object created via #httpCreateStream
  7036. @ingroup HttpTx
  7037. @stability Stable
  7038. */
  7039. PUBLIC void httpFlushAll(HttpStream *stream);
  7040. /**
  7041. Follow redirctions
  7042. @description Enabling follow redirects enables the Http service to transparently follow 301 and 302 redirections
  7043. and fetch the redirected URI.
  7044. @param stream HttpStream stream object created via #httpCreateStream
  7045. @param follow Set to true to enable transparent redirections
  7046. @ingroup HttpTx
  7047. @stability Stable
  7048. */
  7049. PUBLIC void httpFollowRedirects(HttpStream *stream, bool follow);
  7050. /**
  7051. Format an error transmission
  7052. @description Format an error message to use instead of data generated by the request processing pipeline.
  7053. This is typically used to send errors and redirections. The message is also sent to the error log.
  7054. @param stream HttpStream stream object created via #httpCreateStream
  7055. @param status Http response status code
  7056. @param fmt Printf style formatted string. This string may contain HTML tags and is not HTML encoded before
  7057. sending to the user. NOTE: Do not send user input back to the client using this method. Otherwise you open
  7058. large security holes.
  7059. @param ... Arguments for fmt
  7060. @return A count of the number of bytes in the transmission body.
  7061. @ingroup HttpTx
  7062. @stability Stable
  7063. */
  7064. PUBLIC void httpFormatError(HttpStream *stream, int status, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  7065. /**
  7066. Format an alternate response
  7067. @description Format a response to use instead of data generated by the request processing pipeline.
  7068. This is used for alternate responses that are not errors.
  7069. @param stream HttpStream stream object created via #httpCreateStream
  7070. @param fmt Printf style formatted string. This string may contain HTML tags and is not HTML encoded before
  7071. sending to the user. NOTE: Do not send user input back to the client using this method. Otherwise you open
  7072. large security holes.
  7073. @param ... Arguments for fmt
  7074. @return A count of the number of bytes in the transmission body.
  7075. @ingroup HttpTx
  7076. @stability Stable
  7077. */
  7078. PUBLIC ssize httpFormatResponse(HttpStream *stream, cchar *fmt, ...) PRINTF_ATTRIBUTE(2,3);
  7079. /**
  7080. Format an alternate response
  7081. @description Format a response to use instead of data generated by the request processing pipeline.
  7082. This is similar to #httpFormatResponse.
  7083. @param stream HttpStream stream object created via #httpCreateStream
  7084. @param fmt Printf style formatted string. This string may contain HTML tags and is not HTML encoded before
  7085. sending to the user. NOTE: Do not send user input back to the client using this method. Otherwise you open
  7086. large security holes.
  7087. @param args Varargs style list of arguments
  7088. @return A count of the number of bytes in the transmission body.
  7089. @ingroup HttpTx
  7090. @stability Stable
  7091. */
  7092. PUBLIC ssize httpFormatResponsev(HttpStream *stream, cchar *fmt, va_list args);
  7093. /**
  7094. Format a response body.
  7095. @description Format a transmission body to use instead of data generated by the request processing pipeline.
  7096. The body will be created in HTML or in plain text depending on the value of the request Accept header.
  7097. This call is used for alternate responses that are not errors.
  7098. @param stream HttpStream stream object created via #httpCreateStream
  7099. @param title Title string to format into the HTML transmission body.
  7100. @param fmt Printf style formatted string. This string may contain HTML tags and is not HTML encoded before
  7101. sending to the user. NOTE: Do not send user input back to the client using this method. Otherwise you open
  7102. large security holes.
  7103. @param ... Arguments for fmt
  7104. @return A count of the number of bytes in the transmission body.
  7105. @ingroup HttpTx
  7106. @stability Stable
  7107. */
  7108. PUBLIC ssize httpFormatResponseBody(HttpStream *stream, cchar *title, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  7109. /**
  7110. Get a tx http header.
  7111. @description Get a http response header value for a given header key.
  7112. @param stream HttpStream stream object created via #httpCreateStream
  7113. @param key Name of the header to retrieve.
  7114. @return Value associated with the header key or null if the key did not exist in the response.
  7115. @ingroup HttpTx
  7116. @stability Evolving
  7117. */
  7118. PUBLIC cchar *httpGetTxHeader(HttpStream *stream, cchar *key);
  7119. /**
  7120. Get the queue data for the connection.
  7121. @description The queue data is stored on the stream->writeq.
  7122. @param stream HttpStream stream object created via #httpCreateStream
  7123. @return the private queue data object
  7124. */
  7125. PUBLIC void *httpGetQueueData(HttpStream *stream);
  7126. /**
  7127. Return whether transfer chunked encoding will be used on this request
  7128. @param stream HttpStream stream object created via #httpCreateStream
  7129. @returns true if chunk encoding will be used
  7130. @ingroup HttpTx
  7131. @stability Stable
  7132. */
  7133. PUBLIC int httpIsChunked(HttpStream *stream);
  7134. /**
  7135. Test if request has been finalized
  7136. @description This call tests if #httpFinalize has been called.
  7137. @param stream HttpStream stream object
  7138. @ingroup HttpTx
  7139. @stability Stable
  7140. */
  7141. PUBLIC int httpIsFinalized(HttpStream *stream);
  7142. /**
  7143. Test if request response has been fully generated.
  7144. @description This call tests if all transmit data has been generated and finalized. Handlers call #httpFinalizeOutput
  7145. to signify the end of transmit data.
  7146. @param stream HttpStream stream object
  7147. @ingroup HttpTx
  7148. @stability Stable
  7149. */
  7150. PUBLIC int httpIsOutputFinalized(HttpStream *stream);
  7151. /**
  7152. Determine if the transmission needs a transparent retry to implement authentication or redirection. This is used
  7153. by client requests. If authentication is required, a request must first be tried once to receive some authentication
  7154. key information that must be resubmitted to gain access.
  7155. @param stream HttpStream stream object created via #httpCreateStream
  7156. @param url Reference to a string to receive a redirection URL. Set to NULL if not redirection is required.
  7157. @return true if the request needs to be retried.
  7158. @ingroup HttpTx
  7159. @stability Stable
  7160. */
  7161. PUBLIC bool httpNeedRetry(HttpStream *stream, cchar **url);
  7162. /**
  7163. Tell the tx to omit sending any body
  7164. @param stream HttpStream stream object created via #httpCreateStream
  7165. */
  7166. PUBLIC void httpOmitBody(HttpStream *stream);
  7167. /**
  7168. Redirect the client
  7169. @description Redirect the client to a new uri.
  7170. @param stream HttpStream stream object created via #httpCreateStream
  7171. @param status Http status code to send with the response
  7172. @param uri New uri for the client
  7173. @ingroup HttpTx
  7174. @stability Stable
  7175. */
  7176. PUBLIC void httpRedirect(HttpStream *stream, int status, cchar *uri);
  7177. /**
  7178. Remove a header from the transmission
  7179. @description Remove a header if present.
  7180. @param stream HttpStream stream object created via #httpCreateStream
  7181. @param key Http response header key
  7182. @return "Zero" if successful, otherwise a negative MPR error code.
  7183. @ingroup HttpTx
  7184. @stability Stable
  7185. */
  7186. PUBLIC int httpRemoveHeader(HttpStream *stream, cchar *key);
  7187. /**
  7188. Issue a http request
  7189. @param method HTTP method to use
  7190. @param uri URI to request
  7191. @param data Optional data to send with request. Set to null for GET requests.
  7192. @param protocol HTTP protocol to use. Set to 1 for HTTP/1.1 and 2 for HTTP/2.
  7193. @param err Output parameter to receive any error messages.
  7194. @return HttpStream object. Use #httpGetStatus to read status and #httpReadString to read the response data.
  7195. @ingroup HttpTx
  7196. @stability Stable
  7197. */
  7198. PUBLIC HttpStream *httpRequest(cchar *method, cchar *uri, cchar *data, int protocol, char **err);
  7199. /**
  7200. Set the transmission (response) character set
  7201. @description Set the character set used in the response Content-Type
  7202. @param stream HttpStream stream object created via #httpCreateStream
  7203. @param charSet Character set string
  7204. @ingroup HttpTx
  7205. @stability Stable
  7206. */
  7207. PUBLIC void httpSetCharSet(HttpStream *stream, cchar *charSet);
  7208. /**
  7209. Define a content length header in the transmission. This will define a "Content-Length: NNN" request header and
  7210. set Tx.length.
  7211. @param stream HttpStream stream object created via #httpCreateStream
  7212. @param length Numeric value for the content length header.
  7213. @ingroup HttpTx
  7214. @stability Stable
  7215. */
  7216. PUBLIC void httpSetContentLength(HttpStream *stream, MprOff length);
  7217. /**
  7218. Set the transmission (response) content mime type
  7219. @description Set the mime type Http header in the transmission
  7220. @param stream HttpStream stream object created via #httpCreateStream
  7221. @param mimeType Mime type string
  7222. @ingroup HttpTx
  7223. @stability Stable
  7224. */
  7225. PUBLIC void httpSetContentType(HttpStream *stream, cchar *mimeType);
  7226. /*
  7227. Flags for httpSetCookie
  7228. */
  7229. #define HTTP_COOKIE_SECURE 0x1 /**< Flag for Set-Cookie for SSL only */
  7230. #define HTTP_COOKIE_HTTP 0x2 /**< Flag for Set-Cookie httponly. Not visible to Javascript */
  7231. #define HTTP_COOKIE_SAME_LAX 0x4 /**< Flag for Set-Cookie SameSite=Lax */
  7232. #define HTTP_COOKIE_SAME_STRICT 0x8 /**< Flag for Set-Cookie SameSite=Strict */
  7233. #define HTTP_COOKIE_SAME_NONE 0x10 /**< Flag for Set-Cookie SameSite=None */
  7234. /**
  7235. Set a transmission cookie
  7236. @description Define a cookie to send in the transmission Http header
  7237. @param stream HttpStream stream object created via #httpCreateStream
  7238. @param name Cookie name
  7239. @param value Cookie value
  7240. @param path URI path to which the cookie applies
  7241. @param domain Domain in which the cookie applies. Must have 2-3 dots. If null, a domain is created using the
  7242. current request host header. If set to the empty string, the domain field is omitted.
  7243. If the domain is a numerical IP address or localhost, the domain will not be included as the browsers do not
  7244. support this pattern consistently.
  7245. Note that hostname port numbers are ignored by browsers and so web sites with the same domain name but different
  7246. port numbers may have conflicting cookies. This is according to the Cookie RFC standard.
  7247. @param lifespan Duration for the cookie to persist in msec. Set to zero to create a session cookie that is meant to
  7248. be automatically removed when the user exits their browser. However, beware, Chrome subverts this and will persist
  7249. session cookies if "Continue where you left off" is enabled in Chrome preferences.
  7250. @param flags Cookie options mask. The following options are supported:
  7251. @li HTTP_COOKIE_SECURE - Set the 'Secure' attribute on the cookie.
  7252. @li HTTP_COOKIE_HTTP - Set the 'HttpOnly' attribute on the cookie.
  7253. @li HTTP_COOKIE_SAME_LAX - Set the 'SameSite=Lax' attribute on the cookie.
  7254. @li HTTP_COOKIE_SAME_STRICT - Set the 'SameSite=Strict' attribute on the cookie.
  7255. See RFC 6265 for details about the 'Secure' and 'HttpOnly' cookie attributes.
  7256. @ingroup HttpTx
  7257. @stability Stable
  7258. */
  7259. PUBLIC void httpSetCookie(HttpStream *stream, cchar *name, cchar *value, cchar *path, cchar *domain, MprTicks lifespan,
  7260. int flags);
  7261. /**
  7262. Remove a cookie from the client (browser)
  7263. This will emit a Set-Cookie response header with the value set to "" and a one second lifespan.
  7264. @param stream HttpStream stream object created via #httpCreateStream
  7265. @param name Name of the cookie created with httpSetCookie
  7266. @ingroup HttpTx
  7267. @stability Stable
  7268. */
  7269. PUBLIC void httpRemoveCookie(HttpStream *stream, cchar *name);
  7270. /**
  7271. Set the filename to serve for a request
  7272. @description This routine defines a non-default response document filename.
  7273. The filename may be virtual and not correspond to a physical file. It also may be a file outside the documents root
  7274. directory. If it is not a file under the route documents directory, set the flags parameter to HTTP_TX_NO_CHECK.
  7275. Otherwise, the filename will be checked to ensure it is inside the route documents directory.
  7276. \n\n
  7277. Typically a handler will call #httpMapFile to perform default request URI to filename mapping and should not need
  7278. to call httpSetFilename unless a file outside the route documents directory is required to be served.
  7279. \n\n
  7280. This routine will set the HttpTx filename, ext, etag and fileInfo fields.
  7281. \n\n
  7282. Note: the response header mime type will be set based on the request URI. To override, use #httpSetContentType
  7283. @param stream HttpStream stream object
  7284. @param filename Tx filename to define. Set to NULL to reset the filename.
  7285. @param flags Flags word. Or together the desired flags. Include to HTTP_TX_NO_CHECK to bypass checking if the
  7286. filename resides inside the route documents directory.
  7287. @return True if the filename exists and is readable.
  7288. @ingroup HttpTx
  7289. @stability Stable
  7290. */
  7291. PUBLIC bool httpSetFilename(HttpStream *stream, cchar *filename, int flags);
  7292. /**
  7293. Set the handler for this request
  7294. Use this request from the Handler rewrite callback to change the selected handler to process a request.
  7295. Most useful to set the Tx.filename and pass to the fileHandler.
  7296. @param stream HttpStream stream object created via #httpCreateStream
  7297. @param handler Handler to set
  7298. @stability Stable
  7299. */
  7300. PUBLIC void httpSetHandler(HttpStream *stream, HttpStage *handler);
  7301. /**
  7302. Set a transmission header
  7303. @description Set a Http header to send with the request. If the header already exists, it its value is overwritten.
  7304. @param stream HttpStream stream object created via #httpCreateStream
  7305. @param key Http response header key
  7306. @param fmt Printf style formatted string to use as the header key value
  7307. @param ... Arguments for fmt
  7308. @ingroup HttpTx
  7309. @stability Stable
  7310. */
  7311. PUBLIC void httpSetHeader(HttpStream *stream, cchar *key, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  7312. /**
  7313. Set a simple key/value transmission header
  7314. @description Set a Http header to send with the request. If the header already exists, it its value is overwritten.
  7315. @param stream HttpStream stream object created via #httpCreateStream
  7316. @param key Http response header key
  7317. @param value String value for the key
  7318. @ingroup HttpTx
  7319. @stability Stable
  7320. */
  7321. PUBLIC void httpSetHeaderString(HttpStream *stream, cchar *key, cchar *value);
  7322. /**
  7323. Set a Http response status.
  7324. @description Set the Http response status for the request. This defaults to 200 (OK).
  7325. @param stream HttpStream stream object created via #httpCreateStream
  7326. @param status Http status code.
  7327. @ingroup HttpTx
  7328. @stability Stable
  7329. */
  7330. PUBLIC void httpSetStatus(HttpStream *stream, int status);
  7331. /**
  7332. Set the responded flag for the request
  7333. @description This call sets the requests responded status. Once the HTTP response status code has been defined,
  7334. HTTP response headers or any output has been generated, the request is regarded as having "responded" in-part to the client.
  7335. This means that any errors cannot revise the HTTP response status and may need to prematurely abort the request to signify
  7336. to the clien that the request has failed.
  7337. @param stream HttpStream stream object
  7338. @ingroup HttpTx
  7339. @stability Stable
  7340. */
  7341. PUBLIC void httpSetResponded(HttpStream *stream);
  7342. /**
  7343. Wait for the client connection to achieve the requested state.
  7344. @description This call blocks until the connection reaches the desired state. It creates a wait handler and
  7345. services events while waiting. This is useful for blocking client requests, and should never be used on
  7346. server-side connections.
  7347. \n\n
  7348. It is often required to call mprStartDispatcher on the connection dispatcher after calling $httpCreateStream.
  7349. This ensures that all foreground activity on the connection is serialized with respect to work done in response
  7350. to I/O events while waiting in httpWait.
  7351. \n\n
  7352. This routine may invoke mprYield before it sleeps to consent for the garbage collector to turn. Callers must
  7353. ensure they have retained all required temporary memory before invoking this routine.
  7354. @param stream HttpStream stream object created via #httpCreateStream
  7355. @param state HTTP_STATE_XXX to wait for.
  7356. @param timeout Timeout in milliseconds to wait. Set to -1 to use the default connection timeouts. Set to zero
  7357. to wait forever.
  7358. @return "Zero" if successful. Otherwise return a negative MPR error code. Specific returns include:
  7359. MPR_ERR_TIMEOUT and MPR_ERR_BAD_STATE.
  7360. @ingroup HttpTx
  7361. @stability Stable
  7362. */
  7363. PUBLIC int httpWait(HttpStream *stream, int state, MprTicks timeout);
  7364. /**
  7365. Create a HTTP header packet
  7366. @description Write the Http transmission headers into the given packet. This should only be called by connectors
  7367. just prior to sending output to the client. It should be delayed as long as possible if the content length is
  7368. not yet known to give the pipeline a chance to determine the transmission length. This way, a non-chunked
  7369. transmission can be sent with a content-length header. This is the fastest HTTP transmission.
  7370. @param q Queue owning the packet
  7371. @param packet Packet into which to place the headers
  7372. @ingroup HttpTx
  7373. @stability Stable
  7374. */
  7375. PUBLIC HttpPacket *httpCreateHeaders(HttpQueue *q, HttpPacket *packet);
  7376. #define httpWriteHeaders(q, packet) httpCreateHeaders
  7377. /**
  7378. Write Http upload body data
  7379. @description Write files and form fields as request body data. This will use transfer chunk encoding. This routine
  7380. will block until all the buffer is written.
  7381. This routine may invoke mprYield before it blocks to consent for the garbage collector to turn. Callers must
  7382. ensure they have retained all required temporary memory before invoking this routine.
  7383. @param stream Http stream object created via #httpCreateStream
  7384. @param fileData List of string file names to upload
  7385. @param formData List of strings containing "key=value" pairs. The form data should be already www-urlencoded.
  7386. @return Number of bytes successfully written.
  7387. @ingroup HttpStream
  7388. @stability Stable
  7389. */
  7390. PUBLIC ssize httpWriteUploadData(HttpStream *stream, MprList *formData, MprList *fileData);
  7391. /*
  7392. Internal
  7393. */
  7394. PUBLIC void httpPrepareHeaders(HttpStream *stream);
  7395. PUBLIC void httpCreateHeaders1(HttpQueue *q, HttpPacket *packet);
  7396. PUBLIC void httpCreateHeaders2(HttpQueue *q, HttpPacket *packet);
  7397. /********************************* HttpEndpoint ***********************************/
  7398. /*
  7399. Endpoint flags
  7400. */
  7401. #define HTTP_NEW_DISPATCHER 0x1 /**< New dispatcher for each connection */
  7402. /**
  7403. Listening endpoints. Endpoints may have multiple virtual named hosts.
  7404. @defgroup HttpEndpoint HttpEndpoint
  7405. @see HttpEndpoint httpAcceptNet httpAddHostToEndpoint httpCreateConfiguredEndpoint httpCreateEndpoint
  7406. httpDestroyEndpoint httpGetEndpointContext httpIsEndpointAsync
  7407. httpLookupHostOnEndpoint httpSecureEndpoint httpSecureEndpointByName httpSetEndpointAddress
  7408. httpSetEndpointAsync httpSetEndpointContext httpSetEndpointNotifier
  7409. httpStartEndpoint httpStopEndpoint
  7410. @stability Internal
  7411. */
  7412. typedef struct HttpEndpoint {
  7413. Http *http; /**< Http service object */
  7414. MprList *hosts; /**< List of host objects */
  7415. char *ip; /**< Listen IP address. May be null if listening on all interfaces. */
  7416. int port; /**< Listen port */
  7417. int async; /**< Listening is in async mode (non-blocking) */
  7418. int flags; /**< Endpoint control flags */
  7419. bool multiple: 1; /**< Allow multiple binding on the endpoint */
  7420. void *context; /**< Embedding context */
  7421. HttpLimits *limits; /**< Alias for first host, default route resource limits */
  7422. MprSocket *sock; /**< Listening socket */
  7423. MprDispatcher *dispatcher; /**< Event dispatcher */
  7424. HttpNotifier notifier; /**< Default connection notifier callback */
  7425. MprSsl *ssl; /**< SSL configurations to use */
  7426. MprMutex *mutex; /**< Multithread sync */
  7427. } HttpEndpoint;
  7428. /**
  7429. Accept a new connection.
  7430. Accept a new client connection on a new socket. If multithreaded, this will come in on a worker thread
  7431. dedicated to this connection. This is called from the listen wait handler.
  7432. @param endpoint The endpoint on which the server was listening
  7433. @param event Mpr event object
  7434. @return A HttpNet object representing the new network.
  7435. @ingroup HttpEndpoint
  7436. @stability Internal
  7437. @internal
  7438. */
  7439. PUBLIC HttpNet *httpAccept(HttpEndpoint *endpoint, MprEvent *event);
  7440. /**
  7441. Add a host to an endpoint
  7442. @description Add the host to the endpoint's list of hosts. A listening endpoint may have multiple
  7443. virutal hosts.
  7444. @param endpoint Endpoint to which the host will be added.
  7445. @param host HttpHost object to add.
  7446. @return "Zero" if the host can be added.
  7447. @ingroup HttpEndpoint
  7448. @stability Internal
  7449. */
  7450. PUBLIC void httpAddHostToEndpoint(HttpEndpoint *endpoint, struct HttpHost *host);
  7451. /**
  7452. Create and configure a new endpoint.
  7453. @description Convenience function to create and configure a new endpoint without using a config file.
  7454. If no host is supplied, a default host and route are created.
  7455. @param host Optional HttpHost object.
  7456. @param home Home directory for configuration files for the endpoint
  7457. @param documents Directory containing the
  7458. @param ip IP address to use for the endpoint. Set to null to listen on all interfaces.
  7459. @param port Listening port number to use for the endpoint
  7460. @return A configured HttpEndpoint object instance
  7461. @ingroup HttpEndpoint
  7462. @stability Internal
  7463. */
  7464. PUBLIC HttpEndpoint *httpCreateConfiguredEndpoint(struct HttpHost *host, cchar *home, cchar *documents, cchar *ip, int port);
  7465. /**
  7466. Create an endpoint object.
  7467. @description Creates a listening endpoint on the given IP:PORT. Use httpStartEndpoint to begin listening for client
  7468. connections.
  7469. @param ip IP address on which to listen
  7470. @param port IP port number
  7471. @param dispatcher Dispatcher to use. Can be null.
  7472. @ingroup HttpEndpoint
  7473. @stability Stable
  7474. */
  7475. PUBLIC HttpEndpoint *httpCreateEndpoint(cchar *ip, int port, MprDispatcher *dispatcher);
  7476. /**
  7477. Destroy the endpoint
  7478. @description This destroys the endpoint created by #httpCreateEndpoint. Calling this routine should not
  7479. normally be necessary as the garbage collector will invoke as required.
  7480. @param endpoint HttpEndpoint object returned from #httpCreateEndpoint.
  7481. @ingroup HttpEndpoint
  7482. @stability Stable
  7483. */
  7484. PUBLIC void httpDestroyEndpoint(HttpEndpoint *endpoint);
  7485. /**
  7486. Get the endpoint context object
  7487. @param endpoint HttpEndpoint object created via #httpCreateEndpoint
  7488. @return The endpoint context object defined via httpSetEndpointContext
  7489. @ingroup HttpEndpoint
  7490. @stability Stable
  7491. */
  7492. PUBLIC void *httpGetEndpointContext(HttpEndpoint *endpoint);
  7493. /**
  7494. Get if the endpoint is running in asynchronous mode
  7495. @param endpoint HttpEndpoint object created via #httpCreateEndpoint
  7496. @return True if the endpoint is in async mode
  7497. @ingroup HttpEndpoint
  7498. @stability Stable
  7499. */
  7500. PUBLIC int httpIsEndpointAsync(HttpEndpoint *endpoint);
  7501. /**
  7502. Lookup a host name
  7503. @description Lookup a host by name in the set of defined hosts for this endpoint.
  7504. @param endpoint HttpEndpoint object created via #httpCreateEndpoint
  7505. @param name Host name to search for
  7506. @return An HttpHost object instance or null if the host cannot be found.
  7507. @ingroup HttpEndpoint
  7508. @stability Stable
  7509. */
  7510. PUBLIC struct HttpHost *httpLookupHostOnEndpoint(HttpEndpoint *endpoint, cchar *name);
  7511. /**
  7512. Secure an endpoint
  7513. @description Define the SSL parameters for an endpoint. This must be done before starting listening on
  7514. the endpoint via #httpStartEndpoint.
  7515. @param endpoint HttpEndpoint object created via #httpCreateEndpoint
  7516. @param ssl MprSsl object
  7517. @returns "Zero" if successful, otherwise a negative MPR error code.
  7518. @ingroup HttpEndpoint
  7519. @stability Stable
  7520. */
  7521. PUBLIC int httpSecureEndpoint(HttpEndpoint *endpoint, struct MprSsl *ssl);
  7522. /**
  7523. Secure an endpoint by name
  7524. @description Define the SSL parameters for an endpoint that is selected by name. This must be done before
  7525. starting listening on the endpoint via #httpStartEndpoint.
  7526. @param name Endpoint name. The endpoint name is comprised of the IP and port. For example: "127.0.0.1:7777"
  7527. @param ssl MprSsl object
  7528. @returns Zero if successful, otherwise a negative MPR error code.
  7529. @ingroup HttpEndpoint
  7530. @stability Stable
  7531. */
  7532. PUBLIC int httpSecureEndpointByName(cchar *name, struct MprSsl *ssl);
  7533. /**
  7534. Set the endpoint IP address
  7535. @description This call defines the endpoint's IP address and port number. If the endpoint has already been
  7536. started, this will stop and restart the endpoint. Current requests will not be disturbed.
  7537. This is useful to modify the endpoints address when using dynamically assigned IP addresses.
  7538. @param endpoint HttpEndpoint object created via #httpCreateEndpoint
  7539. @param ip IP address to use for the endpoint. Set to null to listen on all interfaces.
  7540. @param port Listening port number to use for the endpoint
  7541. @returns "Zero" if successful, otherwise a negative MPR error code.
  7542. @ingroup HttpEndpoint
  7543. @stability Stable
  7544. */
  7545. PUBLIC int httpSetEndpointAddress(HttpEndpoint *endpoint, cchar *ip, int port);
  7546. /**
  7547. Control if the endpoint is running in asynchronous mode
  7548. @param endpoint HttpEndpoint object created via #httpCreateEndpoint
  7549. @param enable Set to 1 to enable async mode.
  7550. @ingroup HttpEndpoint
  7551. @stability Stable
  7552. */
  7553. PUBLIC void httpSetEndpointAsync(HttpEndpoint *endpoint, int enable);
  7554. /**
  7555. Set the endpoint context object
  7556. @param endpoint HttpEndpoint object created via #httpCreateEndpoint
  7557. @param context New context object
  7558. @ingroup HttpEndpoint
  7559. @stability Stable
  7560. */
  7561. PUBLIC void httpSetEndpointContext(HttpEndpoint *endpoint, void *context);
  7562. /**
  7563. Define a notifier callback for this endpoint.
  7564. @description The notifier callback will be invoked as Http requests are processed.
  7565. @param endpoint HttpEndpoint object created via #httpCreateEndpoint
  7566. @param fn Notifier function.
  7567. @ingroup HttpEndpoint
  7568. @stability Stable
  7569. */
  7570. PUBLIC void httpSetEndpointNotifier(HttpEndpoint *endpoint, HttpNotifier fn);
  7571. /**
  7572. Start listening for client connections on an endpoint.
  7573. @description Opens the endpoint socket and starts listening for connections.
  7574. @param endpoint HttpEndpoint object created via #httpCreateEndpoint
  7575. @returns "Zero" if successful, otherwise a negative MPR error code.
  7576. @ingroup HttpEndpoint
  7577. @stability Stable
  7578. */
  7579. PUBLIC int httpStartEndpoint(HttpEndpoint *endpoint);
  7580. /**
  7581. Start listening for client connections on all endpoints
  7582. @description Opens all endpoints and starts listening for connections.
  7583. @returns "Zero" if successful, otherwise a negative MPR error code.
  7584. @ingroup HttpEndpoint
  7585. @stability Evolving
  7586. */
  7587. PUBLIC int httpStartEndpoints(void);
  7588. /**
  7589. Stop listening for client connections on all endpoints
  7590. @description Closes all endpoints and stops listening for connections. Does not impact running requests.
  7591. @returns "Zero" if successful, otherwise a negative MPR error code.
  7592. @ingroup HttpEndpoint
  7593. */
  7594. PUBLIC void httpStopEndpoints(void);
  7595. /**
  7596. Stop the server listening for client connections.
  7597. @description Closes the socket endpoint. This preserves connections accepted via the listening endpoint.
  7598. @param endpoint HttpEndpoint object created via #httpCreateEndpoint
  7599. @ingroup HttpEndpoint
  7600. @stability Stable
  7601. */
  7602. PUBLIC void httpStopEndpoint(HttpEndpoint *endpoint);
  7603. /********************************** HttpHost ***************************************/
  7604. /*
  7605. Flags
  7606. */
  7607. #define HTTP_HOST_NO_TRACE 0x10 /**< Host flag to disable the of TRACE HTTP method */
  7608. #define HTTP_HOST_WILD_STARTS 0x20 /**< Host name starts with pattern */
  7609. #define HTTP_HOST_WILD_CONTAINS 0x40 /**< Host name contains the host name */
  7610. #define HTTP_HOST_WILD_REGEXP 0x80 /**< Host name is a regular expression */
  7611. #define HTTP_HOST_ATTACHED 0x100 /**< Host name attached to an endpoint */
  7612. /**
  7613. Host Object
  7614. @description A Host object represents a logical host. Several logical hosts may share a single HttpEndpoint.
  7615. @defgroup HttpHost HttpHost
  7616. @see HttpHost httpAddRoute httpCloneHost httpCreateHost httpResetRoutes httpSetHostHome
  7617. httpSetHostName httpSetHostProtocol
  7618. @stability Internal
  7619. */
  7620. typedef struct HttpHost {
  7621. /*
  7622. NOTE: A host may be associated with multiple listening endpoints.
  7623. */
  7624. cchar *name; /**< Full host name with port */
  7625. cchar *hostname; /**< Host name portion only */
  7626. struct HttpHost *parent; /**< Parent host to inherit aliases, dirs, routes */
  7627. MprCache *responseCache; /**< Response content caching store */
  7628. MprList *routes; /**< List of Route defintions */
  7629. HttpRoute *defaultRoute; /**< Default route for the host */
  7630. HttpEndpoint *defaultEndpoint; /**< Default endpoint for host */
  7631. HttpEndpoint *secureEndpoint; /**< Secure endpoint for host */
  7632. MprHash *streaming; /**< Hash of mime-types use streaming instead of buffering */
  7633. void *nameCompiled; /**< Compiled name regular expression (not alloced) */
  7634. int flags; /**< Host flags */
  7635. } HttpHost;
  7636. /**
  7637. Add a route to a host
  7638. @description Add the route to the host list of routes. During request route matching, routes are processed
  7639. in order, so it is important to define routes in the order in which you wish to match them.
  7640. @param host HttpHost object
  7641. @param route Route to add
  7642. @return "Zero" if the route can be added.
  7643. @ingroup HttpHost
  7644. @stability Stable
  7645. */
  7646. PUBLIC int httpAddRoute(HttpHost *host, HttpRoute *route);
  7647. /**
  7648. Clone a host
  7649. @description The parent host is cloned and a new host returned. The new host inherites the parent's configuration.
  7650. @param parent Parent HttpHost object to clone
  7651. @return The new HttpHost object.
  7652. @ingroup HttpHost
  7653. @stability Stable
  7654. */
  7655. PUBLIC HttpHost *httpCloneHost(HttpHost *parent);
  7656. /**
  7657. Create a host
  7658. @description Create a new host object. The host is added to the Http service's list of hosts.
  7659. @return The new HttpHost object.
  7660. @ingroup HttpHost
  7661. @stability Stable
  7662. */
  7663. PUBLIC HttpHost *httpCreateHost(void);
  7664. /**
  7665. Create the default host
  7666. @description Create and define a default host. The host is added to the Http service's list of hosts.
  7667. A default route is created for the host
  7668. @return The new HttpHost object.
  7669. @ingroup HttpHost
  7670. @stability Evolving
  7671. */
  7672. PUBLIC HttpHost *httpCreateDefaultHost(void);
  7673. /**
  7674. Get the default host defined via httpSetDefaultHost
  7675. @return The defaul thost object
  7676. @ingroup HttpHost
  7677. @stability Stable
  7678. */
  7679. PUBLIC HttpHost *httpGetDefaultHost(void);
  7680. /**
  7681. Get the default route for a host
  7682. @param host Host object
  7683. @return The default route for the host
  7684. @ingroup HttpRoute
  7685. @stability Stable
  7686. */
  7687. PUBLIC HttpRoute *httpGetDefaultRoute(HttpHost *host);
  7688. /**
  7689. Return the default route for a host
  7690. @description The host has a default route which holds default configuration. Typically the default route
  7691. is not directly used when routing URIs. Rather other routes inherit from the default route and are used to
  7692. respond to client requests.
  7693. @param host Host to examine.
  7694. @return Default route object
  7695. @ingroup HttpRoute
  7696. @stability Stable
  7697. */
  7698. PUBLIC HttpRoute *httpGetHostDefaultRoute(HttpHost *host);
  7699. /**
  7700. Show the current route table to the error log.
  7701. @description This emits the currently defined route table for a host to the route table. If the "full" argument is true,
  7702. a more-complete, multi-line output format will be used. Othewise, a one-line, abbreviated route description will
  7703. be output.
  7704. @param host Host to examine.
  7705. @param full Set to true for a "fuller" output route description.
  7706. @ingroup HttpRoute
  7707. @stability Stable
  7708. */
  7709. PUBLIC void httpLogRoutes(HttpHost *host, bool full);
  7710. /**
  7711. Lookup a route by pattern
  7712. @param host HttpHost object owning the route table
  7713. @param pattern Route pattern to find. If null or empty, look for "/"
  7714. @ingroup HttpRoute
  7715. @stability Stable
  7716. */
  7717. PUBLIC HttpRoute *httpLookupRoute(HttpHost *host, cchar *pattern);
  7718. /**
  7719. Reset the list of routes for the host
  7720. @param host HttpHost object
  7721. @ingroup HttpHost
  7722. @stability Stable
  7723. */
  7724. PUBLIC void httpResetRoutes(HttpHost *host);
  7725. /**
  7726. Set the default host for all servers.
  7727. @param host Host to define as the default host
  7728. @ingroup HttpHost
  7729. @stability Stable
  7730. */
  7731. PUBLIC void httpSetDefaultHost(HttpHost *host);
  7732. /**
  7733. Set the default endpoint for a host
  7734. @description The host may have a default endpoint that is used when doing redirections to http.
  7735. @param host Host to examine.
  7736. @param endpoint Secure endpoint to use as the default
  7737. @ingroup HttpHost
  7738. @stability Stable
  7739. */
  7740. PUBLIC void httpSetHostDefaultEndpoint(HttpHost *host, HttpEndpoint *endpoint);
  7741. /**
  7742. Set the default route for a host
  7743. @description The host has a default route which holds default configuration. Typically the default route
  7744. is not directly used when routing URIs. Rather other routes inherit from the default route and are used to
  7745. respond to client requests.
  7746. @param host Host to examine.
  7747. @param route Route to define as the default
  7748. @ingroup HttpHost
  7749. @stability Stable
  7750. */
  7751. PUBLIC void httpSetHostDefaultRoute(HttpHost *host, HttpRoute *route);
  7752. /**
  7753. Set the host name
  7754. @description The host name is used when matching client requests to virtual hosts using the Http request Host header.
  7755. If the host name starts with "*", it will match names that contain the name.
  7756. If the host name ends with "*", it will match names that start with the name.
  7757. If the host name begins and ends with a "/", the name is assumed to be a regular expression. Regular expressions
  7758. may match multiple host names by using the "|" character to separate names.
  7759. @param host HttpHost object
  7760. @param name Host name to use
  7761. @return Zero if successful. May return a negative MPR error code if the name is a regular expression and cannot
  7762. be compiled.
  7763. @ingroup HttpHost
  7764. @stability Stable
  7765. */
  7766. PUBLIC int httpSetHostName(HttpHost *host, cchar *name);
  7767. /**
  7768. Set the default secure endpoint for a host
  7769. @description The host may have a default secure endpoint that is used when doing redirections to https.
  7770. @param host Host to examine.
  7771. @param endpoint Secure endpoint to use as the default
  7772. @ingroup HttpHost
  7773. @stability Stable
  7774. */
  7775. PUBLIC void httpSetHostSecureEndpoint(HttpHost *host, HttpEndpoint *endpoint);
  7776. /**
  7777. Set the server root for a host
  7778. @description The server root is used as the default directory to locate configuration files for the host
  7779. @param host HttpHost object
  7780. @param root Directory path for the host server root
  7781. @ingroup HttpHost
  7782. @stability Stable
  7783. */
  7784. PUBLIC void httpSetHostRoot(HttpHost *host, cchar *root);
  7785. /**
  7786. Set the host HTTP protocol version
  7787. @description Set the host protocol version to either HTTP/1.0 or HTTP/1.1
  7788. @param host HttpHost object
  7789. @param protocol Set to either HTTP/1.0 or HTTP/1.1
  7790. @ingroup HttpHost
  7791. @stability Stable
  7792. */
  7793. PUBLIC void httpSetHostProtocol(HttpHost *host, cchar *protocol);
  7794. /*
  7795. Internal
  7796. */
  7797. PUBLIC int httpStartHost(HttpHost *host);
  7798. PUBLIC void httpStopHost(HttpHost *host);
  7799. /********************************* Web Sockets *************************************/
  7800. /**
  7801. WebSocket Service to implement the WebSockets RFC 6455 specification for client and server communications.
  7802. @description WebSockets is a technology providing interactive communication between a server and client. Normal HTML
  7803. connections follow a request / response paradigm and do not easily support asynchronous communications or unsolicited
  7804. data pushed from the server to the client. WebSockets solves this by supporting bi-directional, full-duplex
  7805. communications over persistent connections. A WebSocket connection is established over a standard HTTP connection and is
  7806. then upgraded without impacting the original connection. This means it will work with existing networking infrastructure
  7807. including firewalls and proxies.
  7808. @defgroup HttpWebSocket HttpWebSocket
  7809. @see httpGetWebSocketCloseReason httpGetWebSocketData httpGetWebSocketMessageLength httpGetWebSocketProtocol
  7810. httpGetWebSocketState httpGetWriteQueueCount httpIsLastPacket httpSend httpSendBlock httpSendClose
  7811. httpSetWebSocketPreserveFrames httpSetWebSocketData httpSetWebSocketProtocols httpWebSocketOrderlyClosed
  7812. @stability Internal
  7813. */
  7814. typedef struct HttpWebSocket {
  7815. int state; /**< State */
  7816. int frameState; /**< Message frame state */
  7817. int closing; /**< Started closing sequnce */
  7818. int closeStatus; /**< Close status provided by peer */
  7819. int currentMessageType; /**< Current incoming messsage type */
  7820. int maskOffset; /**< Offset in dataMask */
  7821. int more; /**< More data to send in a message */
  7822. int preserveFrames; /**< Do not join frames */
  7823. int partialUTF; /**< Last frame had a partial UTF codepoint */
  7824. int rxSeq; /**< Incoming packet number */
  7825. int txSeq; /**< Outgoing packet number */
  7826. ssize frameLength; /**< Length of the current frame */
  7827. ssize messageLength; /**< Length of the current message */
  7828. HttpPacket *currentFrame; /**< Message frame being currently read */
  7829. HttpPacket *currentMessage; /**< Current incoming messsage so far */
  7830. HttpPacket *tailMessage; /**< Subsequent message frames */
  7831. MprEvent *pingEvent; /**< Ping timer event */
  7832. char *subProtocol; /**< Application level sub-protocol */
  7833. cchar *errorMsg; /**< Error message for last I/O */
  7834. cchar *closeReason; /**< Reason for closure */
  7835. void *data; /**< Custom data for applications (marked) */
  7836. uchar dataMask[4]; /**< Mask for data */
  7837. } HttpWebSocket;
  7838. #define WS_MAGIC "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  7839. #define WS_MAX_CONTROL 125 /**< Maximum bytes in control message */
  7840. #define WS_VERSION 13 /**< Current WebSocket specification version */
  7841. /*
  7842. httpSendBlock message types
  7843. */
  7844. #define WS_MSG_CONT 0x0 /**< Continuation of WebSocket message */
  7845. #define WS_MSG_TEXT 0x1 /**< httpSendBlock type for text messages */
  7846. #define WS_MSG_BINARY 0x2 /**< httpSendBlock type for binary messages */
  7847. #define WS_MSG_CONTROL 0x8 /**< Start of control messages */
  7848. #define WS_MSG_CLOSE 0x8 /**< httpSendBlock type for close message */
  7849. #define WS_MSG_PING 0x9 /**< httpSendBlock type for ping messages */
  7850. #define WS_MSG_PONG 0xA /**< httpSendBlock type for pong messages */
  7851. #define WS_MSG_MAX 0xB /**< Max message type for httpSendBlock */
  7852. /*
  7853. Close message status codes
  7854. 0-999 Unused
  7855. 1000-1999 Reserved for spec
  7856. 2000-2999 Reserved for extensions
  7857. 3000-3999 Library use
  7858. 4000-4999 Application use
  7859. */
  7860. #define WS_STATUS_OK 1000 /**< Normal closure */
  7861. #define WS_STATUS_GOING_AWAY 1001 /**< Endpoint is going away. Server down or browser navigating away */
  7862. #define WS_STATUS_PROTOCOL_ERROR 1002 /**< WebSockets protocol error */
  7863. #define WS_STATUS_UNSUPPORTED_TYPE 1003 /**< Unsupported message data type */
  7864. #define WS_STATUS_FRAME_TOO_LARGE 1004 /**< Reserved. Message frame is too large */
  7865. #define WS_STATUS_NO_STATUS 1005 /**< No status was received from the peer in closing */
  7866. #define WS_STATUS_COMMS_ERROR 1006 /**< TCP/IP communications error */
  7867. #define WS_STATUS_INVALID_UTF8 1007 /**< Text message has invalid UTF-8 */
  7868. #define WS_STATUS_POLICY_VIOLATION 1008 /**< Application level policy violation */
  7869. #define WS_STATUS_MESSAGE_TOO_LARGE 1009 /**< Message is too large */
  7870. #define WS_STATUS_MISSING_EXTENSION 1010 /**< Unsupported WebSockets extension */
  7871. #define WS_STATUS_INTERNAL_ERROR 1011 /**< Server terminating due to an internal error */
  7872. #define WS_STATUS_TLS_ERROR 1015 /**< TLS handshake error */
  7873. #define WS_STATUS_MAX 5000 /**< Maximum error status (less one) */
  7874. /*
  7875. WebSocket states (rx->webSockState)
  7876. */
  7877. #define WS_STATE_CONNECTING 0 /**< WebSocket connection is being established */
  7878. #define WS_STATE_OPEN 1 /**< WebSocket handsake is complete and ready for communications */
  7879. #define WS_STATE_CLOSING 2 /**< WebSocket is closing */
  7880. #define WS_STATE_CLOSED 3 /**< WebSocket is closed */
  7881. /**
  7882. Get the close reason supplied by the peer.
  7883. @description The peer may supply a UTF8 messages reason for the closure.
  7884. @param stream HttpStream stream object created via #httpCreateStream
  7885. @return The UTF8 reason string supplied by the peer when closing the WebSocket.
  7886. @ingroup HttpWebSocket
  7887. @stability Evolving
  7888. */
  7889. PUBLIC cchar *httpGetWebSocketCloseReason(HttpStream *stream);
  7890. /**
  7891. Get the WebSocket private data
  7892. @description Get the private data defined with #httpSetWebSocketData
  7893. @param stream HttpStream stream object created via #httpCreateStream
  7894. @return The private data reference
  7895. @ingroup HttpWebSocket
  7896. @stability Evolving
  7897. */
  7898. PUBLIC void *httpGetWebSocketData(HttpStream *stream);
  7899. /**
  7900. Get the message length for the current message
  7901. @description The message length will be updated as the message frames are received. The message length is
  7902. only complete when the last frame has been received. See #httpIsLastPacket
  7903. @param stream HttpStream stream object created via #httpCreateStream
  7904. @return The size of the message.
  7905. @ingroup HttpWebSocket
  7906. @stability Evolving
  7907. */
  7908. PUBLIC ssize httpGetWebSocketMessageLength(HttpStream *stream);
  7909. /**
  7910. Get the selected WebSocket protocol selected by the server
  7911. @param stream HttpStream stream object created via #httpCreateStream
  7912. @return The WebSocket protocol string
  7913. @ingroup HttpWebSocket
  7914. @stability Evolving
  7915. */
  7916. PUBLIC char *httpGetWebSocketProtocol(HttpStream *stream);
  7917. /**
  7918. Get the WebSocket state
  7919. @return The WebSocket state. Will be WS_STATE_CONNECTING, WS_STATE_OPEN, WS_STATE_CLOSING or WS_STATE_CLOSED.
  7920. @ingroup HttpWebSocket
  7921. @stability Evolving
  7922. */
  7923. PUBLIC ssize httpGetWebSocketState(HttpStream *stream);
  7924. /**
  7925. Send a UTF-8 text message to the WebSocket peer
  7926. @description This call invokes httpSend with a type of WS_MSG_TEXT and flags of HTTP_BUFFER.
  7927. The message must be valid UTF8 as the peer will reject invalid UTF8 messages.
  7928. @param stream HttpStream stream object created via #httpCreateStream
  7929. @param fmt Printf style formatted string
  7930. @param ... Arguments for the format
  7931. @return Number of bytes written
  7932. @ingroup HttpWebSocket
  7933. @stability Evolving
  7934. */
  7935. PUBLIC ssize httpSend(HttpStream *stream, cchar *fmt, ...) PRINTF_ATTRIBUTE(2,3);
  7936. /**
  7937. Flag for #httpSendBlock to indicate there are more frames for this message
  7938. */
  7939. #define HTTP_MORE 0x1000
  7940. /**
  7941. Send a message of a given type to the WebSocket peer
  7942. @description This is the lower-level message send routine. It permits control of message types and message framing.
  7943. \n\n
  7944. This routine can operate in a blocking, non-blocking or buffered mode. Blocking mode is specified via the HTTP_BLOCK
  7945. flag. When blocking, the call will wait until it has written all the data. The call will either accept and write all
  7946. the data or it will fail, it will never return "short" with a partial write. If in blocking mode, the call may block
  7947. for up to the inactivity timeout specified in the stream->limits->inactivityTimeout value.
  7948. \n\n
  7949. Non-blocking mode is specified via the HTTP_NON_BLOCK flag. In this mode, the call will consume that amount of data
  7950. that will fit within the outgoing WebSocket queues. Consequently, it may return "short" with a partial write. If this
  7951. occurs the next call to httpSendBlock should set the message type to WS_MSG_CONT to indicate a continued message.
  7952. This is required by the WebSockets specification.
  7953. \n\n
  7954. Buffered mode is the default and may be explicitly specified via the HTTP_BUFFER flag. In buffered mode, the entire
  7955. message will be accepted and will be buffered if required.
  7956. \n\n
  7957. This API may split the message into frames such that no frame is larger than the limit stream->limits->webSocketsFrameSize.
  7958. However, if the HTTP_MORE flag is specified to indicate there is more data to complete this entire message, the data
  7959. provided to this call will not be split into frames and will not be aggregated with previous or subsequent messages.
  7960. i.e. frame boundaries will be presserved and sent as-is to the peer.
  7961. \n\n
  7962. In blocking mode, this routine may invoke mprYield before blocking to consent for the garbage collector to run. Callers
  7963. must ensure they have retained all required temporary memory before invoking this routine.
  7964. @param stream HttpStream stream object created via #httpCreateStream
  7965. @param type Web socket message type. Choose from WS_MSG_TEXT, WS_MSG_BINARY or WS_MSG_PING.
  7966. Use httpSendClose to send a close message. Do not send a WS_MSG_PONG message as it is generated internally
  7967. by the Web Sockets module. If using HTTP_NON_BLOCK and the call returns having written only a portion of the data,
  7968. you must set the type to WS_MSG_CONT for the
  7969. @param msg Message data buffer to send
  7970. @param len Length of msg
  7971. @param flags Include the flag HTTP_BLOCK for blocking operation or HTTP_NON_BLOCK for non-blocking. Set to HTTP_BUFFER to
  7972. buffer the data if required and never block. Set to zero will default to HTTP_BUFFER.
  7973. Include the flag HTTP_MORE to indicate there is more data to come to complete this message. This will set
  7974. frame continuation bit. Setting HTTP_MORE preserve the frame boundaries. i.e. it will ensure the data written is
  7975. not split into frames or aggregated with other data.
  7976. @return Number of data message bytes written. Should equal len if successful, otherwise returns a negative
  7977. MPR error code.
  7978. @ingroup HttpWebSocket
  7979. @stability Evolving
  7980. */
  7981. PUBLIC ssize httpSendBlock(HttpStream *stream, int type, cchar *msg, ssize len, int flags);
  7982. /**
  7983. Send a close message to the WebSocket peer
  7984. @description This call invokes httpSendBlock with a type of WS_MSG_CLOSE and flags of HTTP_BUFFER.
  7985. The status and reason are encoded in the message. The reason is an optional UTF8 closure reason message.
  7986. @param stream HttpStream stream object created via #httpCreateStream
  7987. @param status Web socket status
  7988. @param reason Optional UTF8 reason text message. The reason must be less than 124 bytes in length.
  7989. @return Number of data message bytes written. Should equal len if successful, otherwise returns a negative
  7990. MPR error code.
  7991. @ingroup HttpWebSocket
  7992. @stability Evolving
  7993. */
  7994. PUBLIC ssize httpSendClose(HttpStream *stream, int status, cchar *reason);
  7995. /**
  7996. Set the WebSocket private data
  7997. @description Set private data to be retained by the garbage collector
  7998. @param stream HttpStream stream object created via #httpCreateStream
  7999. @param data Managed data reference.
  8000. @ingroup HttpWebSocket
  8001. @stability Evolving
  8002. */
  8003. PUBLIC void httpSetWebSocketData(HttpStream *stream, void *data);
  8004. /**
  8005. Preserve frames for incoming messages
  8006. @description This routine enables user control of message framing.
  8007. When preserving frames, sent message boundaries will be preserved and will not be split into frames or
  8008. aggregated with other message frames. Received messages will similarly have their frame boundaries preserved
  8009. and will be stored one frame per HttpPacket.
  8010. Note: enabling this option may prevent full validation of UTF8 text messages if UTF8 codepoints span frame boundaries.
  8011. @param stream HttpStream stream object created via #httpCreateStream
  8012. @param on Set to true to preserve frames
  8013. @return True if the WebSocket was orderly closed.
  8014. @ingroup HttpWebSocket
  8015. @stability Evolving
  8016. */
  8017. PUBLIC void httpSetWebSocketPreserveFrames(HttpStream *stream, bool on);
  8018. /**
  8019. Set a list of application-level protocols supported by the client
  8020. @param stream HttpStream stream object created via #httpCreateStream
  8021. @param protocols Comma separated list of application-level protocols
  8022. @ingroup HttpWebSocket
  8023. @stability Evolving
  8024. */
  8025. PUBLIC void httpSetWebSocketProtocols(HttpStream *stream, cchar *protocols);
  8026. /**
  8027. Upgrade a client HTTP connection connection to use WebSockets
  8028. @description This requests an upgrade to use WebSockets. Note this is the upgrade request and the
  8029. confirmation handshake response must still be received and validated. The connection must be upgraded
  8030. before sending any data to the server.
  8031. @param stream HttpStream stream object created via #httpCreateStream
  8032. @return Return Zero if the connection upgrade can be requested.
  8033. @stability Evolving
  8034. @ingroup HttpWebSocket
  8035. @internal
  8036. */
  8037. PUBLIC int httpUpgradeWebSocket(HttpStream *stream);
  8038. /**
  8039. Test if WebSocket connection was orderly closed by sending an acknowledged close message
  8040. @param stream HttpStream stream object created via #httpCreateStream
  8041. @return True if the WebSocket was orderly closed.
  8042. @ingroup HttpWebSocket
  8043. @stability Evolving
  8044. */
  8045. PUBLIC bool httpWebSocketOrderlyClosed(HttpStream *stream);
  8046. /************************************ Dir *****************************************/
  8047. /**
  8048. Directory object for the DirHandler
  8049. @defgroup HttpDir HttpDir
  8050. @stability Internal
  8051. */
  8052. typedef struct HttpDir {
  8053. #if DIR_DIRECTIVES
  8054. MprList *dirList;
  8055. cchar *defaultIcon;
  8056. MprList *extList;
  8057. MprList *ignoreList;
  8058. #endif
  8059. bool enabled;
  8060. int fancyIndexing;
  8061. bool foldersFirst;
  8062. cchar *pattern;
  8063. char *sortField;
  8064. int sortOrder; /* 1 == ascending, -1 descending */
  8065. } HttpDir;
  8066. /**
  8067. Get the HttpDir object for a route
  8068. @ingroup HttpDir
  8069. @stability Evolving
  8070. @internal
  8071. */
  8072. PUBLIC HttpDir *httpGetDirObj(HttpRoute *route);
  8073. /************************************ CreateEvent ***********************************/
  8074. /**
  8075. Invoke a callback on a stream using a stream sequence number.
  8076. @description This routine invokes a callback on a stream's event dispatcher in a thread-safe manner. This API
  8077. is the only safe way to invoke APIs on a stream from foreign threads.
  8078. @param streamSeqno HttpStream->seqno identifier extracted when running in an MPR (Appweb) thread.
  8079. @param callback Callback function to invoke. The callback will always be invoked if the call is successful so that
  8080. you can free any allocated resources. If the stream is destroyed before the event is run, the callback will be
  8081. invoked and the "stream" argument will be set to NULL.
  8082. \n\n
  8083. If is important to check the HttpStream.error and HttpStream.state in the callback to ensure the Stream is in
  8084. an acceptable state for your logic. Typically you want HttpStream.state to be greater than HTTP_STATE_BEGIN and
  8085. less than HTTP_STATE_COMPLETE. You may also wish to check HttpStream.error incase the stream request has errored.
  8086. @param data Data to pass to the callback. This is unmanaged data. The caller is responsible for retaining and freeing.
  8087. @return "Zero" if the stream can be found and the event is scheduled, Otherwise returns MPR_ERR_CANT_FIND.
  8088. @ingroup HttpStream
  8089. @stability Evolving
  8090. */
  8091. PUBLIC int httpCreateEvent(uint64 streamSeqno, HttpEventProc callback, void *data);
  8092. /************************************ Misc *****************************************/
  8093. /**
  8094. Add an option to the options table
  8095. @param options Option table returned from httpGetOptions
  8096. @param field Field key name
  8097. @param value Value to use for the field
  8098. @ingroup Http
  8099. @stability Evolving
  8100. */
  8101. PUBLIC void httpAddOption(MprHash *options, cchar *field, cchar *value);
  8102. /**
  8103. Add an option to the options table.
  8104. @description If the field already exists, the added value is inserted prior to the existing value.
  8105. @param options Option table returned from httpGetOptions
  8106. @param field Field key name
  8107. @param value Value to use for the field
  8108. @ingroup Http
  8109. @stability Evolving
  8110. */
  8111. PUBLIC void httpInsertOption(MprHash *options, cchar *field, cchar *value);
  8112. /**
  8113. Extract a field value from an option string.
  8114. @param options Option string of the form: "field='value' field='value'..."
  8115. @param field Field key name
  8116. @param defaultValue Value to use if "field" is not found in options
  8117. @return Option value.
  8118. @ingroup Http
  8119. @stability Evolving
  8120. */
  8121. PUBLIC void *httpGetOption(MprHash *options, cchar *field, cchar *defaultValue);
  8122. /**
  8123. Get an option value that is itself an object (hash)
  8124. @description This returns an option value that is an instance of MprHash. When deserializing a JSON option string which
  8125. contains multiple levels, this routine can be used to extract lower option container values.
  8126. @param options Options object to examine.
  8127. @param field Property to return.
  8128. @return An MprHash instance for the given field. This will contain option sub-properties.
  8129. @ingroup Http
  8130. @stability Evolving
  8131. */
  8132. PUBLIC MprHash *httpGetOptionHash(MprHash *options, cchar *field);
  8133. /**
  8134. Convert an options string into an options table
  8135. @param options Option string of the form: "{field:'value', field:'value'}"
  8136. This is a sub-set of the JSON syntax. Arrays are not supported.
  8137. @return Options table
  8138. @ingroup Http
  8139. @stability Evolving
  8140. */
  8141. PUBLIC MprHash *httpGetOptions(cchar *options);
  8142. /**
  8143. Test a field value from an option string.
  8144. @param options Option string of the form: "field='value' field='value'..."
  8145. @param field Field key name
  8146. @param value Test if the field is set to this value
  8147. @param useDefault If true and "field" is not found in options, return true
  8148. @return Allocated value string.
  8149. @ingroup Http
  8150. @stability Evolving
  8151. */
  8152. PUBLIC bool httpOption(MprHash *options, cchar *field, cchar *value, int useDefault);
  8153. /**
  8154. Remove an option
  8155. @description Remove a property from an options hash
  8156. @param options Options table returned from httpGetOptions
  8157. @param field Property field to remove
  8158. @ingroup Http
  8159. @stability Evolving
  8160. */
  8161. PUBLIC void httpRemoveOption(MprHash *options, cchar *field);
  8162. /**
  8163. Set an option
  8164. @description Set a property in an options hash
  8165. @param options Options table returned from httpGetOptions
  8166. @param field Property field to set
  8167. @param value Property value to use
  8168. @ingroup Http
  8169. @stability Evolving
  8170. */
  8171. PUBLIC void httpSetOption(MprHash *options, cchar *field, cchar *value);
  8172. /**
  8173. Get more output by invoking the handler's writable callback.
  8174. Called by processRunning.
  8175. Also issues an HTTP_EVENT_WRITABLE for application level notification.
  8176. @description Get more output by invoking the handler's writable callback. Called by processRunning.
  8177. Also issues an HTTP_EVENT_WRITABLE for application level notification.
  8178. @param q HttpQueue input queue object
  8179. @ingroup HttpConn
  8180. @stability Internal
  8181. */
  8182. PUBLIC bool httpPumpOutput(HttpQueue *q);
  8183. /********************************* Compat **************************************/
  8184. /*
  8185. LEGACY redefines for compatibility with http versions 4-7
  8186. */
  8187. #if ME_COMPAT
  8188. #define conn stream
  8189. #define HttpConn HttpStream
  8190. #define httpCreateConn httpCreateStream
  8191. #define httpDestroyConn httpDestoryStream
  8192. #define httpDisconnectConn httpDisconnectStream
  8193. #define httpResetClientConn httpResetClientStream
  8194. #define httpPrepClientConn httpPrepClientStream
  8195. #define httpGetConnContext httpGetStreamContext
  8196. #define httpGetConnEventMask httpGetStreamEventMask
  8197. #define httpGetConnHost httpGetStreamHost
  8198. #define httpSetConnContext httpSetStreamContext
  8199. #define httpSetConnHost httpSetStreamHost
  8200. #define httpSetConnData httpSetStreamData
  8201. #define httpSetConnNotifier httpSetStreamNotifier
  8202. #define httpSetConnUser httpSetStreamUser
  8203. #define httpEnableConnEvents(stream) httpEnableNetEvents(stream->net)
  8204. #define httpClientConn(stream) httpClientStream(stream)
  8205. #define httpServerConn(stream) httpServerStream(stream)
  8206. #define httpDisconnect(stream) httpDisconnectStream(stream)
  8207. #endif
  8208. #ifdef __cplusplus
  8209. } /* extern C */
  8210. #endif
  8211. #endif /* _h_HTTP */
  8212. /*
  8213. Copyright (c) Embedthis Software. All Rights Reserved.
  8214. This software is distributed under a commercial license. Consult the LICENSE.md
  8215. distributed with this software for full details and copyrights.
  8216. */