mpr.h 429 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680
  1. /*
  2. mpr.h -- Header for the Multithreaded Portable Runtime (MPR).
  3. Copyright (c) All Rights Reserved. See details at the end of the file.
  4. */
  5. /**
  6. @file mpr.h
  7. The Multithreaded Portable Runtime (MPR) is a portable runtime library for embedded applications.
  8. @description The MPR provides management for logging, error handling, events, files, http, memory, ssl,
  9. sockets, strings, xml parsing, and date/time functions. It also provides a foundation of safe routines for secure
  10. programming, that help to prevent buffer overflows and other security threats. The MPR is a library and a C API that can
  11. be used in both C and C++ programs.
  12. \n\n
  13. The MPR uses a set extended typedefs for common types. These include: bool, cchar, cvoid, uchar, short, ushort,
  14. int, uint, long, ulong, int32, uint32, int64, uint64, float, and double. The cchar type is a const char, cvoid is
  15. const void. Several types have "u" prefixes to denote unsigned qualifiers.
  16. \n\n
  17. The MPR includes a memory allocator and generational garbage collector. The allocator is a fast, immediate
  18. coalescing allocator that will return memory back to the O/S if not required. It is optimized for frequent
  19. allocations of small blocks (< 4K) and uses a scheme of free queues for fast allocation.
  20. \n\n
  21. The MPR provides a high-performance thread-pool to share threads as required to service clients.
  22. When a client request arrives, the MPR allocates an event queue called a dispatcher. This dispatcher then serializes
  23. all activity for the request so that it essentially runs single-threaded This simplifies the code as most
  24. interactions do not need to be lock protected. When a request has activity, it borrows a thread from the thread pool,
  25. does its work and then returns the thread to the thread pool. This all happens very quickly, so a small pool of
  26. threads are effectivelyshared over many requests. Thread are free to block if required, but typically non-blocking
  27. patterns are more economical. If you have non-MPR threads that need to call into the MPR, you must synchronize
  28. such calls via #mprCreateEvent.
  29. */
  30. #ifndef _h_MPR
  31. #define _h_MPR 1
  32. /********************************** Includes **********************************/
  33. #include "me.h"
  34. #include "osdep.h"
  35. /*********************************** Defines **********************************/
  36. #if DOXYGEN
  37. /** Argument for sockets */
  38. typedef int Socket;
  39. /** Unsigned integral type. Equivalent in size to void* */
  40. typedef long size_t;
  41. #endif
  42. #ifdef __cplusplus
  43. extern "C" {
  44. #endif
  45. struct tm;
  46. struct Mpr;
  47. struct MprMem;
  48. struct MprBuf;
  49. struct MprCmd;
  50. struct MprCache;
  51. struct MprCond;
  52. struct MprDispatcher;
  53. struct MprEvent;
  54. struct MprEventService;
  55. struct MprFile;
  56. struct MprFileSystem;
  57. struct MprHash;
  58. struct MprHeap;
  59. struct MprJson;
  60. struct MprJsonParser;
  61. struct MprList;
  62. struct MprKey;
  63. struct MprModule;
  64. struct MprMutex;
  65. struct MprOsService;
  66. struct MprPath;
  67. struct MprSignal;
  68. struct MprSocket;
  69. struct MprSocketService;
  70. struct MprSsl;
  71. struct MprThread;
  72. struct MprThreadService;
  73. struct MprWaitService;
  74. struct MprWaitHandler;
  75. struct MprWorker;
  76. struct MprWorkerService;
  77. struct MprXml;
  78. #ifndef ME_MPR_LOGGING
  79. #define ME_MPR_LOGGING 1 /**< Default for logging is "on" */
  80. #endif
  81. #ifndef ME_MPR_DEBUG_LOGGING
  82. #if ME_DEBUG
  83. #define ME_MPR_DEBUG_LOGGING 1
  84. #else
  85. #define ME_MPR_DEBUG_LOGGING 0
  86. #endif
  87. #endif
  88. #ifndef ME_MPR_TEST
  89. #define ME_MPR_TEST 1
  90. #endif
  91. #ifndef ME_MPR_MAX_PASSWORD
  92. #define ME_MPR_MAX_PASSWORD 256 /**< Max password length */
  93. #endif
  94. #ifndef ME_MPR_THREAD_LIMIT_BY_CORES
  95. #define ME_MPR_THREAD_LIMIT_BY_CORES 1
  96. #endif
  97. /*
  98. Select wakeup port. Port can be any free port number. If this is not free, the MPR will use the next free port.
  99. */
  100. #ifndef ME_WAKEUP_ADDR
  101. #define ME_WAKEUP_ADDR "127.0.0.1"
  102. #endif
  103. #ifndef ME_WAKEUP_PORT
  104. #define ME_WAKEUP_PORT 9473
  105. #endif
  106. #define MPR_FD_MIN 32
  107. /*
  108. Signal sent on Unix to break out of a select call.
  109. */
  110. #define MPR_WAIT_SIGNAL (SIGUSR2)
  111. /*
  112. Socket event message
  113. */
  114. #define MPR_SOCKET_MESSAGE (WM_USER + 32)
  115. /*
  116. Coalesce vectored write packets when using SSL
  117. */
  118. #ifndef ME_MPR_SOCKET_VECTOR_JOIN
  119. #define ME_MPR_SOCKET_VECTOR_JOIN 1
  120. #endif
  121. /*
  122. Priorities
  123. */
  124. #define MPR_BACKGROUND_PRIORITY 15 /**< May only get CPU if idle */
  125. #define MPR_LOW_PRIORITY 25
  126. #define MPR_NORMAL_PRIORITY 50 /**< Normal (default) priority */
  127. #define MPR_HIGH_PRIORITY 75
  128. #define MPR_CRITICAL_PRIORITY 99 /**< May not yield */
  129. #define MPR_EVENT_PRIORITY 50 /**< Normal priority */
  130. #define MPR_WORKER_PRIORITY 50 /**< Normal priority */
  131. #define MPR_REQUEST_PRIORITY 50 /**< Normal priority */
  132. /*
  133. Timeouts
  134. */
  135. #define MPR_TIMEOUT_PRUNER 120000 /**< Time between worker thread pruner runs (2 min) */
  136. #define MPR_TIMEOUT_WORKER 60000 /**< Prune worker that has been idle for 1 min */
  137. #define MPR_TIMEOUT_START_TASK 10000 /**< Time to start tasks running */
  138. #define MPR_TIMEOUT_STOP 30000 /**< Default wait when stopping resources (30 sec) */
  139. #define MPR_TIMEOUT_STOP_TASK 10000 /**< Time to stop or reap tasks (vxworks) */
  140. #define MPR_TIMEOUT_LINGER 2000 /**< Close socket linger timeout */
  141. #define MPR_TIMEOUT_GC_SYNC 100 /**< Short wait period for threads to synchronize */
  142. #define MPR_TIMEOUT_NO_BUSY 1000 /**< Wait period to minimize CPU drain */
  143. #define MPR_TIMEOUT_NAP 20 /**< Short pause */
  144. #define MPR_MAX_TIMEOUT MAXINT64
  145. /*
  146. Default thread counts
  147. */
  148. #define MPR_DEFAULT_MIN_THREADS 0 /**< Default min threads */
  149. #define MPR_DEFAULT_MAX_THREADS 5 /**< Default max threads */
  150. /*
  151. Debug control
  152. */
  153. #define MPR_MAX_BLOCKED_LOCKS 100 /* Max threads blocked on lock */
  154. #define MPR_MAX_RECURSION 15 /* Max recursion with one thread */
  155. #define MPR_MAX_LOCKS 512 /* Total lock count max */
  156. #define MPR_MAX_LOCK_TIME (60 * 1000) /* Time in msec to hold a lock */
  157. #define MPR_TIMER_TOLERANCE 2 /* Used in timer calculations */
  158. #define MPR_CMD_TIMER_PERIOD 5000 /* Check for expired commands */
  159. /**
  160. Events
  161. */
  162. #define MPR_EVENT_TIME_SLICE 20 /* 20 msec */
  163. /**
  164. Maximum number of files to close when forking
  165. */
  166. #define MPR_MAX_FILE 256
  167. /*
  168. Event notification mechanisms
  169. */
  170. #define MPR_EVENT_ASYNC 1 /**< Windows async select */
  171. #define MPR_EVENT_EPOLL 2 /**< epoll_wait */
  172. #define MPR_EVENT_KQUEUE 3 /**< BSD kqueue */
  173. #define MPR_EVENT_SELECT 4 /**< traditional select() */
  174. #define MPR_EVENT_SELECT_PIPE 5 /**< Select with pipe for wakeup */
  175. #ifndef ME_EVENT_NOTIFIER
  176. #if MACOSX || SOLARIS
  177. #define ME_EVENT_NOTIFIER MPR_EVENT_KQUEUE
  178. #elif WINDOWS
  179. #define ME_EVENT_NOTIFIER MPR_EVENT_ASYNC
  180. #elif VXWORKS
  181. #define ME_EVENT_NOTIFIER MPR_EVENT_SELECT
  182. #elif LINUX
  183. #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
  184. #define ME_EVENT_NOTIFIER MPR_EVENT_EPOLL
  185. #else
  186. #define ME_EVENT_NOTIFIER MPR_EVENT_SELECT
  187. #endif
  188. #else
  189. #define ME_EVENT_NOTIFIER MPR_EVENT_SELECT
  190. #endif
  191. #endif
  192. /**
  193. Maximum number of notifier events
  194. */
  195. #ifndef ME_MAX_EVENTS
  196. #define ME_MAX_EVENTS 32
  197. #endif
  198. /*
  199. Garbage collector tuning
  200. */
  201. #define MPR_MIN_TIME_FOR_GC 2 /**< Wait till 2 milliseconds of idle time possible */
  202. /************************************ Error Codes *****************************/
  203. /* Prevent collisions with 3rd party software */
  204. #undef UNUSED
  205. /*
  206. Standard errors
  207. */
  208. #define MPR_ERR_OK 0 /**< Success */
  209. #define MPR_ERR_BASE -1 /**< Base error code */
  210. #define MPR_ERR -1 /**< Default error code */
  211. #define MPR_ERR_ABORTED -2 /**< Action aborted */
  212. #define MPR_ERR_ALREADY_EXISTS -3 /**< Item already exists */
  213. #define MPR_ERR_BAD_ARGS -4 /**< Bad arguments or paramaeters */
  214. #define MPR_ERR_BAD_FORMAT -5 /**< Bad input format */
  215. #define MPR_ERR_BAD_HANDLE -6 /**< Bad file handle */
  216. #define MPR_ERR_BAD_STATE -7 /**< Module is in a bad state */
  217. #define MPR_ERR_BAD_SYNTAX -8 /**< Input has bad syntax */
  218. #define MPR_ERR_BAD_TYPE -9 /**< Bad object type */
  219. #define MPR_ERR_BAD_VALUE -10 /**< Bad or unexpected value */
  220. #define MPR_ERR_BUSY -11 /**< Resource is busy */
  221. #define MPR_ERR_CANT_ACCESS -12 /**< Cannot access the file or resource */
  222. #define MPR_ERR_CANT_ALLOCATE -13 /**< Cannot allocate resource */
  223. #define MPR_ERR_CANT_COMPLETE -14 /**< Operation cannot complete */
  224. #define MPR_ERR_CANT_CONNECT -15 /**< Cannot connect to network or resource */
  225. #define MPR_ERR_CANT_CREATE -16 /**< Cannot create the file or resource */
  226. #define MPR_ERR_CANT_DELETE -17 /**< Cannot delete the resource */
  227. #define MPR_ERR_CANT_FIND -18 /**< Cannot find resource */
  228. #define MPR_ERR_CANT_INITIALIZE -19 /**< Cannot initialize resource */
  229. #define MPR_ERR_CANT_LOAD -20 /**< Cannot load the resource */
  230. #define MPR_ERR_CANT_OPEN -21 /**< Cannot open the file or resource */
  231. #define MPR_ERR_CANT_READ -22 /**< Cannot read from the file or resource */
  232. #define MPR_ERR_CANT_WRITE -23 /**< Cannot write to the file or resource */
  233. #define MPR_ERR_DELETED -24 /**< Resource has been deleted */
  234. #define MPR_ERR_MEMORY -25 /**< Memory allocation error */
  235. #define MPR_ERR_NETWORK -26 /**< Underlying network error */
  236. #define MPR_ERR_NOT_INITIALIZED -27 /**< Module or resource is not initialized */
  237. #define MPR_ERR_NOT_READY -28 /**< Resource is not ready */
  238. #define MPR_ERR_READ_ONLY -29 /**< The operation timed out */
  239. #define MPR_ERR_TIMEOUT -30 /**< Operation exceeded specified time allowed */
  240. #define MPR_ERR_TOO_MANY -31 /**< Too many requests or resources */
  241. #define MPR_ERR_WONT_FIT -32 /**< Requested operation won't fit in available space */
  242. #define MPR_ERR_WOULD_BLOCK -33 /**< Blocking operation would block */
  243. #define MPR_ERR_MAX -34
  244. /*
  245. Error line number information.
  246. */
  247. #define MPR_LINE(s) #s
  248. #define MPR_LINE2(s) MPR_LINE(s)
  249. #define MPR_LINE3 MPR_LINE2(__LINE__)
  250. #define MPR_LOC __FILE__ ":" MPR_LINE3
  251. #define MPR_NAME(msg) msg "@" MPR_LOC
  252. #define MPR_STRINGIFY(s) #s
  253. /*
  254. Convenience define to declare a main program entry point that works for Windows, VxWorks and Unix
  255. */
  256. #if VXWORKS
  257. #define MAIN(name, _argc, _argv, _envp) \
  258. static int innerMain(int argc, char **argv, char **envp); \
  259. int name(char *arg0, ...) { \
  260. va_list args; \
  261. char *argp, *largv[ME_MAX_ARGC]; \
  262. int largc = 0; \
  263. va_start(args, arg0); \
  264. largv[largc++] = #name; \
  265. if (arg0) { \
  266. largv[largc++] = arg0; \
  267. } \
  268. for (argp = va_arg(args, char*); argp && largc < ME_MAX_ARGC; argp = va_arg(args, char*)) { \
  269. largv[largc++] = argp; \
  270. } \
  271. return innerMain(largc, largv, NULL); \
  272. } \
  273. static int innerMain(_argc, _argv, _envp)
  274. #elif ME_WIN_LIKE
  275. #define MAIN(name, _argc, _argv, _envp) \
  276. APIENTRY WinMain(HINSTANCE inst, HINSTANCE junk, char *command, int junk2) { \
  277. PUBLIC int main(); \
  278. char *largv[ME_MAX_ARGC]; \
  279. int largc; \
  280. largc = mprParseArgs(command, &largv[1], ME_MAX_ARGC - 1); \
  281. largv[0] = #name; \
  282. main(largc, largv, NULL); \
  283. } \
  284. int main(_argc, _argv, _envp)
  285. #else
  286. #define MAIN(name, _argc, _argv, _envp) int main(_argc, _argv, _envp)
  287. #endif
  288. #if ME_UNIX_LIKE
  289. typedef pthread_t MprOsThread;
  290. #elif ME_64
  291. typedef int64 MprOsThread;
  292. #else
  293. typedef int MprOsThread;
  294. #endif
  295. /**
  296. Elapsed time data type. Stores time in milliseconds from some arbitrary start epoch.
  297. */
  298. typedef Ticks MprTicks;
  299. /************************************** Debug *********************************/
  300. /**
  301. Trigger a breakpoint.
  302. @description This routine is invoked for assertion errors from #mprAssert and errors from #mprError.
  303. It is useful in debuggers as breakpoint location for detecting errors.
  304. @ingroup Mpr
  305. @stability Stable
  306. */
  307. PUBLIC void mprBreakpoint(void);
  308. #undef assert
  309. #if DOXYGEN
  310. /**
  311. Assert that a condition is true
  312. @param cond Boolean result of a conditional test
  313. @ingroup Mpr
  314. @stability Stable
  315. */
  316. PUBLIC void assert(bool cond);
  317. #elif ME_MPR_DEBUG_LOGGING
  318. #undef assert
  319. #define assert(C) if (C) ; else mprAssert(MPR_LOC, #C)
  320. #else
  321. #undef assert
  322. #define assert(C) if (1) ; else {}
  323. #endif
  324. /*********************************** Thread Sync ******************************/
  325. /**
  326. Multithreaded Synchronization Services
  327. @see MprCond MprMutex MprSpin mprAtomicAdd mprAtomicAdd64 mprAtomicBarrier mprAtomicCas mprAtomicExchange
  328. mprAtomicListInsert mprCreateCond mprCreateLock mprCreateSpinLock mprGlobalLock mprGlobalUnlock mprInitLock
  329. mprInitSpinLock mprLock mprResetCond mprSignalCond mprSignalMultiCond mprSpinLock mprSpinUnlock mprTryLock
  330. mprTrySpinLock mprUnlock mprWaitForCond mprWaitForMultiCond
  331. @stability Internal.
  332. @defgroup MprSync MprSync
  333. */
  334. typedef struct MprSync { int dummy; } MprSync;
  335. #ifndef ME_MPR_SPIN_COUNT
  336. #define ME_MPR_SPIN_COUNT 1500 /* Windows lock spin count */
  337. #endif
  338. /**
  339. Condition variable for single and multi-thread synchronization. Condition variables can be used to coordinate
  340. activities. These variables are level triggered in that a condition can be signalled prior to another thread
  341. waiting. Condition variables can be used when single threaded but mprServiceEvents should be called to pump events
  342. until another callback invokes mprWaitForCond.
  343. @ingroup MprSync
  344. @stability Internal.
  345. */
  346. typedef struct MprCond {
  347. #if ME_UNIX_LIKE
  348. pthread_cond_t cv; /**< Unix pthreads condition variable */
  349. #elif ME_WIN_LIKE
  350. HANDLE cv; /**< Windows event handle */
  351. #elif VXWORKS
  352. SEM_ID cv; /**< Condition variable */
  353. #else
  354. #warning "Unsupported OS in MprCond definition in mpr.h"
  355. #endif
  356. struct MprMutex *mutex; /**< Thread synchronization mutex */
  357. volatile int triggered; /**< Value of the condition */
  358. } MprCond;
  359. /**
  360. Create a condition lock variable.
  361. @description This call creates a condition variable object that can be used in #mprWaitForCond and #mprSignalCond calls.
  362. @ingroup MprSync
  363. @stability Stable.
  364. */
  365. PUBLIC MprCond *mprCreateCond(void);
  366. /**
  367. Reset a condition variable. This sets the condition variable to the unsignalled condition.
  368. @param cond Condition variable object created via #mprCreateCond
  369. @ingroup MprSync
  370. @stability Stable.
  371. */
  372. PUBLIC void mprResetCond(MprCond *cond);
  373. /**
  374. Wait for a condition lock variable.
  375. @description Wait for a condition lock variable to be signaled. If the condition is signaled before the timeout
  376. expires, this call will reset the condition variable and return. This way, it automatically resets the variable
  377. for future waiters.
  378. @param cond Condition variable object created via #mprCreateCond
  379. @param timeout Time in milliseconds to wait for the condition variable to be signaled.
  380. @return Zero if the event was signalled. Returns < 0 for a timeout.
  381. @ingroup MprSync
  382. @stability Stable.
  383. */
  384. PUBLIC int mprWaitForCond(MprCond *cond, MprTicks timeout);
  385. /**
  386. Signal a condition lock variable.
  387. @description Signal a condition variable and set it to the \a triggered status. Existing or future caller of
  388. #mprWaitForCond will be awakened. The condition variable will be automatically reset when the waiter awakes.
  389. Should only be used for single waiters. Use mprSignalMultiCond for use with multiple waiters.
  390. \n\n
  391. This API (like nearly all MPR APIs) must only be used by MPR threads and not by non-MPR (foreign) threads.
  392. If you need to synchronize active of MPR threads with non-MPR threads, use #mprCreateEvent which can be called from
  393. foreign threads.
  394. @param cond Condition variable object created via #mprCreateCond
  395. @ingroup MprSync
  396. @stability Stable.
  397. */
  398. PUBLIC void mprSignalCond(MprCond *cond);
  399. /**
  400. Signal a condition lock variable for use with multiple waiters.
  401. @description Signal a condition variable and set it to the \a triggered status. Existing or future callers of
  402. #mprWaitForCond will be awakened. The conditional variable will not be automatically reset and must be reset
  403. manually via mprResetCond.
  404. @param cond Condition variable object created via #mprCreateCond
  405. @ingroup MprSync
  406. @stability Stable.
  407. */
  408. PUBLIC void mprSignalMultiCond(MprCond *cond);
  409. /**
  410. Wait for a condition lock variable for use with multiple waiters.
  411. @description Wait for a condition lock variable to be signaled. Multiple waiters are supported and the
  412. condition variable must be manually reset via mprResetCond. The condition may signaled before calling
  413. mprWaitForMultiCond.
  414. @param cond Condition variable object created via #mprCreateCond
  415. @param timeout Time in milliseconds to wait for the condition variable to be signaled.
  416. @return Zero if the event was signalled. Returns < 0 for a timeout.
  417. @ingroup MprSync
  418. @stability Stable.
  419. */
  420. PUBLIC int mprWaitForMultiCond(MprCond *cond, MprTicks timeout);
  421. /**
  422. Multithreading lock control structure
  423. @description MprMutex is used for multithread locking in multithreaded applications.
  424. @ingroup MprSync
  425. @stability Internal.
  426. */
  427. typedef struct MprMutex {
  428. #if ME_WIN_LIKE
  429. CRITICAL_SECTION cs; /**< Internal mutex critical section */
  430. bool freed; /**< Mutex has been destroyed */
  431. #elif VXWORKS
  432. SEM_ID cs;
  433. #elif ME_UNIX_LIKE
  434. pthread_mutex_t cs;
  435. #else
  436. #warning "Unsupported OS in MprMutex definition in mpr.h"
  437. #endif
  438. #if ME_DEBUG
  439. MprOsThread owner;
  440. #endif
  441. } MprMutex;
  442. /**
  443. Multithreading spin lock control structure
  444. @description MprSpin is used for multithread locking in multithreaded applications.
  445. @ingroup MprSync
  446. @stability Internal.
  447. */
  448. typedef struct MprSpin {
  449. #if USE_MPR_LOCK
  450. MprMutex cs;
  451. #elif ME_WIN_LIKE
  452. CRITICAL_SECTION cs; /**< Internal mutex critical section */
  453. bool freed; /**< Mutex has been destroyed */
  454. #elif VXWORKS
  455. SEM_ID cs;
  456. #elif ME_UNIX_LIKE
  457. #if ME_COMPILER_HAS_SPINLOCK
  458. pthread_spinlock_t cs;
  459. #else
  460. pthread_mutex_t cs;
  461. #endif
  462. #else
  463. #warning "Unsupported OS in MprSpin definition in mpr.h"
  464. #endif
  465. #if ME_DEBUG
  466. MprOsThread owner;
  467. #endif
  468. } MprSpin;
  469. #undef lock
  470. #undef unlock
  471. #undef spinlock
  472. #undef spinunlock
  473. #define lock(arg) if (arg && (arg)->mutex) mprLock((arg)->mutex)
  474. #define unlock(arg) if (arg && (arg)->mutex) mprUnlock((arg)->mutex)
  475. #define spinlock(arg) if (arg) mprSpinLock((arg)->spin)
  476. #define spinunlock(arg) if (arg) mprSpinUnlock((arg)->spin)
  477. /**
  478. Create a Mutex lock object.
  479. @description This call creates a Mutex lock object that can be used in mprLock #mprTryLock and mprUnlock calls.
  480. @ingroup MprSync
  481. @stability Stable.
  482. */
  483. PUBLIC MprMutex *mprCreateLock(void);
  484. /**
  485. Initialize a statically allocated Mutex lock object.
  486. @description This call initialized a Mutex lock object without allocation. The object can then be used used
  487. in mprLock mprTryLock and mprUnlock calls.
  488. @param mutex Reference to an MprMutex structure to initialize
  489. @returns A reference to the supplied mutex. Returns null on errors.
  490. @ingroup MprSync
  491. @stability Stable.
  492. */
  493. PUBLIC MprMutex *mprInitLock(MprMutex *mutex);
  494. /**
  495. Attempt to lock access.
  496. @description This call attempts to assert a lock on the given \a lock mutex so that other threads calling
  497. mprLock or mprTryLock will block until the current thread calls mprUnlock.
  498. @returns Returns zero if the successful in locking the mutex. Returns a negative MPR error code if unsuccessful.
  499. @ingroup MprSync
  500. @stability Stable.
  501. */
  502. PUBLIC bool mprTryLock(MprMutex *lock);
  503. /**
  504. Create a spin lock lock object.
  505. @description This call creates a spinlock object that can be used in mprSpinLock, and mprSpinUnlock calls. Spin locks
  506. using MprSpin are much faster than MprMutex based locks on some systems.
  507. @ingroup MprSync
  508. @stability Stable.
  509. */
  510. PUBLIC MprSpin *mprCreateSpinLock(void);
  511. /**
  512. Initialize a statically allocated spinlock object.
  513. @description This call initialized a spinlock lock object without allocation. The object can then be used used
  514. in mprSpinLock and mprSpinUnlock calls.
  515. @param lock Reference to a static #MprSpin object.
  516. @returns A reference to the MprSpin object. Returns null on errors.
  517. @ingroup MprSync
  518. */
  519. PUBLIC MprSpin *mprInitSpinLock(MprSpin *lock);
  520. /**
  521. Attempt to lock access on a spin lock
  522. @description This call attempts to assert a lock on the given \a spin lock so that other threads calling
  523. mprSpinLock or mprTrySpinLock will block until the current thread calls mprSpinUnlock.
  524. @returns Returns zero if the successful in locking the spinlock. Returns a negative MPR error code if unsuccessful.
  525. @ingroup MprSync
  526. @stability Stable.
  527. */
  528. PUBLIC bool mprTrySpinLock(MprSpin *lock);
  529. /*
  530. For maximum performance, use the spin lock/unlock routines macros
  531. */
  532. #if !ME_DEBUG
  533. #define ME_USE_LOCK_MACROS 1
  534. #endif
  535. #if ME_USE_LOCK_MACROS && !DOXYGEN
  536. /*
  537. Spin lock macros
  538. */
  539. #if ME_UNIX_LIKE && ME_COMPILER_HAS_SPINLOCK
  540. #define mprSpinLock(lock) if (lock) pthread_spin_lock(&((lock)->cs))
  541. #define mprSpinUnlock(lock) if (lock) pthread_spin_unlock(&((lock)->cs))
  542. #elif ME_UNIX_LIKE
  543. #define mprSpinLock(lock) if (lock) pthread_mutex_lock(&((lock)->cs))
  544. #define mprSpinUnlock(lock) if (lock) pthread_mutex_unlock(&((lock)->cs))
  545. #elif ME_WIN_LIKE
  546. #define mprSpinLock(lock) if (lock && (!((MprSpin*)(lock))->freed)) EnterCriticalSection(&((lock)->cs))
  547. #define mprSpinUnlock(lock) if (lock) LeaveCriticalSection(&((lock)->cs))
  548. #elif VXWORKS
  549. #define mprSpinLock(lock) if (lock) semTake((lock)->cs, WAIT_FOREVER)
  550. #define mprSpinUnlock(lock) if (lock) semGive((lock)->cs)
  551. #endif
  552. /*
  553. Lock macros
  554. */
  555. #if ME_UNIX_LIKE
  556. #define mprLock(lock) if (lock) pthread_mutex_lock(&((lock)->cs))
  557. #define mprUnlock(lock) if (lock) pthread_mutex_unlock(&((lock)->cs))
  558. #elif ME_WIN_LIKE
  559. #define mprLock(lock) if (lock && !(((MprSpin*)(lock))->freed)) EnterCriticalSection(&((lock)->cs))
  560. #define mprUnlock(lock) if (lock) LeaveCriticalSection(&((lock)->cs))
  561. #elif VXWORKS
  562. #define mprLock(lock) if (lock) semTake((lock)->cs, WAIT_FOREVER)
  563. #define mprUnlock(lock) if (lock) semGive((lock)->cs)
  564. #endif
  565. #else
  566. /**
  567. Lock access.
  568. @description This call asserts a lock on the given \a lock mutex so that other threads calling mprLock will
  569. block until the current thread calls mprUnlock.
  570. @ingroup MprSync
  571. @stability Stable.
  572. */
  573. PUBLIC void mprLock(MprMutex *lock);
  574. /**
  575. Unlock a mutex.
  576. @description This call unlocks a mutex previously locked via mprLock or mprTryLock.
  577. @ingroup MprSync
  578. @stability Stable.
  579. */
  580. PUBLIC void mprUnlock(MprMutex *lock);
  581. /**
  582. Lock a spinlock.
  583. @description This call asserts a lock on the given \a spinlock so that other threads calling mprSpinLock will
  584. block until the curren thread calls mprSpinUnlock.
  585. @ingroup MprSync
  586. @stability Stable.
  587. */
  588. PUBLIC void mprSpinLock(MprSpin *lock);
  589. /**
  590. Unlock a spinlock.
  591. @description This call unlocks a spinlock previously locked via mprSpinLock or mprTrySpinLock.
  592. @ingroup MprSync
  593. @stability Stable.
  594. */
  595. PUBLIC void mprSpinUnlock(MprSpin *lock);
  596. #endif
  597. /**
  598. Globally lock the application.
  599. @description This call asserts the application global lock so that other threads calling mprGlobalLock will
  600. block until the current thread calls mprGlobalUnlock. WARNING: Use this API very sparingly.
  601. @ingroup MprSync
  602. @stability Stable.
  603. */
  604. PUBLIC void mprGlobalLock(void);
  605. /**
  606. Unlock the global mutex.
  607. @description This call unlocks the global mutex previously locked via mprGlobalLock.
  608. @ingroup MprSync
  609. @stability Stable.
  610. */
  611. PUBLIC void mprGlobalUnlock(void);
  612. /*
  613. Lock free primitives
  614. */
  615. /*
  616. AtomicBarrier memory models
  617. */
  618. #if ME_UNIX_LIKE
  619. #define MPR_ATOMIC_RELAXED __ATOMIC_RELAXED
  620. #define MPR_ATOMIC_CONSUME __ATOMIC_CONSUME
  621. #define MPR_ATOMIC_ACQUIRE __ATOMIC_ACQUIRE
  622. #define MPR_ATOMIC_RELEASE __ATOMIC_RELEASE
  623. #define MPR_ATOMIC_ACQ_REL __ATOMIC_ACQ_REL
  624. #define MPR_ATOMIC_SEQUENTIAL __ATOMIC_SEQ_CST
  625. #else
  626. #define MPR_ATOMIC_RELAXED 0
  627. #define MPR_ATOMIC_CONSUME 1
  628. #define MPR_ATOMIC_ACQUIRE 2
  629. #define MPR_ATOMIC_RELEASE 3
  630. #define MPR_ATOMIC_ACQ_REL 4
  631. #define MPR_ATOMIC_SEQUENTIAL 5
  632. #endif
  633. /**
  634. Open and initialize the atomic subystem
  635. @ingroup MprSync
  636. @stability Stable.
  637. */
  638. PUBLIC void mprAtomicOpen(void);
  639. /**
  640. Apply a full (read+write) memory barrier
  641. @param model Memory model. Set to MPR_ATOMIC_RELAXED, MPR_ATOMIC_CONSUME, MPR_ATOMIC_ACQUIRE,
  642. MPR_ATOMIC_RELEASE, MPR_ATOMIC_ACQREL, MPR_ATOMIC_SEQUENTIAL
  643. @ingroup MprSync
  644. @stability Evolving.
  645. */
  646. PUBLIC void mprAtomicBarrier(int model);
  647. /**
  648. Atomic list insertion. Inserts "item" at the "head" of the list. The "link" field is the next field in item.
  649. This is a lock-free function
  650. @param head list head
  651. @param link Reference to the list head link field
  652. @param item Item to insert
  653. @ingroup MprSync
  654. @stability Stable
  655. */
  656. PUBLIC void mprAtomicListInsert(void **head, void **link, void *item);
  657. /**
  658. Atomic Compare and Swap. This is a lock free function.
  659. @param target Address of the target word to swap
  660. @param expected Expected value of the target
  661. @param value New value to store at the target
  662. @return TRUE if the swap was successful
  663. @ingroup MprSync
  664. @stability Stable
  665. */
  666. PUBLIC int mprAtomicCas(void * volatile * target, void *expected, cvoid *value);
  667. /**
  668. Atomic Add. This is a lock free function.
  669. @param target Address of the target word to add to.
  670. @param value Value to add to the target
  671. @ingroup MprSync
  672. @stability Stable.
  673. */
  674. PUBLIC void mprAtomicAdd(volatile int *target, int value);
  675. /**
  676. Atomic 64 bit Add. This is a lock free function.
  677. @param target Address of the target word to add to.
  678. @param value Value to add to the target
  679. @ingroup MprSync
  680. @stability Stable.
  681. */
  682. PUBLIC void mprAtomicAdd64(volatile int64 *target, int64 value);
  683. #if ME_COMPILER_HAS_ATOMIC
  684. #define mprAtomicLoad(ptr, ret, model) __atomic_load(ptr, ret, model)
  685. #define mprAtomicStore(ptr, valptr, model) __atomic_store(ptr, valptr, model)
  686. #else
  687. #define mprAtomicLoad(ptr, ret, model) \
  688. if (1) { \
  689. mprAtomicBarrier(model); \
  690. *ret = *(ptr); \
  691. } else
  692. #define mprAtomicStore(ptr, valptr, model) \
  693. if (1) { \
  694. mprAtomicBarrier(model); \
  695. *ptr = *(valptr); \
  696. } else
  697. #endif
  698. /********************************* Memory Allocator ***************************/
  699. /*
  700. Allocator debug and stats selection
  701. To set via configure:
  702. configure --set mpr.alloc.check=true
  703. configure --set mpr.alloc.cache=NNN
  704. configure --set mpr.alloc.quota=NNN
  705. */
  706. #if ME_MPR_ALLOC_CHECK
  707. #ifndef ME_MPR_ALLOC_DEBUG
  708. #define ME_MPR_ALLOC_DEBUG 1 /**< Fill blocks, verifies block integrity, block names */
  709. #endif
  710. #ifndef ME_MPR_ALLOC_STATS
  711. #define ME_MPR_ALLOC_STATS 1 /**< Include memory statistics */
  712. #endif
  713. #ifndef ME_MPR_ALLOC_STACK
  714. #define ME_MPR_ALLOC_STACK 1 /**< Monitor stack usage */
  715. #endif
  716. #ifndef ME_MPR_ALLOC_TRACE
  717. #define ME_MPR_ALLOC_TRACE 0 /**< Trace to stdout */
  718. #endif
  719. #else
  720. #ifndef ME_MPR_ALLOC_DEBUG
  721. #define ME_MPR_ALLOC_DEBUG 0
  722. #endif
  723. #ifndef ME_MPR_ALLOC_STATS
  724. #define ME_MPR_ALLOC_STATS 0
  725. #endif
  726. #ifndef ME_MPR_ALLOC_STACK
  727. #define ME_MPR_ALLOC_STACK 0
  728. #endif
  729. #ifndef ME_MPR_ALLOC_TRACE
  730. #define ME_MPR_ALLOC_TRACE 0 /**< Trace to stdout */
  731. #endif
  732. #endif
  733. /*
  734. Allocator Tunables
  735. */
  736. #ifndef ME_MPR_ALLOC_CACHE
  737. /*
  738. Try to cache at least this amount in the heap free queues
  739. */
  740. #if ME_TUNE_SIZE
  741. #define ME_MPR_ALLOC_CACHE 0
  742. #elif ME_TUNE_SPEED
  743. #define ME_MPR_ALLOC_CACHE (1 * 1024 * 1024) /* 1MB */
  744. #else
  745. #define ME_MPR_ALLOC_CACHE ME_MPR_ALLOC_REGION_SIZE
  746. #endif
  747. #endif
  748. #ifndef ME_MPR_ALLOC_LEVEL
  749. #define ME_MPR_ALLOC_LEVEL 7 /* Emit mark/sweek elapsed time at this level */
  750. #endif
  751. #if ME_COMPILER_HAS_MMU
  752. #define ME_MPR_ALLOC_VIRTUAL 1 /* Use virtual memory allocations */
  753. #else
  754. #define ME_MPR_ALLOC_VIRTUAL 0 /* Use malloc() for region allocations */
  755. #endif
  756. #ifndef ME_MPR_ALLOC_QUOTA
  757. #if ME_TUNE_SIZE
  758. #define ME_MPR_ALLOC_QUOTA (100 * 1024) /* Allocations before a GC. Scaled by workers/2 */
  759. #else
  760. #define ME_MPR_ALLOC_QUOTA (200 * 1024)
  761. #endif
  762. #endif
  763. #ifndef ME_MPR_ALLOC_REGION_SIZE
  764. #define ME_MPR_ALLOC_REGION_SIZE (256 * 1024) /* Memory region allocation chunk size */
  765. #endif
  766. #ifndef ME_MPR_ALLOC_ALIGN_SHIFT
  767. /*
  768. Allocated block alignment expressed as a bit shift. The default alignment is set so that allocated memory can be used
  769. for doubles. NOTE: SSE and AltiVec instuctions may require 16 byte alignment.
  770. */
  771. #if !ME_64 && !(ME_CPU_ARCH == ME_CPU_MIPS)
  772. #define ME_MPR_ALLOC_ALIGN_SHIFT 3 /* 8 byte alignment */
  773. #else
  774. #define ME_MPR_ALLOC_ALIGN_SHIFT 3
  775. #endif
  776. #endif
  777. #define ME_MPR_ALLOC_ALIGN (1 << ME_MPR_ALLOC_ALIGN_SHIFT)
  778. /*
  779. The allocator (by default) is limited to individual allocations of 4GB (32 bits). This enables memory blocks to
  780. be optimally aligned with minimal overhead. Define ME_MPR_ALLOC_BIG on 64-bit systems to enable allocating blocks
  781. greater than 4GB.
  782. */
  783. #if ME_MPR_ALLOC_BIG && ME_64
  784. typedef uint64 MprMemSize;
  785. #else
  786. typedef uint MprMemSize;
  787. #endif
  788. #define MPR_ALLOC_MAX ((MprMemSize) - ME_MPR_ALLOC_ALIGN)
  789. /**
  790. Memory Allocation Service.
  791. @description The MPR provides an application specific memory allocator to use instead of malloc. This allocator is
  792. tailored to the needs of embedded applications and is faster than most general purpose malloc allocators. It is
  793. deterministic and allocates and frees in constant time O(1). It exhibits very low fragmentation and accurate
  794. coalescing.
  795. \n\n
  796. The allocator uses a garbage collector for freeing unused memory. The collector is a cooperative, non-compacting,
  797. parallel collector. The allocator is optimized for frequent allocations of small blocks (< 4K) and uses a scheme
  798. of free queues for fast allocation. Allocations are aligned as specified by ME_MPR_ALLOC_ALIGN_SHIFT. This is typically
  799. 16 byte aligned for 64-bit systems and 8 byte aligned for 32-bit systems. The allocator will return unused memory
  800. back to the O/S to minimize application memory footprint.
  801. \n\n
  802. The allocator handles memory allocation errors globally. The application may configure a memory limit so that
  803. memory depletion can be proactively detected and handled before memory allocations actually fail.
  804. \n\n
  805. A memory block that is being used must be marked as active to prevent the garbage collector from reclaiming it.
  806. To mark a block as active, #mprMark must be called during each garbage collection cycle. When allocating
  807. non-temporal memory blocks, a manager callback can be specified via #mprAllocObj. This manager routine will be
  808. called by the collector so that dependent memory blocks can be marked as active.
  809. \n\n
  810. The collector performs the marking phase by invoking the manager routines for a set of root blocks. A block can be
  811. added to the set of roots by calling #mprAddRoot. Each root's manager routine will mark other blocks which will cause
  812. their manager routines to run and so on, until all active blocks have been marked. Non-marked blocks can then safely
  813. be reclaimed as garbage. A block may alternatively be permanently marked as active by calling #mprHold.
  814. \n\n
  815. The mark phase begins when all threads explicitly "yield" to the garbage collector. This cooperative approach ensures
  816. that user threads will not inadvertendly loose allocated blocks to the collector. Once all active blocks are marked,
  817. user threads are resumed and the garbage sweeper frees unused blocks in parallel with user threads.
  818. @stability Internal
  819. @defgroup MprMem MprMem
  820. @see MprFreeMem MprHeap MprManager MprMemNotifier MprRegion mprAddRoot mprAlloc mprAllocMem mprAllocObj
  821. mprAllocZeroed mprCreateMemService mprDestroyMemService mprEnableGC mprGetBlockSize mprGetMem
  822. mprGetMemStats mprGetMpr mprGetPageSize mprHasMemError mprHold mprIsPathContained mprIsValid mprMark
  823. mprMemcmp mprMemcpy mprMemdup mprPrintMem mprRealloc mprRelease mprRemoveRoot mprGC mprResetMemError
  824. mprRevive mprSetAllocLimits mprSetManager mprSetMemError mprSetMemLimits mprSetMemNotifier mprSetMemPolicy
  825. mprSetName mprVerifyMem mprVirtAlloc mprVirtFree
  826. */
  827. typedef struct MprMem {
  828. MprMemSize size; /**< Size of the block in bytes. Not the amount requested by the user which
  829. may be smaller. This is a 32-bit quantity on all systems unless
  830. ME_MPR_ALLOC_BIG is defined and then it will be 64 bits. */
  831. uchar qindex; /**< Freeq index. Always less than 512 queues. */
  832. uchar eternal; /**< Immune from GC. Implemented as a byte to be atomic */
  833. uchar mark; /**< GC mark indicator. Toggled for each GC pass by mark() when thread yielded. */
  834. /*
  835. Bits for fields only updated by mark/sweeper. Must not use bits for fields updated by multiple threads.
  836. */
  837. uchar free: 1; /**< Block not in use */
  838. uchar first: 1; /**< Block is first block in region */
  839. uchar hasManager: 1; /**< Has manager function. Set at block init. */
  840. uchar fullRegion: 1; /**< Block is an entire region - never on free queues . */
  841. #if ME_MPR_ALLOC_DEBUG
  842. /* This increases the size of MprMem from 8 bytes to 16 bytes on 32-bit systems and 24 bytes on 64 bit systems */
  843. cchar *name; /**< Debug name */
  844. ushort magic; /**< Unique signature */
  845. ushort seqno; /**< Allocation sequence number */
  846. #if ME_64
  847. uchar filler[4];
  848. #endif
  849. #endif
  850. } MprMem;
  851. /**
  852. Block structure when on a free list. This overlays MprMem and replaces sibling and children with forw/back
  853. The implies a minimum memory block size of 16 bytes.
  854. @ingroup MprMem
  855. @stability Internal.
  856. */
  857. typedef struct MprFreeMem {
  858. MprMem blk;
  859. struct MprFreeMem *prev; /**< Previous free block */
  860. struct MprFreeMem *next; /**< Next free block */
  861. } MprFreeMem;
  862. /**
  863. Free queue head structure. These must share the same layout as MprFreeMem for the prev/next pointers.
  864. */
  865. typedef struct MprFreeQueue {
  866. MprMem blk; /**< Unused in queue head */
  867. struct MprFreeMem *prev; /**< Previous free block */
  868. struct MprFreeMem *next; /**< Next free block */
  869. MprSpin lock; /**< Queue lock-free lock */
  870. uint count; /**< Number of blocks on the queue */
  871. MprMemSize minSize; /**< Minimum size of blocks in queue. This is the user block size sans
  872. MprMem header. */
  873. } MprFreeQueue;
  874. #define MPR_ALLOC_ALIGN(x) (((x) + ME_MPR_ALLOC_ALIGN - 1) & ~(ME_MPR_ALLOC_ALIGN - 1))
  875. #define MPR_ALLOC_MIN_BLOCK sizeof(MprFreeMem)
  876. #define MPR_ALLOC_MAX_BLOCK (ME_MPR_ALLOC_REGION_SIZE - sizeof(MprRegion))
  877. #define MPR_ALLOC_MIN_SPLIT (32 + sizeof(MprMem))
  878. #define MPR_ALLOC_MAGIC 0xe813
  879. #define MPR_PAGE_ALIGN(x, psize) ((((ssize) (x)) + ((ssize) (psize)) - 1) & ~(((ssize) (psize)) - 1))
  880. #define MPR_PAGE_ALIGNED(x, psize) ((((ssize) (x)) % ((ssize) (psize))) == 0)
  881. /*
  882. The allocator has a set of free queues to hold blocks of a given size range. Higher queues progressively address
  883. a larger range of block sizes. This mapping is achived by taking the most significant QBIT bits of the requested
  884. block size and then discarding the top bit (MSB). All combinations of the REST bits are mapped to the same queue.
  885. +-------------------------------+
  886. | QBits | REST |
  887. +-------------------------------+
  888. | 0 | 1 | X | X | X | ......... |
  889. +-------------------------------+
  890. | 1 | X | X | X | ............. |
  891. +-------------------------------+
  892. A bitmap records for each queue whether it has any free blocks in the queue.
  893. Note: qindex 2 is the first queue used because the minimum block size is sizeof(MprFreeMem)
  894. */
  895. #define MPR_ALLOC_QBITS_SHIFT 2
  896. #define MPR_ALLOC_NUM_QBITS (1 << MPR_ALLOC_QBITS_SHIFT)
  897. /*
  898. Should set region shift to log(ME_MPR_ALLOC_REGION_SIZE)
  899. We don't expect users to tinker with these
  900. */
  901. #if ME_MPR_ALLOC_REGION_SIZE == (128 * 1024)
  902. #define ME_MPR_ALLOC_REGION_SHIFT 18
  903. #elif ME_MPR_ALLOC_REGION_SIZE == (256 * 1024)
  904. #define ME_MPR_ALLOC_REGION_SHIFT 19
  905. #elif ME_MPR_ALLOC_REGION_SIZE == (512 * 1024)
  906. #define ME_MPR_ALLOC_REGION_SHIFT 20
  907. #else
  908. #define ME_MPR_ALLOC_REGION_SHIFT 24
  909. #endif
  910. #define MPR_ALLOC_NUM_QUEUES ((ME_MPR_ALLOC_REGION_SHIFT - ME_MPR_ALLOC_ALIGN_SHIFT - MPR_ALLOC_QBITS_SHIFT) * \
  911. MPR_ALLOC_NUM_QBITS)
  912. #define MPR_ALLOC_BITMAP_BITS BITS(size_t)
  913. #define MPR_ALLOC_NUM_BITMAPS ((MPR_ALLOC_NUM_QUEUES + MPR_ALLOC_BITMAP_BITS - 1) / MPR_ALLOC_BITMAP_BITS)
  914. /*
  915. Pointer to MprMem and vice-versa
  916. */
  917. #define MPR_GET_PTR(bp) ((void*) (((char*) (bp)) + sizeof(MprMem)))
  918. #define MPR_GET_MEM(ptr) ((MprMem*) (((char*) (ptr)) - sizeof(MprMem)))
  919. #define MPR_GET_USIZE(mp) ((size_t) (mp->size - sizeof(MprMem) - (mp->hasManager * sizeof(void*))))
  920. /*
  921. Manager callback is stored in the padding region at the end of the user memory in the block.
  922. */
  923. #define MPR_MANAGER_SIZE 1
  924. #define MPR_MANAGER_OFFSET 1
  925. #define MPR_MEM_PAD_PTR(mp, offset) ((void*) (((char*) mp) + mp->size - ((offset) * sizeof(void*))))
  926. #define GET_MANAGER(mp) ((MprManager) (*(void**) ((MPR_MEM_PAD_PTR(mp, MPR_MANAGER_OFFSET)))))
  927. #define SET_MANAGER(mp, fn) do { \
  928. *((MprManager*) MPR_MEM_PAD_PTR(mp, MPR_MANAGER_OFFSET)) = fn ; \
  929. mp->hasManager = 1; \
  930. } while (0);
  931. /*
  932. Manager callback flags
  933. */
  934. #define MPR_MANAGE_FREE 0x1 /**< Block being freed. Free dependant resources */
  935. #define MPR_MANAGE_MARK 0x2 /**< Block being marked by GC. Mark dependant resources */
  936. /*
  937. VirtAloc flags
  938. */
  939. #if ME_WIN_LIKE || VXWORKS
  940. #define MPR_MAP_READ 0x1
  941. #define MPR_MAP_WRITE 0x2
  942. #define MPR_MAP_EXECUTE 0x4
  943. #else
  944. #define MPR_MAP_READ PROT_READ
  945. #define MPR_MAP_WRITE PROT_WRITE
  946. #define MPR_MAP_EXECUTE PROT_EXEC
  947. #endif
  948. #if ME_MPR_ALLOC_DEBUG
  949. #define MPR_CHECK_BLOCK(bp) mprCheckBlock(bp)
  950. #define MPR_VERIFY_MEM() if (MPR->heap->verify) { mprVerifyMem(); } else {}
  951. #else
  952. #define MPR_CHECK_BLOCK(bp)
  953. #define MPR_VERIFY_MEM()
  954. #endif
  955. /*
  956. Memory depletion policy (mprSetAllocPolicy)
  957. */
  958. #define MPR_ALLOC_POLICY_NOTHING 0 /**< Do nothing */
  959. #define MPR_ALLOC_POLICY_PRUNE 1 /**< Prune all non-essential memory and continue */
  960. #define MPR_ALLOC_POLICY_RESTART 2 /**< Gracefully restart the app */
  961. #define MPR_ALLOC_POLICY_EXIT 3 /**< Exit the app cleanly */
  962. #define MPR_ALLOC_POLICY_ABORT 4 /**< Abort the app and dump core */
  963. /*
  964. MprMemNotifier cause argument
  965. */
  966. #define MPR_MEM_WARNING 0x1 /**< Memory use exceeds warnHeap level limit */
  967. #define MPR_MEM_LIMIT 0x2 /**< Memory use exceeds memory limit - invoking policy */
  968. #define MPR_MEM_FAIL 0x4 /**< Memory allocation failed - immediate exit */
  969. #define MPR_MEM_TOO_BIG 0x8 /**< Memory allocation request is too big - immediate exit */
  970. /**
  971. Memory allocation error callback. Notifiers are called if a low memory condition exists.
  972. @param cause Set to the cause of the memory error. Set to #MPR_MEM_WARNING if the allocation will exceed the warnHeap
  973. limit. Set to #MPR_MEM_LIMIT if it would exceed the maxHeap memory limit. Set to #MPR_MEM_FAIL if the
  974. allocation failed.
  975. Set to #MPR_MEM_TOO_BIG if the allocation block size is too large.
  976. Allocations will be rejected for MPR_MEM_FAIL and MPR_MEM_TOO_BIG, otherwise the allocations will proceed and the
  977. memory notifier will be invoked.
  978. @param policy Memory depletion policy. Set to one of #MPR_ALLOC_POLICY_NOTHING, #MPR_ALLOC_POLICY_PRUNE,
  979. #MPR_ALLOC_POLICY_RESTART, #MPR_ALLOC_POLICY_EXIT or #MPR_ALLOC_POLICY_ABORT.
  980. @param size Size of the allocation that triggered the low memory condition.
  981. @param total Total memory currently in use
  982. @ingroup MprMem
  983. @stability Stable.
  984. */
  985. typedef void (*MprMemNotifier)(int cause, int policy, size_t size, size_t total);
  986. /**
  987. Mpr memory block manager prototype
  988. @param ptr Any memory context allocated by the MPR.
  989. @ingroup MprMem
  990. @stability Stable.
  991. */
  992. typedef void (*MprManager)(void *ptr, int flags);
  993. #if ME_MPR_ALLOC_DEBUG
  994. /*
  995. The location stats table tracks the source code location responsible for each allocation
  996. Very costly. Don't use except for debug.
  997. */
  998. #define MPR_TRACK_HASH 2053 /* Size of location name hash */
  999. #define MPR_TRACK_NAMES 8 /* Length of collision chain */
  1000. typedef struct MprLocationStats {
  1001. size_t total; /* Total allocations for this location */
  1002. int count; /* Count of allocations for this location */
  1003. cchar *names[MPR_TRACK_NAMES]; /* Manager names */
  1004. } MprLocationStats;
  1005. #endif
  1006. /**
  1007. Memory allocator statistics
  1008. @ingroup MprMem
  1009. @stability Internal.
  1010. */
  1011. typedef struct MprMemStats {
  1012. int inMemException; /**< Recursive protect */
  1013. uint cpuCores; /**< Number of CPU cores */
  1014. uint pageSize; /**< System page size */
  1015. uint heapRegions; /**< Heap region count */
  1016. uint sweeps; /**< Number of GC sweeps */
  1017. uint64 cpuUsage; /**< Process CPU usage in ticks */
  1018. uint64 cacheHeap; /**< Heap cache. Try to keep at least this amount in the free queues */
  1019. uint64 bytesAllocated; /**< Bytes currently allocated. Includes active and free. */
  1020. uint64 bytesAllocatedPeak; /**< Max ever bytes allocated */
  1021. uint64 bytesFree; /**< Bytes currently free and retained in the heap queues */
  1022. uint64 errors; /**< Allocation errors */
  1023. uint64 lowHeap; /**< Low memory level at which to initiate a collection */
  1024. uint64 maxHeap; /**< Max memory that can be allocated */
  1025. uint64 ram; /**< System RAM size in bytes */
  1026. uint64 rss; /**< OS calculated memory resident set size in bytes */
  1027. uint64 user; /**< System user RAM size in bytes (excludes kernel) */
  1028. uint64 warnHeap; /**< Warn if heap size exceeds this level */
  1029. uint64 swept; /**< Number of blocks swept */
  1030. uint64 sweptBytes; /**< Number of bytes swept */
  1031. #if ME_MPR_ALLOC_STATS
  1032. /*
  1033. Extended memory stats
  1034. */
  1035. uint64 allocs; /**< Count of times a block was split Calls to allocate memory from the O/S */
  1036. uint64 cached; /**< Count of blocks that are cached rather then joined with adjacent blocks */
  1037. uint64 compacted; /**< Count of blocks that are compacted during compacting sweeps */
  1038. uint64 collections; /**< Number of GC collections */
  1039. uint64 freed; /**< Bytes freed in last sweep */
  1040. uint64 joins; /**< Count of times a block was joined (coalesced) with its neighbours */
  1041. uint64 markVisited; /**< Number of blocks examined for marking */
  1042. uint64 marked; /**< Number of blocks marked */
  1043. uint64 race; /**< Another thread raced for a block and won */
  1044. uint64 requests; /**< Count of memory requests */
  1045. uint64 reuse; /**< Count of times a block was reused from a free queue */
  1046. uint64 retries; /**< Queue retries */
  1047. uint64 qrace; /**< Count of times a queue was empty - racing with another thread */
  1048. uint64 splits; /**< Count of times a block was split */
  1049. uint64 sweepVisited; /**< Number of blocks examined for sweeping */
  1050. uint64 trys; /**< Attempts to acquire a freeq */
  1051. uint64 tryFails; /** Acquire a freeq fail count */
  1052. uint64 unpins; /**< Count of times a block was unpinned and released back to the O/S */
  1053. #endif
  1054. #if ME_MPR_ALLOC_DEBUG
  1055. MprLocationStats locations[MPR_TRACK_HASH]; /* Per location allocation stats */
  1056. #endif
  1057. } MprMemStats;
  1058. /**
  1059. Memmory regions allocated from the O/S
  1060. @ingroup MprMem
  1061. @stability Internal.
  1062. */
  1063. typedef struct MprRegion {
  1064. struct MprRegion *next; /**< Next region */
  1065. MprMem *start; /**< Start of region data */
  1066. MprMem *end; /**< End of region data */
  1067. size_t size; /**< Size of region including region header */
  1068. int freeable; /**< Set to true when completely unused */
  1069. } MprRegion;
  1070. /**
  1071. Memory allocator heap
  1072. @ingroup MprMem
  1073. @stability Internal.
  1074. */
  1075. typedef struct MprHeap {
  1076. MprFreeQueue freeq[MPR_ALLOC_NUM_QUEUES]; /**< Heap free queues */
  1077. size_t bitmap[MPR_ALLOC_NUM_BITMAPS]; /* Freeq bit map. Must be size_t for cas() */
  1078. struct MprList *roots; /**< List of GC root objects */
  1079. MprMemStats stats; /**< Memory allocation statistics */
  1080. MprMemNotifier notifier; /**< Memory allocation failure callback */
  1081. MprCond *gcCond; /**< GC sleep cond var */
  1082. MprRegion *regions; /**< List of memory regions */
  1083. struct MprThread *sweeper; /**< GC sweeper thread */
  1084. int allocPolicy; /**< Memory allocation depletion policy */
  1085. int regionSize; /**< Memory allocation region size */
  1086. int compact; /**< Next GC sweep should do a full compact */
  1087. int collecting; /**< Manual GC is running */
  1088. int freedBlocks; /**< True if the last sweep freed blocks */
  1089. int flags; /**< GC operational control flags */
  1090. int from; /**< Eligible mprCollectGarbage flags */
  1091. int gcEnabled; /**< GC is enabled */
  1092. int gcRequested; /**< GC has been requested */
  1093. int hasError; /**< Memory allocation error */
  1094. int marking; /**< Actually marking objects now */
  1095. int mustYield; /**< Threads must yield for GC which is due */
  1096. int nextSeqno; /**< Next sequence number */
  1097. int pageSize; /**< System page size */
  1098. int printStats; /**< Print diagnostic heap statistics */
  1099. uint64 priorFree; /**< Last sweep free memory */
  1100. uint64 priorWorkDone; /**< Prior workDone before last sweep */
  1101. int scribble; /**< Scribble over freed memory (slow) */
  1102. int sweeping; /**< Actually sweeping objects now */
  1103. int track; /**< Track memory allocations (requires ME_MPR_ALLOC_DEBUG) */
  1104. int verify; /**< Verify memory contents (very slow) */
  1105. uint64 workDone; /**< Count of allocations weighted by block size */
  1106. uint64 workQuota; /**< Quota of work done before idle GC worthwhile */
  1107. uchar mark; /**< Mark version */
  1108. } MprHeap;
  1109. /**
  1110. Create and initialize the Memory service
  1111. @description Called internally by the MPR. Should not be called by users.
  1112. @param manager Memory manager to manage the Mpr object
  1113. @param flags Memory initialization control flags
  1114. @return The Mpr control structure
  1115. @ingroup MprMem
  1116. @stability Internal.
  1117. */
  1118. PUBLIC struct Mpr *mprCreateMemService(MprManager manager, int flags);
  1119. /*
  1120. Flags for mprAllocMem
  1121. */
  1122. #define MPR_ALLOC_MANAGER 0x1 /**< Reserve room for a manager */
  1123. #define MPR_ALLOC_ZERO 0x2 /**< Zero memory */
  1124. #define MPR_ALLOC_HOLD 0x4 /**< Allocate and hold -- immune from GC until mprRelease */
  1125. #define MPR_ALLOC_PAD_MASK 0x1 /**< Flags that impact padding */
  1126. /**
  1127. Allocate a block of memory.
  1128. @description This is the lowest level of memory allocation routine. Memory is freed via the garbage collector.
  1129. To protect an active memory block memory block from being reclaimed, it must have a reference to it. Memory blocks
  1130. can specify a manager routine via #mprAllocObj. The manager is is invoked by the garbage collector to "mark"
  1131. dependant active blocks. Marked blocks will not be reclaimed by the garbage collector.
  1132. \n\n
  1133. This function can be called by foreign (non Mpr) threads provided you use the MPR_ALLOC_HOLD flag so that the memory
  1134. will be preserved until you call mprRelease on the memory block. This is important, as without the MPR_ALLOC_HOLD flag,
  1135. the garbage collector could run immediately after calling mprAlloc and collect the memory.
  1136. When used in an Mpr thread, the garbage collector cannot run until your thread calls #mprYield and so the memory is
  1137. safe from immediate collection.
  1138. @param size Size of the memory block to allocate.
  1139. @param flags Allocation flags. Supported flags include: MPR_ALLOC_MANAGER to reserve room for a manager callback and
  1140. MPR_ALLOC_ZERO to zero allocated memory. Use MPR_ALLOC_HOLD to return memory immune from GC. Must use this flag if
  1141. calling from a foreign thread. Use #mprRelease to release back to the system.
  1142. @return Returns a pointer to the allocated block. If memory is not available the memory exhaustion handler
  1143. specified via mprCreate will be called to allow global recovery.
  1144. @remarks Do not mix calls to malloc and mprAlloc.
  1145. @ingroup MprMem
  1146. @stability Stable.
  1147. */
  1148. PUBLIC void *mprAllocMem(size_t size, int flags);
  1149. /**
  1150. Return the process CPU usage.
  1151. @returns The total number of ticks of cpu usage since process tart
  1152. @ingroup MprMem
  1153. @stability Stable
  1154. */
  1155. PUBLIC uint64 mprGetCPU(void);
  1156. /**
  1157. Return the current allocation memory statistics block
  1158. @returns a reference to the allocation memory statistics. Do not modify its contents.
  1159. @ingroup MprMem
  1160. @stability Internal.
  1161. */
  1162. PUBLIC MprMemStats *mprGetMemStats(void);
  1163. /**
  1164. Return the amount of memory currently used by the application. On Unix, this returns the total application memory
  1165. size including code, stack, data and heap. On Windows, VxWorks and other operatings systems, it returns the
  1166. amount of allocated heap memory.
  1167. @returns the amount of memory used by the application in bytes.
  1168. @ingroup MprMem
  1169. @stability Stable.
  1170. */
  1171. PUBLIC size_t mprGetMem(void);
  1172. /**
  1173. Get the current O/S virtual page size
  1174. @returns the page size in bytes
  1175. @ingroup MprMem
  1176. @stability Stable.
  1177. */
  1178. PUBLIC int mprGetPageSize(void);
  1179. /**
  1180. Get the allocated size of a memory block
  1181. @param ptr Any memory allocated by mprAlloc
  1182. @returns the block size in bytes
  1183. @ingroup MprMem
  1184. @stability Internal.
  1185. */
  1186. PUBLIC size_t mprGetBlockSize(cvoid *ptr);
  1187. /**
  1188. Determine if the MPR has encountered memory allocation errors.
  1189. @description Returns true if the MPR has had a memory allocation error. Allocation errors occur if any
  1190. memory allocation would cause the application to exceed the configured warnHeap limit, or if any O/S memory
  1191. allocation request fails.
  1192. @return TRUE if a memory allocation error has occurred. Otherwise returns FALSE.
  1193. @ingroup MprMem
  1194. @stability Stable.
  1195. */
  1196. PUBLIC bool mprHasMemError(void);
  1197. /**
  1198. Test is a pointer is a valid memory context. This is used to test if a block has been dynamically allocated.
  1199. @param ptr Any memory context allocated by mprAlloc or mprCreate.
  1200. @ingroup MprMem
  1201. @stability Internal.
  1202. */
  1203. PUBLIC int mprIsValid(cvoid *ptr);
  1204. /**
  1205. Compare two byte strings.
  1206. @description Safely compare two byte strings. This is a safe replacement for memcmp.
  1207. @param b1 Pointer to the first byte string.
  1208. @param b1Len Length of the first byte string.
  1209. @param b2 Pointer to the second byte string.
  1210. @param b2Len Length of the second byte string.
  1211. @return Returns zero if the byte strings are identical. Otherwise returns -1 if the first string is less than the
  1212. second. Returns 1 if the first is greater than the first.
  1213. @ingroup MprMem
  1214. @stability Stable.
  1215. */
  1216. PUBLIC int mprMemcmp(cvoid *b1, size_t b1Len, cvoid *b2, size_t b2Len);
  1217. /**
  1218. Safe copy for a block of data.
  1219. @description Safely copy a block of data into an existing memory block. The call ensures the destination
  1220. block is not overflowed and returns the size of the block actually copied. This is similar to memcpy, but
  1221. is a safer alternative.
  1222. @param dest Pointer to the destination block.
  1223. @param destMax Maximum size of the destination block.
  1224. @param src Block to copy
  1225. @param nbytes Size of the source block
  1226. @return Returns the number of characters in the allocated block.
  1227. @ingroup MprMem
  1228. @stability Stable.
  1229. */
  1230. PUBLIC size_t mprMemcpy(void *dest, size_t destMax, cvoid *src, size_t nbytes);
  1231. /**
  1232. Duplicate a block of memory.
  1233. @description Copy a block of memory into a newly allocated block.
  1234. @param ptr Pointer to the block to duplicate.
  1235. @param size Size of the block to copy.
  1236. @return Returns an allocated block.
  1237. @ingroup MprMem
  1238. @stability Stable.
  1239. */
  1240. PUBLIC void *mprMemdup(cvoid *ptr, size_t size);
  1241. #define MPR_MEM_DETAIL 0x1 /* Print a detailed report */
  1242. /**
  1243. Print a memory usage report to stdout
  1244. @param msg Prefix message to the report
  1245. @param flags Set to MPR_MEM_DETAIL for a detailed memory report
  1246. @ingroup MprMem
  1247. @stability Internal.
  1248. */
  1249. PUBLIC void mprPrintMem(cchar *msg, int flags);
  1250. /**
  1251. Reallocate a block
  1252. @description Reallocates a block increasing its size. If the specified size is less than the current block size,
  1253. the call will ignore the request and simply return the existing block. The new memory portion is not zeroed.
  1254. @param ptr Memory to reallocate. If NULL, call malloc.
  1255. @param size New size of the required memory block.
  1256. @return Returns a pointer to the allocated block. If memory is not available the memory exhaustion handler
  1257. specified via mprCreate will be called to allow global recovery.
  1258. @remarks Do not mix calls to realloc and mprRealloc.
  1259. @ingroup MprMem
  1260. @stability Stable.
  1261. */
  1262. PUBLIC void *mprRealloc(void *ptr, size_t size);
  1263. /**
  1264. Reset the memory allocation error flag
  1265. @description Reset the alloc error flag triggered.
  1266. @ingroup MprMem
  1267. @stability Internal.
  1268. */
  1269. PUBLIC void mprResetMemError(void);
  1270. /*
  1271. Revive a memory block scheduled for collection. This should only ever be called in the manager routine for a block
  1272. when the manage flags parameter is set to MPR_MANAGE_FREE. Reviving a block aborts its collection.
  1273. @param ptr Reference to an allocated memory block.
  1274. @internal
  1275. @stability Internal.
  1276. */
  1277. PUBLIC void mprRevive(cvoid* ptr);
  1278. /**
  1279. Define a memory notifier
  1280. @description A notifier callback will be invoked for memory allocation errors for the given memory context.
  1281. @param cback Notifier callback function
  1282. @ingroup MprMem
  1283. @stability Stable.
  1284. */
  1285. PUBLIC void mprSetMemNotifier(MprMemNotifier cback);
  1286. /**
  1287. Set an memory allocation error condition on a memory context. This will set an allocation error condition on the
  1288. given context and all its parents. This way, you can test the ultimate parent and detect if any memory allocation
  1289. errors have occurred.
  1290. @ingroup MprMem
  1291. @stability Stable.
  1292. */
  1293. PUBLIC void mprSetMemError(void);
  1294. /**
  1295. Configure the application memory limits
  1296. @description Configure memory limits to constrain memory usage by the application. The memory allocation subsystem
  1297. will check these limits before granting memory allocation requrests. The warnHeap is a soft limit that if exceeded
  1298. will invoke the memory allocation callback, but will still honor the request. The maximum limit is a hard limit.
  1299. The MPR will prevent allocations which exceed this maximum. The memory callback handler is defined via
  1300. the #mprCreate call.
  1301. @param warnHeap Soft memory limit. If exceeded, the request will be granted, but the memory handler will be invoked.
  1302. to issue a warning and potentially take remedial acation. If -1, then do not update the warnHeap.
  1303. @param maximum Hard memory limit. If exceeded, the request will not be granted, and the memory handler will be invoked.
  1304. If -1, then do not update the maximum.
  1305. @param cache Heap cache. Try to keep at least this amount of memory in the heap free queues
  1306. If -1, then do not update the cache.
  1307. @ingroup MprMem
  1308. @stability Stable.
  1309. */
  1310. PUBLIC void mprSetMemLimits(ssize warnHeap, ssize maximum, ssize cache);
  1311. /**
  1312. Set the memory allocation policy for when allocations fail.
  1313. @param policy Set to MPR_ALLOC_POLICY_EXIT for the application to immediately exit on memory allocation errors.
  1314. Set to MPR_ALLOC_POLICY_RESTART to restart the appplication on memory allocation errors.
  1315. @ingroup MprMem
  1316. @stability Stable.
  1317. */
  1318. PUBLIC void mprSetMemPolicy(int policy);
  1319. /**
  1320. Update the manager for a block of memory.
  1321. @description This call updates the manager for a block of memory allocated via mprAllocWithManager.
  1322. @param ptr Memory to free. If NULL, take no action.
  1323. @param manager Manager function to invoke when the memory is released.
  1324. @return Returns the original object
  1325. @ingroup MprMem
  1326. @stability Stable.
  1327. */
  1328. PUBLIC void *mprSetManager(void *ptr, MprManager manager);
  1329. /**
  1330. Memory virtual memory into the applications address space.
  1331. @param size of virtual memory to map. This size will be rounded up to the nearest page boundary.
  1332. @param mode Mask set to MPR_MAP_READ | MPR_MAP_WRITE
  1333. @ingroup MprMem
  1334. @stability Stable.
  1335. */
  1336. PUBLIC void *mprVirtAlloc(size_t size, int mode);
  1337. /**
  1338. Free (unpin) a mapped section of virtual memory
  1339. @param ptr Virtual address to free. Should be page aligned
  1340. @param size Size of memory to free in bytes
  1341. @ingroup MprMem
  1342. @stability Stable.
  1343. */
  1344. PUBLIC void mprVirtFree(void *ptr, size_t size);
  1345. /**
  1346. Allocate a "permanent" block of memory that is not subject GC.
  1347. @description This allocates a block of memory using the MPR allocator. It then calls mprHold on the block.
  1348. to prevent GC from freeing the block.
  1349. @param size Size of the memory block to allocate.
  1350. @return Returns a pointer to the allocated block. If memory is not available the memory exhaustion handler
  1351. specified via mprCreate will be called to allow global recovery.
  1352. @remarks Do not mix calls to palloc and malloc.
  1353. @ingroup MprMem
  1354. @stability Stable
  1355. */
  1356. PUBLIC void *palloc(size_t size);
  1357. /**
  1358. Free a "permanent" block of memory allocated via "palloc".
  1359. @description This releases a block of memory allocated via "palloc" to be collected by the garbage collector.
  1360. @param ptr Pointer to the block
  1361. @remarks Do not mix calls to pfree and free.
  1362. @ingroup MprMem
  1363. @stability Stable
  1364. */
  1365. PUBLIC void pfree(void *ptr);
  1366. /**
  1367. Reallocate a "permanent" block of memory allocated via "palloc".
  1368. This function should not be used by foreign (non Mpr) threads.
  1369. @description This increases the size of a block of memory allocated via "palloc".
  1370. @param ptr Pointer to the block
  1371. @param size New block size
  1372. @return Returns a pointer to the allocated block. If memory is not available the memory exhaustion handler
  1373. specified via mprCreate will be called to allow global recovery.
  1374. @remarks Do not mix calls to prealloc and malloc.
  1375. @ingroup MprMem
  1376. @stability Stable
  1377. */
  1378. PUBLIC void *prealloc(void *ptr, size_t size);
  1379. /**
  1380. Return the size of the block. This may be larger than what was originally requested.
  1381. This function should not be used by foreign (non Mpr) threads.
  1382. @param ptr Pointer to the block
  1383. @return Size of the allocated block.
  1384. @ingroup MprMem
  1385. @stability Stable
  1386. */
  1387. PUBLIC size_t psize(void *ptr);
  1388. /*
  1389. Macros. When building documentation (DOXYGEN), define pretend function defintions for the documentation.
  1390. */
  1391. /*
  1392. In debug mode, all memory blocks can have a debug name
  1393. */
  1394. #if ME_MPR_ALLOC_DEBUG
  1395. PUBLIC void *mprSetName(void *ptr, cchar *name);
  1396. PUBLIC void *mprCopyName(void *dest, void *src);
  1397. #define mprGetName(ptr) (MPR_GET_MEM(ptr)->name)
  1398. PUBLIC void *mprSetAllocName(void *ptr, cchar *name);
  1399. #else
  1400. #define mprCopyName(dest, src)
  1401. #define mprGetName(ptr) ""
  1402. #define mprSetAllocName(ptr, name) ptr
  1403. #define mprSetName(ptr, name)
  1404. #endif
  1405. #define mprAlloc(size) mprSetAllocName(mprAllocFast(size), MPR_LOC)
  1406. #define mprMemdup(ptr, size) mprSetAllocName(mprMemdupMem(ptr, size), MPR_LOC)
  1407. #define mprRealloc(ptr, size) mprSetAllocName(mprReallocMem(ptr, size), MPR_LOC)
  1408. #define mprAllocZeroed(size) mprSetAllocName(mprAllocMem(size, MPR_ALLOC_ZERO), MPR_LOC)
  1409. #define mprAllocBlock(size, flags) mprSetAllocName(mprAllocMem(size, flags), MPR_LOC)
  1410. #define mprAllocObj(type, manage) ((type*) mprSetManager( \
  1411. mprSetAllocName(mprAllocMem(sizeof(type), MPR_ALLOC_MANAGER | MPR_ALLOC_ZERO), #type "@" MPR_LOC), (MprManager) manage))
  1412. #define mprAllocObjWithFlags(type, manage, flags) ((type*) mprSetManager( \
  1413. mprSetAllocName(mprAllocMem(sizeof(type), MPR_ALLOC_MANAGER | MPR_ALLOC_ZERO | flags), #type "@" MPR_LOC), (MprManager) manage))
  1414. #define mprAllocStruct(type) ((type*) mprSetAllocName(mprAllocMem(sizeof(type), MPR_ALLOC_ZERO), #type "@" MPR_LOC))
  1415. #define mprAllocObjNoZero(type, manage) ((type*) mprSetManager( \
  1416. mprSetAllocName(mprAllocMem(sizeof(type), MPR_ALLOC_MANAGER), #type "@" MPR_LOC), (MprManager) manage))
  1417. #define mprAllocStructNoZero(type) ((type*) mprSetAllocName(mprAllocFast(sizeof(type)), #type "@" MPR_LOC))
  1418. #if DOXYGEN
  1419. typedef void *Type;
  1420. /**
  1421. Allocate a block of memory
  1422. @description Allocates a block of memory of the required size. The memory is not zeroed.
  1423. @param size Size of the memory block to allocate.
  1424. @return Returns a pointer to the allocated block. If memory is not available the memory exhaustion handler
  1425. specified via mprCreate will be called to allow global recovery.
  1426. @remarks Do not mix calls to malloc and mprAlloc.
  1427. @ingroup MprMem
  1428. @stability Stable.
  1429. */
  1430. PUBLIC void *mprAlloc(size_t size);
  1431. /**
  1432. Allocate an object of a given type.
  1433. @description Allocates a zeroed block of memory large enough to hold an instance of the specified type with a
  1434. manager callback. This call associates a manager function with an object that will be invoked when the
  1435. object is freed or the garbage collector needs the object to mark internal properties as being used.
  1436. This call is implemented as a macro.
  1437. @param type Type of the object to allocate
  1438. @param manager Manager function to invoke when the allocation is managed.
  1439. @return Returns a pointer to the allocated block. If memory is not available the memory exhaustion handler
  1440. specified via mprCreate will be called to allow global recovery.
  1441. @remarks Do not mix calls to malloc and mprAlloc.
  1442. @ingroup MprMem
  1443. @stability Stable.
  1444. */
  1445. PUBLIC void *mprAllocObj(Type type, MprManager manager) { return 0;}
  1446. /**
  1447. Allocate an object of a given type.
  1448. @description Allocates a zeroed block of memory large enough to hold an instance of the specified type with a
  1449. manager callback. This call associates a manager function with an object that will be invoked when the
  1450. object is freed or the garbage collector needs the object to mark internal properties as being used.
  1451. This call is implemented as a macro.
  1452. This function can be called by foreign (non Mpr) threads provided you use the MPR_ALLOC_HOLD flag so that the memory
  1453. will be preserved until you call mprRelease on the memory block. This is important as without the MPR_ALLOC_HOLD flag,
  1454. the garbage collector could run immediately after calling mprAlloc and collect the memory. When used in an Mpr thread,
  1455. the garbage collector cannot run unless you call mprYield and so the memory is safe from immediate collection.
  1456. @param type Type of the object to allocate
  1457. @param manager Manager function to invoke when the allocation is managed.
  1458. @param flags Allocation flags. Supported flags include: MPR_ALLOC_MANAGER to reserve room for a manager callback and
  1459. MPR_ALLOC_ZERO to zero allocated memory. Use MPR_ALLOC_HOLD to return memory immune from GC. Must use this flag if
  1460. calling from a foreign thread. Use #mprRelease to release back to the system.
  1461. @return Returns a pointer to the allocated block. If memory is not available the memory exhaustion handler
  1462. specified via mprCreate will be called to allow global recovery.
  1463. @remarks Do not mix calls to malloc and mprAlloc.
  1464. @ingroup MprMem
  1465. @stability Stable.
  1466. */
  1467. PUBLIC void *mprAllocObjWithFlags(Type type, MprManager manager, int flags) { return 0;}
  1468. /**
  1469. Allocate a zeroed block of memory
  1470. @description Allocates a zeroed block of memory.
  1471. @param size Size of the memory block to allocate.
  1472. @return Returns a pointer to the allocated block. If memory is not available the memory exhaustion handler
  1473. specified via mprCreate will be called to allow global recovery.
  1474. @remarks Do not mix calls to malloc and mprAlloc.
  1475. @ingroup MprMem
  1476. @stability Stable.
  1477. */
  1478. PUBLIC void *mprAllocZeroed(size_t size);
  1479. #else /* !DOXYGEN */
  1480. PUBLIC void *mprAllocMem(size_t size, int flags);
  1481. PUBLIC void *mprReallocMem(void *ptr, size_t size);
  1482. PUBLIC void *mprMemdupMem(cvoid *ptr, size_t size);
  1483. PUBLIC void mprCheckBlock(MprMem *bp);
  1484. #endif
  1485. /*
  1486. Internal APIs
  1487. */
  1488. PUBLIC void mprDestroyMemService(void);
  1489. PUBLIC void mprStartGCService(void);
  1490. PUBLIC void mprStopGCService(void);
  1491. PUBLIC void *mprAllocFast(size_t usize);
  1492. /******************************** Garbage Coolector ***************************/
  1493. /**
  1494. Add a memory block as a root for garbage collection
  1495. @description Remove the root when no longer required via #mprAddRoot.
  1496. @param ptr Any memory pointer
  1497. @ingroup MprMem
  1498. @stability Stable.
  1499. */
  1500. PUBLIC void mprAddRoot(cvoid *ptr);
  1501. /*
  1502. Flags for mprGC
  1503. */
  1504. #define MPR_CG_DEFAULT 0x0 /**< mprGC flag to run GC if necessary. Will trigger GC and yield. Will
  1505. block if GC is required. */
  1506. #define MPR_GC_FORCE 0x1 /**< mprGC flag to force start a GC sweep whether it is required or not */
  1507. #define MPR_GC_NO_BLOCK 0x2 /**< mprGC flag to run GC if ncessary and return without yielding. Will not block. */
  1508. #define MPR_GC_COMPLETE 0x4 /**< mprGC flag to force start a GC and wait until the GC cycle fully completes
  1509. including sweep phase */
  1510. /**
  1511. Collect garbage
  1512. @description Initiates garbage collection to free unreachable memory blocks.
  1513. It is normally not required for users to invoke this routine as the garbage collector will be scheduled as required.
  1514. If the MPR_GC_NO_BLOCK is not specified, this routine yields to the garbage collector by calling #mprYield.
  1515. Callers must retain all required memory.
  1516. @param flags Flags to control the collection. Set flags to MPR_GC_FORCE to force a collection. Set to MPR_GC_DEFAULT
  1517. to perform a conditional sweep where the sweep is only performed if there is sufficient garbage to warrant a collection.
  1518. Set to MPR_GC_NO_BLOCK to run GC if necessary and return without yielding. Use MPR_GC_COMPLETE to force a GC and wait
  1519. until the GC cycle fully completes including the sweep phase.
  1520. @return The number of blocks freed on the last GC sweep. If using MPR_GC_NO_BLOCK, this may be the result from a prior GC
  1521. sweep.
  1522. @ingroup MprMem
  1523. @stability Stable
  1524. */
  1525. PUBLIC int mprGC(int flags);
  1526. /**
  1527. Enable or disable the garbage collector
  1528. @param on Set to one to enable and zero to disable.
  1529. @return Returns one if the collector was previously enabled. Otherwise returns zero.
  1530. @ingroup MprMem
  1531. @stability Stable.
  1532. */
  1533. PUBLIC bool mprEnableGC(bool on);
  1534. /**
  1535. Hold a memory block
  1536. @description This call will protect a memory block from freeing by the garbage collector. Call #mprRelease to
  1537. allow the block to be collected.
  1538. @param ptr Any memory block
  1539. @ingroup MprMem
  1540. @stability Stable.
  1541. */
  1542. PUBLIC void mprHold(cvoid *ptr);
  1543. /**
  1544. Hold memory blocks
  1545. @description This call will protect a set of memory blocks from freeing by the garbage collector.
  1546. Call #mprReleaseBlocks to allow the blocks to be collected.
  1547. @param ptr Any memory block
  1548. @param ... Other memory blocks. Terminate the list with a NULL.
  1549. @ingroup MprMem
  1550. @stability Stable
  1551. */
  1552. PUBLIC void mprHoldBlocks(cvoid *ptr, ...);
  1553. /**
  1554. Release a memory block
  1555. @description This call is used to allow a memory block to be freed by the garbage collector after calling mprHold.
  1556. You must NEVER use or access the memory block after calling mprRelease. The memory may be freed before the call returns, even when executing in an MPR thread.
  1557. @param ptr Any memory block
  1558. @ingroup MprMem
  1559. @stability Stable.
  1560. */
  1561. PUBLIC void mprRelease(cvoid *ptr);
  1562. /**
  1563. Release a memory blocks
  1564. @description This call is used to allow a memory blocks to be freed by the garbage collector after calling mprHoldBlocks.
  1565. You must NEVER use or access the memory blocks after calling mprRelease. The memory may be freed before the call returns, even when executing in an MPR thread.
  1566. @param ptr Any memory block
  1567. @param ... Other memory blocks. Terminate the list with a NULL.
  1568. @ingroup MprMem
  1569. @stability Stable
  1570. */
  1571. PUBLIC void mprReleaseBlocks(cvoid *ptr, ...);
  1572. /**
  1573. Remove a memory block as a root for garbage collection
  1574. @description The memory block should have previously been added as a root via #mprAddRoot.
  1575. @param ptr Any memory pointer
  1576. @ingroup MprMem
  1577. @stability Stable.
  1578. */
  1579. PUBLIC void mprRemoveRoot(cvoid *ptr);
  1580. #if DOXYGEN
  1581. /**
  1582. Mark a memory block as in-use
  1583. @description To prevent a memory block being freed by the garbage collector, it must be marked as "active".
  1584. Memory blocks can define a manager that will be invoked by the garbage collector to mark any fields
  1585. that are required by the original block.
  1586. @param ptr Reference to managed memory block. This must be managed memory allocated by the MPR. Do not call
  1587. mprMark on memory allocated via malloc(), strdup() or other non-MPR allocation routines.
  1588. It is safe pass a NULL pointer to mprMark and this will have no effect. This is a convenient pattern
  1589. where manager functions can call mprMark() without testing if the element reference is null or not.
  1590. */
  1591. PUBLIC void mprMark(void *ptr);
  1592. @ingroup MprMem
  1593. #else
  1594. #if ME_MPR_ALLOC_STATS
  1595. #define HINC(field) MPR->heap->stats.field++
  1596. #else
  1597. #define HINC(field)
  1598. #endif
  1599. #define mprMark(ptr) \
  1600. if (ptr) { \
  1601. MprMem *_mp = MPR_GET_MEM((ptr)); \
  1602. HINC(markVisited); \
  1603. if (_mp->mark != MPR->heap->mark) { \
  1604. _mp->mark = MPR->heap->mark; \
  1605. if (_mp->hasManager) { \
  1606. (GET_MANAGER(_mp))((void*) ptr, MPR_MANAGE_MARK); \
  1607. } \
  1608. HINC(marked); \
  1609. } \
  1610. } else {}
  1611. #endif
  1612. /*
  1613. Internal
  1614. */
  1615. PUBLIC int mprCreateGCService(void);
  1616. PUBLIC void mprWakeGCService(void);
  1617. PUBLIC void mprResumeThreads(void);
  1618. PUBLIC int mprSyncThreads(MprTicks timeout);
  1619. /********************************** Safe Strings ******************************/
  1620. /**
  1621. Safe String Module
  1622. @description The MPR provides a suite of safe ascii string manipulation routines to help prevent buffer overflows
  1623. and other potential security traps.
  1624. @defgroup MprString MprString
  1625. @see MprString itos itosradix itosbuf mprEprintf mprPrintf scamel scaselesscmp scaselessmatch schr
  1626. sclone scmp scontains scopy sends sfmt sfmtv shash shashlower sjoin sjoinv slen slower smatch sncaselesscmp snclone
  1627. sncmp sncopy snumber sfnumber shnumber stitle spbrk srchr srejoin srejoinv sreplace sspn sstarts ssub stemplate
  1628. stemplateJson stoi stoiradix stok strim supper sncontains mprFprintf fmtv fmt
  1629. @stability Internal
  1630. */
  1631. typedef struct MprString { void *dummy; } MprString;
  1632. /**
  1633. Format a string into a static buffer.
  1634. @description This call format a string using printf style formatting arguments. A trailing null will
  1635. always be appended. The call returns the size of the allocated string excluding the null.
  1636. @param buf Pointer to the buffer.
  1637. @param maxSize Size of the buffer.
  1638. @param fmt Printf style format string
  1639. @param ... Variable arguments to format
  1640. @return Returns the buffer.
  1641. @ingroup MprString
  1642. @stability Stable
  1643. */
  1644. PUBLIC char *fmt(char *buf, ssize maxSize, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  1645. /**
  1646. Format a string into a statically allocated buffer.
  1647. @description This call format a string using printf style formatting arguments. A trailing null will
  1648. always be appended. The call returns the size of the allocated string excluding the null.
  1649. @param buf Pointer to the buffer.
  1650. @param maxSize Size of the buffer.
  1651. @param fmt Printf style format string
  1652. @param args Varargs argument obtained from va_start.
  1653. @return Returns the buffer;
  1654. @ingroup MprString
  1655. @stability Stable
  1656. */
  1657. PUBLIC char *fmtv(char *buf, ssize maxSize, cchar *fmt, va_list args);
  1658. /**
  1659. Convert an integer to a string.
  1660. @description This call converts the supplied 64 bit integer to a string using base 10.
  1661. @param value Integer value to convert
  1662. @return An allocated string with the converted number.
  1663. @ingroup MprString
  1664. @stability Stable
  1665. */
  1666. PUBLIC char *itos(int64 value);
  1667. /**
  1668. Convert an integer to a string.
  1669. @description This call converts the supplied 64 bit integer to a string according to the specified radix.
  1670. @param value Integer value to convert
  1671. @param radix The base radix to use when encoding the number
  1672. @return An allocated string with the converted number.
  1673. @ingroup MprString
  1674. @stability Stable
  1675. */
  1676. PUBLIC char *itosradix(int64 value, int radix);
  1677. /**
  1678. Convert an integer to a string buffer.
  1679. @description This call converts the supplied 64 bit integer into a string formatted into the supplied buffer according
  1680. to the specified radix.
  1681. @param buf Pointer to the buffer that will hold the string.
  1682. @param size Size of the buffer.
  1683. @param value Integer value to convert
  1684. @param radix The base radix to use when encoding the number
  1685. @return Returns a reference to the string.
  1686. @ingroup MprString
  1687. @stability Stable
  1688. */
  1689. PUBLIC char *itosbuf(char *buf, ssize size, int64 value, int radix);
  1690. /**
  1691. Compare strings ignoring case. This is a safe replacement for strcasecmp. It can handle NULL args.
  1692. @description Compare two strings ignoring case differences. This call operates similarly to strcmp.
  1693. @param s1 First string to compare.
  1694. @param s2 Second string to compare.
  1695. @return Returns zero if the strings are equivalent, < 0 if s1 sorts lower than s2 in the collating sequence
  1696. or > 0 if it sorts higher.
  1697. @ingroup MprString
  1698. @stability Stable
  1699. */
  1700. PUBLIC int scaselesscmp(cchar *s1, cchar *s2);
  1701. /**
  1702. Find a pattern in a string with a caseless comparision
  1703. @description Locate the first occurrence of pattern in a string.
  1704. @param str Pointer to the string to search.
  1705. @param pattern String pattern to search for.
  1706. @return Returns a reference to the start of the pattern in the string. If not found, returns NULL.
  1707. @ingroup MprString
  1708. @stability Evolving
  1709. */
  1710. PUBLIC char *scaselesscontains(cchar *str, cchar *pattern);
  1711. /**
  1712. Compare strings ignoring case. This is similar to scaselesscmp but it returns a boolean.
  1713. @description Compare two strings ignoring case differences.
  1714. @param s1 First string to compare.
  1715. @param s2 Second string to compare.
  1716. @return Returns true if the strings are equivalent, otherwise false.
  1717. @ingroup MprString
  1718. @stability Stable
  1719. */
  1720. PUBLIC bool scaselessmatch(cchar *s1, cchar *s2);
  1721. /**
  1722. Create a camel case version of the string
  1723. @description Copy a string into a newly allocated block and make the first character lower case
  1724. @param str Pointer to the block to duplicate.
  1725. @return Returns a newly allocated string.
  1726. @ingroup MprString
  1727. @stability Stable
  1728. */
  1729. PUBLIC char *scamel(cchar *str);
  1730. /**
  1731. Find a character in a string.
  1732. @description This is a safe replacement for strchr. It can handle NULL args.
  1733. @param str String to examine
  1734. @param c Character to search for
  1735. @return If the character is found, the call returns a reference to the character position in the string. Otherwise,
  1736. returns NULL.
  1737. @ingroup MprString
  1738. @stability Stable
  1739. */
  1740. PUBLIC char *schr(cchar *str, int c);
  1741. /**
  1742. Clone a string.
  1743. @description Copy a string into a newly allocated block.
  1744. @param str Pointer to the block to duplicate.
  1745. @return Returns a newly allocated string.
  1746. @ingroup MprString
  1747. @stability Stable
  1748. */
  1749. PUBLIC char *sclone(cchar *str);
  1750. /**
  1751. Compare strings.
  1752. @description Compare two strings. This is a safe replacement for strcmp. It can handle null args.
  1753. @param s1 First string to compare.
  1754. @param s2 Second string to compare.
  1755. @return Returns zero if the strings are identical. Return -1 if the first string is less than the second. Return 1
  1756. if the first string is greater than the second.
  1757. @ingroup MprString
  1758. @stability Stable
  1759. */
  1760. PUBLIC int scmp(cchar *s1, cchar *s2);
  1761. /**
  1762. Find a pattern in a string.
  1763. @description Locate the first occurrence of pattern in a string.
  1764. @param str Pointer to the string to search.
  1765. @param pattern String pattern to search for.
  1766. @return Returns a reference to the start of the pattern in the string. If not found, returns NULL.
  1767. @ingroup MprString
  1768. @stability Stable
  1769. */
  1770. PUBLIC char *scontains(cchar *str, cchar *pattern);
  1771. /**
  1772. Copy a string.
  1773. @description Safe replacement for strcpy. Copy a string and ensure the destination buffer is not overflowed.
  1774. The call returns the length of the resultant string or an error code if it will not fit into the target
  1775. string. This is similar to strcpy, but it will enforce a maximum size for the copied string and will
  1776. ensure it is always terminated with a null.
  1777. @param dest Pointer to a pointer that will hold the address of the allocated block.
  1778. @param destMax Maximum size of the target string in characters.
  1779. @param src String to copy
  1780. @return Returns the number of characters in the target string.
  1781. @ingroup MprString
  1782. @stability Stable
  1783. */
  1784. PUBLIC ssize scopy(char *dest, ssize destMax, cchar *src);
  1785. /**
  1786. Test if the string ends with a given pattern.
  1787. @param str String to examine
  1788. @param suffix Pattern to search for
  1789. @return Returns a pointer to the start of the pattern if found. Otherwise returns NULL.
  1790. @ingroup MprString
  1791. @stability Stable
  1792. */
  1793. PUBLIC cchar *sends(cchar *str, cchar *suffix);
  1794. /**
  1795. Erase the contents of a string
  1796. @param str String to erase
  1797. @ingroup MprString
  1798. @stability Stable
  1799. */
  1800. PUBLIC void serase(char *str);
  1801. /**
  1802. Format a string. This is a secure verion of printf that can handle null args.
  1803. @description Format the given arguments according to the printf style format. See mprPrintf for a full list of the
  1804. format specifies. This is a secure replacement for sprintf, it can handle null arguments without crashes.
  1805. @param fmt Printf style format string
  1806. @param ... Variable arguments for the format string
  1807. @return Returns a newly allocated string
  1808. @ingroup MprString
  1809. @stability Stable
  1810. */
  1811. PUBLIC char *sfmt(cchar *fmt, ...) PRINTF_ATTRIBUTE(1,2);
  1812. /**
  1813. Format a string. This is a secure verion of printf that can handle null args.
  1814. @description Format the given arguments according to the printf style format. See mprPrintf for a full list of the
  1815. format specifies. This is a secure replacement for sprintf, it can handle null arguments without crashes.
  1816. @param fmt Printf style format string
  1817. @param args Varargs argument obtained from va_start.
  1818. @return Returns a newly allocated string
  1819. @ingroup MprString
  1820. @stability Stable
  1821. */
  1822. PUBLIC char *sfmtv(cchar *fmt, va_list args);
  1823. /**
  1824. Compute a hash code for a string
  1825. @param str String to examine
  1826. @param len Length in characters of the string to include in the hash code
  1827. @return Returns an unsigned integer hash code
  1828. @ingroup MprString
  1829. @stability Stable
  1830. */
  1831. PUBLIC uint shash(cchar *str, ssize len);
  1832. /**
  1833. Compute a caseless hash code for a string
  1834. @description This computes a hash code for the string after converting it to lower case.
  1835. @param str String to examine
  1836. @param len Length in characters of the string to include in the hash code
  1837. @return Returns an unsigned integer hash code
  1838. @ingroup MprString
  1839. @stability Stable
  1840. */
  1841. PUBLIC uint shashlower(cchar *str, ssize len);
  1842. /**
  1843. Catenate strings.
  1844. @description This catenates strings together with an optional string separator.
  1845. If the separator is NULL, not separator is used. This call accepts a variable list of strings to append,
  1846. terminated by a null argument.
  1847. @param str First string to catentate
  1848. @param ... Variable number of string arguments to append. Terminate list with NULL.
  1849. @return Returns an allocated string.
  1850. @ingroup MprString
  1851. @stability Stable
  1852. */
  1853. PUBLIC char *sjoin(cchar *str, ...);
  1854. /**
  1855. Catenate strings.
  1856. @description This catenates strings together with an optional string separator.
  1857. If the separator is NULL, not separator is used. This call accepts a variable list of strings to append,
  1858. terminated by a null argument.
  1859. @param str First string to catentate
  1860. @param args Varargs argument obtained from va_start.
  1861. @return Returns an allocated string.
  1862. @ingroup MprString
  1863. @stability Stable
  1864. */
  1865. PUBLIC char *sjoinv(cchar *str, va_list args);
  1866. /**
  1867. Join an array of strings
  1868. @param argc number of strings to join
  1869. @param argv Array of strings
  1870. @param sep Separator string to use. If NULL, then no separator is used.
  1871. @return A single joined string.
  1872. @stability Stable
  1873. @ingroup MprString
  1874. */
  1875. PUBLIC cchar *sjoinArgs(int argc, cchar **argv, cchar *sep);
  1876. /**
  1877. Return the length of a string.
  1878. @description Safe replacement for strlen. This call returns the length of a string and tests if the length is
  1879. less than a given maximum. It will return zero for NULL args.
  1880. @param str String to measure.
  1881. @return Returns the length of the string
  1882. @ingroup MprString
  1883. @stability Stable
  1884. */
  1885. PUBLIC ssize slen(cchar *str);
  1886. /**
  1887. Convert a string to lower case.
  1888. @description Convert a string to its lower case equivalent.
  1889. @param str String to convert.
  1890. @return An allocated string.
  1891. @ingroup MprString
  1892. @stability Stable
  1893. */
  1894. PUBLIC char *slower(cchar *str);
  1895. /**
  1896. Compare strings.
  1897. @description Compare two strings. This is similar to #scmp but it returns a boolean.
  1898. @param s1 First string to compare.
  1899. @param s2 Second string to compare.
  1900. @return Returns true if the strings are equivalent, otherwise false.
  1901. @ingroup MprString
  1902. @stability Stable
  1903. */
  1904. PUBLIC bool smatch(cchar *s1, cchar *s2);
  1905. /**
  1906. Secure compare strings.
  1907. @description Compare two strings in constant time. This is similar to #smatch but will not fail fast on first char mismatch.
  1908. @param s1 First string to compare.
  1909. @param s2 Second string to compare.
  1910. @return Returns true if the strings are equivalent, otherwise false.
  1911. @ingroup MprString
  1912. @stability Prototype
  1913. */
  1914. PUBLIC bool smatchsec(cchar *s1, cchar *s2);
  1915. /**
  1916. Compare strings ignoring case.
  1917. @description Compare two strings ignoring case differences for a given string length. This call operates
  1918. similarly to strncasecmp.
  1919. @param s1 First string to compare.
  1920. @param s2 Second string to compare.
  1921. @param len Length of characters to compare.
  1922. @return Returns zero if the strings are equivalent, < 0 if s1 sorts lower than s2 in the collating sequence
  1923. or > 0 if it sorts higher.
  1924. @ingroup MprString
  1925. @stability Stable
  1926. */
  1927. PUBLIC int sncaselesscmp(cchar *s1, cchar *s2, ssize len);
  1928. /**
  1929. Find a pattern in a string with a limit and a caseless comparision
  1930. @description Locate the first occurrence of pattern in a string, but do not search more than the given character limit.
  1931. @param str Pointer to the string to search.
  1932. @param pattern String pattern to search for.
  1933. @param limit Count of characters in the string to search.
  1934. @return Returns a reference to the start of the pattern in the string. If not found, returns NULL.
  1935. @ingroup MprString
  1936. @stability Stable
  1937. */
  1938. PUBLIC char *sncaselesscontains(cchar *str, cchar *pattern, ssize limit);
  1939. /**
  1940. Clone a substring.
  1941. @description Copy a substring into a newly allocated block.
  1942. @param str Pointer to the block to duplicate.
  1943. @param len Number of bytes to copy. The actual length copied is the minimum of the given length and the length of
  1944. the supplied string. The result is null terminated.
  1945. @return Returns a newly allocated string.
  1946. @ingroup MprString
  1947. @stability Stable
  1948. */
  1949. PUBLIC char *snclone(cchar *str, ssize len);
  1950. /**
  1951. Compare strings.
  1952. @description Compare two strings for a given string length. This call operates similarly to strncmp.
  1953. @param s1 First string to compare.
  1954. @param s2 Second string to compare.
  1955. @param len Length of characters to compare.
  1956. @return Returns zero if the strings are equivalent, < 0 if s1 sorts lower than s2 in the collating sequence
  1957. or > 0 if it sorts higher.
  1958. @ingroup MprString
  1959. @stability Stable
  1960. */
  1961. PUBLIC int sncmp(cchar *s1, cchar *s2, ssize len);
  1962. /**
  1963. Find a pattern in a string with a limit.
  1964. @description Locate the first occurrence of pattern in a string, but do not search more than the given character limit.
  1965. @param str Pointer to the string to search.
  1966. @param pattern String pattern to search for.
  1967. @param limit Count of characters in the string to search.
  1968. @return Returns a reference to the start of the pattern in the string. If not found, returns NULL.
  1969. @ingroup MprString
  1970. @stability Stable
  1971. */
  1972. PUBLIC char *sncontains(cchar *str, cchar *pattern, ssize limit);
  1973. /**
  1974. Copy characters from a string.
  1975. @description Safe replacement for strncpy. Copy bytes from a string and ensure the target string is not overflowed.
  1976. The call returns the length of the resultant string or an error code if it will not fit into the target
  1977. string. This is similar to strcpy, but it will enforce a maximum size for the copied string and will
  1978. ensure it is terminated with a null.
  1979. @param dest Pointer to a pointer that will hold the address of the allocated block.
  1980. @param destMax Maximum size of the target string in characters.
  1981. @param src String to copy
  1982. @param len Maximum count of characters to copy
  1983. @return Returns a reference to the destination if successful or NULL if the string won't fit.
  1984. @ingroup MprString
  1985. @stability Stable
  1986. */
  1987. PUBLIC ssize sncopy(char *dest, ssize destMax, cchar *src, ssize len);
  1988. /*
  1989. Test if a string is a floating point number
  1990. @description The supported format is: [+|-][DIGITS][.][DIGITS][(e|E)[+|-]DIGITS]
  1991. @return true if all characters are digits or '.', 'e', 'E', '+' or '-'
  1992. @ingroup MprString
  1993. @stability Stable
  1994. */
  1995. PUBLIC bool sfnumber(cchar *s);
  1996. /*
  1997. Test if a string is a hexadecimal number
  1998. @description The supported format is: [(+|-)][0][(x|X)][HEX_DIGITS]
  1999. @return true if all characters are digits or 'x' or 'X'
  2000. @ingroup MprString
  2001. @stability Stable
  2002. */
  2003. PUBLIC bool shnumber(cchar *s);
  2004. /*
  2005. Test if a string is a radix 10 number.
  2006. @description The supported format is: [(+|-)][DIGITS]
  2007. @return true if all characters are digits or '+' or '-'
  2008. @ingroup MprString
  2009. @stability Stable
  2010. */
  2011. PUBLIC bool snumber(cchar *s);
  2012. /**
  2013. Create a Title Case version of the string
  2014. @description Copy a string into a newly allocated block and make the first character upper case
  2015. @param str Pointer to the block to duplicate.
  2016. @return Returns a newly allocated string.
  2017. @ingroup MprString
  2018. @stability Stable
  2019. */
  2020. PUBLIC char *stitle(cchar *str);
  2021. /**
  2022. Locate the a character from a set in a string.
  2023. @description This locates in the string the first occurence of any character from a given set of characters.
  2024. @param str String to examine
  2025. @param set Set of characters to scan for
  2026. @return Returns a reference to the first character from the given set. Returns NULL if none found.
  2027. @ingroup MprString
  2028. @stability Stable
  2029. */
  2030. PUBLIC char *spbrk(cchar *str, cchar *set);
  2031. /**
  2032. Find a character in a string by searching backwards.
  2033. @description This locates in the string the last occurence of a character.
  2034. @param str String to examine
  2035. @param c Character to scan for
  2036. @return Returns a reference in the string to the requested character. Returns NULL if none found.
  2037. @ingroup MprString
  2038. @stability Stable
  2039. */
  2040. PUBLIC char *srchr(cchar *str, int c);
  2041. /**
  2042. Append strings to an existing string and reallocate as required.
  2043. @description Append a list of strings to an existing string. The list of strings is terminated by a
  2044. null argument. The call returns the size of the allocated block.
  2045. @param buf Existing (allocated) string to reallocate. May be null. May not be a string literal.
  2046. @param ... Variable number of string arguments to append. Terminate list with NULL
  2047. @return Returns an allocated string.
  2048. @ingroup MprString
  2049. @stability Stable
  2050. */
  2051. PUBLIC char *srejoin(char *buf, ...);
  2052. /**
  2053. Append strings to an existing string and reallocate as required.
  2054. @description Append a list of strings to an existing string. The list of strings is terminated by a
  2055. null argument. The call returns the size of the allocated block.
  2056. @param buf Existing (allocated) string to reallocate. May be null. May not be a string literal.
  2057. @param args Varargs argument obtained from va_start.
  2058. @return Returns an allocated string.
  2059. @ingroup MprString
  2060. @stability Stable
  2061. */
  2062. PUBLIC char *srejoinv(char *buf, va_list args);
  2063. /*
  2064. Replace a pattern in a string
  2065. @description This will replace all occurrences of the pattern in the string.
  2066. @param str String to examine
  2067. @param pattern Pattern to search for. Can be null in which case the str is cloned.
  2068. @param replacement Replacement pattern. If replacement is null, the pattern is removed.
  2069. @return A new allocated string
  2070. @ingroup MprString
  2071. @stability Stable
  2072. */
  2073. PUBLIC char *sreplace(cchar *str, cchar *pattern, cchar *replacement);
  2074. /*
  2075. Test if a string is all white space
  2076. @return true if all characters are ' ', '\t', '\n', '\r'. True if the string is empty.
  2077. @ingroup MprString
  2078. @stability Stable
  2079. */
  2080. PUBLIC bool sspace(cchar *s);
  2081. /**
  2082. Split a string at a delimiter
  2083. @description Split a string and return parts. The string is modified.
  2084. This routiner never returns null. If there are leading delimiters, the empty string will be returned
  2085. and *last will be set to the portion after the delimiters.
  2086. If str is null, a managed reference to the empty string will be returned.
  2087. If there are no characters after the delimiter, then *last will be set to the empty string.
  2088. @param str String to tokenize.
  2089. @param delim Set of characters that are used as token separators.
  2090. @param last Reference to the portion after the delimiters. Will return an empty string if is not trailing portion.
  2091. @return Returns a pointer to the first part before the delimiters. If the string begins with delimiters, the empty
  2092. string will be returned.
  2093. @ingroup MprString
  2094. @stability Stable
  2095. */
  2096. PUBLIC char *ssplit(char *str, cchar *delim, char **last);
  2097. /**
  2098. Find the end of a spanning prefix
  2099. @description This scans the given string for characters from the set and returns an index to the first character not in the set.
  2100. @param str String to examine
  2101. @param set Set of characters to span
  2102. @return Returns an index to the first character after the spanning set. If not found, returns the index of the first null.
  2103. @ingroup MprString
  2104. @stability Stable
  2105. */
  2106. PUBLIC ssize sspn(cchar *str, cchar *set);
  2107. /**
  2108. Test if the string starts with a given pattern.
  2109. @param str String to examine
  2110. @param prefix Pattern to search for
  2111. @return Returns TRUE if the pattern was found. Otherwise returns zero.
  2112. @ingroup MprString
  2113. @stability Stable
  2114. */
  2115. PUBLIC bool sstarts(cchar *str, cchar *prefix);
  2116. /**
  2117. Replace template tokens in a string with values from a lookup table. Tokens are ${variable} references.
  2118. @param str String to expand
  2119. @param tokens Hash table of token values to use
  2120. @return An expanded string. May return the original string if no "$" references are present.
  2121. @ingroup MprString
  2122. @stability Stable
  2123. @see stemplateJson
  2124. */
  2125. PUBLIC char *stemplate(cchar *str, struct MprHash *tokens);
  2126. /**
  2127. Replace template tokens in a string with values from a lookup table. Tokens are ${variable} references.
  2128. @param str String to expand
  2129. @param tokens Json object of token values to use
  2130. @return An expanded string. May return the original string if no "$" references are present.
  2131. @ingroup MprString
  2132. @stability Stable
  2133. @see stemplate
  2134. */
  2135. PUBLIC char *stemplateJson(cchar *str, struct MprJson *tokens);
  2136. /**
  2137. Convert a string to a double.
  2138. @description This call converts the supplied string to a double.
  2139. @param str Pointer to the string to parse.
  2140. @return Returns the double equivalent value of the string.
  2141. @ingroup MprString
  2142. @stability Stable
  2143. */
  2144. PUBLIC double stof(cchar *str);
  2145. /**
  2146. Convert a string to an integer.
  2147. @description This call converts the supplied string to an integer using base 10.
  2148. @param str Pointer to the string to parse.
  2149. @return Returns the integer equivalent value of the string.
  2150. @ingroup MprString
  2151. @stability Stable
  2152. */
  2153. PUBLIC int64 stoi(cchar *str);
  2154. /**
  2155. Convert a string to an integer.
  2156. @description This call converts the supplied string to an integer using the specified radix (base).
  2157. @param str Pointer to the string to parse.
  2158. @param radix Base to use when parsing the string
  2159. @param err Return error code. Set to 0 if successful.
  2160. @return Returns the integer equivalent value of the string.
  2161. @ingroup MprString
  2162. */
  2163. PUBLIC int64 stoiradix(cchar *str, int radix, int *err);
  2164. /**
  2165. Tokenize a string
  2166. @description Split a string into tokens using a character set as delimiters.
  2167. @param str String to tokenize.
  2168. @param delim Set of characters that are used as token separators.
  2169. @param last Last token pointer. This is a pointer inside the original string.
  2170. @return Returns a pointer to the next token. The pointer is inside the original string and is not allocated.
  2171. @ingroup MprString
  2172. @stability Stable
  2173. */
  2174. PUBLIC char *stok(char *str, cchar *delim, char **last);
  2175. /**
  2176. Tokenize a string
  2177. @description Split a string into tokens using a string pattern as delimiters.
  2178. @param str String to tokenize.
  2179. @param pattern String pattern to use for token delimiters.
  2180. @param last Last token pointer.
  2181. @return Returns a pointer to the next token.
  2182. @ingroup MprString
  2183. @stability Stable
  2184. */
  2185. PUBLIC char *sptok(char *str, cchar *pattern, char **last);
  2186. /**
  2187. String to list. This parses the string into space separated arguments. Single and double quotes are supported.
  2188. @param src Source string to parse
  2189. @return List of arguments
  2190. @ingroup MprString
  2191. @stability Stable
  2192. */
  2193. PUBLIC struct MprList *stolist(cchar *src);
  2194. /**
  2195. Create a substring
  2196. @param str String to examine
  2197. @param offset Starting offset within str for the beginning of the substring
  2198. @param length Length of the substring in characters
  2199. @return Returns a newly allocated substring
  2200. @ingroup MprString
  2201. @stability Stable
  2202. */
  2203. PUBLIC char *ssub(cchar *str, ssize offset, ssize length);
  2204. /*
  2205. String trim flags
  2206. */
  2207. #define MPR_TRIM_START 0x1 /**< Flag for #strim to trim from the start of the string */
  2208. #define MPR_TRIM_END 0x2 /**< Flag for #strim to trim from the end of the string */
  2209. #define MPR_TRIM_BOTH 0x3 /**< Flag for #strim to trim from both the start and the end of the string */
  2210. /**
  2211. Trim a string.
  2212. @description Trim leading and trailing characters off a string.
  2213. The original string is not modified and the return value is a newly allocated string.
  2214. @param str String to trim.
  2215. @param set String of characters to remove.
  2216. @param where Flags to indicate trim from the start, end or both. Use MPR_TRIM_START, MPR_TRIM_END, MPR_TRIM_BOTH.
  2217. @return Returns a newly allocated trimmed string. May not equal \a str.
  2218. @ingroup MprString
  2219. @stability Stable
  2220. */
  2221. PUBLIC char *strim(cchar *str, cchar *set, int where);
  2222. /**
  2223. Convert a string to upper case.
  2224. @description Convert a string to its upper case equivalent.
  2225. @param str String to convert.
  2226. @return Returns a pointer to an allocated string.
  2227. @ingroup MprString
  2228. @stability Stable
  2229. */
  2230. PUBLIC char *supper(cchar *str);
  2231. /************************************ Unicode *********************************/
  2232. /*
  2233. Low-level unicode wide string support. Unicode characters are build-time configurable to be 1, 2 or 4 bytes
  2234. This API is not yet public
  2235. */
  2236. /* Allocating */
  2237. PUBLIC wchar *amtow(cchar *src, ssize *len);
  2238. PUBLIC char *awtom(wchar *src, ssize *len);
  2239. #if ME_CHAR_LEN > 1
  2240. #define multi(s) awtom(s, 0)
  2241. #define wide(s) amtow(s, 0)
  2242. #else
  2243. #define multi(s) (s)
  2244. #define wide(s) (s)
  2245. #endif
  2246. #if ME_CHAR_LEN > 1
  2247. PUBLIC ssize wtom(char *dest, ssize count, wchar *src, ssize len);
  2248. PUBLIC ssize mtow(wchar *dest, ssize count, cchar *src, ssize len);
  2249. #if FUTURE
  2250. PUBLIC wchar *wfmt(wchar *fmt, ...);
  2251. PUBLIC wchar *itow(wchar *buf, ssize bufCount, int64 value, int radix);
  2252. PUBLIC wchar *wchr(wchar *s, int c);
  2253. PUBLIC int wcasecmp(wchar *s1, wchar *s2);
  2254. PUBLIC wchar *wclone(wchar *str);
  2255. PUBLIC int wcmp(wchar *s1, wchar *s2);
  2256. PUBLIC wchar *wcontains(wchar *str, wchar *pattern, ssize limit);
  2257. PUBLIC ssize wcopy(wchar *dest, ssize destMax, wchar *src);
  2258. PUBLIC int wends(wchar *str, wchar *suffix);
  2259. PUBLIC wchar *wfmtv(wchar *fmt, va_list arg);
  2260. PUBLIC uint whash(wchar *name, ssize len);
  2261. PUBLIC uint whashlower(wchar *name, ssize len);
  2262. PUBLIC wchar *wjoin(wchar *sep, ...);
  2263. PUBLIC wchar *wjoinv(wchar *sep, va_list args);
  2264. PUBLIC ssize wlen(wchar *s);
  2265. #endif
  2266. PUBLIC wchar *wlower(wchar *s);
  2267. PUBLIC int wncaselesscmp(wchar *s1, wchar *s2, ssize len);
  2268. PUBLIC int wncmp(wchar *s1, wchar *s2, ssize len);
  2269. PUBLIC ssize wncopy(wchar *dest, ssize destCount, wchar *src, ssize len);
  2270. PUBLIC wchar *wpbrk(wchar *str, wchar *set);
  2271. PUBLIC wchar *wrchr(wchar *s, int c);
  2272. PUBLIC wchar *wrejoin(wchar *buf, wchar *sep, ...);
  2273. PUBLIC wchar *wrejoinv(wchar *buf, wchar *sep, va_list args);
  2274. PUBLIC ssize wspn(wchar *str, wchar *set);
  2275. PUBLIC int wstarts(wchar *str, wchar *prefix);
  2276. PUBLIC wchar *wsub(wchar *str, ssize offset, ssize len);
  2277. PUBLIC int64 wtoi(wchar *str);
  2278. PUBLIC int64 wtoiradix(wchar *str, int radix, int *err);
  2279. PUBLIC wchar *wtok(wchar *str, wchar *delim, wchar **last);
  2280. PUBLIC wchar *wtrim(wchar *str, wchar *set, int where);
  2281. PUBLIC wchar *wupper(wchar *s);
  2282. #else
  2283. /* CHAR_LEN == 1 */
  2284. #define wtom(dest, count, src, len) sncopy(dest, count, src, len)
  2285. #define mtow(dest, count, src, len) sncopy(dest, count, src, len)
  2286. #define itowbuf(buf, bufCount, value, radix) itosbuf(buf, bufCount, value, radix)
  2287. #define wchr(str, c) schr(str, c)
  2288. #define wclone(str) sclone(str)
  2289. #define wcasecmp(s1, s2) scaselesscmp(s1, s2)
  2290. #define wcmp(s1, s2) scmp(s1, s2)
  2291. #define wcontains(str, pattern) scontains(str, pattern)
  2292. #define wncontains(str, pattern, limit) sncontains(str, pattern, limit)
  2293. #define wcopy(dest, count, src) scopy(dest, count, src)
  2294. #define wends(str, suffix) sends(str, suffix)
  2295. #define wfmt sfmt
  2296. #define wfmtv(fmt, arg) sfmtv(fmt, arg)
  2297. #define whash(name, len) shash(name, len)
  2298. #define whashlower(name, len) shashlower(name, len)
  2299. #define wjoin sjoin
  2300. #define wjoinv(sep, args) sjoinv(sep, args)
  2301. #define wlen(str) slen(str)
  2302. #define wlower(str) slower(str)
  2303. #define wncmp(s1, s2, len) sncmp(s1, s2, len)
  2304. #define wncaselesscmp(s1, s2, len) sncaselesscmp(s1, s2, len)
  2305. #define wncopy(dest, count, src, len) sncopy(dest, count, src, len)
  2306. #define wpbrk(str, set) spbrk(str, set)
  2307. #define wrchr(str, c) srchr(str, c)
  2308. #define wrejoin srejoin
  2309. #define wrejoinv(buf, sep, args) srejoinv(buf, sep, args)
  2310. #define wspn(str, set) sspn(str, set)
  2311. #define wstarts(str, prefix) sstarts(str, prefix)
  2312. #define wsub(str, offset, len) ssub(str, offset, len)
  2313. #define wtoi(str) stoi(str)
  2314. #define wtoiradix(str, radix, err) stoiradix(str, radix, err)
  2315. #define wtok(str, delim, last) stok(str, delim, last)
  2316. #define wtrim(str, set, where) strim(str, set, where)
  2317. #define wupper(str) supper(str)
  2318. #endif /* ME_CHAR_LEN > 1 */
  2319. /********************************* Mixed Strings ******************************/
  2320. /*
  2321. These routines operate on wide strings mixed with a multibyte/ascii operand
  2322. This API is not yet public
  2323. */
  2324. #if ME_CHAR_LEN > 1
  2325. #if FUTURE
  2326. PUBLIC int mcaselesscmp(wchar *s1, cchar *s2);
  2327. PUBLIC int mcmp(wchar *s1, cchar *s2);
  2328. PUBLIC wchar *mcontains(wchar *str, cchar *pattern);
  2329. PUBLIC wchar *mncontains(wchar *str, cchar *pattern, ssize limit);
  2330. PUBLIC ssize mcopy(wchar *dest, ssize destMax, cchar *src);
  2331. PUBLIC int mends(wchar *str, cchar *suffix);
  2332. PUBLIC wchar *mfmt(cchar *fmt, ...);
  2333. PUBLIC wchar *mfmtv(cchar *fmt, va_list arg);
  2334. PUBLIC wchar *mjoin(cchar *str, ...);
  2335. PUBLIC wchar *mjoinv(wchar *buf, va_list args);
  2336. PUBLIC int mncmp(wchar *s1, cchar *s2, ssize len);
  2337. PUBLIC int mncaselesscmp(wchar *s1, cchar *s2, ssize len);
  2338. PUBLIC ssize mncopy(wchar *dest, ssize destMax, cchar *src, ssize len);
  2339. PUBLIC wchar *mpbrk(wchar *str, cchar *set);
  2340. PUBLIC wchar *mrejoin(wchar *buf, cchar *sep, ...);
  2341. PUBLIC wchar *mrejoinv(wchar *buf, cchar *sep, va_list args);
  2342. PUBLIC ssize mspn(wchar *str, cchar *set);
  2343. PUBLIC int mstarts(wchar *str, cchar *prefix);
  2344. PUBLIC wchar *mtok(wchar *str, cchar *delim, wchar **last);
  2345. PUBLIC wchar *mtrim(wchar *str, cchar *set, int where);
  2346. #endif
  2347. #else /* ME_CHAR_LEN <= 1 */
  2348. #define mcaselesscmp(s1, s2) scaselesscmp(s1, s2)
  2349. #define mcmp(s1, s2) scmp(s1, s2)
  2350. #define mcontains(str, pattern) scontains(str, pattern)
  2351. #define mncontains(str, pattern, limit) sncontains(str, pattern, limit)
  2352. #define mcopy(dest, count, src) scopy(dest, count, src)
  2353. #define mends(str, suffix) sends(str, suffix)
  2354. #define mfmt sfmt
  2355. #define mfmtv(fmt, arg) sfmtv(fmt, arg)
  2356. #define mjoin sjoin
  2357. #define mjoinv(sep, args) sjoinv(sep, args)
  2358. #define mncmp(s1, s2, len) sncmp(s1, s2, len)
  2359. #define mncaselesscmp(s1, s2, len) sncaselesscmp(s1, s2, len)
  2360. #define mncopy(dest, count, src, len) sncopy(dest, count, src, len)
  2361. #define mpbrk(str, set) spbrk(str, set)
  2362. #define mrejoin srejoin
  2363. #define mrejoinv(buf, sep, args) srejoinv(buf, sep, args)
  2364. #define mspn(str, set) sspn(str, set)
  2365. #define mstarts(str, prefix) sstarts(str, prefix)
  2366. #define mtok(str, delim, last) stok(str, delim, last)
  2367. #define mtrim(str, set, where) strim(str, set, where)
  2368. #endif /* ME_CHAR_LEN <= 1 */
  2369. /************************************ Formatting ******************************/
  2370. /**
  2371. Print a formatted message to the standard error channel
  2372. @description This is a secure replacement for fprintf(stderr).
  2373. @param fmt Printf style format string
  2374. @param ... Variable arguments to format
  2375. @return Returns the number of bytes written
  2376. @ingroup MprString
  2377. @stability Stable
  2378. */
  2379. PUBLIC ssize mprEprintf(cchar *fmt, ...) PRINTF_ATTRIBUTE(1,2);
  2380. /**
  2381. Print a formatted message to a file descriptor
  2382. @description This is a replacement for fprintf as part of the safe string MPR library. It minimizes
  2383. memory use and uses a file descriptor instead of a File pointer.
  2384. @param file MprFile object returned via #mprOpenFile.
  2385. @param fmt Printf style format string
  2386. @param ... Variable arguments to format
  2387. @return Returns the number of bytes written
  2388. @ingroup MprString
  2389. @stability Stable
  2390. */
  2391. PUBLIC ssize mprFprintf(struct MprFile *file, cchar *fmt, ...) PRINTF_ATTRIBUTE(2,3);
  2392. /**
  2393. Formatted print. This is a secure verion of printf that can handle null args.
  2394. @description This is a secure replacement for printf. It can handle null arguments without crashes.
  2395. @param fmt Printf style format string
  2396. @param ... Variable arguments to format
  2397. @return Returns the number of bytes written
  2398. @ingroup MprString
  2399. @stability Stable
  2400. */
  2401. PUBLIC ssize mprPrintf(cchar *fmt, ...) PRINTF_ATTRIBUTE(1, 2);
  2402. /**
  2403. Print to stdout and add a trailing newline
  2404. @internal
  2405. */
  2406. PUBLIC ssize print(cchar *fmt, ...) PRINTF_ATTRIBUTE(1,2);
  2407. /**
  2408. Format a string into a buffer.
  2409. @description This routine will format the arguments into a result. If a buffer is supplied, it will be used.
  2410. Otherwise if the buf argument is NULL, a buffer will be allocated. The arguments will be formatted up
  2411. to the maximum size supplied by the maxsize argument. A trailing null will always be appended.
  2412. @param buf Optional buffer to contain the formatted result
  2413. @param maxsize Maximum size of the result
  2414. @param fmt Printf style format string
  2415. @param args Variable arguments to format
  2416. @return Returns the number of characters in the string.
  2417. @ingroup MprString
  2418. @internal
  2419. @stability Stable
  2420. */
  2421. PUBLIC char *mprPrintfCore(char *buf, ssize maxsize, cchar *fmt, va_list args);
  2422. /********************************* Floating Point *****************************/
  2423. #if ME_FLOAT
  2424. /**
  2425. Floating Point Services
  2426. @stability Stable
  2427. @see mprDota mprIsInfinite mprIsNan mprIsZero
  2428. @defgroup MprFloat MprFloat
  2429. @stability Internal
  2430. */
  2431. typedef struct MprFloat { int dummy; } MprFloat;
  2432. /**
  2433. Test if a double value is infinte
  2434. @param value Value to test
  2435. @return True if the value is +Infinity or -Infinity
  2436. @ingroup MprFloat
  2437. @stability Stable
  2438. */
  2439. PUBLIC int mprIsInfinite(double value);
  2440. /**
  2441. Test if a double value is zero
  2442. @param value Value to test
  2443. @return True if the value is zero
  2444. @ingroup MprFloat
  2445. @stability Stable
  2446. */
  2447. PUBLIC int mprIsZero(double value);
  2448. /**
  2449. Test if a double value is not-a-number
  2450. @param value Value to test
  2451. @return True if the value is NaN
  2452. @ingroup MprFloat
  2453. @stability Stable
  2454. */
  2455. PUBLIC int mprIsNan(double value);
  2456. #endif /* ME_FLOAT */
  2457. /********************************* Buffering **********************************/
  2458. /**
  2459. Buffer refill callback function
  2460. @description Function to call when the buffer is depleted and needs more data.
  2461. @param buf Instance of an MprBuf
  2462. @param arg Data argument supplied to #mprSetBufRefillProc
  2463. @returns The callback should return 0 if successful, otherwise a negative error code.
  2464. @ingroup MprBuf
  2465. @stability Stable
  2466. */
  2467. typedef int (*MprBufProc)(struct MprBuf* bp, void *arg);
  2468. /**
  2469. Dynamic Buffer Module
  2470. @description MprBuf is a flexible, dynamic growable buffer structure. It has start and end pointers to the
  2471. data buffer which act as read/write pointers. Routines are provided to get and put data into and out of the
  2472. buffer and automatically advance the appropriate start/end pointer. By definition, the buffer is empty when
  2473. the start pointer == the end pointer. Buffers can be created with a fixed size or can grow dynamically as
  2474. more data is added to the buffer.
  2475. \n\n
  2476. For performance, the specification of MprBuf is deliberately exposed. All members of MprBuf are implicitly public.
  2477. However, it is still recommended that wherever possible, you use the accessor routines provided.
  2478. @see MprBuf MprBufProc mprAddNullToBuf mprAddNullToWideBuf mprAdjustBufEnd mprAdjustBufStart mprBufToString mprCloneBuf
  2479. mprCompactBuf mprCreateBuf mprFlushBuf mprGetBlockFromBuf mprGetBufEnd mprGetBufLength mprGetBufOrigin
  2480. mprGetBufRefillProc mprGetBufSize mprGetBufSpace mprGetBufStart mprGetCharFromBuf mprGrowBuf
  2481. mprInsertCharToBuf mprLookAtLastCharInBuf mprLookAtNextCharInBuf mprPutBlockToBuf mprPutCharToBuf
  2482. mprPutCharToWideBuf mprPutToBuf mprPutFmtToWideBuf mprPutIntToBuf mprPutPadToBuf mprPutStringToBuf
  2483. mprPutStringToWideBuf mprPutSubStringToBuf mprRefillBuf mprResetBufIfEmpty mprSetBufMax mprSetBufRefillProc
  2484. mprSetBufSize
  2485. @defgroup MprBuf MprBuf
  2486. @stability Internal.
  2487. */
  2488. typedef struct MprBuf {
  2489. char *data; /**< Actual buffer for data */
  2490. char *endbuf; /**< Pointer one past the end of buffer */
  2491. char *start; /**< Pointer to next data char */
  2492. char *end; /**< Pointer one past the last data chr */
  2493. ssize buflen; /**< Current size of buffer */
  2494. ssize maxsize; /**< Max size the buffer can ever grow */
  2495. ssize growBy; /**< Next growth increment to use */
  2496. MprBufProc refillProc; /**< Auto-refill procedure */
  2497. void *refillArg; /**< Refill arg - must be alloced memory */
  2498. } MprBuf;
  2499. /**
  2500. Add a null character to the buffer contents.
  2501. @description Add a null byte but do not change the buffer content lengths. The null is added outside the
  2502. "official" content length. This is useful when calling #mprGetBufStart and using the returned pointer
  2503. as a "C" string pointer.
  2504. @param buf Buffer created via mprCreateBuf
  2505. @ingroup MprBuf
  2506. @stability Stable.
  2507. */
  2508. PUBLIC void mprAddNullToBuf(MprBuf *buf);
  2509. /**
  2510. Adjust the buffer end position
  2511. @description Adjust the buffer end position by the specified amount. This is typically used to advance the
  2512. end position as content is appended to the buffer. Adjusting the start or end position will change the value
  2513. returned by #mprGetBufLength. If using the mprPutBlock or mprPutChar routines, adjusting the end position is
  2514. done automatically.
  2515. @param buf Buffer created via mprCreateBuf
  2516. @param count Positive or negative count of bytes to adjust the end position.
  2517. @ingroup MprBuf
  2518. @stability Stable.
  2519. */
  2520. PUBLIC void mprAdjustBufEnd(MprBuf *buf, ssize count);
  2521. /**
  2522. Adjust the buffer start position
  2523. @description Adjust the buffer start position by the specified amount. This is typically used to advance the
  2524. start position as content is consumed. Adjusting the start or end position will change the value returned
  2525. by #mprGetBufLength. If using the mprGetBlock or mprGetChar routines, adjusting the start position is
  2526. done automatically.
  2527. @param buf Buffer created via mprCreateBuf
  2528. @param count Positive or negative count of bytes to adjust the start position.
  2529. @ingroup MprBuf
  2530. @stability Stable.
  2531. */
  2532. PUBLIC void mprAdjustBufStart(MprBuf *buf, ssize count);
  2533. /**
  2534. Convert the buffer contents to a string
  2535. @param buf Buffer created via mprCreateBuf
  2536. @returns Allocated string
  2537. @ingroup MprBuf
  2538. @stability Stable.
  2539. */
  2540. PUBLIC char *mprBufToString(MprBuf *buf);
  2541. /**
  2542. Create a new buffer
  2543. @description Create a new buffer.
  2544. @param initialSize Initial size of the buffer
  2545. @param maxSize Maximum size the buffer can grow to
  2546. @return a new buffer
  2547. @ingroup MprBuf
  2548. @stability Stable.
  2549. */
  2550. PUBLIC MprBuf *mprCreateBuf(ssize initialSize, ssize maxSize);
  2551. /**
  2552. Clone a buffer
  2553. @description Copy the buffer and contents into a newly allocated buffer
  2554. @param orig Original buffer to copy
  2555. @return Returns a newly allocated buffer
  2556. @stability Stable.
  2557. */
  2558. PUBLIC MprBuf *mprCloneBuf(MprBuf *orig);
  2559. /**
  2560. Clone a buffer contents
  2561. @param bp Buffer to copy
  2562. @return Returns a newly allocated memory block containing the buffer contents.
  2563. @stability Stable.
  2564. */
  2565. PUBLIC char *mprCloneBufMem(MprBuf *bp);
  2566. /**
  2567. Clone a buffer contents
  2568. @param bp Buffer to copy
  2569. @return Returns a string containing the buffer contents.
  2570. @stability Stable.
  2571. */
  2572. PUBLIC char *mprCloneBufAsString(MprBuf *bp);
  2573. /**
  2574. Compact the buffer contents
  2575. @description Compact the buffer contents by copying the contents down to start the the buffer origin.
  2576. @param buf Buffer created via mprCreateBuf
  2577. @ingroup MprBuf
  2578. @stability Stable.
  2579. */
  2580. PUBLIC void mprCompactBuf(MprBuf *buf);
  2581. /**
  2582. Flush the buffer contents
  2583. @description Discard the buffer contents and reset the start end content pointers.
  2584. @param buf Buffer created via mprCreateBuf
  2585. @ingroup MprBuf
  2586. @stability Stable.
  2587. */
  2588. PUBLIC void mprFlushBuf(MprBuf *buf);
  2589. /**
  2590. Get a block of data from the buffer
  2591. @description Get a block of data from the buffer start and advance the start position. If the requested
  2592. length is greater than the available buffer content, then return whatever data is available.
  2593. @param buf Buffer created via mprCreateBuf
  2594. @param blk Destination block for the read data.
  2595. @param count Count of bytes to read from the buffer.
  2596. @return The count of bytes read into the block or -1 if the buffer is empty.
  2597. @ingroup MprBuf
  2598. @stability Stable.
  2599. */
  2600. PUBLIC ssize mprGetBlockFromBuf(MprBuf *buf, char *blk, ssize count);
  2601. /**
  2602. Get a reference to the end of the buffer contents
  2603. @description Get a pointer to the location immediately after the end of the buffer contents.
  2604. @param buf Buffer created via mprCreateBuf
  2605. @returns Pointer to the end of the buffer data contents. Points to the location one after the last data byte.
  2606. @ingroup MprBuf
  2607. @stability Stable.
  2608. */
  2609. PUBLIC char *mprGetBufEnd(MprBuf *buf);
  2610. /**
  2611. Get the buffer content length.
  2612. @description Get the length of the buffer contents. This is not the same as the buffer size which may be larger.
  2613. @param buf Buffer created via mprCreateBuf
  2614. @returns The length of the content stored in the buffer in bytes
  2615. @ingroup MprBuf
  2616. @stability Stable.
  2617. */
  2618. PUBLIC ssize mprGetBufLength(MprBuf *buf);
  2619. /**
  2620. Get the buffer refill procedure
  2621. @description Return the buffer refill callback function.
  2622. @param buf Buffer created via mprCreateBuf
  2623. @returns The refill call back function if defined.
  2624. @ingroup MprBuf
  2625. @stability Stable.
  2626. */
  2627. PUBLIC MprBufProc mprGetBufRefillProc(MprBuf *buf);
  2628. /**
  2629. Get the origin of the buffer content storage.
  2630. @description Get a pointer to the start of the buffer content storage. This is always and allocated block.
  2631. @param buf Buffer created via mprCreateBuf
  2632. @returns A pointer to the buffer content storage.
  2633. @ingroup MprBuf
  2634. @stability Stable.
  2635. */
  2636. PUBLIC char *mprGetBuf(MprBuf *buf);
  2637. /**
  2638. Get the current size of the buffer content storage.
  2639. @description This returns the size of the memory block allocated for storing the buffer contents.
  2640. @param buf Buffer created via mprCreateBuf
  2641. @returns The size of the buffer content storage.
  2642. @ingroup MprBuf
  2643. @stability Stable.
  2644. */
  2645. PUBLIC ssize mprGetBufSize(MprBuf *buf);
  2646. /**
  2647. Get the space available to store content
  2648. @description Get the number of bytes available to store content in the buffer
  2649. @param buf Buffer created via mprCreateBuf
  2650. @returns The number of bytes available
  2651. @ingroup MprBuf
  2652. @stability Stable.
  2653. */
  2654. PUBLIC ssize mprGetBufSpace(MprBuf *buf);
  2655. /**
  2656. Get the start of the buffer contents
  2657. @description Get a pointer to the start of the buffer contents. Use #mprGetBufLength to determine the length
  2658. of the content. Use #mprGetBufEnd to get a pointer to the location after the end of the content.
  2659. @param buf Buffer created via mprCreateBuf
  2660. @returns Pointer to the start of the buffer data contents
  2661. @ingroup MprBuf
  2662. @stability Stable.
  2663. */
  2664. PUBLIC char *mprGetBufStart(MprBuf *buf);
  2665. /**
  2666. Get a character from the buffer
  2667. @description Get the next byte from the buffer start and advance the start position.
  2668. @param buf Buffer created via mprCreateBuf
  2669. @return The character or -1 if the buffer is empty.
  2670. @ingroup MprBuf
  2671. @stability Stable.
  2672. */
  2673. PUBLIC int mprGetCharFromBuf(MprBuf *buf);
  2674. /**
  2675. Grow the buffer
  2676. @description Grow the storage allocated for content for the buffer. The new size must be less than the maximum
  2677. limit specified via #mprCreateBuf or #mprSetBufSize.
  2678. @param buf Buffer created via mprCreateBuf
  2679. @param count Count of bytes by which to grow the buffer content size.
  2680. @returns Zero if successful and otherwise a negative error code
  2681. @ingroup MprBuf
  2682. @stability Stable.
  2683. */
  2684. PUBLIC int mprGrowBuf(MprBuf *buf, ssize count);
  2685. /**
  2686. Insert a character into the buffer
  2687. @description Insert a character into to the buffer prior to the current buffer start point.
  2688. @param buf Buffer created via mprCreateBuf
  2689. @param c Character to append.
  2690. @returns Zero if successful and otherwise a negative error code
  2691. @ingroup MprBuf
  2692. @stability Stable.
  2693. */
  2694. PUBLIC int mprInsertCharToBuf(MprBuf *buf, int c);
  2695. /**
  2696. Peek at the next character in the buffer
  2697. @description Non-destructively return the next character from the start position in the buffer.
  2698. The character is returned and the start position is not altered.
  2699. @param buf Buffer created via mprCreateBuf
  2700. @returns Zero if successful and otherwise a negative error code
  2701. @ingroup MprBuf
  2702. @stability Stable.
  2703. */
  2704. PUBLIC int mprLookAtNextCharInBuf(MprBuf *buf);
  2705. /**
  2706. Peek at the last character in the buffer
  2707. @description Non-destructively return the last character from just prior to the end position in the buffer.
  2708. The character is returned and the end position is not altered.
  2709. @param buf Buffer created via mprCreateBuf
  2710. @returns Zero if successful and otherwise a negative error code
  2711. @ingroup MprBuf
  2712. @stability Stable.
  2713. */
  2714. PUBLIC int mprLookAtLastCharInBuf(MprBuf *buf);
  2715. /**
  2716. Put a block to the buffer.
  2717. @description Append a block of data to the buffer at the end position and increment the end pointer.
  2718. @param buf Buffer created via mprCreateBuf
  2719. @param ptr Block to append
  2720. @param size Size of block to append
  2721. @returns Zero if successful and otherwise a negative error code
  2722. @ingroup MprBuf
  2723. @stability Stable.
  2724. */
  2725. PUBLIC ssize mprPutBlockToBuf(MprBuf *buf, cchar *ptr, ssize size);
  2726. /**
  2727. Put a character to the buffer.
  2728. @description Append a character to the buffer at the end position and increment the end pointer.
  2729. @param buf Buffer created via mprCreateBuf
  2730. @param c Character to append
  2731. @returns Zero if successful and otherwise a negative error code
  2732. @ingroup MprBuf
  2733. @stability Stable.
  2734. */
  2735. PUBLIC int mprPutCharToBuf(MprBuf *buf, int c);
  2736. /**
  2737. Put a formatted string to the buffer.
  2738. @description Format a string and append to the buffer at the end position and increment the end pointer.
  2739. @param buf Buffer created via mprCreateBuf
  2740. @param fmt Printf style format string
  2741. @param ... Variable arguments for the format string
  2742. @returns Zero if successful and otherwise a negative error code
  2743. @ingroup MprBuf
  2744. @stability Stable.
  2745. */
  2746. PUBLIC ssize mprPutToBuf(MprBuf *buf, cchar *fmt, ...) PRINTF_ATTRIBUTE(2,3);
  2747. /**
  2748. Put an integer to the buffer.
  2749. @description Append a integer to the buffer at the end position and increment the end pointer.
  2750. @param buf Buffer created via mprCreateBuf
  2751. @param i Integer to append to the buffer
  2752. @returns Number of characters added to the buffer, otherwise a negative error code
  2753. @ingroup MprBuf
  2754. @stability Stable.
  2755. */
  2756. PUBLIC ssize mprPutIntToBuf(MprBuf *buf, int64 i);
  2757. /**
  2758. Put padding characters to the buffer.
  2759. @description Append padding characters to the buffer at the end position and increment the end pointer.
  2760. @param buf Buffer created via mprCreateBuf
  2761. @param c Character to append
  2762. @param count Count of pad characters to put
  2763. @returns Zero if successful and otherwise a negative error code
  2764. @ingroup MprBuf
  2765. @stability Stable
  2766. */
  2767. PUBLIC ssize mprPutPadToBuf(MprBuf *buf, int c, ssize count);
  2768. /**
  2769. Put a string to the buffer.
  2770. @description Append a null terminated string to the buffer at the end position and increment the end pointer.
  2771. @param buf Buffer created via mprCreateBuf
  2772. @param str String to append
  2773. @returns Zero if successful and otherwise a negative error code
  2774. @ingroup MprBuf
  2775. @stability Stable.
  2776. */
  2777. PUBLIC ssize mprPutStringToBuf(MprBuf *buf, cchar *str);
  2778. /**
  2779. Put a substring to the buffer.
  2780. @description Append a null terminated substring to the buffer at the end position and increment the end pointer.
  2781. @param buf Buffer created via mprCreateBuf
  2782. @param str String to append
  2783. @param count Put at most count characters to the buffer
  2784. @returns Zero if successful and otherwise a negative error code
  2785. @ingroup MprBuf
  2786. @stability Stable.
  2787. */
  2788. PUBLIC ssize mprPutSubStringToBuf(MprBuf *buf, cchar *str, ssize count);
  2789. /**
  2790. Refill the buffer with data
  2791. @description Refill the buffer by calling the refill procedure specified via #mprSetBufRefillProc
  2792. @param buf Buffer created via mprCreateBuf
  2793. @returns Zero if successful and otherwise a negative error code
  2794. @ingroup MprBuf
  2795. @stability Stable.
  2796. */
  2797. PUBLIC int mprRefillBuf(MprBuf *buf);
  2798. /**
  2799. Reset the buffer
  2800. @description If the buffer is empty, reset the buffer start and end pointers to the beginning of the buffer.
  2801. @param buf Buffer created via mprCreateBuf
  2802. @ingroup MprBuf
  2803. @stability Stable.
  2804. */
  2805. PUBLIC void mprResetBufIfEmpty(MprBuf *buf);
  2806. /**
  2807. Set the maximum buffer size
  2808. @description Update the maximum buffer size set when the buffer was created
  2809. @param buf Buffer created via mprCreateBuf
  2810. @param maxSize New maximum size the buffer can grow to
  2811. @ingroup MprBuf
  2812. @stability Stable.
  2813. */
  2814. PUBLIC void mprSetBufMax(MprBuf *buf, ssize maxSize);
  2815. /**
  2816. Set the buffer refill procedure
  2817. @description Define a buffer refill procedure. The MprBuf module will not invoke or manage this refill procedure.
  2818. It is simply stored to allow upper layers to use and provide their own auto-refill mechanism.
  2819. @param buf Buffer created via mprCreateBuf
  2820. @param fn Callback function to store.
  2821. @param arg Callback data argument.
  2822. @ingroup MprBuf
  2823. @stability Stable.
  2824. */
  2825. PUBLIC void mprSetBufRefillProc(MprBuf *buf, MprBufProc fn, void *arg);
  2826. /**
  2827. Set the buffer size
  2828. @description Set the current buffer content size and maximum size limit. Setting a current size will
  2829. immediately grow the buffer to be this size. If the size is less than the current buffer size,
  2830. the requested size will be ignored. ie. this call will not shrink the buffer. Setting a maxSize
  2831. will define a maximum limit for how big the buffer contents can grow. Set either argument to
  2832. -1 to be ignored.
  2833. @param buf Buffer created via mprCreateBuf
  2834. @param size Size to immediately make the buffer. If size is less than the current buffer size, it will be ignored.
  2835. Set to -1 to ignore this parameter.
  2836. @param maxSize Maximum size the buffer contents can grow to.
  2837. @returns Zero if successful and otherwise a negative error code
  2838. @ingroup MprBuf
  2839. @stability Stable.
  2840. */
  2841. PUBLIC int mprSetBufSize(MprBuf *buf, ssize size, ssize maxSize);
  2842. #if DOXYGEN || ME_CHAR_LEN > 1
  2843. #if FUTURE
  2844. /**
  2845. Add a wide null character to the buffer contents.
  2846. @description Add a null character but do not change the buffer content lengths. The null is added outside the
  2847. "official" content length. This is useful when calling #mprGetBufStart and using the returned pointer
  2848. as a string pointer.
  2849. @param buf Buffer created via mprCreateBuf
  2850. @ingroup MprBuf
  2851. @stability Evolving
  2852. */
  2853. PUBLIC void mprAddNullToWideBuf(MprBuf *buf);
  2854. /**
  2855. Put a wide character to the buffer.
  2856. @description Append a wide character to the buffer at the end position and increment the end pointer.
  2857. @param buf Buffer created via mprCreateBuf
  2858. @param c Character to append
  2859. @returns Zero if successful and otherwise a negative error code
  2860. @ingroup MprBuf
  2861. @stability Prototype
  2862. */
  2863. PUBLIC int mprPutCharToWideBuf(MprBuf *buf, int c);
  2864. /**
  2865. Put a wide string to the buffer.
  2866. @description Append a null terminated wide string to the buffer at the end position and increment the end pointer.
  2867. @param buf Buffer created via mprCreateBuf
  2868. @param str String to append
  2869. @returns Count of bytes written and otherwise a negative error code
  2870. @ingroup MprBuf
  2871. @stability Prototype
  2872. */
  2873. PUBLIC ssize mprPutStringToWideBuf(MprBuf *buf, cchar *str);
  2874. /**
  2875. Put a formatted wide string to the buffer.
  2876. @description Format a string and append to the buffer at the end position and increment the end pointer.
  2877. @param buf Buffer created via mprCreateBuf
  2878. @param fmt Printf style format string
  2879. @param ... Variable arguments for the format string
  2880. @returns Count of bytes written and otherwise a negative error code
  2881. @ingroup MprBuf
  2882. @stability Prototype
  2883. */
  2884. PUBLIC ssize mprPutFmtToWideBuf(MprBuf *buf, cchar *fmt, ...) PRINTF_ATTRIBUTE(2,3);
  2885. #endif /* FUTURE */
  2886. #else /* ME_CHAR_LEN == 1 */
  2887. #define mprAddNullToWideBuf mprAddNullToBuf
  2888. #define mprPutCharToWideBuf mprPutCharToBuf
  2889. #define mprPutStringToWideBuf mprPutStringToBuf
  2890. #define mprPutFmtToWideBuf mprPutToBuf
  2891. #endif
  2892. /*
  2893. Macros for speed
  2894. */
  2895. #define mprGetBufLength(bp) ((bp) ? ((ssize) ((bp)->end - (bp)->start)) : 0)
  2896. #define mprGetBufSize(bp) ((bp)->buflen)
  2897. #define mprGetBufSpace(bp) ((bp)->endbuf - (bp)->end)
  2898. #define mprGetBuf(bp) ((bp)->data)
  2899. #define mprGetBufStart(bp) ((bp)->start)
  2900. #define mprGetBufEnd(bp) ((bp)->end)
  2901. /*
  2902. Prototype
  2903. */
  2904. PUBLIC uint mprGetUint16FromBuf(MprBuf *buf);
  2905. PUBLIC uint mprGetUint24FromBuf(MprBuf *buf);
  2906. PUBLIC uint mprGetUint32FromBuf(MprBuf *buf);
  2907. PUBLIC uint mprPeekUint32FromBuf(MprBuf *buf);
  2908. PUBLIC void mprPutUint16ToBuf(MprBuf *buf, uint16 num);
  2909. PUBLIC void mprPutUint32ToBuf(MprBuf *buf, uint32 num);
  2910. /******************************** Date and Time *******************************/
  2911. /**
  2912. Format a date according to RFC822: (Fri, 07 Jan 2003 12:12:21 PDT)
  2913. */
  2914. #define MPR_RFC_DATE "%a, %d %b %Y %T %Z"
  2915. #define MPR_RFC822_DATE "%a, %d %b %Y %T %Z"
  2916. /*
  2917. ISO dates. 2009-05-21T16:06:05.000Z
  2918. */
  2919. #define MPR_ISO_DATE "%Y-%m-%dT%H:%M:%S.%fZ"
  2920. /**
  2921. Default date format used in mprFormatLocalTime/mprFormatUniversalTime when no format supplied
  2922. */
  2923. #define MPR_DEFAULT_DATE "%a %b %d %T %Y %Z"
  2924. /**
  2925. Date format for use in HTTP (headers)
  2926. */
  2927. #define MPR_HTTP_DATE "%a, %d %b %Y %T GMT"
  2928. /**
  2929. Date format for RFC 3399 for use in HTML 5
  2930. */
  2931. #define MPR_RFC3399_DATE "%FT%TZ"
  2932. /**
  2933. Date for use in log files (compact)
  2934. */
  2935. #define MPR_LOG_DATE "%D %T"
  2936. /********************************** Defines ***********************************/
  2937. /**
  2938. Date and Time Service
  2939. @stability Stable
  2940. @see MprTime mprCompareTime mprCreateTimeService mprDecodeLocalTime mprDecodeUniversalTime mprFormatLocalTime
  2941. mprFormatTm mprGetDate mprGetElapsedTicks mprGetRemainingTicks mprGetHiResTicks mprGetTimeZoneOffset mprMakeTime
  2942. mprMakeUniversalTime mprParseTime
  2943. @defgroup MprTime MprTime
  2944. */
  2945. typedef Time MprTime;
  2946. /**
  2947. Mpr time structure.
  2948. @description MprTime is the cross platform time abstraction structure. Time is stored as milliseconds
  2949. since the epoch: 00:00:00 UTC Jan 1 1970. MprTime is typically a 64 bit quantity.
  2950. @ingroup MprTime
  2951. @stability Internal
  2952. */
  2953. PUBLIC int mprCreateTimeService(void);
  2954. /**
  2955. Compare two times
  2956. @description compare two times and return a code indicating which is greater, less or equal
  2957. @param t1 First time
  2958. @param t2 Second time
  2959. @returns Zero if equal, -1 if t1 is less than t2 otherwise one.
  2960. @ingroup MprTime
  2961. @stability Stable
  2962. */
  2963. PUBLIC int mprCompareTime(MprTime t1, MprTime t2);
  2964. /**
  2965. Decode a time value into a tokenized local time value.
  2966. @description Safe replacement for localtime. This call converts the time value to local time and formats
  2967. the as a struct tm.
  2968. @param timep Pointer to a tm structure to hold the result
  2969. @param time Time to format
  2970. @ingroup MprTime
  2971. @stability Stable
  2972. */
  2973. PUBLIC void mprDecodeLocalTime(struct tm *timep, MprTime time);
  2974. /**
  2975. Decode a time value into a tokenized UTC time structure.
  2976. @description Safe replacement for gmtime. This call converts the supplied time value
  2977. to UTC time and parses the result into a tm structure.
  2978. @param timep Pointer to a tm structure to hold the result.
  2979. @param time The time to format
  2980. @ingroup MprTime
  2981. @stability Stable
  2982. */
  2983. PUBLIC void mprDecodeUniversalTime(struct tm *timep, MprTime time);
  2984. /**
  2985. Convert a time value to local time and format as a string.
  2986. @description Safe replacement for ctime.
  2987. @param fmt Time format string. See #mprFormatUniversalTime for time formats.
  2988. @param time Time to format. Use mprGetTime to retrieve the current time.
  2989. @return The formatting time string
  2990. @ingroup MprTime
  2991. @stability Stable
  2992. */
  2993. PUBLIC char *mprFormatLocalTime(cchar *fmt, MprTime time);
  2994. /**
  2995. Convert a time value to universal time and format as a string.
  2996. @description Format a time string. This uses strftime if available and so the supported formats vary from
  2997. platform to platform. Strftime should supports some of these these formats described below.
  2998. @param time Time to format. Use mprGetTime to retrieve the current time.
  2999. @param fmt Time format string
  3000. \n
  3001. %A ... full weekday name (Monday)
  3002. \n
  3003. %a ... abbreviated weekday name (Mon)
  3004. \n
  3005. %B ... full month name (January)
  3006. \n
  3007. %b ... abbreviated month name (Jan)
  3008. \n
  3009. %C ... century. Year / 100. (0-N)
  3010. \n
  3011. %c ... standard date and time representation
  3012. \n
  3013. %D ... date (%m/%d/%y)
  3014. \n
  3015. %d ... day-of-month (01-31)
  3016. \n
  3017. %e ... day-of-month with a leading space if only one digit ( 1-31)
  3018. \n
  3019. %f ... milliseconds
  3020. \n
  3021. %F ... same as %Y-%m-%d
  3022. \n
  3023. %H ... hour (24 hour clock) (00-23)
  3024. \n
  3025. %h ... same as %b
  3026. \n
  3027. %I ... hour (12 hour clock) (01-12)
  3028. \n
  3029. %j ... day-of-year (001-366)
  3030. \n
  3031. %k ... hour (24 hour clock) (0-23)
  3032. \n
  3033. %l ... the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank.
  3034. \n
  3035. %M ... minute (00-59)
  3036. \n
  3037. %m ... month (01-12)
  3038. \n
  3039. %n ... a newline
  3040. \n
  3041. %P ... lower case am / pm
  3042. \n
  3043. %p ... AM / PM
  3044. \n
  3045. %R ... same as %H:%M
  3046. \n
  3047. %r ... same as %H:%M:%S %p
  3048. \n
  3049. %S ... second (00-59)
  3050. \n
  3051. %s ... seconds since epoch
  3052. \n
  3053. %T ... time (%H:%M:%S)
  3054. \n
  3055. %t ... a tab.
  3056. \n
  3057. %U ... week-of-year, first day sunday (00-53)
  3058. \n
  3059. %u ... the weekday (Monday as the first day of the week) as a decimal number (1-7).
  3060. \n
  3061. %v ... is equivalent to ``%e-%b-%Y''.
  3062. \n
  3063. %W ... week-of-year, first day monday (00-53)
  3064. \n
  3065. %w ... weekday (0-6, sunday is 0)
  3066. \n
  3067. %X ... standard time representation
  3068. \n
  3069. %x ... standard date representation
  3070. \n
  3071. %Y ... year with century
  3072. \n
  3073. %y ... year without century (00-99)
  3074. \n
  3075. %Z ... timezone name
  3076. \n
  3077. %z ... offset from UTC (-hhmm or +hhmm)
  3078. \n
  3079. %+ ... national representation of the date and time (the format is similar to that produced by date(1)).
  3080. \n
  3081. %% ... percent sign
  3082. \n\n
  3083. Some platforms may also support the following format extensions:
  3084. \n
  3085. %E* ... POSIX locale extensions. Where "*" is one of the characters: c, C, x, X, y, Y.
  3086. \n
  3087. %G ... a year as a decimal number with century. This year is the one that contains the greater part of
  3088. the week (Monday as the first day of the week).
  3089. \n
  3090. %g ... the same year as in ``%G'', but as a decimal number without century (00-99).
  3091. \n
  3092. %O* ... POSIX locale extensions. Where "*" is one of the characters: d, e, H, I, m, M, S, u, U, V, w, W, y.
  3093. Additionly %OB implemented to represent alternative months names (used standalone, without day mentioned).
  3094. \n
  3095. %V ... the week number of the year (Monday as the first day of the week) as a decimal number (01-53). If the week
  3096. containing January 1 has four or more days in the new year, then it is week 1; otherwise it is the last
  3097. week of the previous year, and the next week is week 1.
  3098. \n\n
  3099. Useful formats:
  3100. \n
  3101. RFC822: "%a, %d %b %Y %H:%M:%S %Z "Fri, 07 Jan 2003 12:12:21 PDT"
  3102. \n
  3103. "%T %F "12:12:21 2007-01-03"
  3104. \n
  3105. "%v "07-Jul-2003"
  3106. \n
  3107. RFC3399: "%FT%TZ" "1985-04-12T23:20:50.52Z" which is April 12 1985, 23:20.50 and 52 msec
  3108. @return The formatting time string
  3109. @ingroup MprTime
  3110. @stability Stable
  3111. */
  3112. PUBLIC char *mprFormatUniversalTime(cchar *fmt, MprTime time);
  3113. /**
  3114. Format a time value as a local time.
  3115. @description This call formats the time value supplied via \a timep.
  3116. @param fmt The time format to use. See #mprFormatUniversalTime for time formats.
  3117. @param timep The time value to format.
  3118. @return The formatting time string.
  3119. @ingroup MprTime
  3120. @stability Stable
  3121. */
  3122. PUBLIC char *mprFormatTm(cchar *fmt, struct tm *timep);
  3123. /**
  3124. Get the system time.
  3125. @description Get the system time in milliseconds. This is a monotonically increasing time counter.
  3126. It does not represent wall-clock time.
  3127. @return Returns the system time in milliseconds.
  3128. @ingroup MprTime
  3129. @stability Stable
  3130. */
  3131. PUBLIC MprTicks mprGetTicks(void);
  3132. /**
  3133. Get the time.
  3134. @description Get the date/time in milliseconds since Jan 1 1970.
  3135. @return Returns the time in milliseconds since Jan 1 1970.
  3136. @ingroup MprTime
  3137. @stability Stable
  3138. */
  3139. PUBLIC MprTime mprGetTime(void);
  3140. /**
  3141. Get a string representation of the current date/time
  3142. @description Get the current date/time as a string according to the given format.
  3143. @param fmt Date formatting string. See strftime for acceptable date format specifiers.
  3144. If null, then this routine uses the #MPR_DEFAULT_DATE format.
  3145. @return An allocated date string
  3146. @ingroup MprTime
  3147. @stability Stable
  3148. */
  3149. PUBLIC char *mprGetDate(char *fmt);
  3150. /**
  3151. Get the CPU tick count.
  3152. @description Get the current CPU tick count. This is a system dependant high resolution timer. On some systems,
  3153. this returns time in nanosecond resolution.
  3154. @return Returns the CPU time in ticks. Will return the system time if CPU ticks are not available.
  3155. @ingroup MprTicks
  3156. @stability Internal
  3157. */
  3158. PUBLIC uint64 mprGetHiResTicks(void);
  3159. #if (LINUX || MACOSX || WINDOWS) && (ME_CPU_ARCH == ME_CPU_X86 || ME_CPU_ARCH == ME_CPU_X64)
  3160. #define MPR_HIGH_RES_TIMER 1
  3161. #else
  3162. #define MPR_HIGH_RES_TIMER 0
  3163. #endif
  3164. #if ME_MPR_DEBUG_LOGGING
  3165. #if MPR_HIGH_RES_TIMER
  3166. #define MPR_MEASURE(level, tag1, tag2, op) \
  3167. if ((level) <= MPR->logLevel) { \
  3168. MprTicks elapsed, start = mprGetTicks(); \
  3169. uint64 ticks = mprGetHiResTicks(); \
  3170. op; \
  3171. elapsed = mprGetTicks() - start; \
  3172. if (elapsed < 1000) { \
  3173. mprLog("mpr time", level, "%s.%s elapsed %'lld msec, %'lld ticks", \
  3174. tag1, tag2, elapsed, mprGetHiResTicks() - ticks); \
  3175. } else { \
  3176. mprLog("mpr time", level, "%s.%s elapsed %'lld msec", tag1, tag2, elapsed); \
  3177. } \
  3178. } else { \
  3179. op; \
  3180. }
  3181. #else
  3182. #define MPR_MEASURE(level, tag1, tag2, op) \
  3183. if ((level) <= MPR->logLevel) { \
  3184. MprTicks start = mprGetTicks(); \
  3185. op; \
  3186. mprLog("mpr time", level, "%s.%s elapsed %'lld msec", tag1, tag2, mprGetTicks() - start); \
  3187. } else { \
  3188. op; \
  3189. }
  3190. #endif
  3191. #else
  3192. #define MPR_MEASURE(level, tag1, tag2, op) op
  3193. #endif
  3194. /**
  3195. Return the time remaining until a timeout has elapsed
  3196. @param mark Starting time stamp
  3197. @param timeout Time in milliseconds
  3198. @return Time in milliseconds until the timeout elapses
  3199. @ingroup MprTime
  3200. @stability Stable
  3201. */
  3202. PUBLIC MprTicks mprGetRemainingTicks(MprTicks mark, MprTicks timeout);
  3203. /**
  3204. Get the elapsed time since a ticks mark. Create the ticks mark with mprGetTicks()
  3205. @param mark Starting time stamp
  3206. @returns the time elapsed since the mark was taken.
  3207. @ingroup MprTime
  3208. @stability Stable
  3209. */
  3210. PUBLIC MprTicks mprGetElapsedTicks(MprTicks mark);
  3211. /**
  3212. Get the elapsed time since a starting time mark.
  3213. @param mark Starting time created via mprGetTime()
  3214. @returns the time elapsed since the mark was taken.
  3215. @ingroup MprTime
  3216. @stability Stable
  3217. */
  3218. PUBLIC MprTime mprGetElapsedTime(MprTime mark);
  3219. /*
  3220. Convert a time structure into a time value using local time.
  3221. @param timep Pointer to a time structure
  3222. @return a time value
  3223. @ingroup MprTime
  3224. @stability Stable
  3225. */
  3226. PUBLIC MprTime mprMakeTime(struct tm *timep);
  3227. /*
  3228. Convert a time structure into a time value using UTC time.
  3229. @param timep Pointer to a time structure
  3230. @return a time value
  3231. @ingroup MprTime
  3232. @stability Stable
  3233. */
  3234. PUBLIC MprTime mprMakeUniversalTime(struct tm *tm);
  3235. /**
  3236. Constants for mprParseTime
  3237. */
  3238. #define MPR_LOCAL_TIMEZONE MAXINT /**< Use local timezone */
  3239. #define MPR_UTC_TIMEZONE 0 /**< Use UTC timezone */
  3240. /*
  3241. Parse a string into a time value
  3242. @description Try to intelligently parse a date.
  3243. This is a tolerant parser. It is not validating and will do its best to parse any possible date string.
  3244. Supports the following date/time formats:
  3245. \n\n
  3246. ISO dates: 2009-05-21t16:06:05.000z
  3247. \n\n
  3248. Date: 07/28/2014, 07/28/08, Jan/28/2014, Jaunuary-28-2014, 28-jan-2014.
  3249. \n\n
  3250. Support date order: dd/mm/yy, mm/dd/yy and yyyy/mm/dd
  3251. \n\n
  3252. Support separators "/", ".", "-"
  3253. \n\n
  3254. Timezones: GMT|UTC[+-]NN[:]NN
  3255. \n\n
  3256. Time: 10:52[:23]
  3257. \n\n
  3258. @param time Pointer to a time value to receive the parsed time value
  3259. @param dateString String to parse
  3260. @param timezone Timezone in which to interpret the date
  3261. @param defaults Date default values to use for missing components
  3262. @returns Zero if successful
  3263. @ingroup MprTime
  3264. @stability Stable
  3265. */
  3266. PUBLIC int mprParseTime(MprTime *time, cchar *dateString, int timezone, struct tm *defaults);
  3267. /**
  3268. Get the current timezone offset for a given time
  3269. @description Calculate the current timezone (including DST)
  3270. @param when Time to examine to extract the timezone
  3271. @returns Returns a timezone offset in msec. Local time == (UTC + offset).
  3272. @ingroup MprTime
  3273. @stability Stable
  3274. */
  3275. PUBLIC int mprGetTimeZoneOffset(MprTime when);
  3276. /*********************************** Lists ************************************/
  3277. /*
  3278. List flags
  3279. */
  3280. #define MPR_OBJ_LIST 0x1 /**< Object is a hash */
  3281. #define MPR_LIST_STATIC_VALUES 0x20 /**< Flag for #mprCreateList when values are permanent */
  3282. #define MPR_LIST_STABLE 0x40 /**< Contents are stable or only accessed by one thread. Does not need thread locking */
  3283. /**
  3284. List data structure.
  3285. @description The MprList is a dynamic, growable list suitable for storing pointers to arbitrary objects.
  3286. @see MprList MprListCompareProc mprAddItem mprAddNullItem mprAppendList mprClearList mprCloneList mprCopyList
  3287. mprCreateKeyPair mprCreateList mprGetFirstItem mprGetItem mprGetLastItem mprGetListCapacity mprGetListLength
  3288. mprGetNextItem mprGetPrevItem mprInitList mprInsertItemAtPos mprLookupItem mprLookupStringItem mprPopItem
  3289. mprPushItem mprRemoveItem mprRemoveItemAtPos mprRemoveRangeOfItems mprRemoveStringItem mprSetItem
  3290. mprSetListLimits mprSortList
  3291. @defgroup MprList MprList
  3292. @stability Internal.
  3293. */
  3294. typedef struct MprList {
  3295. int flags; /**< Control flags */
  3296. int size; /**< Current list capacity */
  3297. int length; /**< Current length of the list contents */
  3298. int maxSize; /**< Maximum capacity */
  3299. MprMutex *mutex; /**< Multithread lock */
  3300. void **items; /**< List item data */
  3301. } MprList;
  3302. /**
  3303. List comparison procedure for sorting
  3304. @description Callback function signature used by #mprSortList
  3305. @param arg1 First list item to compare
  3306. @param arg2 Second list item to compare
  3307. @returns Return zero if the items are equal. Return -1 if the first arg is less than the second. Otherwise return 1.
  3308. @ingroup MprList
  3309. @stability Stable.
  3310. */
  3311. typedef int (*MprListCompareProc)(cvoid *arg1, cvoid *arg2);
  3312. /**
  3313. Add an item to a list
  3314. @description Add the specified item to the list. The list must have been previously created via
  3315. mprCreateList. The list will grow as required to store the item
  3316. @param list List pointer returned from #mprCreateList
  3317. @param item Pointer to item to store
  3318. @return Returns a positive list index for the inserted item. If the item cannot be inserted due
  3319. to a memory allocation failure, -1 is returned
  3320. @ingroup MprList
  3321. @stability Stable.
  3322. */
  3323. PUBLIC int mprAddItem(MprList *list, cvoid *item);
  3324. /**
  3325. Add a null item to the list.
  3326. @description Add a null item to the list. This item does not count in the length returned by #mprGetListLength
  3327. and will not be visible when iterating using #mprGetNextItem.
  3328. @ingroup MprList
  3329. @stability Stable.
  3330. */
  3331. PUBLIC int mprAddNullItem(MprList *list);
  3332. /**
  3333. Append a list
  3334. @description Append the contents of one list to another. The list will grow as required to store the item
  3335. @param list List pointer returned from #mprCreateList
  3336. @param add List whose contents are added
  3337. @return Returns a pointer to the original list if successful. Returns NULL on memory allocation errors.
  3338. @ingroup MprList
  3339. @stability Stable.
  3340. */
  3341. PUBLIC MprList *mprAppendList(MprList *list, MprList *add);
  3342. /**
  3343. Clears the list of all items.
  3344. @description Resets the list length to zero and clears all items.
  3345. @param list List pointer returned from mprCreateList.
  3346. @ingroup MprList
  3347. @stability Stable.
  3348. */
  3349. PUBLIC void mprClearList(MprList *list);
  3350. /**
  3351. Clone a list and all elements
  3352. @description Copy the contents of a list into a new list.
  3353. @param src Source list to copy
  3354. @return Returns a new list reference
  3355. @ingroup MprList
  3356. @stability Stable.
  3357. */
  3358. PUBLIC MprList *mprCloneList(MprList *src);
  3359. /**
  3360. Copy list contents
  3361. @description Copy the contents of a list into an existing list. The destination list is cleared first and
  3362. has its dimensions set to that of the source clist.
  3363. @param dest Destination list for the copy
  3364. @param src Source list
  3365. @return Returns zero if successful, otherwise a negative MPR error code.
  3366. @ingroup MprList
  3367. @stability Stable.
  3368. */
  3369. PUBLIC int mprCopyListContents(MprList *dest, MprList *src);
  3370. /**
  3371. Create a list.
  3372. @description Creates an empty list. MprList's can store generic pointers. They automatically grow as
  3373. required when items are added to the list.
  3374. @param size Initial capacity of the list. Set to < 0 to get a growable list with a default initial size.
  3375. Set to 0 to to create the list but without any initial list storage. Then call mprSetListLimits to define
  3376. the initial and maximum list size.
  3377. @param flags Control flags. Possible values are: MPR_LIST_STATIC_VALUES to indicate list items are static
  3378. and should not be marked for GC. MPR_LIST_STABLE to create an optimized list for private use that is not thread-safe.
  3379. @return Returns a pointer to the list.
  3380. @ingroup MprList
  3381. @stability Stable.
  3382. */
  3383. PUBLIC MprList *mprCreateList(int size, int flags);
  3384. /**
  3385. Create a list of words
  3386. @description Create a list of words from the given string. The word separators are white space and comma.
  3387. @param str String containing white space or comma separated words
  3388. @return Returns a list of words
  3389. @ingroup MprList
  3390. @stability Stable
  3391. */
  3392. PUBLIC MprList *mprCreateListFromWords(cchar *str);
  3393. /**
  3394. Get the first item in the list.
  3395. @description Returns the value of the first item in the list. After calling this routine, the remaining
  3396. list items can be walked using mprGetNextItem.
  3397. @param list List pointer returned from mprCreateList.
  3398. @ingroup MprList
  3399. @stability Stable.
  3400. */
  3401. PUBLIC void *mprGetFirstItem(MprList *list);
  3402. #if DOXYGEN || 1
  3403. /**
  3404. Get an list item.
  3405. @description Get an list item specified by its index.
  3406. @param list List pointer returned from mprCreateList.
  3407. @param index Item index into the list. Indexes have a range from zero to the lenghth of the list - 1.
  3408. @ingroup MprList
  3409. @stability Stable.
  3410. */
  3411. PUBLIC void *mprGetItem(MprList *list, int index);
  3412. #else
  3413. #define mprGetItem(lp, index) (index < 0 || index >= lp->length) ? 0 : lp->items[index];
  3414. #endif
  3415. /**
  3416. Get the last item in the list.
  3417. @description Returns the value of the last item in the list. After calling this routine, the remaining
  3418. list items can be walked using mprGetPrevItem.
  3419. @param list List pointer returned from mprCreateList.
  3420. @ingroup MprList
  3421. @stability Stable.
  3422. */
  3423. PUBLIC void *mprGetLastItem(MprList *list);
  3424. /**
  3425. Get the current capacity of the list.
  3426. @description Returns the capacity of the list. This will always be equal to or greater than the list length.
  3427. @param list List pointer returned from mprCreateList.
  3428. @ingroup MprList
  3429. @stability Stable.
  3430. */
  3431. PUBLIC int mprGetListCapacity(MprList *list);
  3432. /**
  3433. Get the number of items in the list.
  3434. @description Returns the number of items in the list. This will always be less than or equal to the list capacity.
  3435. @param list List pointer returned from mprCreateList.
  3436. @ingroup MprList
  3437. @stability Stable.
  3438. */
  3439. PUBLIC int mprGetListLength(MprList *list);
  3440. /**
  3441. Get the next item in the list.
  3442. @description Returns the value of the next item in the list. Before calling
  3443. this routine, mprGetFirstItem must be called to initialize the traversal of the list.
  3444. @param list List pointer returned from mprCreateList.
  3445. @param lastIndex Pointer to an integer that will hold the last index retrieved.
  3446. @return Next item in list or null for an empty list or after the last item.
  3447. @ingroup MprList
  3448. @stability Stable.
  3449. */
  3450. PUBLIC void *mprGetNextItem(MprList *list, int *lastIndex);
  3451. /**
  3452. Get the next item in a stable list.
  3453. This is an optimized version of mprGetNextItem.
  3454. @description Returns the value of the next item in the list. Before calling
  3455. this routine, mprGetFirstItem must be called to initialize the traversal of the list.
  3456. @param list List pointer returned from mprCreateList.
  3457. @param lastIndex Pointer to an integer that will hold the last index retrieved.
  3458. @return Next item in list
  3459. @ingroup MprList
  3460. @internal
  3461. @stability Stable
  3462. */
  3463. PUBLIC void *mprGetNextStableItem(MprList *list, int *lastIndex);
  3464. /**
  3465. Get the previous item in the list.
  3466. @description Returns the value of the previous item in the list. Before
  3467. calling this routine, mprGetFirstItem and/or mprGetNextItem must be
  3468. called to initialize the traversal of the list.
  3469. @param list List pointer returned from mprCreateList.
  3470. @param lastIndex Pointer to an integer that will hold the last index retrieved.
  3471. @ingroup MprList
  3472. @stability Stable.
  3473. */
  3474. PUBLIC void *mprGetPrevItem(MprList *list, int *lastIndex);
  3475. /**
  3476. Initialize a list structure
  3477. @description If a list is statically declared inside another structure, mprInitList can be used to
  3478. initialize it before use.
  3479. @param list Reference to the MprList struct.
  3480. @param flags Control flags. Possible values are: MPR_LIST_STATIC_VALUES to indicate list items are static
  3481. and should not be marked for GC. MPR_LIST_STABLE to create an optimized list for private use that is not
  3482. thread-safe.
  3483. @ingroup MprList
  3484. @stability Stable.
  3485. */
  3486. PUBLIC void mprInitList(MprList *list, int flags);
  3487. /**
  3488. Insert an item into a list at a specific position
  3489. @description Insert the item into the list before the specified position. The list will grow as required
  3490. to store the item
  3491. @param list List pointer returned from #mprCreateList
  3492. @param index Location at which to store the item. The previous item at this index is moved up to make room.
  3493. @param item Pointer to item to store
  3494. @return Returns the position index (positive integer) if successful. If the item cannot be inserted due
  3495. to a memory allocation failure, -1 is returned
  3496. @ingroup MprList
  3497. @stability Stable.
  3498. */
  3499. PUBLIC int mprInsertItemAtPos(MprList *list, int index, cvoid *item);
  3500. /**
  3501. Convert a list of strings to a single string. This uses the specified join string between the elements.
  3502. @param list List pointer returned from mprCreateList.
  3503. @param join String to use as the element join string. May be null.
  3504. @ingroup MprList
  3505. @stability Stable
  3506. */
  3507. PUBLIC char *mprListToString(MprList *list, cchar *join);
  3508. /**
  3509. Find an item and return its index.
  3510. @description Search for an item in the list and return its index.
  3511. @param list List pointer returned from mprCreateList.
  3512. @param item Pointer to value stored in the list.
  3513. @return Positive list index if found, otherwise a negative MPR error code.
  3514. @ingroup MprList
  3515. @stability Stable.
  3516. */
  3517. PUBLIC int mprLookupItem(MprList *list, cvoid *item);
  3518. /**
  3519. Find a string item and return its index.
  3520. @description Search for the first matching string in the list and return its index.
  3521. @param list List pointer returned from mprCreateList.
  3522. @param str Pointer to string to look for.
  3523. @return Positive list index if found, otherwise a negative MPR error code.
  3524. @ingroup MprList
  3525. @stability Stable.
  3526. */
  3527. PUBLIC int mprLookupStringItem(MprList *list, cchar *str);
  3528. /**
  3529. Remove an item from the list
  3530. @description Search for a specified item and then remove it from the list.
  3531. @param list List pointer returned from mprCreateList.
  3532. @param item Item pointer to remove.
  3533. @return Returns the positive index of the removed item, otherwise a negative MPR error code.
  3534. @ingroup MprList
  3535. @stability Stable.
  3536. */
  3537. PUBLIC int mprRemoveItem(MprList *list, cvoid *item);
  3538. /**
  3539. Remove an item from the list
  3540. @description Removes the element specified by \a index, from the list. The
  3541. list index is provided by mprInsertItem.
  3542. @return Returns the positive index of the removed item, otherwise a negative MPR error code.
  3543. @ingroup MprList
  3544. @stability Stable.
  3545. */
  3546. PUBLIC int mprRemoveItemAtPos(MprList *list, int index);
  3547. /**
  3548. Remove the last item from the list
  3549. @description Remove the item at the highest index position.
  3550. @param list List pointer returned from mprCreateList.
  3551. @return Returns the positive index of the removed item, otherwise a negative MPR error code.
  3552. @ingroup MprList
  3553. @stability Stable.
  3554. */
  3555. PUBLIC int mprRemoveLastItem(MprList *list);
  3556. /**
  3557. Remove a range of items from the list.
  3558. @description Remove a range of items from the list. The range is specified
  3559. from the \a start index up to and including the \a end index.
  3560. @param list List pointer returned from mprCreateList.
  3561. @param start Starting item index to remove (inclusive)
  3562. @param end Ending item index to remove (inclusive)
  3563. @return Returns zero if successful, otherwise a negative MPR error code.
  3564. @ingroup MprList
  3565. @stability Stable.
  3566. */
  3567. PUBLIC int mprRemoveRangeOfItems(MprList *list, int start, int end);
  3568. /**
  3569. Remove a string item from the list
  3570. @description Search for the first matching string and then remove it from the list.
  3571. @param list List pointer returned from mprCreateList.
  3572. @param str String value to remove.
  3573. @return Returns the positive index of the removed item, otherwise a negative MPR error code.
  3574. @ingroup MprList
  3575. @stability Stable.
  3576. */
  3577. PUBLIC int mprRemoveStringItem(MprList *list, cchar *str);
  3578. /**
  3579. Set a list item
  3580. @description Update the list item stored at the specified index
  3581. @param list List pointer returned from mprCreateList.
  3582. @param index Location to update
  3583. @param item Pointer to item to store
  3584. @return Returns the old item previously at that location index
  3585. @ingroup MprList
  3586. @stability Stable.
  3587. */
  3588. PUBLIC void *mprSetItem(MprList *list, int index, cvoid *item);
  3589. /**
  3590. Define the list size limits
  3591. @description Define the list initial size and maximum size it can grow to.
  3592. @param list List pointer returned from mprCreateList.
  3593. @param initialSize Initial size for the list. This call will allocate space for at least this number of items.
  3594. @param maxSize Set the maximum limit the list can grow to become.
  3595. @return Returns zero if successful, otherwise a negative MPR error code.
  3596. @ingroup MprList
  3597. @stability Stable.
  3598. */
  3599. PUBLIC int mprSetListLimits(MprList *list, int initialSize, int maxSize);
  3600. /**
  3601. Quicksort callback function
  3602. @description This is a quicksort callback with a context argument.
  3603. @param p1 Pointer to first element
  3604. @param p2 Pointer to second element
  3605. @param ctx Context argument to provide to comparison function
  3606. @return -1, 0, or 1, depending on if the elements are p1 < p2, p1 == p2 or p1 > p2
  3607. @ingroup MprList
  3608. @stability Stable
  3609. */
  3610. typedef int (*MprSortProc)(cvoid *p1, cvoid *p2, void *ctx);
  3611. /**
  3612. Quicksort
  3613. @description This is a quicksort with a context argument.
  3614. @param base Base of array to sort
  3615. @param num Number of array elements
  3616. @param width Width of array elements
  3617. @param compare Comparison function
  3618. @param ctx Context argument to provide to comparison function
  3619. @return The base array for chaining
  3620. @ingroup MprList
  3621. @stability Stable
  3622. */
  3623. PUBLIC void *mprSort(void *base, ssize num, ssize width, MprSortProc compare, void *ctx);
  3624. /**
  3625. Sort a list
  3626. @description Sort a list using the sort ordering dictated by the supplied compare function.
  3627. @param list List pointer returned from mprCreateList.
  3628. @param compare Comparison function. If null, then a default string comparison is used.
  3629. @param ctx Context to provide to comparison function
  3630. @return The sorted list
  3631. @ingroup MprList
  3632. @stability Stable
  3633. */
  3634. PUBLIC MprList *mprSortList(MprList *list, MprSortProc compare, void *ctx);
  3635. /**
  3636. Key value pairs for use with MprList or MprKey
  3637. @ingroup MprList
  3638. @stability Stable
  3639. */
  3640. typedef struct MprKeyValue {
  3641. void *key; /**< Key string (managed) */
  3642. void *value; /**< Associated value for the key (managed) */
  3643. int flags; /**< General flags word */
  3644. } MprKeyValue;
  3645. /**
  3646. Create a key / value pair
  3647. @description Allocate and initialize a key value pair for use by the MprList or MprHash modules.
  3648. @param key Key string
  3649. @param value Key value string
  3650. @param flags Flags value
  3651. @returns An initialized MprKeyValue
  3652. @ingroup MprList
  3653. @stability Stable
  3654. */
  3655. PUBLIC MprKeyValue *mprCreateKeyPair(cchar *key, cchar *value, int flags);
  3656. /**
  3657. Pop an item
  3658. @description Treat the list as a stack and pop the last pushed item
  3659. @param list List pointer returned from mprCreateList.
  3660. @return Returns the last pushed item. If the list is empty, returns NULL.
  3661. @ingroup MprList
  3662. @stability Stable
  3663. */
  3664. PUBLIC void *mprPopItem(MprList *list);
  3665. /**
  3666. Push an item onto the list
  3667. @description Treat the list as a stack and push the last pushed item
  3668. @param list List pointer returned from mprCreateList.
  3669. @param item Item to push onto the list
  3670. @return Returns a positive integer list index for the inserted item. If the item cannot be inserted due
  3671. to a memory allocation failure, -1 is returned
  3672. @ingroup MprList
  3673. @stability Stable
  3674. */
  3675. PUBLIC int mprPushItem(MprList *list, cvoid *item);
  3676. #define MPR_GET_ITEM(list, index) list->items[index]
  3677. #define ITERATE_ITEMS(list, item, next) next = 0; (item = mprGetNextItem(list, &next)) != 0;
  3678. #define ITERATE_STABLE_ITEMS(list, item, next) next = 0; (item = mprGetNextStableItem(list, &next)) != 0;
  3679. #define mprGetListLength(lp) ((lp) ? (lp)->length : 0)
  3680. /********************************** Logging ***********************************/
  3681. /**
  3682. Logging Services
  3683. @defgroup MprLog MprLog
  3684. @see MprLogHandler mprAssert mprError mprGetLogFile mprGetLogHandler mprInfo mprLog mprRawLog mprDebug
  3685. mprSetLogFile mprSetLogHandler mprSetLogLevel mprStaticError mprUsingDefaultLogHandler mprWarn
  3686. @stability Internal
  3687. */
  3688. typedef struct MprLog { int dummy; } MprLog;
  3689. /**
  3690. Log handler callback type.
  3691. @description Callback prototype for the log handler. Used by mprSetLogHandler to define
  3692. a message logging handler to process log and error messages. See #mprLog for more details.
  3693. @param file Source filename. Derived by using __FILE__.
  3694. @param line Source line number. Derived by using __LINE__.
  3695. @param flags Error flags.
  3696. @param tags List of space separated tag words.
  3697. @param level Message logging level. Levels are 0-5 with five being the most verbose.
  3698. @param msg Message being logged.
  3699. @ingroup MprLog
  3700. @stability Stable
  3701. */
  3702. typedef void (*MprLogHandler)(cchar *tags, int level, cchar *msg);
  3703. /**
  3704. Output an assure assertion failed message.
  3705. @description This will emit an assure assertion failed message to the standard error output.
  3706. It may bypass the logging system.
  3707. @param loc Source code location string. Use MPR_LOC to define a file name and line number string suitable for this
  3708. parameter.
  3709. @param msg Simple string message to output
  3710. @ingroup MprLog
  3711. @stability Stable
  3712. */
  3713. PUBLIC void mprAssert(cchar *loc, cchar *msg);
  3714. /**
  3715. Initialize the log service
  3716. @ingroup MprLog
  3717. @stability Internal
  3718. */
  3719. PUBLIC void mprCreateLogService(void);
  3720. /**
  3721. Backup a log
  3722. @param path Base log filename
  3723. @param count Count of archived logs to keep
  3724. @ingroup MprLog
  3725. @stability Stable
  3726. */
  3727. PUBLIC int mprBackupLog(cchar *path, int count);
  3728. /**
  3729. Default MPR log handler
  3730. @param tags Descriptive tag words to classify this message.
  3731. @param level Logging level for this message. The level is 0-5 with five being the most verbose.
  3732. @param msg Message to log
  3733. @ingroup MprLog
  3734. @stability Stable
  3735. */
  3736. PUBLIC void mprDefaultLogHandler(cchar *tags, int level, cchar *msg);
  3737. /**
  3738. Log an error message.
  3739. @description Send an error message to the MPR debug logging subsystem. The
  3740. message will be to the log handler defined by #mprSetLogHandler. It
  3741. is up to the log handler to respond appropriately and log the message.
  3742. This will invoke mprLog with a severity tag of "error".
  3743. @param fmt Printf style format string. Variable number of arguments to
  3744. @param ... Variable number of arguments for printf data
  3745. @ingroup MprLog
  3746. @stability Stable
  3747. */
  3748. PUBLIC void mprError(cchar *fmt, ...) PRINTF_ATTRIBUTE(1,2);
  3749. /**
  3750. Get the log file object
  3751. @description Returns the MprFile object used for logging
  3752. @returns An MprFile object for logging
  3753. @ingroup MprLog
  3754. @stability Stable
  3755. */
  3756. PUBLIC struct MprFile *mprGetLogFile(void);
  3757. /**
  3758. Get the current MPR debug log handler.
  3759. @description Get the log handler defined via #mprSetLogHandler
  3760. @returns A function of the signature #MprLogHandler
  3761. @ingroup MprLog
  3762. @stability Stable
  3763. */
  3764. PUBLIC MprLogHandler mprGetLogHandler(void);
  3765. #if DOXYGEN
  3766. /**
  3767. Write a message to the error log file.
  3768. @description Send a message to the MPR error logging subsystem.
  3769. The purpose of the error log is to record essential configuration and error conditions. Per-request trace typically is sent to a separate trace log.
  3770. \n\n
  3771. By default, error log messages are sent to the standard error output. Applications may redirect output by installing a log handler using #mprSetLogHandler.
  3772. \n\n
  3773. Log messages should be a single text line to facilitate machine processing of log files. Descriptive tag words may be provided to indicate a severity level and to classifiy messages. By convention, tags may include one of the severity levels defined in RFC 5424: "debug", "info", "notice", "warn", "error", "critical". Messages using the "error", "critical" tags should use a level of zero. Tags should be space separated. By convention, specify the RFC tag name first in a list of tags.
  3774. \n\n
  3775. The default log handler emits messages in three formats depending on whether MPR_LOG_DETAILED is provided to #mprStartLogging and the value of the tags parameter. If MPR_LOG_DETAILED and tags are supplied, the format is: "MM/DD/YY HH:MM:SS LEVEL TAGS, Message". Otherwise a a simplified output format is used: "Name: severity: message", where severity is set to "error" for level 0 messages. This is useful for utility programs. If tags are null, the message is output raw, without any any prefixes.
  3776. \n\n
  3777. Logging typically is enabled in both debug and release builds and may be controlled via the build define ME_MPR_LOGGING which is typically set via the MakeMe setting "logging: true".
  3778. \n\n
  3779. The #mprDebug API may be used to emit log messages only in debug builds.
  3780. \n\n
  3781. If level zero is used, the message is also sent to any relevant operating system logging facility such as syslog or the Windows event database.
  3782. \n\n
  3783. It is good practice to only include debug trace at levels above level 2 so that essential error messages are clearly visible in the error log and are not swamped by debug messages.
  3784. @param tags Descriptive space separated tag words to classify this message. Tag words may be provided to indicate a severity level and to classifiy messages. By convention, tags may include one of the severity levels defined in RFC 5424: "debug", "info", "notice", "warn", "error", "critical". Messages using the "error", "critical" tags should use a level of zero. Tags should be space separated. By convention, specify the RFC tag name first in a list of tags.
  3785. @param level Logging level for this message. The level is 0-5 with five being the most verbose.
  3786. @param fmt Printf style format string. Variable number of arguments to print
  3787. @param ... Variable number of arguments for printf data
  3788. @remarks mprLog is highly useful as a debugging aid.
  3789. @ingroup MprLog
  3790. @stability Stable
  3791. */
  3792. PUBLIC void mprLog(cchar *tags, int level, cchar *fmt, ...);
  3793. #endif
  3794. PUBLIC void mprLogProc(cchar *tags, int level, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  3795. /**
  3796. Show the product configuration at the start of the log file
  3797. @ingroup MprLog
  3798. @stability Stable
  3799. */
  3800. PUBLIC void mprLogConfig(void);
  3801. /**
  3802. Set the log rotation parameters
  3803. @param logSize If the size is zero, then the log file will be rotated on each application boot. Otherwise,
  3804. the log file will be rotated if on application boot, the log file is larger than this size.
  3805. @param backupCount Count of the number of log files to keep
  3806. @param flags Set to MPR_LOG_ANEW to truncate existing files (after backup).
  3807. @ingroup MprLog
  3808. @stability Stable
  3809. */
  3810. PUBLIC void mprSetLogBackup(ssize logSize, int backupCount, int flags);
  3811. /**
  3812. Set a file to be used for logging
  3813. @param file MprFile object instance
  3814. @stability Stable
  3815. */
  3816. PUBLIC void mprSetLogFile(struct MprFile *file);
  3817. /**
  3818. Set an MPR debug log handler.
  3819. @description Defines a callback handler for MPR debug and error log messages. When output is sent to
  3820. the debug channel, the log handler will be invoked to accept the output message.
  3821. @param handler Callback handler
  3822. @return Prior log handler
  3823. @stability Stable
  3824. */
  3825. PUBLIC MprLogHandler mprSetLogHandler(MprLogHandler handler);
  3826. /**
  3827. Start logging
  3828. @param logSpec Set the log file name and level. The format is "pathName[:level]".
  3829. The level is a verbosity level from 0 to 5 with 5 being the most verbose.
  3830. The following levels are generally observed:
  3831. <ul>
  3832. <li>0 - Essential messages: errors and warnings</li>
  3833. <li>1 - Non-essential warnings</li>
  3834. <li>2 - Configuration information</li>
  3835. <li>3 - Useful informational messages</li>
  3836. <li>4 - Debug information</li>
  3837. <li>5 - Most verbose levels of messages useful for debugging</li>
  3838. </ul>
  3839. If logSpec is set to null, then logging is not started.
  3840. The filename may be set to "stdout", "stderr" or "none". The latter is the same as supplying null as the logSpec.
  3841. @param flags Set to MPR_LOG_CONFIG to show the configuration in the log file. Set to MPR_LOG_CMDLINE if a command line
  3842. override has been used to initiate logging. Set MPR_LOG_DETAILED to use the detailed message format.
  3843. Set MPR_LOG_ANEW to truncate existing log files after backup.
  3844. @return Zero if successful, otherwise a negative Mpr error code. See the log for diagnostics.
  3845. @ingroup MprLog
  3846. @stability Stable
  3847. */
  3848. PUBLIC int mprStartLogging(cchar *logSpec, int flags);
  3849. #if DOXYGEN
  3850. /**
  3851. Write a log message to the log file when the product is built in debug mode.
  3852. @description This routine permits the addition of debug messages that are compiled out in production builds.
  3853. @param tags List of space separated tag words.
  3854. @param level Logging level for this message. The level is 0-5 with five being the most verbose.
  3855. @param fmt Printf style format string. Variable number of arguments to
  3856. @param ... Variable number of arguments for printf data
  3857. @ingroup MprLog
  3858. @stability Stable
  3859. */
  3860. PUBLIC void mprDebug(cchar *tags, int level, cchar *fmt, ...);
  3861. #endif
  3862. PUBLIC void mprLogProc(cchar *tags, int level, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  3863. /**
  3864. Determine if the app is using the default MPR log handler.
  3865. @description Returns true if no custom log handler has been installed.
  3866. @returns True if using the default log handler
  3867. @ingroup MprLog
  3868. @stability Stable
  3869. */
  3870. PUBLIC int mprUsingDefaultLogHandler(void);
  3871. #if ME_MPR_DEBUG_LOGGING
  3872. #define mprDebug(tags, l, ...) if ((l) <= MPR->logLevel) { mprLogProc(tags, l, __VA_ARGS__); } else {}
  3873. #else
  3874. #define mprDebug(tags, l, ...) if (1) ; else {}
  3875. #endif
  3876. #if ME_MPR_LOGGING
  3877. #define mprLog(tags, l, ...) if ((l) <= MPR->logLevel) { mprLogProc(tags, l, __VA_ARGS__); } else {}
  3878. #else
  3879. #define mprLog(tags, l, ...) if (1) ; else {}
  3880. #endif
  3881. /************************************ Hash ************************************/
  3882. /**
  3883. Hash table entry structure.
  3884. @description The hash structure supports growable hash tables with high performance, collision resistant hashes.
  3885. Each hash entry has a descriptor entry. This is used to manage the hash table link chains.
  3886. @see MprKey MprHashProc MprHash mprAddDuplicateHash mprAddKey mprAddKeyFmt mprCloneHash mprCreateHash
  3887. mprGetFirstKey mprGetHashLength mprGetKeyBits mprGetNextKey mprLookupKey mprLookupKeyEntry mprRemoveKey
  3888. mprSetKeyBits mprBlendHash
  3889. @defgroup MprHash MprHash
  3890. @stability Internal.
  3891. */
  3892. typedef struct MprKey {
  3893. struct MprKey *next; /**< Next symbol in hash chain */
  3894. char *key; /**< Hash key */
  3895. cvoid *data; /**< Pointer to symbol data (managed) */
  3896. int type: 4; /**< Data type */
  3897. int bucket: 28; /**< Hash bucket index */
  3898. } MprKey;
  3899. /**
  3900. Hashing function to use for the table
  3901. @param name Name to hash
  3902. @param len Length of the name to hash
  3903. @return An integer hash index
  3904. @internal
  3905. @stability Internal.
  3906. */
  3907. typedef uint (*MprHashProc)(cvoid *name, ssize len);
  3908. /*
  3909. Flags for MprHash
  3910. */
  3911. #define MPR_OBJ_HASH 0x1 /**< Object is a hash */
  3912. #define MPR_HASH_CASELESS 0x10 /**< Key comparisons ignore case */
  3913. #define MPR_HASH_UNICODE 0x20 /**< Hash keys are unicode strings */
  3914. #define MPR_HASH_STATIC_KEYS 0x40 /**< Keys are permanent - don't dup or mark */
  3915. #define MPR_HASH_STATIC_VALUES 0x80 /**< Values are permanent - don't mark */
  3916. #define MPR_HASH_MANAGED_KEYS 0x100 /**< Keys are managed - mark but don't dup */
  3917. #define MPR_HASH_MANAGED_VALUES 0x200 /**< Values are managed - mark but don't dup */
  3918. #define MPR_HASH_UNIQUE 0x400 /**< Add to existing will fail */
  3919. #define MPR_HASH_STABLE 0x800 /**< Contents are stable or only accessed by one thread. Does not need thread locking */
  3920. #define MPR_HASH_STATIC_ALL (MPR_HASH_STATIC_KEYS | MPR_HASH_STATIC_VALUES)
  3921. /**
  3922. Hash table control structure
  3923. @see MprHash
  3924. @stability Internal.
  3925. */
  3926. typedef struct MprHash {
  3927. int flags; /**< Hash control flags */
  3928. int size; /**< Size of the buckets array */
  3929. int length; /**< Number of symbols in the table */
  3930. MprKey **buckets; /**< Hash collision bucket table */
  3931. MprHashProc fn; /**< Hash function */
  3932. MprMutex *mutex; /**< GC marker sync */
  3933. } MprHash;
  3934. /*
  3935. Macros
  3936. */
  3937. #define ITERATE_KEYS(table, key) key = 0; (key = mprGetNextKey(table, key)) != 0;
  3938. #define ITERATE_KEY_DATA(table, key, item) key = 0; (key = mprGetNextKey(table, key)) != 0 && ((item = (void*) ((key)->data)) != 0 || 1);
  3939. /**
  3940. Add a duplicate symbol value into the hash table
  3941. @description Add a symbol to the hash which may clash with an existing entry. Duplicate symbols can be added to
  3942. the hash, but only one may be retrieved via #mprLookupKey. To recover duplicate entries walk the hash using
  3943. #mprGetNextKey.
  3944. @param table Symbol table returned via mprCreateHash.
  3945. @param key String key of the symbol entry to delete.
  3946. @param ptr Arbitrary pointer to associate with the key in the table.
  3947. @return Integer count of the number of entries.
  3948. @ingroup MprHash
  3949. @stability Stable.
  3950. */
  3951. PUBLIC MprKey *mprAddDuplicateKey(MprHash *table, cvoid *key, cvoid *ptr);
  3952. /**
  3953. Add a symbol value into the hash table
  3954. @description Associate an arbitrary value with a string symbol key and insert into the symbol table.
  3955. This will replace existing key values. Use mprAddDuplicateKey to allow duplicates.
  3956. @param table Symbol table returned via mprCreateHash.
  3957. @param key String key of the symbol entry to delete.
  3958. @param ptr Arbitrary pointer to associate with the key in the table.
  3959. @return Added MprKey reference.
  3960. @ingroup MprHash
  3961. @stability Stable.
  3962. */
  3963. PUBLIC MprKey *mprAddKey(MprHash *table, cvoid *key, cvoid *ptr);
  3964. /**
  3965. Add a symbol value into the hash table and set the key type.
  3966. @description Associate an arbitrary value with a string symbol key and insert into the symbol table.
  3967. @param table Symbol table returned via mprCreateHash.
  3968. @param key String key of the symbol entry to delete.
  3969. @param ptr Arbitrary pointer to associate with the key in the table.
  3970. @param type Type of value.
  3971. @return Added MprKey reference.
  3972. @ingroup MprHash
  3973. @stability internal.
  3974. */
  3975. PUBLIC MprKey *mprAddKeyWithType(MprHash *table, cvoid *key, cvoid *ptr, int type);
  3976. /**
  3977. Add a key with a formatting value into the hash table
  3978. @description Associate a formatted value with a key and insert into the symbol table.
  3979. @param table Symbol table returned via mprCreateHash.
  3980. @param key String key of the symbol entry to delete.
  3981. @param fmt Format string. See #mprPrintf.
  3982. @return Integer count of the number of entries.
  3983. @ingroup MprHash
  3984. @stability Stable.
  3985. */
  3986. PUBLIC MprKey *mprAddKeyFmt(MprHash *table, cvoid *key, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  3987. /**
  3988. Copy a hash table
  3989. @description Create a new hash table and copy all the entries from an existing table.
  3990. @param table Symbol table returned via mprCreateHash.
  3991. @return A new hash table initialized with the contents of the original hash table.
  3992. @ingroup MprHash
  3993. @stability Stable.
  3994. */
  3995. PUBLIC MprHash *mprCloneHash(MprHash *table);
  3996. /**
  3997. Create a hash table
  3998. @description Creates a hash table that can store arbitrary objects associated with string key values.
  3999. @param hashSize Size of the hash table for the symbol table. Should be a prime number. Set to 0 or -1 to get
  4000. a default (small) hash table.
  4001. @param flags Table control flags. Use MPR_HASH_CASELESS for case insensitive comparisions, MPR_HASH_UNICODE
  4002. if the hash keys are unicode strings, MPR_HASH_STATIC_KEYS if the keys are permanent and should not be
  4003. managed for Garbage collection, and MPR_HASH_STATIC_VALUES if the values are permanent.
  4004. MPR_HASH_STABLE to create an optimized list when the contents are stable or only accessed by one thread.
  4005. @return Returns a pointer to the allocated symbol table.
  4006. @ingroup MprHash
  4007. @stability Stable.
  4008. */
  4009. PUBLIC MprHash *mprCreateHash(int hashSize, int flags);
  4010. /**
  4011. Create a hash of words
  4012. @description Create a hash table of words from the given string. The hash key entry is the same as the key.
  4013. The word separators are white space and comma.
  4014. @param str String containing white space or comma separated words
  4015. @return Returns a hash of words
  4016. @ingroup MprHash
  4017. @stability Stable.
  4018. */
  4019. PUBLIC MprHash *mprCreateHashFromWords(cchar *str);
  4020. /**
  4021. Return the first symbol in a symbol entry
  4022. @description Prepares for walking the contents of a symbol table by returning the first entry in the symbol table.
  4023. @param table Symbol table returned via mprCreateHash.
  4024. @return Pointer to the first entry in the symbol table.
  4025. @ingroup MprHash
  4026. @stability Stable.
  4027. */
  4028. PUBLIC MprKey *mprGetFirstKey(MprHash *table);
  4029. /**
  4030. Return the next symbol in a symbol entry
  4031. @description Continues walking the contents of a symbol table by returning
  4032. the next entry in the symbol table. A previous call to mprGetFirstSymbol
  4033. or mprGetNextSymbol is required to supply the value of the \a last
  4034. argument.
  4035. @param table Symbol table returned via mprCreateHash.
  4036. @param last Symbol table entry returned via mprGetFirstSymbol or mprGetNextSymbol.
  4037. @return Pointer to the first entry in the symbol table.
  4038. @ingroup MprHash
  4039. @stability Stable.
  4040. */
  4041. PUBLIC MprKey *mprGetNextKey(MprHash *table, MprKey *last);
  4042. /**
  4043. Return the count of symbols in a symbol entry
  4044. @description Returns the number of symbols currently existing in a symbol table.
  4045. @param table Symbol table returned via mprCreateHash.
  4046. @return Integer count of the number of entries.
  4047. @ingroup MprHash
  4048. @stability Stable.
  4049. */
  4050. PUBLIC int mprGetHashLength(MprHash *table);
  4051. /**
  4052. Lookup a symbol in the hash table.
  4053. @description Lookup a symbol key and return the value associated with that key.
  4054. @param table Symbol table returned via mprCreateHash.
  4055. @param key String key of the symbol entry to delete.
  4056. @return Value associated with the key when the entry was inserted via mprInsertSymbol.
  4057. @ingroup MprHash
  4058. @stability Stable.
  4059. */
  4060. PUBLIC void *mprLookupKey(MprHash *table, cvoid *key);
  4061. /**
  4062. Lookup a symbol in the hash table and return the hash entry
  4063. @description Lookup a symbol key and return the hash table descriptor associated with that key.
  4064. @param table Symbol table returned via mprCreateHash.
  4065. @param key String key of the symbol entry to delete.
  4066. @return MprKey for the entry
  4067. @ingroup MprHash
  4068. @stability Stable.
  4069. */
  4070. PUBLIC MprKey *mprLookupKeyEntry(MprHash *table, cvoid *key);
  4071. /**
  4072. Remove a symbol entry from the hash table.
  4073. @description Removes a symbol entry from the symbol table. The entry is looked up via the supplied \a key.
  4074. @param table Symbol table returned via mprCreateHash.
  4075. @param key String key of the symbol entry to delete.
  4076. @return Returns zero if successful, otherwise a negative MPR error code is returned.
  4077. @ingroup MprHash
  4078. @stability Stable.
  4079. */
  4080. PUBLIC int mprRemoveKey(MprHash *table, cvoid *key);
  4081. /**
  4082. Blend two hash tables
  4083. @description Blend a hash table into a target hash
  4084. @param target Target hash to receive the properties from the other hash
  4085. @param other Hash to provide properties to blend
  4086. @return Returns target
  4087. @ingroup MprHash
  4088. @stability Stable.
  4089. */
  4090. PUBLIC MprHash *mprBlendHash(MprHash *target, MprHash *other);
  4091. /**
  4092. Convert a hash of strings to a single string
  4093. @param hash Hash pointer returned from mprCreateHash.
  4094. @param join String to use as the element join string.
  4095. @return String consisting of the joined hash values
  4096. @ingroup MprHash
  4097. @stability Stable
  4098. */
  4099. PUBLIC char *mprHashToString(MprHash *hash, cchar *join);
  4100. /**
  4101. Convert hash keys to a single string
  4102. @param hash Hash pointer returned from mprCreateHash.
  4103. @param join String to use as the element join string.
  4104. @return String consisting of the joined hash keys
  4105. @ingroup MprHash
  4106. @stability Stable
  4107. */
  4108. PUBLIC char *mprHashKeysToString(MprHash *hash, cchar *join);
  4109. /*********************************** Files ************************************/
  4110. /**
  4111. Signed file offset data type. Supports large files greater than 4GB in size on all systems.
  4112. */
  4113. typedef Offset MprOff;
  4114. #ifndef ME_MPR_DISK
  4115. #define ME_MPR_DISK 1
  4116. #endif
  4117. #ifndef ME_MPR_ROM_MOUNT
  4118. #define ME_MPR_ROM_MOUNT "/rom"
  4119. #endif
  4120. /*
  4121. Prototypes for file system switch methods
  4122. All internal.
  4123. */
  4124. typedef bool (*MprAccessFileProc)(struct MprFileSystem *fs, cchar *path, int omode);
  4125. typedef int (*MprDeleteFileProc)(struct MprFileSystem *fs, cchar *path);
  4126. typedef int (*MprDeleteDirProc)(struct MprFileSystem *fs, cchar *path);
  4127. typedef int (*MprGetPathInfoProc)(struct MprFileSystem *fs, cchar *path, struct MprPath *info);
  4128. typedef char *(*MprGetPathLinkProc)(struct MprFileSystem *fs, cchar *path);
  4129. typedef MprList*(*MprListDirProc)(struct MprFileSystem *fs, cchar *path);
  4130. typedef int (*MprMakeDirProc)(struct MprFileSystem *fs, cchar *path, int perms, int owner, int group);
  4131. typedef int (*MprMakeLinkProc)(struct MprFileSystem *fs, cchar *path, cchar *target, int hard);
  4132. typedef int (*MprCloseFileProc)(struct MprFile *file);
  4133. typedef ssize (*MprReadFileProc)(struct MprFile *file, void *buf, ssize size);
  4134. typedef MprOff (*MprSeekFileProc)(struct MprFile *file, int seekType, MprOff distance);
  4135. typedef int (*MprSetBufferedProc)(struct MprFile *file, ssize initialSize, ssize maxSize);
  4136. typedef int (*MprTruncateFileProc)(struct MprFileSystem *fs, cchar *path, MprOff size);
  4137. typedef ssize (*MprWriteFileProc)(struct MprFile *file, cvoid *buf, ssize count);
  4138. #if !DOXYGEN
  4139. /* Work around doxygen bug */
  4140. typedef struct MprFile* (*MprOpenFileProc)(struct MprFileSystem *fs, cchar *path, int omode, int perms);
  4141. #endif
  4142. /**
  4143. File system service
  4144. @description The MPR provides a file system abstraction to support non-disk based file access such as flash or
  4145. other ROM based file systems. The MprFileSystem structure defines a virtual file system interface that
  4146. will be invoked by the various MPR file routines.
  4147. @see MprRomInode mprAddFileSystem mprCreateDiskFileSystem mprCreateFileSystem mprCreateRomFileSystem
  4148. mprLookupFileSystem mprSetPathNewline mprSetPathSeparators
  4149. @defgroup MprFileSystem MprFileSystem
  4150. @stability Internal
  4151. */
  4152. typedef struct MprFileSystem {
  4153. MprAccessFileProc accessPath; /**< Virtual access file routine */
  4154. MprDeleteFileProc deletePath; /**< Virtual delete file routine */
  4155. MprGetPathInfoProc getPathInfo; /**< Virtual get file information routine */
  4156. MprGetPathLinkProc getPathLink; /**< Virtual get the symbolic link target */
  4157. MprListDirProc listDir; /**< Virtual get directory list */
  4158. MprMakeDirProc makeDir; /**< Virtual make directory routine */
  4159. MprMakeLinkProc makeLink; /**< Virtual make link routine */
  4160. MprOpenFileProc openFile; /**< Virtual open file routine */
  4161. MprCloseFileProc closeFile; /**< Virtual close file routine */
  4162. MprReadFileProc readFile; /**< Virtual read file routine */
  4163. MprSeekFileProc seekFile; /**< Virtual seek file routine */
  4164. MprSetBufferedProc setBuffered; /**< Virtual set buffered I/O routine */
  4165. MprWriteFileProc writeFile; /**< Virtual write file routine */
  4166. MprTruncateFileProc truncateFile; /**< Virtual truncate file routine */
  4167. bool caseSensitive; /**< Path comparisons are case sensitive */
  4168. bool hasDriveSpecs; /**< Paths can have drive specifications */
  4169. char *separators; /**< Filename path separators. First separator is the preferred separator. */
  4170. char *newline; /**< Newline for text files */
  4171. cchar *root; /**< Root file path */
  4172. #if ME_WIN_LIKE || CYGWIN
  4173. char *cygwin; /**< Cygwin install directory */
  4174. char *cygdrive; /**< Cygwin drive root */
  4175. #endif
  4176. } MprFileSystem;
  4177. /**
  4178. Create and initialize the FileSystem subsystem.
  4179. @description This is an internal routine called by the MPR during initialization.
  4180. @param fs File system object.
  4181. @param path Path name to the root of the file system.
  4182. @ingroup MprFileSystem
  4183. @stability Internal
  4184. */
  4185. PUBLIC void mprInitFileSystem(MprFileSystem *fs, cchar *path);
  4186. /**
  4187. A RomInode is created for each file in the Rom file system.
  4188. @ingroup FileSystem
  4189. @stability Internal
  4190. */
  4191. typedef struct MprRomInode {
  4192. char *path; /**< File path */
  4193. uchar *data; /**< Pointer to file data (unmanaged) */
  4194. int size; /**< Size of file */
  4195. int num; /**< Inode number */
  4196. } MprRomInode;
  4197. typedef struct MprRomFileSystem {
  4198. MprFileSystem fileSystem; /**< Extends MprFileSystem */
  4199. MprHash *fileIndex;
  4200. MprRomInode *romInodes; /**< File inode data (unmanaged) */
  4201. } MprRomFileSystem;
  4202. #if ME_ROM
  4203. /**
  4204. Create and initialize the ROM FileSystem.
  4205. @description This is an internal routine called by the MPR during initialization.
  4206. @param path Path name to the root of the file system.
  4207. @param inodes File definitions
  4208. @return Returns a new file system object
  4209. @ingroup MprFileSystem
  4210. @stability Internal
  4211. */
  4212. PUBLIC MprRomFileSystem *mprCreateRomFileSystem(cchar *path, MprRomInode *inodes);
  4213. /**
  4214. Get the ROM file system data
  4215. @return Returns a pointer to the list of ROM inodes.
  4216. @ingroup MprFileSystem
  4217. @stability Stable
  4218. */
  4219. PUBLIC MprRomInode *mprGetRomFiles(void);
  4220. #endif /* ME_ROM */
  4221. typedef MprFileSystem MprDiskFileSystem;
  4222. /**
  4223. Create and initialize the disk FileSystem.
  4224. @description This is an internal routine called by the MPR during initialization.
  4225. @param path Path name to the root of the file system.
  4226. @return Returns a new file system object
  4227. @ingroup MprFileSystem
  4228. @stability Internal
  4229. */
  4230. PUBLIC MprDiskFileSystem *mprCreateDiskFileSystem(cchar *path);
  4231. /**
  4232. Create and initialize the disk FileSystem.
  4233. @description This is an internal routine called by the MPR during initialization.
  4234. @param fs File system object
  4235. @ingroup MprFileSystem
  4236. @stability Internal
  4237. */
  4238. PUBLIC void mprAddFileSystem(MprFileSystem *fs);
  4239. /**
  4240. Lookup a file system
  4241. @param path Path representing a file in the file system.
  4242. @return Returns a file system object.
  4243. @ingroup MprFileSystem
  4244. @stability Internal
  4245. */
  4246. PUBLIC MprFileSystem *mprLookupFileSystem(cchar *path);
  4247. /**
  4248. Set the file system path separators
  4249. @param path Path representing a file in the file system.
  4250. @param separators String containing the directory path separators. Defaults to "/". Windows uses "/\/".
  4251. @ingroup MprFileSystem
  4252. @stability Stable
  4253. */
  4254. PUBLIC void mprSetPathSeparators(cchar *path, cchar *separators);
  4255. /**
  4256. Set the file system new line character string
  4257. @param path Path representing a file in the file system.
  4258. @param newline String containing the newline character(s). "\\n". Windows uses "\\r\\n".
  4259. @ingroup MprFileSystem
  4260. @stability Stable
  4261. */
  4262. PUBLIC void mprSetPathNewline(cchar *path, cchar *newline);
  4263. PUBLIC MprList *mprGetDirList(cchar *path);
  4264. /**
  4265. File I/O Module
  4266. @description MprFile is the cross platform File I/O abstraction control structure. An instance will be
  4267. created when a file is created or opened via #mprOpenFile.
  4268. Note: Individual files are not thread-safe and should only be used by one file.
  4269. @stability Stable.
  4270. @see MprFile mprAttachFileFd mprCloseFile mprDisableFileBuffering mprEnableFileBuffering mprFlushFile mprGetFileChar
  4271. mprGetFilePosition mprGetFileSize mprGetStderr mprGetStdin mprGetStdout mprOpenFile
  4272. mprPeekFileChar mprPutFileChar mprPutFileString mprReadFile mprReadLine mprSeekFile mprTruncateFile mprWriteFile
  4273. mprWriteFileFmt mprWriteFileString
  4274. mprGetFileFd
  4275. @defgroup MprFile MprFile
  4276. */
  4277. typedef struct MprFile {
  4278. char *path; /**< Filename */
  4279. MprFileSystem *fileSystem; /**< File system owning this file */
  4280. MprBuf *buf; /**< Buffer for I/O if buffered */
  4281. MprOff pos; /**< Current read position */
  4282. MprOff iopos; /**< Raw I/O position */
  4283. MprOff size; /**< Current file size */
  4284. int mode; /**< File open mode */
  4285. int perms; /**< File permissions */
  4286. int fd; /**< File handle */
  4287. int attached; /**< Attached to existing descriptor */
  4288. MprRomInode *inode; /**< Reference to ROM file */
  4289. } MprFile;
  4290. /**
  4291. Attach to an existing file descriptor
  4292. @description Attach a file to an open file decriptor and return a file object.
  4293. @param fd File descriptor to attach to
  4294. @param name Descriptive name for the file.
  4295. @param omode Posix style file open mode mask. The open mode may contain
  4296. the following mask values ored together:
  4297. @li O_RDONLY Open read only
  4298. @li O_WRONLY Open write only
  4299. @li O_RDWR Open for read and write
  4300. @li O_CREAT Create or re-create
  4301. @li O_TRUNC Truncate
  4302. @li O_BINARY Open for binary data
  4303. @li O_TEXT Open for text data
  4304. @li O_EXCL Open with an exclusive lock
  4305. @li O_APPEND Open to append
  4306. @return Returns an MprFile object to use in other file operations.
  4307. @ingroup MprFile
  4308. @stability Stable
  4309. */
  4310. PUBLIC MprFile *mprAttachFileFd(int fd, cchar *name, int omode);
  4311. /**
  4312. Close a file
  4313. @description This call closes a file without destroying the file object.
  4314. @param file File instance returned from #mprOpenFile
  4315. @return Returns zero if successful, otherwise a negative MPR error code..
  4316. @ingroup MprFile
  4317. @stability Stable
  4318. */
  4319. PUBLIC int mprCloseFile(MprFile *file);
  4320. /**
  4321. Disable file buffering
  4322. @description Disable any buffering of data when using the buffer.
  4323. @param file File instance returned from #mprOpenFile
  4324. @ingroup MprFile
  4325. @stability Stable
  4326. */
  4327. PUBLIC void mprDisableFileBuffering(MprFile *file);
  4328. /**
  4329. Enable file buffering
  4330. @description Enable data buffering when using the buffer.
  4331. @param file File instance returned from #mprOpenFile
  4332. @param size Size to allocate for the buffer.
  4333. @param maxSize Maximum size the data buffer can grow to
  4334. @ingroup MprFile
  4335. @stability Stable
  4336. */
  4337. PUBLIC int mprEnableFileBuffering(MprFile *file, ssize size, ssize maxSize);
  4338. /**
  4339. Flush any buffered write data
  4340. @description Write buffered write data and then reset the internal buffers.
  4341. @param file Pointer to an MprFile object returned via MprOpen.
  4342. @return Zero if successful, otherwise a negative MPR error code.
  4343. @ingroup MprFile
  4344. @stability Stable
  4345. */
  4346. PUBLIC int mprFlushFile(MprFile *file);
  4347. /**
  4348. Read a character from the file.
  4349. @description Read a single character from the file and advance the read position.
  4350. @param file Pointer to an MprFile object returned via MprOpen.
  4351. @return If successful, return the character just read. Otherwise return a negative MPR error code.
  4352. End of file is signified by reading 0.
  4353. @ingroup MprFile
  4354. @stability Stable
  4355. */
  4356. PUBLIC int mprGetFileChar(MprFile *file);
  4357. /**
  4358. Get the file descriptor for a file
  4359. @param file File object returned via #mprOpenFile
  4360. @return An integer O/S file descriptor
  4361. @ingroup MprFile
  4362. @stability Stable
  4363. */
  4364. PUBLIC int mprGetFileFd(MprFile *file);
  4365. /**
  4366. Return the current file position
  4367. @description Return the current read/write file position.
  4368. @param file A file object returned from #mprOpenFile
  4369. @returns The current file offset position if successful. Returns a negative MPR error code on errors.
  4370. @ingroup MprFile
  4371. */
  4372. PUBLIC MprOff mprGetFilePosition(MprFile *file);
  4373. /**
  4374. Get the size of the file
  4375. @description Return the current file size
  4376. @param file A file object returned from #mprOpenFile
  4377. @returns The current file size if successful. Returns a negative MPR error code on errors.
  4378. @ingroup MprFile
  4379. @stability Stable
  4380. */
  4381. PUBLIC MprOff mprGetFileSize(MprFile *file);
  4382. /**
  4383. Return a file object for the Stderr I/O channel
  4384. @returns A file object
  4385. @ingroup MprFile
  4386. @stability Stable
  4387. */
  4388. PUBLIC MprFile *mprGetStderr(void);
  4389. /**
  4390. Return a file object for the Stdin I/O channel
  4391. @returns A file object
  4392. @ingroup MprFile
  4393. @stability Stable
  4394. */
  4395. PUBLIC MprFile *mprGetStdin(void);
  4396. /**
  4397. Return a file object for the Stdout I/O channel
  4398. @returns A file object
  4399. @ingroup MprFile
  4400. @stability Stable
  4401. */
  4402. PUBLIC MprFile *mprGetStdout(void);
  4403. /**
  4404. Open a file
  4405. @description Open a file and return a file object.
  4406. @param filename String containing the filename to open or create.
  4407. @param omode Posix style file open mode mask. The open mode may contain
  4408. the following mask values ored together:
  4409. @li O_RDONLY Open read only
  4410. @li O_WRONLY Open write only
  4411. @li O_RDWR Open for read and write
  4412. @li O_CREAT Create file if it does not exist
  4413. @li O_TRUNC Truncate size to zero length
  4414. @li O_BINARY Open for binary data
  4415. @li O_TEXT Open for text data
  4416. @li O_EXCL Open with an exclusive lock
  4417. @li O_APPEND Open to append
  4418. @param perms Posix style file permissions mask.
  4419. @return Returns an MprFile object to use in other file operations.
  4420. @ingroup MprFile
  4421. @stability Stable
  4422. */
  4423. PUBLIC MprFile *mprOpenFile(cchar *filename, int omode, int perms);
  4424. /**
  4425. Non-destructively read a character from the file.
  4426. @description Read a single character from the file without advancing the read position.
  4427. @param file Pointer to an MprFile object returned via MprOpen.
  4428. @return If successful, return the character just read. Otherwise return a negative MPR error code.
  4429. End of file is signified by reading 0.
  4430. @ingroup MprFile
  4431. @stability Stable
  4432. */
  4433. PUBLIC int mprPeekFileChar(MprFile *file);
  4434. /**
  4435. Write a character to the file.
  4436. @description Writes a single character to the file. Output is buffered and is
  4437. flushed as required or when mprClose is called.
  4438. @param file Pointer to an MprFile object returned via MprOpen.
  4439. @param c Character to write
  4440. @return One if successful, otherwise returns a negative MPR error code on errors.
  4441. @ingroup MprFile
  4442. @stability Stable
  4443. */
  4444. PUBLIC ssize mprPutFileChar(MprFile *file, int c);
  4445. /**
  4446. Write a string to the file.
  4447. @description Writes a string to the file. Output is buffered and is flushed as required or when mprClose is called.
  4448. @param file Pointer to an MprFile object returned via MprOpen.
  4449. @param str String to write
  4450. @return The number of characters written to the file. Returns a negative MPR error code on errors.
  4451. @ingroup MprFile
  4452. @stability Stable
  4453. */
  4454. PUBLIC ssize mprPutFileString(MprFile *file, cchar *str);
  4455. /**
  4456. Read data from a file.
  4457. @description Reads data from a file.
  4458. @param file Pointer to an MprFile object returned via MprOpen.
  4459. @param buf Buffer to contain the read data.
  4460. @param size Size of \a buf in characters.
  4461. @return The number of characters read from the file. Returns a negative MPR error code on errors.
  4462. @ingroup MprFile
  4463. @stability Stable
  4464. */
  4465. PUBLIC ssize mprReadFile(MprFile *file, void *buf, ssize size);
  4466. /**
  4467. Read a line from the file.
  4468. @description Read a single line from the file. Lines are delimited by the newline character. The newline is not
  4469. included in the returned buffer. This call will read lines up to the given size in length. If no newline is
  4470. found, all available characters, up to size, will be returned.
  4471. @param file Pointer to an MprFile object returned via MprOpen.
  4472. @param size Maximum number of characters in a line.
  4473. @param len Pointer to an integer to hold the length of the returned string.
  4474. @return An allocated string and sets *len to the number of bytes read.
  4475. @ingroup MprFile
  4476. @stability Stable
  4477. */
  4478. PUBLIC char *mprReadLine(MprFile *file, ssize size, ssize *len);
  4479. /**
  4480. Seek the I/O pointer to a new location in the file.
  4481. @description Move the position in the file to/from which I/O will be performed in the file. Seeking prior
  4482. to a read or write will cause the next I/O to occur at that location.
  4483. @param file Pointer to an MprFile object returned via MprOpen.
  4484. @param seekType Seek type may be one of the following three values:
  4485. @li SEEK_SET Seek to a position relative to the start of the file
  4486. @li SEEK_CUR Seek relative to the current position
  4487. @li SEEK_END Seek relative to the end of the file
  4488. @param distance A positive or negative byte offset.
  4489. @return Returns the new file position if successful otherwise a negative MPR error code is returned.
  4490. @ingroup MprFile
  4491. @stability Stable
  4492. */
  4493. PUBLIC MprOff mprSeekFile(MprFile *file, int seekType, MprOff distance);
  4494. /**
  4495. Truncate a file
  4496. @description Truncate a file to a given size. Note this works on a path and not on an open file.
  4497. @param path File to truncate
  4498. @param size New maximum size for the file.
  4499. @returns Zero if successful.
  4500. @ingroup MprFile
  4501. @stability Stable
  4502. */
  4503. PUBLIC int mprTruncateFile(cchar *path, MprOff size);
  4504. /**
  4505. Write data to a file.
  4506. @description Writes data to a file.
  4507. @param file Pointer to an MprFile object returned via MprOpen.
  4508. @param buf Buffer containing the data to write.
  4509. @param count Cound of characters in \a buf to write
  4510. @return The number of characters actually written to the file. Returns a negative MPR error code on errors.
  4511. @ingroup MprFile
  4512. @stability Stable
  4513. */
  4514. PUBLIC ssize mprWriteFile(MprFile *file, cvoid *buf, ssize count);
  4515. /**
  4516. Write formatted data to a file.
  4517. @description Writes a formatted string to a file.
  4518. @param file Pointer to an MprFile object returned via MprOpen.
  4519. @param fmt Format string
  4520. @return The number of characters actually written to the file. Returns a negative MPR error code on errors.
  4521. @ingroup MprFile
  4522. @stability Stable
  4523. */
  4524. PUBLIC ssize mprWriteFileFmt(MprFile *file, cchar *fmt, ...) PRINTF_ATTRIBUTE(2,3);
  4525. /**
  4526. Write a string to a file.
  4527. @description Writes a string to a file.
  4528. @param file Pointer to an MprFile object returned via MprOpen.
  4529. @param str String to write
  4530. @return The number of characters actually written to the file. Returns a negative MPR error code on errors.
  4531. @ingroup MprFile
  4532. @stability Stable
  4533. */
  4534. PUBLIC ssize mprWriteFileString(MprFile *file, cchar *str);
  4535. /*********************************** Paths ************************************/
  4536. /**
  4537. Path (filename) Information
  4538. @description MprPath is the cross platform Path (filename) information structure.
  4539. @stability Internal.
  4540. @see MprDirEntry MprFile MprPath mprCopyPath mprDeletePath mprGetAbsPath mprGetCurrentPath
  4541. mprGetFirstPathSeparator mprGetLastPathSeparator mprGetNativePath mprGetPathBase
  4542. mprGetPathDir mprGetPathExt mprGetPathFiles mprGetPathLink mprGetPathNewline mprGetPathParent
  4543. mprGetPathSeparators mprGetPortablePath mprGetRelPath mprGetTempPath mprGetWinPath mprIsPathAbs
  4544. mprIsRelPath mprJoinPath mprJoinPaths mprJoinPathExt mprMakeDir mprMakeLink mprMapSeparators mprNormalizePath
  4545. mprPathExists mprReadPathContents mprReplacePathExt mprResolvePath mprSamePath mprSamePathCount mprSearchPath
  4546. mprTransformPath mprTrimPathExt mprTruncatePath
  4547. @defgroup MprPath MprPath
  4548. */
  4549. typedef struct MprPath {
  4550. MprTime atime; /**< Access time */
  4551. MprTime ctime; /**< Create time */
  4552. MprTime mtime; /**< Modified time */
  4553. MprOff size; /**< File length */
  4554. int64 inode; /**< Inode number */
  4555. int perms; /**< Permission mask */
  4556. int owner; /**< Owner ID */
  4557. int group; /**< Group ID */
  4558. bool checked: 1; /**< Path has been checked */
  4559. bool isDir: 1; /**< Set if directory */
  4560. bool isLink: 1; /**< Set if a symbolic link */
  4561. bool isReg: 1; /**< Set if a regular file */
  4562. bool caseMatters: 1; /**< Case comparisons matter */
  4563. bool valid: 1; /**< Valid data bit */
  4564. } MprPath;
  4565. /**
  4566. Directory entry description
  4567. @description The MprGetDirList will create a list of directory entries.
  4568. @ingroup MprPath
  4569. @stability Internal
  4570. */
  4571. typedef struct MprDirEntry {
  4572. char *name; /**< Name of the file */
  4573. MprTime lastModified; /**< Time the file was last modified */
  4574. MprOff size; /**< Size of the file */
  4575. bool isDir: 1; /**< True if the file is a directory */
  4576. bool isLink: 1; /**< True if the file is a symbolic link */
  4577. } MprDirEntry;
  4578. /*
  4579. Search path separator
  4580. */
  4581. #if ME_WIN_LIKE
  4582. #define MPR_SEARCH_SEP ";"
  4583. #define MPR_SEARCH_SEP_CHAR ';'
  4584. #else
  4585. #define MPR_SEARCH_SEP ":"
  4586. #define MPR_SEARCH_SEP_CHAR ':'
  4587. #endif
  4588. /**
  4589. Copy a file
  4590. @description Create a new copy of a file with the specified open permissions mode.
  4591. @param from Path of the existing file to copy
  4592. @param to Name of the new file copy
  4593. @param omode Posix style file open mode mask. See #mprOpenFile for the various modes.
  4594. @returns True if the file exists and can be accessed
  4595. @ingroup MprPath
  4596. @stability Stable
  4597. */
  4598. PUBLIC int mprCopyPath(cchar *from, cchar *to, int omode);
  4599. /**
  4600. Delete a file.
  4601. @description Delete a file or directory.
  4602. @param path String containing the path to delete.
  4603. @return Returns zero if successful otherwise a negative MPR error code is returned.
  4604. @ingroup MprPath
  4605. @stability Stable
  4606. */
  4607. PUBLIC int mprDeletePath(cchar *path);
  4608. /**
  4609. Convert a path to an absolute path
  4610. @description Get an absolute (canonical) equivalent representation of a path. On windows this path will have
  4611. back-slash directory separators and will have a drive specifier. On Cygwin, the path will be a Cygwin style
  4612. path with forward-slash directory specifiers and without a drive specifier. If the path is outside the
  4613. cygwin filesystem (outside c:/cygwin), the path will have a /cygdrive/DRIVE prefix. To get a windows style
  4614. path on *NIX, use mprGetWinPath.
  4615. @param path Path to examine
  4616. @returns An absolute path.
  4617. @ingroup MprPath
  4618. @stability Stable
  4619. */
  4620. PUBLIC char *mprGetAbsPath(cchar *path);
  4621. /**
  4622. Return the current working directory
  4623. @return Returns an allocated string with the current working directory as an absolute path.
  4624. @ingroup MprPath
  4625. @stability Stable
  4626. */
  4627. PUBLIC cchar *mprGetCurrentPath(void);
  4628. /**
  4629. Get the first path separator in a path
  4630. @param path Path to examine
  4631. @return Returns a reference to the first path separator in the given path
  4632. @ingroup MprPath
  4633. @stability Stable
  4634. */
  4635. PUBLIC cchar *mprGetFirstPathSeparator(cchar *path);
  4636. /*
  4637. Get the last path separator in a path
  4638. @param path Path to examine
  4639. @return Returns a reference to the last path separator in the given path
  4640. @ingroup MprPath
  4641. @stability Stable
  4642. */
  4643. PUBLIC cchar *mprGetLastPathSeparator(cchar *path);
  4644. /**
  4645. Get a path formatted according to the native O/S conventions.
  4646. @description Get an equivalent absolute path formatted using the directory separators native to the O/S platform.
  4647. On Windows, it will use backward slashes ("\") as the directory separator and will contain a drive specification.
  4648. @param path Path name to examine
  4649. @returns An allocated string containing the new path.
  4650. @ingroup MprPath
  4651. @stability Stable
  4652. */
  4653. PUBLIC char *mprGetNativePath(cchar *path);
  4654. /**
  4655. Get the base portion of a path
  4656. @description Get the base portion of a path by stripping off all directory components
  4657. @param path Path name to examine
  4658. @returns A path without any directory portion.
  4659. @ingroup MprPath
  4660. @stability Stable
  4661. */
  4662. PUBLIC char *mprGetPathBase(cchar *path);
  4663. /**
  4664. Get a reference to the base portion of a path
  4665. @description Get the base portion of a path by stripping off all directory components. This returns a reference
  4666. into the original path.
  4667. @param path Path name to examine
  4668. @returns A path without any directory portion. The path is a reference into the original file string.
  4669. @ingroup MprPath
  4670. @stability Stable
  4671. */
  4672. PUBLIC cchar *mprGetPathBaseRef(cchar *path);
  4673. /**
  4674. Get the directory portion of a path
  4675. @description Get the directory portion of a path by stripping off the base name.
  4676. @param path Path name to examine
  4677. @returns A new string containing the directory name.
  4678. @ingroup MprPath
  4679. @stability Stable
  4680. */
  4681. PUBLIC char *mprGetPathDir(cchar *path);
  4682. /**
  4683. Get the file extension portion of a path
  4684. @description Get the file extension portion of a path. The file extension is the portion starting with the last "."
  4685. in the path. It thus does not include the "." as the first charcter.
  4686. @param path Path name to examine
  4687. @returns A path extension without the ".". Returns null if no extension exists.
  4688. @ingroup MprPath
  4689. @stability Stable
  4690. */
  4691. PUBLIC char *mprGetPathExt(cchar *path);
  4692. /*
  4693. Flags for mprGetPathFiles
  4694. */
  4695. #define MPR_PATH_DESCEND 0x1 /**< Flag for mprGetPathFiles to traverse subdirectories */
  4696. #define MPR_PATH_DEPTH_FIRST 0x2 /**< Flag for mprGetPathFiles to do a depth-first traversal */
  4697. #define MPR_PATH_INC_HIDDEN 0x4 /**< Flag for mprGetPathFiles to include hidden files */
  4698. #define MPR_PATH_NO_DIRS 0x8 /**< Flag for mprGetPathFiles to exclude subdirectories */
  4699. #define MPR_PATH_RELATIVE 0x10 /**< Flag for mprGetPathFiles to return paths relative to the directory */
  4700. /**
  4701. Create a list of files in a directory or subdirectories. This call returns a list of MprDirEntry objects.
  4702. @description Get the list of files in a directory and return a list.
  4703. @param dir Directory to list.
  4704. @param flags The flags may be set to #MPR_PATH_DESCEND to traverse subdirectories. This effectively appends
  4705. '**' to the path. Set #MPR_PATH_NO_DIRS to exclude directories from the results. Set to MPR_PATH_HIDDEN
  4706. to include hidden files that start with ".". Set to MPR_PATH_DEPTH_FIRST to do a depth-first traversal,
  4707. i.e. traverse subdirectories before considering adding the directory to the list.
  4708. @returns A list (MprList) of MprDirEntry objects.
  4709. @ingroup MprPath
  4710. @stability Stable
  4711. */
  4712. PUBLIC MprList *mprGetPathFiles(cchar *dir, int flags);
  4713. /**
  4714. Create a list of files in a directory or subdirectories that match the given wildcard pattern.
  4715. This call returns a list of filenames.
  4716. @description Get the list of files in a directory and return a list. The pattern list may contain
  4717. wild cards: "?" Matches any single character, "*" matches zero or more characters of the file or directory,
  4718. "**"/ matches zero or more directories, "**" matches zero or more files or directories.
  4719. An exclusion pattern may be specified to apply to subsequent patterns by appending with "!".
  4720. @param path Directory to list.
  4721. @param patterns Wild card pattern to match.
  4722. @param flags Set to MPR_PATH_HIDDEN to include hidden files that start with ".". Set to MPR_PATH_DEPTH_FIRST to do a
  4723. depth-first traversal, i.e. traverse subdirectories before considering adding the directory to the list.
  4724. Set MPR_PATH_RELATIVE to return files relative to the given path. Set MPR_PATH_NO_DIRS to omit directories.
  4725. @returns A list (MprList) of filenames.
  4726. @ingroup MprPath
  4727. @stability Stable
  4728. */
  4729. PUBLIC MprList *mprGlobPathFiles(cchar *path, cchar *patterns, int flags);
  4730. /**
  4731. Get the first directory portion of a path
  4732. @param path Path name to examine
  4733. @returns A new string containing the directory name.
  4734. @ingroup MprPath
  4735. @stability Stable
  4736. */
  4737. PUBLIC char *mprGetPathFirstDir(cchar *path);
  4738. /**
  4739. Return information about a file represented by a path.
  4740. @description Returns file status information regarding the \a path.
  4741. @param path String containing the path to query.
  4742. @param info Pointer to a pre-allocated MprPath structure.
  4743. @return Returns zero if successful, otherwise a negative MPR error code is returned.
  4744. @ingroup MprPath
  4745. @stability Stable
  4746. */
  4747. PUBLIC int mprGetPathInfo(cchar *path, MprPath *info);
  4748. /**
  4749. Get the target of a symbolic link.
  4750. @description Return the path pointed to by a symbolic link. Not all platforms support symbolic links.
  4751. @param path Path name to examine
  4752. @returns A path representing the target of the symbolic link.
  4753. @ingroup MprPath
  4754. @stability Stable
  4755. */
  4756. PUBLIC char *mprGetPathLink(cchar *path);
  4757. /**
  4758. Get the file newline character string for a given path.
  4759. Return the character string used to delimit new lines in text files.
  4760. @param path Use this path to specify either the root of the file system or a file on the file system.
  4761. @returns A string used to delimit new lines. This is typically "\n" or "\r\n"
  4762. @ingroup MprPath
  4763. @stability Stable
  4764. */
  4765. PUBLIC cchar *mprGetPathNewline(cchar *path);
  4766. /**
  4767. Get the parent directory of a path
  4768. @param path Path name to examine
  4769. @returns An allocated string containing the parent directory.
  4770. @ingroup MprPath
  4771. @stability Stable
  4772. */
  4773. PUBLIC char *mprGetPathParent(cchar *path);
  4774. /**
  4775. Get the path directory separator.
  4776. Return the directory separator characters used to separate directories on a given file system. Typically "/" or "\"
  4777. The first entry is the default separator.
  4778. @param path Use this path to specify either the root of the file system or a file on the file system.
  4779. @returns The string of path separators. The first entry is the default separator.
  4780. @ingroup MprPath
  4781. @stability Stable
  4782. */
  4783. PUBLIC cchar *mprGetPathSeparators(cchar *path);
  4784. /**
  4785. Get the default path directory separator.
  4786. Return the default directory separator character used to separate directories on a given file system.
  4787. Typically "/" or "\".
  4788. @param path Use this path to specify either the root of the file system or a file on the file system.
  4789. @returns Character path separator
  4790. @ingroup MprPath
  4791. @stability Stable
  4792. */
  4793. PUBLIC char mprGetPathSeparator(cchar *path);
  4794. /**
  4795. Get a portable path
  4796. @description Get an equivalent absolute path that is somewhat portable.
  4797. This means it will use forward slashes ("/") as the directory separator. This call will not remove drive specifiers.
  4798. @param path Path name to examine
  4799. @returns An allocated string containing the new path.
  4800. @ingroup MprPath
  4801. @stability Stable
  4802. */
  4803. PUBLIC char *mprGetPortablePath(cchar *path);
  4804. /**
  4805. Get a path relative to another path.
  4806. @description Get a relative path path from an origin path to a destination. If a relative path cannot be obtained,
  4807. an absolute path to the destination will be returned. This happens if the paths cross drives.
  4808. @param dest Destination file
  4809. @param origin Starting location from which to compute a relative path to the destination
  4810. If the origin is null, use the application's current working directory as the origin.
  4811. @returns An allocated string containing the relative directory.
  4812. @ingroup MprPath
  4813. @stability Stable
  4814. */
  4815. PUBLIC char *mprGetRelPath(cchar *dest, cchar *origin);
  4816. /**
  4817. Make a temporary file.
  4818. @description Thread-safe way to make a unique temporary file.
  4819. @param tmpDir Base directory in which the temp file will be allocated.
  4820. @return An allocated string containing the path of the temp file.
  4821. @ingroup MprPath
  4822. @stability Stable
  4823. */
  4824. PUBLIC char *mprGetTempPath(cchar *tmpDir);
  4825. /**
  4826. Convert a path to an absolute windows path
  4827. @description Get a windows style, absolute (canonical) equivalent representation of a path. This path will
  4828. have back-slash delimiters and a drive specifier. On non-windows systems, this returns an absolute path using
  4829. mprGetAbsPath.
  4830. @param path Path to examine
  4831. @returns A windows-style absolute path.
  4832. @ingroup MprPath
  4833. @stability Stable
  4834. */
  4835. PUBLIC char *mprGetWinPath(cchar *path);
  4836. /**
  4837. Determine if a directory is the same as or a parent of a path.
  4838. @param dir Directory to examine if it is a parent of path.
  4839. @param path Path name to examine
  4840. @returns True if directory is a parent of the path or is the same as the given path.
  4841. @ingroup MprPath
  4842. @stability Stable
  4843. */
  4844. PUBLIC bool mprIsPathContained(cchar *path, cchar *dir);
  4845. /**
  4846. Fast version of mprIsPathContained that works only for absolute paths.
  4847. Determine if a directory is the same as or a parent of a path.
  4848. @param path Path name to examine
  4849. @param dir Directory to examine if it is a parent of path or equal to path
  4850. @returns True if directory is a parent of the path or is the same as the given path.
  4851. @ingroup MprPath
  4852. @stability Stable
  4853. */
  4854. PUBLIC bool mprIsAbsPathContained(cchar *path, cchar *dir);
  4855. /**
  4856. Determine if a path is absolute
  4857. @param path Path name to examine
  4858. @returns True if the path is absolue
  4859. @ingroup MprPath
  4860. @stability Stable
  4861. */
  4862. PUBLIC bool mprIsPathAbs(cchar *path);
  4863. /**
  4864. Determine if a path is a directory
  4865. @param path Path name to examine
  4866. @returns True if the path is a directory
  4867. @ingroup MprPath
  4868. @stability Stable
  4869. */
  4870. PUBLIC bool mprIsPathDir(cchar *path);
  4871. /**
  4872. Determine if a path is relative
  4873. @param path Path name to examine
  4874. @returns True if the path is relative
  4875. @ingroup MprPath
  4876. @stability Stable
  4877. */
  4878. PUBLIC bool mprIsPathRel(cchar *path);
  4879. /**
  4880. Test if a character is a path separarator
  4881. @param path Path name to identify the file system
  4882. @param c Character to test
  4883. @return Returns true if the character is a path separator on the file system containing the given path
  4884. @ingroup MprPath
  4885. @stability Stable
  4886. */
  4887. PUBLIC bool mprIsPathSeparator(cchar *path, cchar c);
  4888. /**
  4889. Join paths
  4890. @description Join a path to a base path. If path is absolute, it will be returned.
  4891. @param base Directory path name to use as the base.
  4892. @param path Other path name to join to the base path.
  4893. @returns Allocated string containing the resolved path.
  4894. @ingroup MprPath
  4895. @stability Stable
  4896. */
  4897. PUBLIC char *mprJoinPath(cchar *base, cchar *path);
  4898. /**
  4899. Join paths
  4900. @description Join each given path in turn to the path. Calls mprJoinPath for each argument.
  4901. @param base Directory path name to use as the base.
  4902. @param ... Other paths to join to the base path. List of other paths must be NULL terminated.
  4903. @returns Allocated string containing the resolved path.
  4904. @ingroup MprPath
  4905. @stability Stable
  4906. */
  4907. PUBLIC char *mprJoinPaths(cchar *base, ...);
  4908. /**
  4909. Join an extension to a path
  4910. @description Add an extension to a path if it does not already have one.
  4911. @param path Path name to use as a base. Path is not modified.
  4912. @param ext Extension to add. Must should not have a period prefix.
  4913. @returns Allocated string containing the resolved path.
  4914. @ingroup MprPath
  4915. @stability Stable
  4916. */
  4917. PUBLIC char *mprJoinPathExt(cchar *path, cchar *ext);
  4918. /**
  4919. Make a directory
  4920. @description Make a directory using the supplied path. Intermediate directories are created as required.
  4921. @param path String containing the directory pathname to create.
  4922. @param makeMissing If true make all required intervening directory segments.
  4923. @param perms Posix style file permissions mask.
  4924. @param owner User to own the directory. Set to -1 not change the owner.
  4925. @param group Group to own the directory. Set to -1 not change the group.
  4926. @return Returns zero if successful, otherwise a negative MPR error code is returned.
  4927. @ingroup MprPath
  4928. @stability Stable
  4929. */
  4930. PUBLIC int mprMakeDir(cchar *path, int perms, int owner, int group, bool makeMissing);
  4931. /**
  4932. Make a link
  4933. @description Make a link at the target to the specified path. This will make symbolic or hard links
  4934. depending on the value of the hard parameter
  4935. @param path String containing the path to link to
  4936. @param target String containing the new link path to be created.
  4937. @param hard If true, make a hard link, otherwise make a soft link.
  4938. @return Returns zero if successful, otherwise a negative MPR error code is returned.
  4939. @ingroup MprPath
  4940. @stability Stable
  4941. */
  4942. PUBLIC int mprMakeLink(cchar *path, cchar *target, bool hard);
  4943. /**
  4944. Map the separators in a path.
  4945. @description Map the directory separators in a path to the specified separators. This is useful to change from
  4946. backward to forward slashes when dealing with Windows paths.
  4947. @param path Path name to examine
  4948. @param separator Separator character to use.
  4949. @returns An allocated string containing the parent directory.
  4950. @ingroup MprPath
  4951. @stability Stable
  4952. */
  4953. PUBLIC void mprMapSeparators(char *path, int separator);
  4954. /**
  4955. Normalize a path
  4956. @description A path is normalized by redundant segments such as "./" and "../dir" and duplicate
  4957. path separators. Path separators are mapped. Paths are not converted to absolute paths.
  4958. @param path First path to compare
  4959. @returns A newly allocated, clean path.
  4960. @ingroup MprPath
  4961. @stability Stable
  4962. */
  4963. PUBLIC char *mprNormalizePath(cchar *path);
  4964. /**
  4965. Determine if a file exists for a path name and can be accessed
  4966. @description Test if a file can be accessed for a given mode
  4967. @param path Path name to test
  4968. @param omode Posix style file open mode mask. See #mprOpenFile for the various modes.
  4969. @returns True if the file exists and can be accessed
  4970. @ingroup MprPath
  4971. @stability Stable
  4972. */
  4973. PUBLIC bool mprPathExists(cchar *path, int omode);
  4974. /*
  4975. Read the contents of a file
  4976. @param path Filename to open and read
  4977. @param lenp Optional pointer to a ssize integer to contain the length of the returns data string. Set to NULL if not
  4978. required.
  4979. @return An allocated string containing the file contents and return the data length in lenp.
  4980. Returns null if the fail cannot be opened or read.
  4981. @ingroup MprPath
  4982. @stability Stable
  4983. */
  4984. PUBLIC char *mprReadPathContents(cchar *path, ssize *lenp);
  4985. /**
  4986. Replace an extension to a path
  4987. @description Remove any existing path extension and then add the given path extension.
  4988. @param path Path filename to modify
  4989. @param ext Extension to add. The extension should not have a period prefix.
  4990. @returns Allocated string containing the resolved path.
  4991. @ingroup MprPath
  4992. @stability Stable
  4993. */
  4994. PUBLIC char *mprReplacePathExt(cchar *path, cchar *ext);
  4995. /**
  4996. Resolve paths
  4997. @description Resolve paths in the neighborhood of this path. Resolve operates like join, except that it joins the
  4998. given paths to the directory portion of the current ("this") path. For example:
  4999. Path("/usr/bin/ejs/bin").resolve("lib") will return "/usr/lib/ejs/lib". i.e. it will return the
  5000. sibling directory "lib".
  5001. \n\n
  5002. Resolve operates by determining a virtual current directory for this Path object. It then successively
  5003. joins the given paths to the directory portion of the current result. If the next path is an absolute path,
  5004. it is used unmodified. The effect is to find the given paths with a virtual current directory set to the
  5005. directory containing the prior path.
  5006. \n\n
  5007. Resolve is useful for creating paths in the region of the current path and gracefully handles both
  5008. absolute and relative path segments.
  5009. \n\n
  5010. Returns a joined (normalized) path.
  5011. If path is absolute, then return path. If path is null, empty or "." then return path.
  5012. @param base Base path to use as the base.
  5013. @param path Path name to resolve against base.
  5014. @returns Allocated string containing the resolved path.
  5015. @ingroup MprPath
  5016. @stability Stable
  5017. */
  5018. PUBLIC char *mprResolvePath(cchar *base, cchar *path);
  5019. /**
  5020. Compare two paths if they are the same
  5021. @description Compare two paths to see if they are equal. This normalizes the paths to absolute paths first before
  5022. comparing. It does handle case sensitivity appropriately.
  5023. @param path1 First path to compare
  5024. @param path2 Second path to compare
  5025. @returns True if the file exists and can be accessed
  5026. @ingroup MprPath
  5027. @stability Stable
  5028. */
  5029. PUBLIC int mprSamePath(cchar *path1, cchar *path2);
  5030. /**
  5031. Compare two paths if they are the same for a given length.
  5032. @description Compare two paths to see if they are equal. This normalizes the paths to absolute paths first before
  5033. comparing. It does handle case sensitivity appropriately. The len parameter
  5034. if non-zero, specifies how many characters of the paths to compare.
  5035. @param path1 First path to compare
  5036. @param path2 Second path to compare
  5037. @param len How many characters to compare.
  5038. @returns True if the file exists and can be accessed
  5039. @ingroup MprPath
  5040. @stability Stable
  5041. */
  5042. PUBLIC int mprSamePathCount(cchar *path1, cchar *path2, ssize len);
  5043. /*
  5044. Flags for mprSearchPath
  5045. */
  5046. #define MPR_SEARCH_EXE 0x1 /* Search for an executable */
  5047. #define MPR_SEARCH_DIR 0x2 /* Search for a directory */
  5048. #define MPR_SEARCH_FILE 0x4 /* Search for regular file */
  5049. /**
  5050. Search for a path
  5051. @description Search for a file using a given set of search directories
  5052. @param path Path name to locate. Must be an existing file or directory.
  5053. @param flags Flags.
  5054. @param search Variable number of directories to search.
  5055. @returns Allocated string containing the full path name of the located file.
  5056. @ingroup MprPath
  5057. @stability Stable
  5058. */
  5059. PUBLIC char *mprSearchPath(cchar *path, int flags, cchar *search, ...);
  5060. /*
  5061. Flags for mprTransformPath
  5062. */
  5063. #define MPR_PATH_ABS 0x1 /* Normalize to an absolute path */
  5064. #define MPR_PATH_REL 0x2 /* Normalize to an relative path */
  5065. #define MPR_PATH_WIN 0x4 /* Normalize to a windows path */
  5066. #define MPR_PATH_NATIVE_SEP 0x8 /* Use native path separators */
  5067. /**
  5068. Transform a path
  5069. @description A path is transformed by cleaning and then transforming according to the flags.
  5070. @param path First path to compare
  5071. @param flags Flags to modify the path representation.
  5072. @returns A newly allocated, clean path.
  5073. @ingroup MprPath
  5074. @stability Stable
  5075. */
  5076. PUBLIC char *mprTransformPath(cchar *path, int flags);
  5077. /**
  5078. Trim path components from a path
  5079. @description Trim the requested number of path components from the front or end of a path
  5080. @param path Path to examine
  5081. @param count Number of components to trim. If negative, trim from the end.
  5082. @returns An allocated string with the trimmed path.
  5083. @ingroup MprPath
  5084. @stability Stable
  5085. */
  5086. PUBLIC char *mprTrimPathComponents(cchar *path, int count);
  5087. /**
  5088. Trim an extension from a path
  5089. @description Trim a file extension (".ext") from a path name.
  5090. @param path Path to examine
  5091. @returns An allocated string with the trimmed path.
  5092. @ingroup MprPath
  5093. @stability Stable
  5094. */
  5095. PUBLIC char *mprTrimPathExt(cchar *path);
  5096. /**
  5097. Trim the drive from a path
  5098. @description Trim a drive specifier ("c:") from the start of a path.
  5099. @param path Path to examine
  5100. @returns An allocated string with the trimmed drive.
  5101. @ingroup MprPath
  5102. @stability Stable
  5103. */
  5104. PUBLIC char *mprTrimPathDrive(cchar *path);
  5105. /**
  5106. Create a file and write contents
  5107. @description The file is created, written and closed. If the file already exists, it is recreated.
  5108. @param path Filename to create
  5109. @param buf Buffer of data to write to the file
  5110. @param len Size of the buf parameter in bytes
  5111. @param mode File permissions with which to create the file. E.g. 0644.
  5112. @return The number of bytes written. Should equal len. Otherwise return a negative MPR error code.
  5113. @ingroup MprPath
  5114. @stability Stable
  5115. */
  5116. PUBLIC ssize mprWritePathContents(cchar *path, cchar *buf, ssize len, int mode);
  5117. /*
  5118. Internal - prototype
  5119. */
  5120. PUBLIC bool mprMatchPath(cchar *path, cchar *pattern);
  5121. /********************************** O/S Dep ***********************************/
  5122. /**
  5123. Create and initialze the O/S dependent subsystem
  5124. @description Called internally by the MPR. Should not be called by users.
  5125. @ingroup Mpr
  5126. @stability Internal
  5127. */
  5128. PUBLIC int mprCreateOsService(void);
  5129. /**
  5130. Start the O/S dependent subsystem
  5131. @ingroup Mpr
  5132. @stability Internal
  5133. */
  5134. PUBLIC int mprStartOsService(void);
  5135. /**
  5136. Stop the O/S dependent subsystem
  5137. @ingroup Mpr
  5138. @stability Internal
  5139. */
  5140. PUBLIC void mprStopOsService(void);
  5141. /********************************* Modules ************************************/
  5142. /**
  5143. Loadable module service
  5144. @see mprCreateModuleService mprStartModuleService mprStopModuleService
  5145. @defgroup MprModuleSerivce MprModuleService
  5146. @stability Internal
  5147. */
  5148. typedef struct MprModuleService {
  5149. MprList *modules; /**< List of defined modules */
  5150. char *searchPath; /**< Module search path to locate modules */
  5151. MprMutex *mutex;
  5152. } MprModuleService;
  5153. /**
  5154. Create and initialize the module service
  5155. @return MprModuleService object
  5156. @ingroup MprModuleService
  5157. @stability Internal
  5158. */
  5159. PUBLIC MprModuleService *mprCreateModuleService(void);
  5160. /**
  5161. Start the module service
  5162. @description This calls the start entry point for all registered modules
  5163. @return Zero if successful, otherwise a negative MPR error code.
  5164. @ingroup MprModuleService
  5165. @stability Internal
  5166. */
  5167. PUBLIC int mprStartModuleService(void);
  5168. /**
  5169. Stop the module service
  5170. @description This calls the stop entry point for all registered modules
  5171. @return Zero if successful, otherwise a negative MPR error code.
  5172. @ingroup MprModuleService
  5173. @stability Internal
  5174. */
  5175. PUBLIC void mprStopModuleService(void);
  5176. /**
  5177. Module start/stop point function signature
  5178. @param mp Module object reference returned from #mprCreateModule
  5179. @returns zero if successful, otherwise return a negative MPR error code.
  5180. @ingroup MprModule
  5181. @stability Stable
  5182. */
  5183. typedef int (*MprModuleProc)(struct MprModule *mp);
  5184. /*
  5185. Module flags
  5186. */
  5187. #define MPR_MODULE_STARTED 0x1 /**< Module stared **/
  5188. #define MPR_MODULE_STOPPED 0x2 /**< Module stopped */
  5189. #define MPR_MODULE_LOADED 0x4 /**< Dynamic module loaded */
  5190. #define MPR_MODULE_DATA_MANAGED 0x8 /**< Module.moduleData is managed */
  5191. /**
  5192. Loadable Module Service
  5193. @description The MPR provides services to load and unload shared libraries.
  5194. @see MprModule MprModuleEntry MprModuleProc mprCreateModule mprGetModuleSearchPath mprLoadModule mprLoadNativeModule
  5195. mprLookupModule mprLookupModuleData mprSearchForModule mprSetModuleFinalizer mprSetModuleSearchPath
  5196. mprSetModuleTimeout mprStartModule mprStopModule mprUnloadModule mprUnloadNativeModule
  5197. @stability Stable.
  5198. @defgroup MprModule MprModule
  5199. @stability Internal
  5200. */
  5201. typedef struct MprModule {
  5202. char *name; /**< Unique module name */
  5203. char *path; /**< Module library filename */
  5204. char *entry; /**< Module library init entry point */
  5205. void *moduleData; /**< Module specific data - not managed unless MPR_MODULE_DATA_MANAGED */
  5206. void *handle; /**< O/S shared library load handle */
  5207. MprTime modified; /**< When the module file was last modified */
  5208. MprTicks lastActivity; /**< When the module was last used */
  5209. MprTicks timeout; /**< Inactivity unload timeout */
  5210. int flags; /**< Module control flags */
  5211. MprModuleProc start; /**< Start the module */
  5212. MprModuleProc stop; /**< Stop the module. Should be unloadable after stopping */
  5213. } MprModule;
  5214. /**
  5215. Loadable module entry point signature.
  5216. @description Loadable modules can have an entry point that is invoked automatically when a module is loaded.
  5217. @param data Data passed to mprCreateModule
  5218. @param mp Module object reference returned from #mprCreateModule
  5219. @return a new MprModule structure for the module. Return NULL if the module cannot be initialized.
  5220. @ingroup MprModule
  5221. @stability Stable
  5222. */
  5223. typedef int (*MprModuleEntry)(void *data, MprModule *mp);
  5224. /**
  5225. Create a module
  5226. @description This call will create a module object for a loadable module. This should be invoked by the
  5227. module itself in its module entry point to register itself with the MPR.
  5228. @param name Name of the module
  5229. @param path Optional filename of a module library to load. When loading, the filename will be searched using
  5230. the defined module search path (see #mprSetModuleSearchPath). The filename may or may not include a platform
  5231. specific shared library extension such as .dll, .so or .dylib. By omitting the library extension, code can
  5232. portably load shared libraries.
  5233. @param entry Name of function to invoke after loading the module.
  5234. @param data Arbitrary data pointer. This will be defined in MprModule.data and passed into the module initialization
  5235. entry point.
  5236. @returns A module object for this module
  5237. @ingroup MprModule
  5238. @stability Stable
  5239. */
  5240. PUBLIC MprModule *mprCreateModule(cchar *name, cchar *path, cchar *entry, void *data);
  5241. /**
  5242. Get the module search path
  5243. @description Get the directory search path used by the MPR when loading dynamic modules. This is a colon separated (or
  5244. semicolon on Windows) set of directories.
  5245. @returns The module search path.
  5246. @ingroup MprModule
  5247. @stability Stable
  5248. */
  5249. PUBLIC cchar *mprGetModuleSearchPath(void);
  5250. /**
  5251. Load a module
  5252. @description Load a module library. This will load a dynamic shared object (shared library) and call the
  5253. modules library entry point. If the module is already loaded, this call will do nothing.
  5254. @param mp Module object created via #mprCreateModule.
  5255. @returns Zero if successful, otherwise a negative MPR error code.
  5256. @ingroup MprModule
  5257. @stability Stable
  5258. */
  5259. PUBLIC int mprLoadModule(MprModule *mp);
  5260. #if ME_COMPILER_HAS_DYN_LOAD || DOXYGEN
  5261. /**
  5262. Load a native module
  5263. @param mp Module object created via #mprCreateModule.
  5264. @returns Zero if successful, otherwise a negative MPR error code.
  5265. @ingroup MprModule
  5266. @stability Stable
  5267. */
  5268. PUBLIC int mprLoadNativeModule(MprModule *mp);
  5269. /**
  5270. Unload a native module
  5271. @description WARNING: modules must be designed to be unloaded and must be quiesced before unloading.
  5272. @param mp Module object created via #mprCreateModule.
  5273. @returns Zero if successful, otherwise a negative MPR error code.
  5274. @ingroup MprModule
  5275. @stability Stable
  5276. */
  5277. PUBLIC int mprUnloadNativeModule(MprModule *mp);
  5278. #endif
  5279. /**
  5280. Lookup a module
  5281. @description Lookup a module by name and return the module object.
  5282. @param name Name of the module specified to #mprCreateModule.
  5283. @returns A module object for this module created in the module entry point by calling #mprCreateModule
  5284. @ingroup MprModule
  5285. @stability Stable
  5286. */
  5287. PUBLIC MprModule *mprLookupModule(cchar *name);
  5288. /**
  5289. Lookup a module and return the module data
  5290. @description Lookup a module by name and return the module specific data defined via #mprCreateModule.
  5291. @param name Name of the module specified to #mprCreateModule.
  5292. @returns The module data.
  5293. @ingroup MprModule
  5294. @stability Stable
  5295. */
  5296. PUBLIC void *mprLookupModuleData(cchar *name);
  5297. /**
  5298. Search for a module on the current module path
  5299. @param module Name of the module to locate.
  5300. @return A string containing the full path to the module. Returns NULL if the module filename cannot be found.
  5301. @ingroup MprModule
  5302. @stability Stable
  5303. */
  5304. PUBLIC char *mprSearchForModule(cchar *module);
  5305. /**
  5306. Define a module finalizer that will be called before a module is stopped
  5307. @param module Module object to modify
  5308. @param stop Callback function to invoke before stopping the module
  5309. @ingroup MprModule
  5310. @stability Stable
  5311. */
  5312. PUBLIC void mprSetModuleFinalizer(MprModule *module, MprModuleProc stop);
  5313. /**
  5314. Set the module search path
  5315. @description Set the directory search path used by the MPR when loading dynamic modules. This path string must
  5316. should be a colon separated (or semicolon on Windows) set of directories.
  5317. @param searchPath Colon separated set of directories
  5318. @returns The module search path.
  5319. @ingroup MprModule
  5320. @stability Stable
  5321. */
  5322. PUBLIC void mprSetModuleSearchPath(char *searchPath);
  5323. /**
  5324. Set a module timeout
  5325. @param module Module object to modify
  5326. @param timeout Inactivity timeout in milliseconds before unloading the module
  5327. @ingroup MprModule
  5328. @stability Internal
  5329. @internal
  5330. */
  5331. PUBLIC void mprSetModuleTimeout(MprModule *module, MprTicks timeout);
  5332. /**
  5333. Start a module
  5334. @description Invoke the module start entry point. The start routine is only called once.
  5335. @param mp Module object returned via #mprLookupModule
  5336. @ingroup MprModule
  5337. @stability Internal
  5338. */
  5339. PUBLIC int mprStartModule(MprModule *mp);
  5340. /**
  5341. Stop a module
  5342. @description Invoke the module stop entry point. The stop routine is only called once.
  5343. @param mp Module object returned via #mprLookupModule
  5344. @ingroup MprModule
  5345. @stability Internal
  5346. */
  5347. PUBLIC int mprStopModule(MprModule *mp);
  5348. /**
  5349. Unload a module
  5350. @description Unload a module from the MPR. This will unload a dynamic shared object (shared library). This routine
  5351. is not fully supported by the MPR and is often fraught with issues. A module must usually be completely inactive
  5352. with no allocated memory when it is unloaded. USE WITH CARE.
  5353. @param mp Module object returned via #mprLookupModule
  5354. @return Zero if the module can be unloaded. Otherwise a negative MPR error code.
  5355. @ingroup MprModule
  5356. @stability Internal
  5357. */
  5358. PUBLIC int mprUnloadModule(MprModule *mp);
  5359. /********************************* Events *************************************/
  5360. /*
  5361. Flags for mprCreateEvent
  5362. */
  5363. #define MPR_EVENT_CONTINUOUS 0x1 /**< Timer event runs is automatically rescheduled */
  5364. #define MPR_EVENT_QUICK 0x2 /**< Execute inline without executing via a thread */
  5365. #define MPR_EVENT_DONT_QUEUE 0x4 /**< Don't queue the event. User must call mprQueueEvent */
  5366. #define MPR_EVENT_STATIC_DATA 0x8 /**< Event data is permanent and should not be marked by GC */
  5367. #define MPR_EVENT_ALWAYS 0x10 /**< Always invoke the callback even if the event not run */
  5368. #define MPR_EVENT_LOCAL 0x20 /**< Invoked from an MPR local thread */
  5369. #define MPR_EVENT_MAX_PERIOD (MAXINT64 / 2)
  5370. /**
  5371. Event callback function
  5372. @ingroup MprEvent
  5373. @stability Stable
  5374. */
  5375. typedef void (*MprEventProc)(void *data, struct MprEvent *event);
  5376. /**
  5377. Event object
  5378. @description The MPR provides a powerful priority based eventing mechanism. Events are described by MprEvent objects
  5379. which are created and queued via #mprCreateEvent. Each event may have a priority and may be one-shot or
  5380. be continuously rescheduled according to a specified period. The event subsystem provides the basis for
  5381. callback timers.
  5382. @see MprDispatcher MprEvent MprEventProc MprEventService mprCreateDispatcher mprCreateEvent mprCreateEventService
  5383. mprCreateTimerEvent mprDestroyDispatcher mprEnableContinuousEvent mprEnableDispatcher mprGetDispatcher
  5384. mprQueueEvent mprRemoveEvent mprRescheduleEvent mprRestartContinuousEvent mprServiceEvents
  5385. mprSignalDispatcher mprStopContinuousEvent mprWaitForEvent
  5386. @defgroup MprEvent MprEvent
  5387. @stability Internal
  5388. */
  5389. typedef struct MprEvent {
  5390. cchar *name; /**< Static debug name of the event */
  5391. MprEventProc proc; /**< Callback procedure */
  5392. MprTicks timestamp; /**< When was the event created */
  5393. MprTicks due; /**< When is the event due */
  5394. void *data; /**< Event private data (managed|unmanged depending on flags) */
  5395. void *sock; /**< Optional socket data */
  5396. int flags; /**< Event flags */
  5397. int mask; /**< I/O mask of events */
  5398. int hasRun; /**< Event has run */
  5399. MprTicks period; /**< Reschedule period */
  5400. struct MprEvent *next; /**< Next event linkage */
  5401. struct MprEvent *prev; /**< Previous event linkage */
  5402. struct MprDispatcher *dispatcher; /**< Event dispatcher service */
  5403. struct MprWaitHandler *handler; /**< Optional wait handler */
  5404. MprCond *cond; /**< Wait for event to complete */
  5405. } MprEvent;
  5406. /*
  5407. Dispatcher flags
  5408. */
  5409. #define MPR_DISPATCHER_IMMEDIATE 0x1 /**< Dispatcher should run using the service events thread */
  5410. #define MPR_DISPATCHER_WAITING 0x2 /**< Dispatcher waiting for an event in mprWaitForEvent */
  5411. #define MPR_DISPATCHER_DESTROYED 0x4 /**< Dispatcher has been destroyed */
  5412. #define MPR_DISPATCHER_AUTO 0x8 /**< Dispatcher was auto created in response to accept event */
  5413. #define MPR_DISPATCHER_COMPLETE 0x10 /**< Test operation is complete */
  5414. /**
  5415. Event Dispatcher
  5416. @defgroup MprDispatcher MprDispatcher
  5417. @stability Internal
  5418. */
  5419. typedef struct MprDispatcher {
  5420. cchar *name; /**< Static debug dispatcher name / purpose */
  5421. MprEvent *eventQ; /**< Event queue */
  5422. MprEvent *currentQ; /**< Currently executing event */
  5423. MprCond *cond; /**< Multi-thread sync */
  5424. int flags; /**< Dispatcher control flags */
  5425. int64 mark; /**< Last event sequence mark (may reuse over time) */
  5426. struct MprDispatcher *next; /**< Next dispatcher linkage */
  5427. struct MprDispatcher *prev; /**< Previous dispatcher linkage */
  5428. struct MprDispatcher *parent; /**< Queue pointer */
  5429. struct MprEventService *service; /**< Event service reference */
  5430. MprOsThread owner; /**< Thread currently dispatching events, otherwise zero */
  5431. } MprDispatcher;
  5432. /**
  5433. Event Service
  5434. @defgroup MprEvent MprEvent
  5435. @stability Internal
  5436. */
  5437. typedef struct MprEventService {
  5438. MprTicks now; /**< Current notion of system time for the dispatcher service */
  5439. MprTicks willAwake; /**< When the event service will next awake */
  5440. MprDispatcher *runQ; /**< Queue of running dispatchers */
  5441. MprDispatcher *readyQ; /**< Queue of dispatchers with events ready to run */
  5442. MprDispatcher *waitQ; /**< Queue of waiting (future) events */
  5443. MprDispatcher *idleQ; /**< Queue of idle dispatchers */
  5444. MprDispatcher *pendingQ; /**< Queue of pending dispatchers (waiting for resources) */
  5445. MprOsThread serviceThread; /**< Thread running the dispatcher service */
  5446. MprTicks delay; /**< Maximum sleep time before awaking */
  5447. int eventCount; /**< Count of events */
  5448. int waiting; /**< Waiting for I/O (sleeping) */
  5449. struct MprCond *waitCond; /**< Waiting sync */
  5450. struct MprMutex *mutex; /**< Multi-thread sync */
  5451. } MprEventService;
  5452. /**
  5453. Clear the event service waiting flag
  5454. @ingroup MprDispatcher
  5455. @stability Stable
  5456. @internal
  5457. */
  5458. PUBLIC void mprClearWaiting(void);
  5459. /**
  5460. Create a new event dispatcher.
  5461. @description Dispatchers are event queues that serialize the execution of work. Most of the MPR routines are not thread-safe and thus access to objects needs to be serialized by creating events to run on dispatchers. Resources such as connections will typically own a dispatcher that is used to serialize their work.
  5462. @param name Useful name for debugging
  5463. @param flags Dispatcher flags.
  5464. @returns a Dispatcher object that can manage events and be used with mprCreateEvent
  5465. @ingroup MprDispatcher
  5466. @stability Internal
  5467. */
  5468. PUBLIC MprDispatcher *mprCreateDispatcher(cchar *name, int flags);
  5469. /**
  5470. Disable a dispatcher from service events. This removes the dispatcher from any dispatcher queues and allows
  5471. it to be garbage collected.
  5472. @param dispatcher Dispatcher to disable.
  5473. @ingroup MprDispatcher
  5474. @stability Internal
  5475. */
  5476. PUBLIC void mprDestroyDispatcher(MprDispatcher *dispatcher);
  5477. /**
  5478. Get the MPR primary dispatcher
  5479. @returns the MPR dispatcher object
  5480. @ingroup MprDispatcher
  5481. @stability Internal
  5482. */
  5483. PUBLIC MprDispatcher *mprGetDispatcher(void);
  5484. /*
  5485. mprServiceEvents parameters
  5486. */
  5487. #define MPR_SERVICE_NO_BLOCK 0x4 /**< Do not block in mprServiceEvents */
  5488. #define MPR_SERVICE_NO_GC 0x8 /**< Don't run GC */
  5489. /**
  5490. Service events.
  5491. @description This call services events on all dispatchers and services I/O events.
  5492. An app should dedicate one and only one thread to be an event service thread. That thread should call mprServiceEvents
  5493. from the top-level.
  5494. \n\n
  5495. This call will service events until the timeout expires or if MPR_SERVICE_NO_BLOCK is specified in flags,
  5496. until there are no more events to service. This routine will also return if the MPR has been instructed to terminate and
  5497. is stopping. Calling mprServiceE
  5498. \n\n
  5499. Application event code that is running off a dispatcher should never call mprServiceEvents recursively. Rather, the
  5500. event code should call #mprWaitForEvent if it needs to wait while servicing events on its own dispatcher.
  5501. @param delay Time in milliseconds to wait. Set to zero for no wait. Set to -1 to wait forever.
  5502. @param flags If set to MPR_SERVICE_NO_BLOCK, this call will service all due events without blocking. Otherwise set
  5503. to zero.
  5504. @returns The number of events serviced. Returns MPR_ERR_BUSY is another thread is servicing events.
  5505. Returns when the MPR is stopping or if the timeout expires or if MPR_SERVICE_NO_BLOCK is specified and there are
  5506. no more events to service.
  5507. @ingroup MprDispatcher
  5508. @stability Stable
  5509. */
  5510. /*
  5511. Schedule events. An app should dedicate one thread to be an event service thread.
  5512. @param timeout Time in milliseconds to wait. Set to zero for no wait. Set to -1 to wait forever.
  5513. @param flags Set to MPR_SERVICE_NO_BLOCK for non-blocking.
  5514. @returns Number of events serviced.
  5515. */
  5516. PUBLIC int mprServiceEvents(MprTicks delay, int flags);
  5517. /**
  5518. Set the maximum sleep time for the event service
  5519. @param delay Maximum time to sleep before checking for events to service
  5520. @ingroup MprDispatcher
  5521. @stability Stable
  5522. */
  5523. PUBLIC void mprSetEventServiceSleep(MprTicks delay);
  5524. /**
  5525. Suspend the current thread
  5526. @description Suspend the current thread until the application is shutting down.
  5527. @param timeout Timeout to wait for shutdown.
  5528. @ingroup MprDispatcher
  5529. @stability Stable
  5530. */
  5531. PUBLIC void mprSuspendThread(MprTicks timeout);
  5532. /**
  5533. Wait for an event to occur on the given dispatcher
  5534. @description Use this routine to wait for an event and service the event on the given dispatcher.
  5535. This routine should only be called in blocking code.
  5536. \n\n
  5537. This routine yields to the garbage collector by calling #mprYield. Callers must retain all required memory.
  5538. \n\n
  5539. Note that an event may occur before or while invoking this API. To address this window of time, you should
  5540. call #mprGetEventMark to get a Dispatcher event mark and then test your application state to determine if
  5541. waiting is required. If so, then pass the mark to mprWaitForEvent so it can detect
  5542. if any events have been processed since calling mprGetEventMark.
  5543. @param dispatcher Event dispatcher to monitor
  5544. @param timeout for waiting in milliseconds
  5545. @param mark Dispatcher mark returned from #mprGetEventMark
  5546. @return Zero if successful and an event occurred before the timeout expired. Returns #MPR_ERR_TIMEOUT if no event
  5547. is fired before the timeout expires.
  5548. @ingroup MprDispatcher
  5549. @stability Stable
  5550. */
  5551. PUBLIC int mprWaitForEvent(MprDispatcher *dispatcher, MprTicks timeout, int64 mark);
  5552. /**
  5553. Get an event mark for a dispatcher
  5554. @description An event mark indicates a point in time for a dispatcher. Event marks are incremented for each
  5555. event serviced. This API is used with #mprWaitForEvent to supply an event mark so that mprWaitForEvent can
  5556. detect if any events have been serviced since the mark was taken. This is important so that mprWaitForEvent
  5557. will not miss events that occur before or while invoking #mprWaitForEvent.
  5558. @param dispatcher Event dispatcher
  5559. @return Event mark 64 bit integer
  5560. @ingroup MprDispatcher
  5561. @stability Stable
  5562. */
  5563. PUBLIC int64 mprGetEventMark(MprDispatcher *dispatcher);
  5564. /**
  5565. Wake the event service
  5566. @description Used to wake the event service if an event is queued for service.
  5567. @ingroup MprDispatcher
  5568. @stability Stable
  5569. */
  5570. PUBLIC void mprWakeEventService(void);
  5571. /**
  5572. Signal the dispatcher to wakeup and re-examine its queues
  5573. @param dispatcher Event dispatcher to monitor
  5574. @ingroup MprDispatcher
  5575. @stability Internal
  5576. @internal
  5577. */
  5578. PUBLIC void mprSignalDispatcher(MprDispatcher *dispatcher);
  5579. /**
  5580. Queue an new event on a dispatcher.
  5581. @description Create an event to run a callback on an event dispatcher queue.
  5582. The MPR serializes work in a thread-safe manner on dispatcher queues. Resources such as connections will typically
  5583. own a dispatcher that is used to serialize their work.
  5584. \n\n
  5585. This API may be called by foreign (non-mpr) threads and this routine is the only safe way to invoke MPR services from
  5586. a foreign-thread. The reason for this is that the MPR uses a cooperative garbage collector and a foreign thread
  5587. may call into the MPR at an inopportune time when the MPR is running the garbage collector which requires sole
  5588. access to application memory.
  5589. @param dispatcher Dispatcher object created via mprCreateDispatcher
  5590. Set to NULL for the MPR dispatcher. Use MPR_EVENT_QUICK in the flags to run the event on the events nonBlock
  5591. dispatcher. This should only be used for quick, non-block event callbacks. If using another dispatcher,
  5592. it is essential that the dispatcher not be destroyed while this event is queued or running.
  5593. @param name Static string name of the event used for debugging.
  5594. @param period Time in milliseconds used by continuous events between firing of the event.
  5595. @param proc Function to invoke when the event is run.
  5596. @param data Data to associate with the event and stored in event->data. The data must be either an allocated memory
  5597. object or MPR_EVENT_STATIC_DATA must be specified in flags.
  5598. @param flags Flags to modify the behavior of the event. Valid values are: MPR_EVENT_CONTINUOUS to create an event
  5599. which will be automatically rescheduled according to the specified period. Use MPR_EVENT_STATIC_DATA if the
  5600. data argument does not point to a memory object allocated by the Mpr. Include MPR_EVENT_QUICK to execute the event
  5601. without utilizing using a worker thread. This should only be used for quick non-blocking event callbacks.
  5602. \n\n
  5603. When calling this routine from foreign threads, you should use a NULL dispatcher or guarantee the dispatcher is held by
  5604. other means (difficult). Data supplied from foreign threads should generally be non-mpr memory and must persist until
  5605. the callback has completed. This typically means the data memory should either be static or be allocated using malloc()
  5606. before the call and released via free() in the callback. Static data should use the MPR_EVENT_STATIC_DATA flag.
  5607. Use the MPR_EVENT_ALWAYS_CALL to ensure your callback is always invoked even if the dispatcher is destroyed before the
  5608. event is run. In such cases, the callback "event" argument will be NULL to indicate the dispatcher has been destroyed.
  5609. Use this flag to free any allocated "data" memory in the callback. This may be important to prevent leaks.
  5610. \n\n
  5611. If using Appweb or the Http library, it is preferable to use the httpCreateEvent API when invoking callbacks on
  5612. HttpStreams.
  5613. @return Returns the event object. If called from a foreign thread, note that the event may have already run and the event object
  5614. may have been collected by the GC. May return NULL if the dispatcher has already been destroyed.
  5615. @ingroup MprEvent
  5616. @stability Evolving
  5617. */
  5618. PUBLIC MprEvent *mprCreateEvent(MprDispatcher *dispatcher, cchar *name, MprTicks period, void *proc, void *data, int flags);
  5619. /**
  5620. Optimized variety of mprCreateEvent for use by local MPR threads only
  5621. @param dispatcher Event dispatcher created via mprCreateDispatcher
  5622. @param name Static string name of the event used for debugging.
  5623. @param period Time in milliseconds used by continuous events between firing of the event.
  5624. @param proc Function to invoke when the event is run.
  5625. @param data Data to associate with the event. See #mprCreateEvent for details.
  5626. @param flags Flags. See #mprCreateEvent for details.
  5627. @see MprEvent MprWaitHandler mprCreateEvent mprCreateWaitHandler mprQueueIOEvent
  5628. @ingroup MprEvent
  5629. @stability Evolving
  5630. */
  5631. PUBLIC MprEvent *mprCreateLocalEvent(MprDispatcher *dispatcher, cchar *name, MprTicks period, void *proc, void *data, int flags);
  5632. /**
  5633. Create and queue an IO event for a wait handler
  5634. @param dispatcher Event dispatcher created via mprCreateDispatcher
  5635. @param proc Function to invoke when the event is run.
  5636. @param data Data to associate with the event. See #mprCreateEvent for details.
  5637. @param wp WaitHandler reference created via mprWaitHandler
  5638. @param sock Socket for the I/O event.
  5639. @see MprEvent MprWaitHandler mprCreateEvent mprCreateWaitHandler mprQueueIOEvent
  5640. @ingroup MprEvent
  5641. @stability Internal
  5642. */
  5643. PUBLIC void mprCreateIOEvent(MprDispatcher *dispatcher, void *proc, void *data, struct MprWaitHandler *wp, struct MprSocket *sock);
  5644. /**
  5645. Create a timer event
  5646. @description Create and queue a timer event for service. This is a convenience wrapper to create continuous
  5647. events over the #mprCreateEvent call.
  5648. @param dispatcher Dispatcher object created via #mprCreateDispatcher
  5649. @param name Debug name of the event
  5650. @param proc Function to invoke when the event is run
  5651. @param period Time in milliseconds used by continuous events between firing of the event.
  5652. @param data Data to associate with the event and stored in event->data.
  5653. @param flags Reserved. Must be set to zero.
  5654. @return Returns the event object.
  5655. @ingroup MprEvent
  5656. @stability Stable
  5657. */
  5658. PUBLIC MprEvent *mprCreateTimerEvent(MprDispatcher *dispatcher, cchar *name, MprTicks period, void *proc, void *data, int flags);
  5659. /*
  5660. Queue a new event for service.
  5661. @description Queue an event for service
  5662. @param dispatcher Dispatcher object created via mprCreateDispatcher
  5663. @param event Event object to queue
  5664. @ingroup MprEvent
  5665. @stability Stable
  5666. */
  5667. PUBLIC void mprQueueEvent(MprDispatcher *dispatcher, MprEvent *event);
  5668. /**
  5669. Remove an event
  5670. @description Remove a queued event. This is useful to remove continuous events from the event queue.
  5671. @param event Event object returned from #mprCreateEvent
  5672. @ingroup MprEvent
  5673. @stability Stable
  5674. */
  5675. PUBLIC void mprRemoveEvent(MprEvent *event);
  5676. /**
  5677. Stop an event
  5678. @description Stop a continuous event and remove from the queue.
  5679. @param event Event object returned from #mprCreateEvent
  5680. @ingroup MprEvent
  5681. @stability Stable
  5682. */
  5683. PUBLIC void mprStopContinuousEvent(MprEvent *event);
  5684. /**
  5685. Restart an event
  5686. @description Restart a continuous event after it has been stopped via #mprStopContinuousEvent. This call will
  5687. add the event to the event queue and it will run after the configured event period has expired.
  5688. @param event Event object returned from #mprCreateEvent
  5689. @ingroup MprEvent
  5690. @stability Stable
  5691. */
  5692. PUBLIC void mprRestartContinuousEvent(MprEvent *event);
  5693. /**
  5694. Enable or disable an event being continous
  5695. @description This call will modify the continuous property for an event.
  5696. @param event Event object returned from #mprCreateEvent
  5697. @param enable Set to 1 to enable continous scheduling of the event
  5698. @ingroup MprEvent
  5699. @stability Stable
  5700. */
  5701. PUBLIC void mprEnableContinuousEvent(MprEvent *event, int enable);
  5702. /**
  5703. Reschedule an event
  5704. @description Reschedule a continuous event by modifying its period.
  5705. @param event Event object returned from #mprCreateEvent
  5706. @param period Time in milliseconds used by continuous events between firing of the event.
  5707. @ingroup MprEvent
  5708. @stability Stable
  5709. */
  5710. PUBLIC void mprRescheduleEvent(MprEvent *event, MprTicks period);
  5711. /**
  5712. Start a dispatcher by setting it on the run queue
  5713. @description This is used to ensure that all event activity will only happen on the thread that
  5714. calls mprStartDispatcher.
  5715. @param dispatcher Dispatcher object created via #mprCreateDispatcher
  5716. @return Zero if successful, otherwise a negative MPR status code.
  5717. @stability Stable
  5718. @ingroup MprEvent
  5719. */
  5720. PUBLIC int mprStartDispatcher(MprDispatcher *dispatcher);
  5721. /**
  5722. Stop a dispatcher by removing it from the run queue
  5723. @param dispatcher Dispatcher object created via #mprCreateDispatcher
  5724. @return Zero if successful, otherwise a negative MPR status code.
  5725. @stability Stable
  5726. @ingroup MprEvent
  5727. */
  5728. PUBLIC int mprStopDispatcher(MprDispatcher *dispatcher);
  5729. /* Internal API */
  5730. PUBLIC MprEvent *mprCreateEventQueue(void);
  5731. PUBLIC MprEventService *mprCreateEventService(void);
  5732. PUBLIC void mprDedicateWorkerToDispatcher(MprDispatcher *dispatcher, struct MprWorker *worker);
  5733. PUBLIC void mprLinkEvent(MprEvent *prior, MprEvent *event);
  5734. PUBLIC void mprUnlinkEvent(MprEvent *event);
  5735. PUBLIC bool mprDispatcherHasEvents(MprDispatcher *dispatcher);
  5736. PUBLIC int mprDispatchersAreIdle(void);
  5737. PUBLIC int mprGetEventCount(MprDispatcher *dispatcher);
  5738. PUBLIC MprEvent *mprGetNextEvent(MprDispatcher *dispatcher);
  5739. PUBLIC MprDispatcher *mprGetNonBlockDispatcher(void);
  5740. PUBLIC void mprInitEventQ(MprEvent *q);
  5741. PUBLIC void mprQueueTimerEvent(MprDispatcher *dispatcher, MprEvent *event);
  5742. PUBLIC void mprReleaseWorkerFromDispatcher(MprDispatcher *dispatcher, struct MprWorker *worker);
  5743. PUBLIC void mprScheduleDispatcher(MprDispatcher *dispatcher);
  5744. PUBLIC void mprRescheduleDispatcher(MprDispatcher *dispatcher);
  5745. PUBLIC void mprSetDispatcherImmediate(MprDispatcher *dispatcher);
  5746. PUBLIC void mprStopEventService(void);
  5747. PUBLIC void mprWakeDispatchers(void);
  5748. PUBLIC void mprWakePendingDispatchers(void);
  5749. /*
  5750. Used in testme scripts
  5751. */
  5752. PUBLIC void mprSignalCompletion(MprDispatcher *dispatcher);
  5753. PUBLIC bool mprWaitForCompletion(MprDispatcher *dispatcher, MprTicks timeout);
  5754. /*********************************** XML **************************************/
  5755. /*
  5756. XML parser states. The states that are passed to the user handler have "U" appended to the comment.
  5757. The error states (ERR and EOF) must be negative.
  5758. */
  5759. #define MPR_XML_ERR -1 /**< Error */
  5760. #define MPR_XML_EOF -2 /**< End of input */
  5761. #define MPR_XML_BEGIN 1 /**< Before next tag */
  5762. #define MPR_XML_AFTER_LS 2 /**< Seen "<" */
  5763. #define MPR_XML_COMMENT 3 /**< Seen "<!--" (usr) U */
  5764. #define MPR_XML_NEW_ELT 4 /**< Seen "<tag" (usr) U */
  5765. #define MPR_XML_ATT_NAME 5 /**< Seen "<tag att" */
  5766. #define MPR_XML_ATT_EQ 6 /**< Seen "<tag att" = */
  5767. #define MPR_XML_NEW_ATT 7 /**< Seen "<tag att = "val" U */
  5768. #define MPR_XML_SOLO_ELT_DEFINED 8 /**< Seen "<tag../>" U */
  5769. #define MPR_XML_ELT_DEFINED 9 /**< Seen "<tag...>" U */
  5770. #define MPR_XML_ELT_DATA 10 /**< Seen "<tag>....<" U */
  5771. #define MPR_XML_END_ELT 11 /**< Seen "<tag>....</tag>" U */
  5772. #define MPR_XML_PI 12 /**< Seen "<?processingInst" U */
  5773. #define MPR_XML_CDATA 13 /**< Seen "<![CDATA[" U */
  5774. /*
  5775. Lex tokens
  5776. */
  5777. typedef enum MprXmlToken {
  5778. MPR_XMLTOK_ERR,
  5779. MPR_XMLTOK_TOO_BIG, /* Token is too big */
  5780. MPR_XMLTOK_CDATA,
  5781. MPR_XMLTOK_COMMENT,
  5782. MPR_XMLTOK_INSTRUCTIONS,
  5783. MPR_XMLTOK_LS, /* "<" -- Opening a tag */
  5784. MPR_XMLTOK_LS_SLASH, /* "</" -- Closing a tag */
  5785. MPR_XMLTOK_GR, /* ">" -- End of an open tag */
  5786. MPR_XMLTOK_SLASH_GR, /* "/>" -- End of a solo tag */
  5787. MPR_XMLTOK_TEXT,
  5788. MPR_XMLTOK_EQ,
  5789. MPR_XMLTOK_EOF,
  5790. MPR_XMLTOK_SPACE
  5791. } MprXmlToken;
  5792. /**
  5793. XML callback handler
  5794. @param xp XML instance reference
  5795. @param state XML state
  5796. @param tagName Current XML tag
  5797. @param attName Current XML attribute
  5798. @param value Current XML element value
  5799. @ingroup MprXml
  5800. @stability Stable
  5801. */
  5802. typedef int (*MprXmlHandler)(struct MprXml *xp, int state, cchar *tagName, cchar* attName, cchar* value);
  5803. /**
  5804. XML input stream function
  5805. @param xp XML instance reference
  5806. @param arg to input stream
  5807. @param buf Buffer into which to read data
  5808. @param size Size of buf
  5809. @stability Stable
  5810. */
  5811. typedef ssize (*MprXmlInputStream)(struct MprXml *xp, void *arg, char *buf, ssize size);
  5812. /**
  5813. Per XML session structure
  5814. @defgroup MprXml MprXml
  5815. @see MprXml MprXmlHandler MprXmlInputStream mprXmlGetErrorMsg mprXmlGetLineNumber mprXmlGetParseArg mprXmlOpen
  5816. mprXmlParse mprXmlSetInputStraem mprXmlSetParseArg mprXmlSetParseHandler
  5817. @stability Internal
  5818. */
  5819. typedef struct MprXml {
  5820. MprXmlHandler handler; /**< Callback function */
  5821. MprXmlInputStream readFn; /**< Read data function */
  5822. MprBuf *inBuf; /**< Input data queue */
  5823. MprBuf *tokBuf; /**< Parsed token buffer */
  5824. int quoteChar; /**< XdbAtt quote char */
  5825. int lineNumber; /**< Current line no for debug */
  5826. void *parseArg; /**< Arg passed to mprXmlParse() */
  5827. void *inputArg; /**< Arg for mprXmlSetInputStream() */
  5828. char *errMsg; /**< Error message text */
  5829. } MprXml;
  5830. /**
  5831. Get the XML error message if mprXmlParse fails
  5832. @param xp XML parser instance returned from mprXmlOpen
  5833. @return A descriptive null-terminated string
  5834. @ingroup MprXml
  5835. @stability Stable
  5836. */
  5837. PUBLIC cchar *mprXmlGetErrorMsg(MprXml *xp);
  5838. /**
  5839. Get the source XML line number.
  5840. @description This call can be used from within the parser callback or when mprXmlParse fails.
  5841. @param xp XML parser instance returned from mprXmlOpen
  5842. @return The line number for the current token or error.
  5843. @ingroup MprXml
  5844. @stability Stable
  5845. */
  5846. PUBLIC int mprXmlGetLineNumber(MprXml *xp);
  5847. /**
  5848. Get the XML callback argument
  5849. @param xp XML parser instance returned from mprXmlOpen
  5850. @return Argument defined to use for the callback
  5851. @ingroup MprXml
  5852. @stability Stable
  5853. */
  5854. PUBLIC void *mprXmlGetParseArg(MprXml *xp);
  5855. /**
  5856. Open an XML parser instance.
  5857. @param initialSize Initialize size of XML in-memory token buffer
  5858. @param maxSize Maximum size of XML in-memory token buffer. Set to -1 unlimited.
  5859. @return An XML parser instance
  5860. @ingroup MprXml
  5861. @stability Stable
  5862. */
  5863. PUBLIC MprXml *mprXmlOpen(ssize initialSize, ssize maxSize);
  5864. /**
  5865. Run the XML parser
  5866. @param xp XML parser instance returned from mprXmlOpen
  5867. @return Zero if successful. Otherwise returns a negative MPR error code.
  5868. @ingroup MprXml
  5869. @stability Stable
  5870. */
  5871. PUBLIC int mprXmlParse(MprXml *xp);
  5872. /**
  5873. Define the XML parser input stream. This
  5874. @param xp XML parser instance returned from mprXmlOpen
  5875. @param fn Callback function to provide data to the XML parser. The callback is invoked with the signature:
  5876. ssize callbac(MprXml *xp, void *arg, char *buf, ssize size);
  5877. @param arg Callback argument to pass to the
  5878. @ingroup MprXml
  5879. @stability Stable
  5880. */
  5881. PUBLIC void mprXmlSetInputStream(MprXml *xp, MprXmlInputStream fn, void *arg);
  5882. /**
  5883. Set the XML callback argument
  5884. @param xp XML parser instance returned from mprXmlOpen
  5885. @param parseArg Argument to use for the callback
  5886. @ingroup MprXml
  5887. @stability Stable
  5888. */
  5889. PUBLIC void mprXmlSetParseArg(MprXml *xp, void *parseArg);
  5890. /**
  5891. Set the XML parser data handle
  5892. @param xp XML parser instance returned from mprXmlOpen
  5893. @param h Arbitrary data to associate with the parser
  5894. @ingroup MprXml
  5895. @stability Stable
  5896. */
  5897. PUBLIC void mprXmlSetParserHandler(MprXml *xp, MprXmlHandler h);
  5898. /******************************** JSON ****************************************/
  5899. /*
  5900. Flags for mprJsonToString
  5901. */
  5902. #define MPR_JSON_PRETTY 0x1 /**< Serialize output in a more human readable, multiline "pretty" format */
  5903. #define MPR_JSON_QUOTES 0x2 /**< Serialize output quoting keys */
  5904. #define MPR_JSON_STRINGS 0x4 /**< Emit all values as quoted strings */
  5905. #define MPR_JSON_ENCODE_TYPES 0x8 /**< Encode dates and regexp with {type:date} or {type:regexp} */
  5906. /*
  5907. Data types for obj property values
  5908. */
  5909. #define MPR_JSON_OBJ 0x1 /**< The property is an object */
  5910. #define MPR_JSON_ARRAY 0x2 /**< The property is an array */
  5911. #define MPR_JSON_VALUE 0x4 /**< The property is a value (false|true|null|undefined|regexp|number|string) */
  5912. #define MPR_JSON_FALSE 0x8 /**< The property is false. MPR_JSON_VALUE also set. */
  5913. #define MPR_JSON_NULL 0x10 /**< The property is null. MPR_JSON_VALUE also set. */
  5914. #define MPR_JSON_NUMBER 0x20 /**< The property is a number. MPR_JSON_VALUE also set. */
  5915. #define MPR_JSON_REGEXP 0x40 /**< The property is a regular expression. MPR_JSON_VALUE also set. */
  5916. #define MPR_JSON_STRING 0x80 /**< The property is a string. MPR_JSON_VALUE also set. */
  5917. #define MPR_JSON_TRUE 0x100 /**< The property is true. MPR_JSON_VALUE also set. */
  5918. #define MPR_JSON_UNDEFINED 0x200 /**< The property is undefined. MPR_JSON_VALUE also set. */
  5919. #define MPR_JSON_OBJ_TYPE 0x7 /**< Mask for core type of obj (obj|array|value) */
  5920. #define MPR_JSON_DATA_TYPE 0xFF8 /**< Mask for core type of obj (obj|array|value) */
  5921. #define MPR_JSON_STATE_EOF 1 /* End of input */
  5922. #define MPR_JSON_STATE_ERR 2 /* Some parse error */
  5923. #define MPR_JSON_STATE_NAME 3 /* Expecting a name: */
  5924. #define MPR_JSON_STATE_VALUE 4 /* Expecting a value */
  5925. #define ITERATE_JSON(obj, child, index) \
  5926. index = 0, child = obj ? obj->children: 0; obj && child && index < obj->length; child = child->next, index++
  5927. /**
  5928. JSON Object
  5929. @defgroup MprJson MprJson
  5930. @stability Evolving
  5931. @see mprBlendJson mprGetJsonObj mprGetJson mprGetJsonLength mprLoadJson mprParseJson mprSetJsonError
  5932. mprParseJsonEx mprParseJsonInto mprQueryJson mprRemoveJson mprSetJsonObj mprSetJson mprJsonToString mprLogJson
  5933. mprReadJson mprWriteJsonObj mprWriteJson mprWriteJsonObj
  5934. */
  5935. typedef struct MprJson {
  5936. cchar *name; /**< Property name for this object */
  5937. cchar *value; /**< Property value - always strings */
  5938. int type; /**< Property type. Object, Array or value */
  5939. int length; /**< Number of child properties */
  5940. struct MprJson *next; /**< Next sibling */
  5941. struct MprJson *prev; /**< Previous sibling */
  5942. struct MprJson *children; /**< Children properties */
  5943. } MprJson;
  5944. /**
  5945. JSON parsing callbacks
  5946. @ingroup MprJson
  5947. @stability Internal
  5948. */
  5949. typedef struct MprJsonCallback {
  5950. /**
  5951. Check state callback for JSON deserialization. This function is called at the entry and exit of object levels
  5952. for arrays and objects.
  5953. */
  5954. int (*checkBlock)(struct MprJsonParser *parser, cchar *name, bool leave);
  5955. /**
  5956. MakeObject callback for JSON deserialization. This function is called to construct an object for each level
  5957. in the object tree. Objects will be either arrays or objects.
  5958. */
  5959. MprJson *(*createObj)(struct MprJsonParser *parser, int type);
  5960. /**
  5961. Handle a parse error. This function is called from mprSetJsonError to handle error reporting.
  5962. */
  5963. void (*parseError)(struct MprJsonParser *parser, cchar *msg);
  5964. /**
  5965. Set a property value in an object.
  5966. */
  5967. int (*setValue)(struct MprJsonParser *parser, MprJson *obj, cchar *name, MprJson *child);
  5968. /**
  5969. Pattern matching callback
  5970. */
  5971. bool (*match)(struct MprJsonParser *parser, cchar *str, cchar *pattern);
  5972. } MprJsonCallback;
  5973. /**
  5974. JSON parser
  5975. @ingroup MprJson
  5976. @stability Internal
  5977. */
  5978. typedef struct MprJsonParser {
  5979. cchar *input; /* Current input (unmanaged) */
  5980. cchar *token; /* Current parse token */
  5981. cchar *putback; /* Putback parse token */
  5982. cchar *errorMsg; /* Parse error message */
  5983. void *data; /* Custom data handle (unmanaged) */
  5984. cchar *path; /* Optional JSON filename */
  5985. MprBuf *buf; /* Token buffer */
  5986. MprJsonCallback callback; /* JSON parser callbacks */
  5987. int tokid; /* Current tokend ID */
  5988. int type; /* Extra type information */
  5989. int putid; /* Putback token id */
  5990. int lineNumber; /* Current line number in path */
  5991. int state; /* Parse state */
  5992. int tolerant; /* Tolerant parsing: unquoted names, comma before last property of object */
  5993. } MprJsonParser;
  5994. /*
  5995. Flags for mprBlendJson
  5996. */
  5997. #define MPR_JSON_COMBINE 0x1 /**< Combine properties using '+' '-' '=' '?' prefixes */
  5998. #define MPR_JSON_OVERWRITE 0x2 /**< Default to overwrite existing properties '=' */
  5999. #define MPR_JSON_APPEND 0x4 /**< Default to append to existing '+' (default) */
  6000. #define MPR_JSON_REPLACE 0x8 /**< Replace existing properties '-' */
  6001. #define MPR_JSON_CREATE 0x10 /**< Create if not already existing '?' */
  6002. /**
  6003. Blend two JSON objects
  6004. @description This performs an N-level deep clone of the source JSON object to be blended into the destination object.
  6005. By default, this add new object properties and overwrite arrays and string values.
  6006. The property combination prefixes: '+', '=', '-' and '?' to append, overwrite, replace and
  6007. conditionally overwrite are supported if the MPR_JSON_COMBINE flag is present.
  6008. @param dest Parsed JSON object. This is the destination object. The "src" object will be blended into this object.
  6009. @param src Source JSON object to blend into dest. Parsed JSON object returned by mprJsonParser.
  6010. @param flags The MPR_JSON_COMBINE flag enables property name prefixes: '+', '=', '-', '?' to append, overwrite,
  6011. replace and and conditionally overwrite key values if not already present. When adding string properties, values
  6012. will be appended using a space separator. Extra spaces will not be removed on replacement.
  6013. \n\n
  6014. Without MPR_JSON_COMBINE or for properties without a prefix, the default is to blend objects by creating new
  6015. properties if not already existing in the destination, and to treat overwrite arrays and strings.
  6016. Use the MPR_JSON_OVERWRITE flag to override the default appending of objects and rather overwrite existing
  6017. properties. Use the MPR_JSON_APPEND flag to override the default of overwriting arrays and strings and rather
  6018. append to existing properties.
  6019. @return Zero if successful.
  6020. @ingroup MprJson
  6021. @stability Stable
  6022. */
  6023. PUBLIC int mprBlendJson(MprJson *dest, MprJson *src, int flags);
  6024. /**
  6025. Clone a JSON object
  6026. @description This does a deep copy of a JSON object tree. This copies all properties and their sub-properties.
  6027. @return A new JSON object that replices the input object.
  6028. @ingroup MprJson
  6029. @stability Stable
  6030. */
  6031. PUBLIC MprJson *mprCloneJson(MprJson *obj);
  6032. /**
  6033. Create a JSON object
  6034. @param type Set JSON object type to MPR_JSON_OBJ for an object, MPR_JSON_ARRAY for an array or MPR_JSON_VALUE
  6035. for a value. Note: all values are stored as strings.
  6036. Additional type information may be ored into the type for: MPR_JSON_NUMBER, MPR_JSON_TRUE, MPR_JSON_FALSE,
  6037. MPR_JSON_NULL, MPR_JSON_UNDEFINED.
  6038. @return JSON object
  6039. @ingroup MprJson
  6040. @stability Stable
  6041. */
  6042. PUBLIC MprJson *mprCreateJson(int type);
  6043. /**
  6044. Create a JSON object value
  6045. @param value String value of the json object.
  6046. @param type Set JSON object type to MPR_JSON_OBJ for an object, MPR_JSON_ARRAY for an array or MPR_JSON_VALUE
  6047. for a value. Note: all values are stored as strings.
  6048. Additional type information may be ored into the type for: MPR_JSON_NUMBER, MPR_JSON_TRUE, MPR_JSON_FALSE,
  6049. MPR_JSON_NULL, MPR_JSON_UNDEFINED.
  6050. @return JSON object
  6051. @ingroup MprJson
  6052. @stability Stable
  6053. */
  6054. PUBLIC MprJson *mprCreateJsonValue(cchar *value, int type);
  6055. /**
  6056. Deserialize a simple JSON string and return a hash of properties
  6057. @param str JSON string. This must be an object with one-level of properties
  6058. @return Hash of property values if successful, otherwise null.
  6059. @ingroup MprJson
  6060. @stability Stable
  6061. */
  6062. PUBLIC MprHash *mprDeserialize(cchar *str);
  6063. /**
  6064. Deserialize a simple JSON string into the given hash object
  6065. @param str JSON string. This must be an object with one-level of properties
  6066. @param hash Destination MprHash object
  6067. @return The supplied hash if successful. Otherwise null is returned.
  6068. @ingroup MprJson
  6069. @stability Stable
  6070. */
  6071. PUBLIC MprHash *mprDeserializeInto(cchar *str, MprHash *hash);
  6072. /**
  6073. Format a JSON name into and output buffer. This handles quotes and backquotes.
  6074. @param buf MprBuf instance to store the output string
  6075. @param name Json name to format
  6076. @param flags Serialization flags. Supported flags include MPR_JSON_QUOTES to always wrap property names in quotes.
  6077. @return The supplied hash if successful. Otherwise null is returned.
  6078. @ingroup MprJson
  6079. @stability Stable
  6080. */
  6081. PUBLIC void mprFormatJsonName(MprBuf *buf, cchar *name, int flags);
  6082. /**
  6083. Format a string as a JSON string. This handles quotes and backquotes.
  6084. @param buf MprBuf instance to store the output string
  6085. @param value JSON string value to format
  6086. @return The supplied hash if successful. Otherwise null is returned.
  6087. @ingroup MprJson
  6088. @stability Stable
  6089. */
  6090. PUBLIC void mprFormatJsonString(MprBuf *buf, cchar *value);
  6091. /**
  6092. Format a value as a simple JSON string. This converts any JSON value to a string representation.
  6093. @param buf MprBuf instance to store the output string
  6094. @param type JSON type to format
  6095. @param value JSON value to format
  6096. @param flags Serialization flags. Supported flags include MPR_JSON_STRINGS to emit values as quoted strings.
  6097. @return The supplied hash if successful. Otherwise null is returned.
  6098. @ingroup MprJson
  6099. @stability Stable
  6100. */
  6101. PUBLIC void mprFormatJsonValue(MprBuf *buf, int type, cchar *value, int flags);
  6102. /**
  6103. Get a parsed JSON object for a key value
  6104. @param obj Parsed JSON object returned by mprJsonParser
  6105. @param key Property name to search for. This may include ".". For example: "settings.mode".
  6106. See #mprQueryJson for a full description of key formats.
  6107. @return Returns the property value as an object, otherwise NULL if not found or not the correct type.
  6108. @ingroup MprJson
  6109. @stability Stable
  6110. */
  6111. PUBLIC MprJson *mprGetJsonObj(MprJson *obj, cchar *key);
  6112. /**
  6113. Get a JSON key and return a string value.
  6114. @description This routine is useful to querying JSON property or object values.
  6115. If the supplied key is an array or object, or matches more than one property, the
  6116. result is a string representation of the array or object.
  6117. @param obj Parsed JSON object returned by mprParseJson
  6118. @param key Property name to search for. This may include ".". For example: "settings.mode".
  6119. See #mprQueryJson for a full description of key formats.
  6120. @return A string representation of the selected properties. If a single property is selected and its
  6121. value is a string, that is returned. If the selected property is an array or object, or it
  6122. matches more than one property, the result is a JSON string representation.
  6123. If nothing is matched, null is returned.
  6124. @ingroup MprJson
  6125. @stability Stable
  6126. */
  6127. PUBLIC cchar *mprGetJson(MprJson *obj, cchar *key);
  6128. /**
  6129. Get the number of child properties in a JSON object
  6130. @param obj Parsed JSON object returned by mprParseJson
  6131. @return The number of direct dependent child properties
  6132. @ingroup MprJson
  6133. @stability Stable
  6134. */
  6135. PUBLIC ssize mprGetJsonLength(MprJson *obj);
  6136. /**
  6137. Convert a hash object into a JSON object
  6138. @param hash MprHash object
  6139. @return An MprJson instance
  6140. @ingroup MprJson
  6141. @stability Stable
  6142. */
  6143. PUBLIC MprJson *mprHashToJson(MprHash *hash);
  6144. /**
  6145. Convert a JSON object to a string of environment variables
  6146. @param json JSON object tree
  6147. @param prefix String prefix for environment substrings
  6148. @param list MprList to hold environment strings. Set to NULL and this routine will create a list.
  6149. @return A list of environment strings
  6150. @ingroup MprJson
  6151. @stability Evolving
  6152. */
  6153. PUBLIC MprList *mprJsonToEnv(MprJson *json, cchar *prefix, MprList *list);
  6154. /**
  6155. Convert a JSON object into a Hash object
  6156. @param json JSON object tree
  6157. @return An MprHash instance
  6158. @ingroup MprJson
  6159. @stability Stable
  6160. */
  6161. PUBLIC MprHash *mprJsonToHash(MprJson *json);
  6162. /**
  6163. Serialize a JSON object into a string
  6164. @description Serializes a top level JSON object created via mprParseJson into a characters string in JSON format.
  6165. @param obj Object returned via #mprParseJson
  6166. @param flags Serialization flags. Supported flags include MPR_JSON_PRETTY for a human-readable multiline format.
  6167. MPR_JSON_QUOTES to wrap property names in quotes. Use MPR_JSON_STRINGS to emit all property values as quoted strings.
  6168. @return Returns a serialized JSON character string.
  6169. @ingroup MprJson
  6170. @stability Stable
  6171. */
  6172. PUBLIC char *mprJsonToString(MprJson *obj, int flags);
  6173. /**
  6174. Load a JSON object from a filename
  6175. @param path Filename path containing a JSON string to load
  6176. @return JSON object tree
  6177. @ingroup MprJson
  6178. @stability Stable
  6179. */
  6180. PUBLIC MprJson *mprLoadJson(cchar *path);
  6181. /**
  6182. Trace the JSON object to the debug log
  6183. @param level Debug trace level
  6184. @param obj Object to trace
  6185. @param fmt Printf style format and args
  6186. @ingroup MprJson
  6187. @stability Stable
  6188. */
  6189. PUBLIC void mprLogJson(int level, MprJson *obj, cchar *fmt, ...) PRINTF_ATTRIBUTE(3,4);
  6190. /**
  6191. Parse a JSON string into an object tree.
  6192. @description Deserializes a JSON string created into an object.
  6193. The top level of the JSON string must be an object, array, string, number or boolean value.
  6194. @param str JSON string to deserialize.
  6195. @return Returns a tree of MprJson objects. Each object represents a level in the JSON input stream.
  6196. @ingroup MprJson
  6197. @stability Stable
  6198. */
  6199. PUBLIC MprJson *mprParseJson(cchar *str);
  6200. /**
  6201. Extended JSON parsing from a JSON string into an object tree.
  6202. @description Parses a string into a tree of JSON objects
  6203. This extended deserialization API takes callback functions to control how the object tree is constructed.
  6204. The top level of the JSON string must be an object, array, string, number or boolean value.
  6205. @param str JSON string to deserialize. This is an unmanaged reference. i.e. it will not be marked by the garbage
  6206. collector.
  6207. @param callback Callback functions. This is an instance of the #MprJsonCallback structure.
  6208. @param data Opaque object to pass to the given callbacks. This is an unmanaged reference.
  6209. @param obj Optional object to serialize into.
  6210. @param errorMsg Error message if the string fails to parse.
  6211. @return Returns JSON object tree.
  6212. @ingroup MprJson
  6213. @stability Internal
  6214. @internal
  6215. */
  6216. PUBLIC MprJson *mprParseJsonEx(cchar *str, MprJsonCallback *callback, void *data, MprJson *obj, cchar **errorMsg);
  6217. /**
  6218. Parse a JSON string into an existing object
  6219. @description Deserializes a JSON string created into an object.
  6220. The top level of the JSON string must be an object, array, string, number or boolean value.
  6221. @param str JSON string to deserialize.
  6222. @param obj JSON object to store parsed properties from str.
  6223. @return Returns the object passed in via "obj". This permits chaining.
  6224. @ingroup MprJson
  6225. @stability Stable
  6226. */
  6227. PUBLIC MprJson *mprParseJsonInto(cchar *str, MprJson *obj);
  6228. /**
  6229. Query a JSON object for a property key path and execute the given command.
  6230. @description This query API may be used to get, set or remove property values described by a JSON query key.
  6231. @param obj JSON object to examine. This may be a JSON object, array or string.
  6232. @param key The property key may be a multipart property and may include
  6233. . [] and .. substrings. For example: "settings.mode", "colors[2]", "colors[2:4] and "users..name".
  6234. The "." and "[]" operator reference sub-properties. The ".." elipsis operator spans zero or more
  6235. objects levels.
  6236. \n\n
  6237. Inside the [] operator, you may include an expression to select objects that match the given
  6238. expression. The expression is of the form:
  6239. \n\n
  6240. NAME OP value
  6241. \n\n
  6242. where NAME is the name of the property, OP is ==, !=, <=, >=, ~ or !~. The "~" operator is simple
  6243. string pattern match (contains). Note that [expressions] look ahead and select array elements that have
  6244. matching properties.
  6245. \n\n
  6246. For arrays, to compare the array contents value iself, use "@". This is useful
  6247. to select by array element values. For example: colors[@ == 'red'].
  6248. Use "$" to append an element to an array.
  6249. \n\n
  6250. Examples:
  6251. \n\n
  6252. <pre>
  6253. user.name
  6254. user['name']
  6255. users[2]
  6256. users[2:4]
  6257. users[-4:-1] // Range from end of array
  6258. users[name == 'john']
  6259. users[age >= 50]
  6260. users[phone ~ ^206] // Starts with 206
  6261. users[$] // Append a new element
  6262. colors[@ != 'red'] // Array element not 'red'
  6263. people..[name == 'john'] // Elipsis descends down multiple levels
  6264. </pre>
  6265. @param value If a value is provided, the property described by the key is set to the value.
  6266. If getting property values, or removing, set to NULL.
  6267. @param type Value data type used when setting a value. Set to MPR_JSON_FALSE, MPR_JSON_NULL, MPR_JSON_NUMBER,
  6268. MPR_JSON_STRING, MPR_JSON_TRUE, MPR_JSON_UNDEFINED. Set to zero to sleuth the data type based on the supplied
  6269. value. Note: if the type is zero, numeric values will be set to MPR_JSON_NUMBER and "true", "false", "null"
  6270. and "undefined" will have the corresponding data types.
  6271. @return If getting properties, the selected properties are cloned and returned in a JSON array.
  6272. Note: these are not references into the original properties. If the requested properties are not found
  6273. an empty array is returned. If removing properties, the selected properties are removed and returned
  6274. in the result array without cloning. If the properties to be removed cannot be resolved, null is returned.
  6275. If setting properties, the original object is returned if the properties can be successfully defined. Otherwise,
  6276. null is returned.
  6277. @ingroup MprJson
  6278. @stability Evolving
  6279. */
  6280. PUBLIC MprJson *mprQueryJson(MprJson *obj, cchar *key, cchar *value, int type);
  6281. /**
  6282. Read a JSON object
  6283. @description This is a low-level simple JSON property lookup routine. This does a one-level property lookup and
  6284. returns the actual JSON object and not a clone. Be careful with this API. Objects returned by this API cannot be
  6285. modified or inserted into another JSON object without corrupting the original JSON object. Use #mprQueryJson or
  6286. mprGetJson to lookup properties and return a clone of the object.
  6287. @param obj Parsed JSON object returned by mprParseJson
  6288. @param name Name of the property to lookup.
  6289. @return The matching JSON object. Returns NULL if a matching property is not found.
  6290. Note this is a reference to the actaul JSON object and not a clone of the object.
  6291. @ingroup MprJson
  6292. @stability Evolving
  6293. */
  6294. PUBLIC MprJson *mprReadJsonObj(MprJson *obj, cchar *name);
  6295. /**
  6296. Read a JSON property
  6297. @description This is a low-level simple JSON property lookup routine. It does a one-level property lookup.
  6298. Use #mprQueryJson or mprGetJson to lookup properties that are not direct properties at the top level of
  6299. the given object i.e. those that contain ".".
  6300. @param obj Parsed JSON object returned by mprParseJson
  6301. @param name Name of the property to lookup.
  6302. @return The property value as a string. Returns NULL if a matching property is not found.
  6303. Note this is a reference to the actaul JSON property value and not a clone of the value.
  6304. @ingroup MprJson
  6305. @stability Evolving
  6306. */
  6307. PUBLIC cchar *mprReadJson(MprJson *obj, cchar *name);
  6308. /**
  6309. Read a JSON object by value
  6310. @description This is a low-level simple JSON property lookup routine that searches for a property in the JSON object
  6311. by value. It does a one-level property lookup. Use #mprQueryJson or mprGetJson to lookup properties that are not
  6312. direct properties at the top level of the given object i.e. those that contain ".".
  6313. @param obj Parsed JSON object returned by mprParseJson
  6314. @param value Value to search for.
  6315. @return The JSON object or null if not found.
  6316. @ingroup MprJson
  6317. @stability Evolving
  6318. */
  6319. PUBLIC MprJson *mprReadJsonValue(MprJson *obj, cchar *value);
  6320. /**
  6321. Remove a property from a JSON object
  6322. @param obj Parsed JSON object returned by mprParseJson
  6323. @param key Property name to remove for. This may include ".". For example: "settings.mode".
  6324. See #mprQueryJson for a full description of key formats.
  6325. @return Returns a JSON object array of all removed properties. Array will be empty if not qualifying
  6326. properties were found and removed.
  6327. @ingroup MprJson
  6328. @stability Stable
  6329. */
  6330. PUBLIC MprJson *mprRemoveJson(MprJson *obj, cchar *key);
  6331. /**
  6332. Remove a child from a JSON object
  6333. WARNING: do not call this API when traversing the object in question using ITERATE_JSON.
  6334. @param obj Parsed JSON object returned by mprParseJson
  6335. @param child JSON child to remove
  6336. @return The removed child element.
  6337. @ingroup MprJson
  6338. @stability Evolving
  6339. */
  6340. PUBLIC MprJson *mprRemoveJsonChild(MprJson *obj, MprJson *child);
  6341. /**
  6342. Save a JSON object to a filename
  6343. @param obj Parsed JSON object returned by mprParseJson
  6344. @param path Filename path to contain the saved JSON string
  6345. @param flags Same flags as for #mprJsonToString: MPR_JSON_PRETTY, MPR_JSON_QUOTES, MPR_JSON_STRINGS.
  6346. @return Zero if successful, otherwise a negative MPR error code.
  6347. @ingroup MprJson
  6348. @stability Stable
  6349. */
  6350. PUBLIC int mprSaveJson(MprJson *obj, cchar *path, int flags);
  6351. /**
  6352. Serialize a hash of properties as a JSON string
  6353. @param hash Hash of properties to examine
  6354. @param flags Serialization flags. Supported flags include MPR_JSON_PRETTY for a human-readable multiline format.
  6355. MPR_JSON_QUOTES to wrap property names in quotes. Use MPR_JSON_STRINGS to emit all property values as quoted strings.
  6356. @return JSON string
  6357. @ingroup MprJson
  6358. @stability Stable
  6359. */
  6360. PUBLIC char *mprSerialize(MprHash *hash, int flags);
  6361. /**
  6362. Signal a parse error in the JSON input stream.
  6363. @description JSON callback functions will invoke mprSetJsonError when JSON parse or data semantic errors are
  6364. encountered. This routine may be called by the user JSON parse callback to emit a custom parse error notification.
  6365. @param jp JSON control structure
  6366. @param fmt Printf style format string
  6367. @param ... Printf arguments
  6368. @ingroup MprJson
  6369. @stability Evolving
  6370. */
  6371. PUBLIC void mprSetJsonError(MprJsonParser *jp, cchar *fmt, ...) PRINTF_ATTRIBUTE(2,3);
  6372. /**
  6373. Update a property in a JSON object
  6374. @description This call takes a multipart property name and will operate at any level of depth in the JSON object.
  6375. @param obj Parsed JSON object returned by mprParseJson
  6376. @param key Property name to add/update. This may include ".". For example: "settings.mode".
  6377. See #mprQueryJson for a full description of key formats.
  6378. @param value Property value to set.
  6379. @return Zero if updated successfully.
  6380. @ingroup MprJson
  6381. @stability Evolving
  6382. */
  6383. PUBLIC int mprSetJsonObj(MprJson *obj, cchar *key, MprJson *value);
  6384. /**
  6385. Update a key/value in the JSON object with a string value
  6386. @description This call takes a multipart property name and will operate at any level of depth in the JSON object.
  6387. This routine supports the mprQueryJson key syntax.
  6388. @param obj Parsed JSON object returned by mprParseJson
  6389. @param key Property name to add/update. This may include "." and the full mprQueryJson syntax.
  6390. For example: "settings.mode". See #mprQueryJson for a full description of key formats.
  6391. @param value Character string value.
  6392. @param type Set to MPR_JSON_FALSE, MPR_JSON_NULL, MPR_JSON_NUMBER, MPR_JSON_STRING, MPR_JSON_TRUE, MPR_JSON_UNDEFINED.
  6393. @return Zero if updated successfully.
  6394. @ingroup MprJson
  6395. @stability Evolving
  6396. */
  6397. PUBLIC int mprSetJson(MprJson *obj, cchar *key, cchar *value, int type);
  6398. /**
  6399. Write a property in a JSON object
  6400. @description This is a low-level update of Json property using simple (non-query) keys.
  6401. @param obj Parsed JSON object returned by mprParseJson
  6402. @param key Property name to add/update.
  6403. @param value Property value to set.
  6404. @return Zero if updated successfully.
  6405. @ingroup MprJson
  6406. @stability Evolving
  6407. */
  6408. PUBLIC int mprWriteJsonObj(MprJson *obj, cchar *key, MprJson *value);
  6409. /**
  6410. Write a key/value in the JSON object with a string value
  6411. @description This is a low-level update of a Json property using simple (non-query) keys.
  6412. @param obj Parsed JSON object returned by mprParseJson
  6413. @param key Property name to add/update.
  6414. @param value Character string value.
  6415. @param type Set to MPR_JSON_FALSE, MPR_JSON_NULL, MPR_JSON_NUMBER, MPR_JSON_STRING, MPR_JSON_TRUE, MPR_JSON_UNDEFINED.
  6416. @return Zero if updated successfully.
  6417. @ingroup MprJson
  6418. @stability Evolving
  6419. */
  6420. PUBLIC int mprWriteJson(MprJson *obj, cchar *key, cchar *value, int type);
  6421. /********************************* Threads ************************************/
  6422. /**
  6423. Thread service
  6424. @ingroup MprThread
  6425. @stability Internal
  6426. */
  6427. typedef struct MprThreadService {
  6428. MprList *threads; /**< List of all threads */
  6429. struct MprThread *mainThread; /**< Main application thread */
  6430. struct MprThread *eventsThread; /**< Event service thread */
  6431. MprCond *pauseThreads; /**< Waiting for threads to yield */
  6432. ssize stackSize; /**< Default thread stack size */
  6433. } MprThreadService;
  6434. /**
  6435. Thread main procedure
  6436. @param arg Argument to the thread main
  6437. @param tp Thread instance reference
  6438. @ingroup MprThread
  6439. @stability Stable
  6440. */
  6441. typedef void (*MprThreadProc)(void *arg, struct MprThread *tp);
  6442. /*
  6443. Internal
  6444. */
  6445. PUBLIC MprThreadService *mprCreateThreadService(void);
  6446. PUBLIC void mprStopThreadService(void);
  6447. /**
  6448. Thread Service.
  6449. @description The MPR provides a cross-platform thread abstraction above O/S native threads. It supports
  6450. arbitrary thread creation, thread priorities, thread management and thread local storage. By using these
  6451. thread primitives with the locking and synchronization primitives offered by #MprMutex, #MprSpin and
  6452. #MprCond - you can create cross platform multi-threaded applications.
  6453. @see MprThread MprThreadProc MprThreadService mprCreateThread mprGetCurrentOsThread mprGetCurrentThread
  6454. mprGetCurrentThreadName mprGetThreadName mprNeedYield mprResetYield mprStartThread mprYield
  6455. @defgroup MprThread MprThread
  6456. @stability Internal
  6457. */
  6458. typedef struct MprThread {
  6459. MprOsThread osThread; /**< O/S thread id */
  6460. #if ME_WIN_LIKE
  6461. handle threadHandle; /**< Threads OS handle */
  6462. HWND hwnd; /**< Window handle */
  6463. #endif
  6464. MprThreadProc entry; /**< Users thread entry point */
  6465. MprMutex *mutex; /**< Multi-thread locking */
  6466. MprCond *cond; /**< Multi-thread synchronization */
  6467. void *data; /**< Data argument (managed) */
  6468. char *name; /**< Name of thead for trace */
  6469. ulong pid; /**< Owning process id */
  6470. int priority; /**< Current priority */
  6471. ssize stackSize; /**< Only VxWorks implements */
  6472. #if ME_MPR_ALLOC_STACK
  6473. void *stackBase; /**< Base of stack (approx) */
  6474. int peakStack; /**< Peak stack usage */
  6475. #endif
  6476. bool isWorker; /**< Is a worker thread */
  6477. bool isMain; /**< Is the main thread */
  6478. /*
  6479. Don' use bit fields for racing updates
  6480. */
  6481. bool stickyYield; /**< Yielded does not auto-clear after GC */
  6482. bool yielded; /**< Thread has yielded to GC */
  6483. bool waiting; /**< Waiting in mprYield */
  6484. bool noyield; /**< Do not yield (temporary) */
  6485. bool waitForSweeper; /**< Yield untill the GC sweeper is complete */
  6486. } MprThread;
  6487. /**
  6488. Thread local data storage
  6489. @stability Internal
  6490. @internal
  6491. */
  6492. typedef struct MprThreadLocal {
  6493. #if ME_UNIX_LIKE
  6494. pthread_key_t key; /**< Data key */
  6495. #elif ME_WIN_LIKE
  6496. DWORD key;
  6497. #else
  6498. MprHash *store; /**< Thread local data store */
  6499. #endif
  6500. } MprThreadLocal;
  6501. /**
  6502. Create a new thread
  6503. @description MPR threads are usually real O/S threads and can be used with the various locking services (#MprMutex,
  6504. #MprCond, #MprSpin) to enable scalable multithreaded applications.
  6505. @param name Unique name to give the thread
  6506. @param proc Entry point function for the thread. #mprStartThread will invoke this function to start the thread
  6507. @param data Thread private data stored in MprThread.data
  6508. @param stackSize Stack size to use for the thread. On VM based systems, increasing this value, does not
  6509. necessarily incurr a real memory (working-set) increase. Set to zero for a default stack size.
  6510. @returns A MprThread object
  6511. @ingroup MprThread
  6512. @stability Stable
  6513. */
  6514. PUBLIC MprThread *mprCreateThread(cchar *name, void *proc, void *data, ssize stackSize);
  6515. /**
  6516. Get the O/S thread
  6517. @description Get the O/S thread ID for the currently executing thread.
  6518. @return Returns a platform specific O/S thread ID. On Unix, this is a pthread reference. On other systems it is
  6519. a thread integer value.
  6520. @ingroup MprThread
  6521. @stability Stable
  6522. */
  6523. PUBLIC MprOsThread mprGetCurrentOsThread(void);
  6524. /**
  6525. Get the currently executing thread.
  6526. @description Get the thread object for the currently executing O/S thread.
  6527. @return Returns a thread object representing the current O/S thread.
  6528. @ingroup MprThread
  6529. @stability Stable
  6530. */
  6531. PUBLIC MprThread *mprGetCurrentThread(void);
  6532. /**
  6533. Return the name of the current thread
  6534. @returns a static thread name.
  6535. @stability Stable
  6536. */
  6537. PUBLIC cchar *mprGetCurrentThreadName(void);
  6538. /**
  6539. Get the thread name.
  6540. @description MPR threads are usually real O/S threads and can be used with the various locking services (#MprMutex,
  6541. #MprCond, #MprSpin) to enable scalable multithreaded applications.
  6542. @param thread Thread object returned from #mprCreateThread
  6543. @return Returns a string name for the thread.
  6544. @ingroup MprThread
  6545. @stability Stable
  6546. */
  6547. PUBLIC cchar *mprGetThreadName(MprThread *thread);
  6548. /**
  6549. Set whether a thread can yield for GC
  6550. @param tp Thread object returned by #mprCreateThread. Set to NULL for the current thread.
  6551. @param on Set to true to enable yielding
  6552. @ingroup MprThread
  6553. @stability Evolving
  6554. */
  6555. PUBLIC bool mprSetThreadYield(MprThread *tp, bool on);
  6556. /**
  6557. Start a thread
  6558. @description Start a thread previously created via #mprCreateThread. The thread will begin at the entry function
  6559. defined in #mprCreateThread.
  6560. @param thread Thread object returned from #mprCreateThread
  6561. @return Returns zero if successful, otherwise a negative MPR error code.
  6562. @ingroup MprThread
  6563. @stability Stable
  6564. */
  6565. PUBLIC int mprStartThread(MprThread *thread);
  6566. /**
  6567. Start an O/S thread
  6568. @description Start an O/S thread.
  6569. @param name Task name to use on VxWorks
  6570. @param proc Callback function for the thread's main
  6571. @param data Data for the callback to receive.
  6572. @param tp Optional MprThread object to receive thread handles
  6573. @return Returns zero if successful, otherwise a negative MPR error code.
  6574. @ingroup MprThread
  6575. @stability Stable
  6576. */
  6577. PUBLIC int mprStartOsThread(cchar *name, void *proc, void *data, MprThread *tp);
  6578. #define MPR_YIELD_DEFAULT 0x0 /**< mprYield flag if GC is required, yield and wait for mark phase to coplete,
  6579. otherwise return without blocking.*/
  6580. #define MPR_YIELD_COMPLETE 0x1 /**< mprYield flag to wait until the GC entirely completes including sweep phase */
  6581. #define MPR_YIELD_STICKY 0x2 /**< mprYield flag to yield and remain yielded until reset. Does not block */
  6582. /**
  6583. Signify to the garbage collector that the thread is ready for garbage collection
  6584. @description This routine informas the garbage collector that the thread has secured all memory that must be
  6585. retained and is now ready for garbage collection. The MPR has a cooperative garbage collector that runs only
  6586. when all threads are ready for collection. Consequently, it is essential that threads "yield" before sleeping
  6587. or blocking.
  6588. \n\n
  6589. Normally, all threads yield automatically when waiting for I/O or otherwise sleeping via standard MPR routines.
  6590. MPR threads tyically yield in their event loops and thread pool idle routines, so threads should not need to
  6591. call mprYield unless calling custom blocking routines or long running routines.
  6592. \n\n
  6593. When calling a blocking routine, you should call mprYield(MPR_YIELD_STICK) to put the thread into a yielded state.
  6594. When the blocking call returns, you should call mprResetYield()
  6595. \n\n
  6596. While yielded, all transient memory must have references from "managed" objects (see mprAlloc) to ensure required
  6597. memory is retained. All other memory will be reclaimed.
  6598. \n\n
  6599. If a thread blocks and does not yield, it will prevent garbage collection and the applications memory size will grow
  6600. unnecessarily.
  6601. @param flags Set to MPR_YIELD_WAIT to wait until the next collection is run. Set to MPR_YIELD_COMPLETE to wait until
  6602. the garbage collection is fully complete including sweep phase. This is not normally required as the sweeper runs
  6603. in parallel with user threads. Set to MPR_YIELD_STICKY to remain in the yielded state. This is useful when sleeping
  6604. or blocking waiting for I/O. #mprResetYield must be called after setting a sticky yield.
  6605. @stability Stable
  6606. */
  6607. PUBLIC void mprYield(int flags);
  6608. #if DOXYGEN
  6609. /**
  6610. Test if a thread should call mprYield
  6611. @description This call tests if a thread should yield to the garbage collector.
  6612. @stability Stable
  6613. */
  6614. PUBLIC bool mprNeedYield(void);
  6615. #else
  6616. #define mprNeedYield() (MPR->heap->mustYield)
  6617. #endif
  6618. /**
  6619. Reset a sticky yield
  6620. @description This call resets a sticky yield established with #mprYield.
  6621. @stability Stable
  6622. */
  6623. PUBLIC void mprResetYield(void);
  6624. /*
  6625. Internal APIs
  6626. */
  6627. PUBLIC int mprMapMprPriorityToOs(int mprPriority);
  6628. PUBLIC int mprMapOsPriorityToMpr(int nativePriority);
  6629. PUBLIC void mprSetThreadStackSize(ssize size);
  6630. PUBLIC int mprSetThreadData(MprThreadLocal *tls, void *value);
  6631. PUBLIC void *mprGetThreadData(MprThreadLocal *tls);
  6632. PUBLIC MprThreadLocal *mprCreateThreadLocal(void);
  6633. /******************************** I/O Wait ************************************/
  6634. #define MPR_READABLE 0x2 /**< Read event mask */
  6635. #define MPR_WRITABLE 0x4 /**< Write event mask */
  6636. #define MPR_READ_PIPE 0 /* Read side of breakPipe */
  6637. #define MPR_WRITE_PIPE 1 /* Write side of breakPipe */
  6638. #if ME_WIN_LIKE
  6639. typedef long (*MprMsgCallback)(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp);
  6640. #endif
  6641. /**
  6642. Wait Service
  6643. @ingroup MprWaitHandler
  6644. @stability Internal
  6645. */
  6646. typedef struct MprWaitService {
  6647. MprList *handlers; /* List of handlers */
  6648. int needRecall; /* A handler needs a recall due to buffered data */
  6649. int wakeRequested; /* Wakeup of the wait service has been requested */
  6650. MprList *handlerMap; /* Map of fds to handlers */
  6651. #if ME_EVENT_NOTIFIER == MPR_EVENT_ASYNC
  6652. ATOM wclass; /* Window class */
  6653. HWND hwnd; /* Window handle */
  6654. int nfd; /* Last used entry in the handlerMap array */
  6655. int fdmax; /* Size of the fds array */
  6656. int socketMessage; /* Message id for socket events */
  6657. MprMsgCallback msgCallback; /* Message handler callback */
  6658. #elif ME_EVENT_NOTIFIER == MPR_EVENT_EPOLL
  6659. int epoll; /* Epoll descriptor */
  6660. int breakFd[2]; /* Event or pipe to wakeup */
  6661. #elif ME_EVENT_NOTIFIER == MPR_EVENT_KQUEUE
  6662. int kq; /* Kqueue() return descriptor */
  6663. #elif ME_EVENT_NOTIFIER == MPR_EVENT_SELECT || ME_EVENT_NOTIFIER == MPR_EVENT_SELECT_PIPE
  6664. fd_set readMask; /* Current read events mask */
  6665. fd_set writeMask; /* Current write events mask */
  6666. int highestFd; /* Highest socket in masks + 1 */
  6667. int breakFd[2]; /* Socket to wakeup select in [0] */
  6668. struct sockaddr_in breakAddress; /* Address of wakeup socket */
  6669. #endif /* EVENT_SELECT || MPR_EVENT_SELECT_PIPE */
  6670. MprMutex *mutex; /* General multi-thread sync */
  6671. MprSpin *spin; /* Fast short locking */
  6672. } MprWaitService;
  6673. /*
  6674. Internal
  6675. */
  6676. PUBLIC MprWaitService *mprCreateWaitService(void);
  6677. PUBLIC void mprTermOsWait(MprWaitService *ws);
  6678. PUBLIC void mprStopWaitService(void);
  6679. PUBLIC void mprSetWaitServiceThread(MprWaitService *ws, MprThread *thread);
  6680. PUBLIC void mprWakeNotifier(void);
  6681. #if MPR_EVENT_ASYNC
  6682. PUBLIC void mprManageAsync(MprWaitService *ws, int flags);
  6683. #endif
  6684. #if MPR_EVENT_EPOLL
  6685. PUBLIC void mprManageEpoll(MprWaitService *ws, int flags);
  6686. #endif
  6687. #if MPR_EVENT_KQUEUE
  6688. PUBLIC void mprManageKqueue(MprWaitService *ws, int flags);
  6689. #endif
  6690. #if MPR_EVENT_SELECT
  6691. PUBLIC void mprManageSelect(MprWaitService *ws, int flags);
  6692. #endif
  6693. #if ME_WIN_LIKE
  6694. PUBLIC void mprSetWinMsgCallback(MprMsgCallback callback);
  6695. PUBLIC void mprServiceWinIO(MprWaitService *ws, int sockFd, int winMask);
  6696. PUBLIC HWND mprCreateWindow(MprThread *tp);
  6697. PUBLIC ATOM mprCreateWindowClass(cchar *name);
  6698. PUBLIC void mprDestroyWindow(HWND hwnd);
  6699. PUBLIC void mprDestroyWindowClass(ATOM wclass);
  6700. PUBLIC HWND mprGetWindow(bool *created);
  6701. PUBLIC HWND mprSetWindowsThread(MprThread *tp);
  6702. #else
  6703. #define mprSetWindowsThread(tp)
  6704. #endif
  6705. /**
  6706. Wait for I/O.
  6707. @description
  6708. This call waits for any I/O events on wait handlers until the given timeout expires.
  6709. This routine yields to the garbage collector by calling #mprYield. Callers must retain all required memory.
  6710. @param ws Wait service object
  6711. @param timeout Timeout in milliseconds to wait for an event.
  6712. @ingroup MprWaitHandler
  6713. @stability Stable
  6714. */
  6715. PUBLIC void mprWaitForIO(MprWaitService *ws, MprTicks timeout);
  6716. /**
  6717. Wait for I/O on a file descriptor. No processing of the I/O event is done.
  6718. @description This routine yields to the garbage collector by calling #mprYield. Callers must retain all required memory.
  6719. @param fd File descriptor to examine
  6720. @param mask Mask of events of interest (MPR_READABLE | MPR_WRITABLE)
  6721. @param timeout Timeout in milliseconds to wait for an event.
  6722. @returns A count of events received.
  6723. @ingroup MprWaitHandler
  6724. @stability Stable
  6725. */
  6726. PUBLIC int mprWaitForSingleIO(int fd, int mask, MprTicks timeout);
  6727. /*
  6728. Handler Flags
  6729. */
  6730. #define MPR_WAIT_RECALL_HANDLER 0x1 /**< Wait handler flag to recall the handler asap */
  6731. #define MPR_WAIT_NEW_DISPATCHER 0x2 /**< Wait handler flag to create a new dispatcher for each I/O event */
  6732. #define MPR_WAIT_IMMEDIATE 0x4 /**< Wait handler flag to immediately service event on same thread */
  6733. #define MPR_WAIT_NOT_SOCKET 0x8 /**< I/O file descriptor is not a socket - windows will ignore */
  6734. /**
  6735. Wait Handler Service
  6736. @description Wait handlers provide callbacks for when I/O events occur. They provide a wait to service many
  6737. I/O file descriptors without requiring a thread per descriptor.
  6738. @see MprEvent MprWaitHandler mprCreateWaitHandler mprQueueIOEvent mprRecallWaitHandler mprRecallWaitHandlerByFd
  6739. mprDestroyWaitHandler mprWaitOn
  6740. @defgroup MprWaitHandler MprWaitHandler
  6741. @stability Internal
  6742. */
  6743. typedef struct MprWaitHandler {
  6744. int desiredMask; /**< Mask of desired events */
  6745. int presentMask; /**< Mask of current events */
  6746. int fd; /**< O/S File descriptor (sp->sock) */
  6747. int notifierIndex; /**< Index for notifier */
  6748. int flags; /**< Control flags */
  6749. void *handlerData; /**< Argument to pass to proc - managed reference */
  6750. MprWaitService *service; /**< Wait service pointer */
  6751. MprDispatcher *dispatcher; /**< Event dispatcher to use for I/O events */
  6752. MprEventProc proc; /**< Callback event procedure */
  6753. struct MprWorker *requiredWorker; /**< Designate the required worker thread to run the callback */
  6754. struct MprThread *thread; /**< Thread executing the callback, set even if worker is null */
  6755. MprCond *callbackComplete; /**< Signalled when a callback is complete */
  6756. } MprWaitHandler;
  6757. /**
  6758. Create a wait handler
  6759. @description Create a wait handler that will be invoked when I/O of interest occurs on the specified file handle
  6760. The wait handler is registered with the MPR event I/O mechanism.
  6761. @param fd File descriptor
  6762. @param mask Mask of events of interest. This is made by oring MPR_READABLE and MPR_WRITABLE
  6763. @param dispatcher Dispatcher object to use for scheduling the I/O event.
  6764. @param proc Callback function to invoke when an I/O event of interest has occurred.
  6765. @param data Data item to pass to the callback
  6766. @param flags Wait handler flags. Use MPR_WAIT_NEW_DISPATCHER to auto-create a new dispatcher for each I/O event.
  6767. @returns A new wait handler registered with the MPR event mechanism
  6768. @ingroup MprWaitHandler
  6769. @stability Stable
  6770. */
  6771. PUBLIC MprWaitHandler *mprCreateWaitHandler(int fd, int mask, MprDispatcher *dispatcher, void *proc, void *data, int flags);
  6772. /**
  6773. Destroy a wait handler
  6774. @param wp Wait handler object
  6775. @ingroup MprWaitHandler
  6776. @stability Stable
  6777. */
  6778. PUBLIC void mprDestroyWaitHandler(MprWaitHandler *wp);
  6779. /**
  6780. Remove a wait handler from the wait service
  6781. @param wp Wait handler object
  6782. @ingroup MprWaitHandler
  6783. @stability Stable
  6784. */
  6785. PUBLIC void mprRemoveWaitHandler(MprWaitHandler *wp);
  6786. /**
  6787. Queue an IO event for dispatch on the wait handler dispatcher
  6788. @param wp Wait handler created via mprCreateWaitHandler
  6789. @stability Stable
  6790. */
  6791. PUBLIC void mprQueueIOEvent(MprWaitHandler *wp);
  6792. /**
  6793. Recall a wait handler
  6794. @description Signal that a wait handler should be recalled at the earliest opportunity. This is useful
  6795. when a protocol stack has buffered data that must be processed regardless of whether more I/O occurs.
  6796. @param wp Wait handler to recall
  6797. @ingroup MprWaitHandler
  6798. @stability Stable
  6799. */
  6800. PUBLIC void mprRecallWaitHandler(MprWaitHandler *wp);
  6801. /**
  6802. Recall a wait handler by fd
  6803. @description Signal that a wait handler should be recalled at the earliest opportunity. This is useful
  6804. when a protocol stack has buffered data that must be processed regardless of whether more I/O occurs.
  6805. @param fd File descriptor that matches that of a wait handler to recall
  6806. @ingroup MprWaitHandler
  6807. @stability Stable
  6808. */
  6809. PUBLIC void mprRecallWaitHandlerByFd(Socket fd);
  6810. /**
  6811. Subscribe for desired wait events
  6812. @description Subscribe to the desired wait events for a given wait handler.
  6813. @param wp Wait handler created via mprCreateWaitHandler
  6814. @param desiredMask Mask of desired events (MPR_READABLE | MPR_WRITABLE)
  6815. @ingroup MprWaitHandler
  6816. @stability Stable
  6817. */
  6818. PUBLIC void mprWaitOn(MprWaitHandler *wp, int desiredMask);
  6819. /*
  6820. Internal
  6821. */
  6822. PUBLIC int mprDoWaitRecall(MprWaitService *ws);
  6823. /******************************* Notification *********************************/
  6824. /**
  6825. Internal
  6826. @ingroup MprWaitHandler
  6827. @stability Internal
  6828. */
  6829. PUBLIC int mprCreateNotifierService(MprWaitService *ws);
  6830. /**
  6831. Begin I/O notification services on a wait handler
  6832. @param wp Wait handler associated with the file descriptor
  6833. @param mask Mask of events of interest. This is made by oring MPR_READABLE and MPR_WRITABLE
  6834. @return Zero if successful, otherwise a negative MPR error code.
  6835. @ingroup MprWaithHandler
  6836. @stability Internal
  6837. */
  6838. PUBLIC int mprNotifyOn(MprWaitHandler *wp, int mask);
  6839. /********************************** Sockets ***********************************/
  6840. /**
  6841. Socket I/O callback procedure. Proc returns non-zero if the socket has been deleted.
  6842. @ingroup MprSocket
  6843. @stability Stable
  6844. */
  6845. typedef int (*MprSocketProc)(void *data, int mask);
  6846. /**
  6847. Socket service provider interface.
  6848. @ingroup MprSocket
  6849. @stability Internal
  6850. */
  6851. typedef struct MprSocketProvider {
  6852. char *name; /**< Socket provider name */
  6853. void *data; /**< Socket provider private data (unmanaged) */
  6854. void *managed; /**< Socket provider private data managed */
  6855. /**
  6856. Close a socket
  6857. @description Close a socket. If the \a graceful option is true, the socket will first wait for written data to drain
  6858. before doing a graceful close.
  6859. @param socket Socket object returned from #mprCreateSocket
  6860. @param graceful Set to true to do a graceful close. Otherwise, an abortive close will be performed.
  6861. @stability Stable
  6862. */
  6863. void (*closeSocket)(struct MprSocket *socket, bool graceful);
  6864. /**
  6865. Disconnect a socket by closing its underlying file descriptor.
  6866. This is used to prevent further I/O wait events while still preserving the socket object.
  6867. @param socket Socket object
  6868. @stability Stable
  6869. */
  6870. void (*disconnectSocket)(struct MprSocket *socket);
  6871. /**
  6872. Flush a socket
  6873. @description Flush any buffered data in a socket. Standard sockets do not use buffering and this call
  6874. will do nothing. SSL sockets do buffer and calling mprFlushSocket will write pending written data.
  6875. @param socket Socket object returned from #mprCreateSocket
  6876. @return A count of bytes actually written. Return a negative MPR error code on errors.
  6877. @stability Stable
  6878. */
  6879. ssize (*flushSocket)(struct MprSocket *socket);
  6880. /**
  6881. Preload SSL configuration
  6882. @param ssl SSL configurations to use.
  6883. @param flags Set to MPR_SOCKET_SERVER for server side use.
  6884. @returns Zero if successful, otherwise a negative MPR error code.
  6885. @stability Evolving
  6886. */
  6887. int (*preload)(struct MprSsl *ssl, int flags);
  6888. /**
  6889. Read from a socket
  6890. @description Read data from a socket. The read will return with whatever bytes are available. If none and the socket
  6891. is in blocking mode, it will block untill there is some data available or the socket is disconnected.
  6892. @param socket Socket object returned from #mprCreateSocket
  6893. @param buf Pointer to a buffer to hold the read data.
  6894. @param size Size of the buffer.
  6895. @return A count of bytes actually read. Return a negative MPR error code on errors.
  6896. @return Return -1 for EOF and errors. On success, return the number of bytes read. Use mprIsSocketEof to
  6897. distinguision between EOF and errors.
  6898. @stability Stable
  6899. */
  6900. ssize (*readSocket)(struct MprSocket *socket, void *buf, ssize size);
  6901. /**
  6902. Write to a socket
  6903. @description Write a block of data to a socket. If the socket is in non-blocking mode (the default), the write
  6904. may return having written less than the required bytes.
  6905. @param socket Socket object returned from #mprCreateSocket
  6906. @param buf Reference to a block to write to the socket
  6907. @param size Length of data to write. This may be less than the requested write length if the socket is in
  6908. non-blocking mode. Will return a negative MPR error code on errors.
  6909. @return A count of bytes actually written. Return a negative MPR error code on errors.
  6910. @stability Stable
  6911. */
  6912. ssize (*writeSocket)(struct MprSocket *socket, cvoid *buf, ssize size);
  6913. /**
  6914. Upgrade a socket to use SSL/TLS
  6915. @param sp Socket to upgrade
  6916. @param ssl SSL configurations to use. Set to NULL to use the default.
  6917. @param peerName Required peer name in handshake with peer. Used by clients to verify the server hostname.
  6918. @returns Zero if successful, otherwise a negative MPR error code.
  6919. @stability Stable
  6920. */
  6921. int (*upgradeSocket)(struct MprSocket *socket, struct MprSsl *ssl, cchar *peerName);
  6922. /**
  6923. Get the socket state
  6924. @description Get the socket state as a parseable string description
  6925. @param sp Socket object returned from #mprCreateSocket
  6926. @return The an allocated string
  6927. @stability Stable
  6928. */
  6929. char *(*socketState)(struct MprSocket *socket);
  6930. } MprSocketProvider;
  6931. /**
  6932. Callback before binding a socket
  6933. @ingroup MprSocket
  6934. @stability Stable
  6935. */
  6936. typedef int (*MprSocketPrebind)(struct MprSocket *sock);
  6937. /**
  6938. Mpr socket service class
  6939. @ingroup MprSocket
  6940. @stability Internal
  6941. */
  6942. typedef struct MprSocketService {
  6943. MprSocketProvider *standardProvider; /**< Socket provider for non-SSL connections */
  6944. MprSocketProvider *sslProvider; /**< Socket provider for SSL connections */
  6945. MprSocketPrebind prebind; /**< Prebind callback */
  6946. MprList *secureSockets; /**< List of secured (matrixssl) sockets */
  6947. MprMutex *mutex; /**< Multithread locking */
  6948. int maxAccept; /**< Maximum number of accepted client socket connections */
  6949. int numAccept; /**< Count of client socket connections */
  6950. int hasIPv6; /**< System has supoprt for IPv6 */
  6951. int loaded; /**< Provider loaded */
  6952. } MprSocketService;
  6953. #if DOXYGEN
  6954. typedef int Socklen;
  6955. #endif
  6956. /*
  6957. Internal
  6958. */
  6959. PUBLIC MprSocketService *mprCreateSocketService(void);
  6960. /**
  6961. Determine if SSL is available
  6962. @returns True if SSL is available
  6963. @ingroup MprSocket
  6964. @stability Stable
  6965. */
  6966. PUBLIC bool mprHasSecureSockets(void);
  6967. /**
  6968. Set the maximum number of accepted client connections that are permissable
  6969. @param max New maximum number of accepted client connections.
  6970. @ingroup MprSocket
  6971. @stability Stable
  6972. */
  6973. PUBLIC int mprSetMaxSocketAccept(int max);
  6974. /*
  6975. Set the prebind callback for a socket
  6976. @param callback Callback to invoke
  6977. @ingroup MprSocket
  6978. @stability Evolving
  6979. */
  6980. PUBLIC void mprSetSocketPrebindCallback(MprSocketPrebind callback);
  6981. /*
  6982. Socket close flags
  6983. */
  6984. #define MPR_SOCKET_GRACEFUL 1 /**< Do a graceful shutdown */
  6985. /*
  6986. Socket event types
  6987. */
  6988. #define MPR_SOCKET_READABLE MPR_READABLE
  6989. #define MPR_SOCKET_WRITABLE MPR_WRITABLE
  6990. /*
  6991. Socket Flags
  6992. */
  6993. #define MPR_SOCKET_BLOCK 0x1 /**< Use blocking I/O */
  6994. #define MPR_SOCKET_BROADCAST 0x2 /**< Broadcast mode */
  6995. #define MPR_SOCKET_CLOSED 0x4 /**< MprSocket has been closed */
  6996. #define MPR_SOCKET_CONNECTING 0x8 /**< MprSocket is connecting */
  6997. #define MPR_SOCKET_DATAGRAM 0x10 /**< Use datagrams */
  6998. #define MPR_SOCKET_EOF 0x20 /**< Seen end of file */
  6999. #define MPR_SOCKET_LISTENER 0x40 /**< MprSocket is server listener */
  7000. #define MPR_SOCKET_NOREUSE 0x80 /**< Don't set SO_REUSEADDR option */
  7001. #define MPR_SOCKET_NODELAY 0x100 /**< Disable Nagle algorithm */
  7002. #define MPR_SOCKET_THREAD 0x200 /**< Process callbacks on a worker thread */
  7003. #define MPR_SOCKET_SERVER 0x400 /**< Socket is on the server-side */
  7004. #define MPR_SOCKET_BUFFERED_READ 0x800 /**< Socket has buffered read data (in SSL stack) */
  7005. #define MPR_SOCKET_BUFFERED_WRITE 0x1000 /**< Socket has buffered write data (in SSL stack) */
  7006. #define MPR_SOCKET_DISCONNECTED 0x4000 /**< The mprDisconnectSocket has been called */
  7007. #define MPR_SOCKET_HANDSHAKING 0x8000 /**< Doing an SSL handshake */
  7008. #define MPR_SOCKET_CERT_ERROR 0x10000 /**< Error when validating peer certificate */
  7009. #define MPR_SOCKET_ERROR 0x20000 /**< Hard error (not just eof) */
  7010. #define MPR_SOCKET_REUSE_PORT 0x40000 /**< Set SO_REUSEPORT option */
  7011. /**
  7012. Socket Service
  7013. @description The MPR Socket service provides IPv4 and IPv6 capabilities for both client and server endpoints.
  7014. Datagrams, Broadcast and point to point services are supported. The APIs can be used in both blocking and
  7015. non-blocking modes.
  7016. \n\n
  7017. The socket service integrates with the MPR worker thread pool and eventing services. Socket connections can be handled
  7018. by threads from the worker thread pool for scalable, multithreaded applications.
  7019. @stability Stable
  7020. @see MprSocket MprSocketPrebind MprSocketProc MprSocketProvider MprSocketService mprAddSocketHandler
  7021. mprCloseSocket mprConnectSocket mprCreateSocket mprCreateSocketService mprCreateSsl mprCloneSsl
  7022. mprDisconnectSocket mprEnableSocketEvents mprFlushSocket mprGetSocketBlockingMode mprGetSocketError
  7023. mprGetSocketHandle mprGetSocketInfo mprGetSocketPort mprGetSocketState mprHasSecureSockets mprIsSocketEof
  7024. mprIsSocketSecure mprListenOnSocket mprLoadSsl mprParseIp mprReadSocket mprSendFileToSocket mprSetSecureProvider
  7025. mprSetSocketBlockingMode mprSetSocketCallback mprSetSocketEof mprSetSocketNoDelay mprSetSslCaFile mprSetSslCaPath
  7026. mprSetSslCertFile mprSetSslCiphers mprSetSslKeyFile mprSetSslDhFile mprSetSslSslProtocols mprSetSslVerifySslClients
  7027. mprWriteSocket mprWriteSocketString mprWriteSocketVector mprSocketHandshaking mprSocketHasBufferedRead
  7028. mprSocketHasBufferedWrite mprUpgradeSocket
  7029. @defgroup MprSocket MprSocket
  7030. @stability Internal
  7031. */
  7032. typedef struct MprSocket {
  7033. MprSocketService *service; /**< Socket service */
  7034. MprWaitHandler *handler; /**< Wait handler */
  7035. char *acceptIp; /**< Server address that accepted a new connection (actual interface) */
  7036. char *ip; /**< Server listen address or remote client address */
  7037. char *errorMsg; /**< Connection related error messages */
  7038. int acceptPort; /**< Server port doing the listening */
  7039. int port; /**< Port to listen or connect on */
  7040. Socket fd; /**< Actual socket file handle */
  7041. int flags; /**< Current state flags */
  7042. MprSocketProvider *provider; /**< Socket implementation provider */
  7043. struct MprSocket *listenSock; /**< Listening socket */
  7044. void *sslSocket; /**< Extended SSL socket state */
  7045. struct MprSsl *ssl; /**< Selected SSL configuration */
  7046. cchar *cipher; /**< Selected SSL cipher */
  7047. cchar *session; /**< SSL session ID (dependent on SSL provider) */
  7048. cchar *peerName; /**< Peer common SSL name */
  7049. cchar *peerCert; /**< Peer SSL certificate */
  7050. cchar *peerCertIssuer; /**< Issuer of peer certificate */
  7051. bool secured; /**< SSL Peer verified */
  7052. MprMutex *mutex; /**< Multi-thread sync */
  7053. void *data; /**< Custom user data (unmanaged) */
  7054. } MprSocket;
  7055. /**
  7056. Vectored write array
  7057. @stability Internal
  7058. */
  7059. typedef struct MprIOVec {
  7060. char *start; /**< Start of block to write */
  7061. ssize len; /**< Length of block to write */
  7062. } MprIOVec;
  7063. /**
  7064. Accept an incoming connection
  7065. @param listen Listening server socket
  7066. @returns A new socket connection. Windows can return NULL with error set to EAGAIN.
  7067. @ingroup MprSocket
  7068. @stability Stable
  7069. */
  7070. PUBLIC MprSocket *mprAcceptSocket(MprSocket *listen);
  7071. /**
  7072. Add a wait handler to a socket.
  7073. @description Create a wait handler that will be invoked when I/O of interest occurs on the specified socket.
  7074. The wait handler is registered with the MPR event I/O mechanism.
  7075. @param sp Socket object created via mprCreateSocket
  7076. @param mask Mask of events of interest. This is made by oring MPR_READABLE and MPR_WRITABLE
  7077. @param dispatcher Dispatcher object to use for scheduling the I/O event.
  7078. @param proc Callback function to invoke when an I/O event of interest has occurred.
  7079. @param data Data item to pass to the callback
  7080. @param flags Socket handler flags
  7081. @returns A new wait handler registered with the MPR event mechanism
  7082. @ingroup MprSocket
  7083. @stability Stable
  7084. */
  7085. PUBLIC MprWaitHandler *mprAddSocketHandler(MprSocket *sp, int mask, MprDispatcher *dispatcher, void *proc, void *data, int flags);
  7086. /**
  7087. Clone a socket object
  7088. @description Create an exact copy of a socket object. On return both socket objects share the same O/S socket handle.
  7089. If the original socket has an SSL configuration, the new socket will share the same SSL configuration object.
  7090. @return A new socket object
  7091. @ingroup MprSocket
  7092. @stability Stable
  7093. */
  7094. PUBLIC MprSocket *mprCloneSocket(MprSocket *sp);
  7095. /**
  7096. Close a socket
  7097. @description Close a socket. If the \a graceful option is true, the socket will first wait for written data to drain
  7098. before doing a graceful close.
  7099. @param sp Socket object returned from #mprCreateSocket
  7100. @param graceful Set to true to do a graceful close. Otherwise, an abortive close will be performed.
  7101. @ingroup MprSocket
  7102. @stability Stable
  7103. */
  7104. PUBLIC void mprCloseSocket(MprSocket *sp, bool graceful);
  7105. /**
  7106. Connect a client socket
  7107. @description Open a client connection
  7108. @param sp Socket object returned via #mprCreateSocket
  7109. @param ip Host or IP address to connect to.
  7110. @param port TCP/IP port number to connect to.
  7111. @param flags Socket flags may use the following flags ored together:
  7112. @li MPR_SOCKET_BLOCK - to use blocking I/O. The default is non-blocking.
  7113. @li MPR_SOCKET_BROADCAST - Use IPv4 broadcast
  7114. @li MPR_SOCKET_DATAGRAM - Use IPv4 datagrams
  7115. @li MPR_SOCKET_NOREUSE - Set NOREUSE flag on the socket
  7116. @li MPR_SOCKET_NODELAY - Set NODELAY on the socket
  7117. @li MPR_SOCKET_THREAD - Process callbacks on a separate thread.
  7118. @return Zero if the connection is successful. Otherwise a negative MPR error code.
  7119. @ingroup MprSocket
  7120. @stability Stable
  7121. */
  7122. PUBLIC int mprConnectSocket(MprSocket *sp, cchar *ip, int port, int flags);
  7123. /**
  7124. Create a socket
  7125. @description Create a new socket
  7126. @return A new socket object
  7127. @ingroup MprSocket
  7128. @stability Stable
  7129. */
  7130. PUBLIC MprSocket *mprCreateSocket(void);
  7131. /**
  7132. Disconnect a socket by closing its underlying file descriptor. This is used to prevent further I/O wait events while
  7133. still preserving the socket object.
  7134. @param sp Socket object
  7135. @ingroup MprSocket
  7136. @stability Stable
  7137. */
  7138. PUBLIC void mprDisconnectSocket(MprSocket *sp);
  7139. /**
  7140. Enable socket events for a socket callback
  7141. @param sp Socket object returned from #mprCreateSocket
  7142. @param mask Mask of events to enable
  7143. @ingroup MprSocket
  7144. @stability Stable
  7145. */
  7146. PUBLIC void mprEnableSocketEvents(MprSocket *sp, int mask);
  7147. /**
  7148. Flush a socket
  7149. @description Flush any buffered data in a socket. Standard sockets do not use buffering and this call will do nothing.
  7150. SSL sockets do buffer and calling mprFlushSocket will write pending written data.
  7151. @param sp Socket object returned from #mprCreateSocket
  7152. @return A count of bytes actually written. Return a negative MPR error code on errors.
  7153. @ingroup MprSocket
  7154. @stability Stable
  7155. */
  7156. PUBLIC ssize mprFlushSocket(MprSocket *sp);
  7157. /**
  7158. Get the socket blocking mode.
  7159. @description Return the current blocking mode setting.
  7160. @param sp Socket object returned from #mprCreateSocket
  7161. @return True if the socket is in blocking mode. Otherwise false.
  7162. @ingroup MprSocket
  7163. @stability Stable
  7164. */
  7165. PUBLIC bool mprGetSocketBlockingMode(MprSocket *sp);
  7166. /**
  7167. Get a socket error code
  7168. @description This will map a Windows socket error code into a posix error code.
  7169. @param sp Socket object returned from #mprCreateSocket
  7170. @return A posix error code.
  7171. @ingroup MprSocket
  7172. @stability Stable
  7173. */
  7174. PUBLIC int mprGetSocketError(MprSocket *sp);
  7175. /**
  7176. Get the socket file descriptor.
  7177. @description Get the file descriptor associated with a socket.
  7178. @param sp Socket object returned from #mprCreateSocket
  7179. @return The Socket file descriptor used by the O/S for the socket.
  7180. @ingroup MprSocket
  7181. @stability Stable
  7182. */
  7183. PUBLIC Socket mprGetSocketHandle(MprSocket *sp);
  7184. /**
  7185. Get the socket for an IP:Port address
  7186. @param ip IP address or hostname
  7187. @param port Port number
  7188. @param family Output parameter to contain the Internet protocol family
  7189. @param protocol Output parameter to contain the Internet TCP/IP protocol
  7190. @param addr Allocated block to contain the sockaddr description of the socket address
  7191. @param addrlen Output parameter to hold the length of the sockaddr object
  7192. @return Zero if the call is successful. Otherwise return a negative MPR error code.
  7193. @ingroup MprSocket
  7194. @stability Stable
  7195. */
  7196. PUBLIC int mprGetSocketInfo(cchar *ip, int port, int *family, int *protocol, struct sockaddr **addr, Socklen *addrlen);
  7197. /**
  7198. Get the port used by a socket
  7199. @description Get the TCP/IP port number used by the socket.
  7200. @param sp Socket object returned from #mprCreateSocket
  7201. @return The integer TCP/IP port number used by the socket.
  7202. @ingroup MprSocket
  7203. @stability Stable
  7204. */
  7205. PUBLIC int mprGetSocketPort(MprSocket *sp);
  7206. /**
  7207. Get the socket state
  7208. @description Get the socket state as string description in JSON format.
  7209. @param sp Socket object returned from #mprCreateSocket
  7210. @return The an allocated string in JSON format. Returns NULL if the state is not available or supported.
  7211. @ingroup MprSocket
  7212. @stability Stable
  7213. */
  7214. PUBLIC char *mprGetSocketState(MprSocket *sp);
  7215. /**
  7216. has the system got a dual IPv4 + IPv6 network stack
  7217. @return True if the network can listen on IPv4 and IPv6 on a single socket
  7218. @ingroup MprSocket
  7219. @stability Stable
  7220. */
  7221. PUBLIC bool mprHasDualNetworkStack(void);
  7222. /**
  7223. Determine if the system support IPv6
  7224. @return True if the address system supports IPv6 networking.
  7225. @ingroup MprSocket
  7226. @stability Stable
  7227. @internal
  7228. */
  7229. PUBLIC bool mprHasIPv6(void);
  7230. /**
  7231. Indicate that the application layer has buffered data for the socket.
  7232. @description This is used by SSL and other network stacks that buffer pending data
  7233. @param sp Socket object returned from #mprCreateSocket
  7234. @param len Length of buffered data in bytes
  7235. @param dir Buffer direction. Set to MPR_READABLE for buffered read data and MPR_WRITABLE for buffered write data.
  7236. */
  7237. PUBLIC void mprHiddenSocketData(MprSocket *sp, ssize len, int dir);
  7238. /**
  7239. Determine if the IP address is an IPv6 address
  7240. @param ip IP address
  7241. @return True if the address is an IPv6 address, otherwise zero.
  7242. @ingroup MprSocket
  7243. @stability Stable
  7244. @internal
  7245. */
  7246. PUBLIC bool mprIsIPv6(cchar *ip);
  7247. /**
  7248. Determine if the socket is secure
  7249. @description Determine if the socket is using SSL to provide enhanced security.
  7250. @param sp Socket object returned from #mprCreateSocket
  7251. @return True if the socket is using SSL, otherwise zero.
  7252. @ingroup MprSocket
  7253. @stability Stable
  7254. */
  7255. PUBLIC bool mprIsSocketSecure(MprSocket *sp);
  7256. /**
  7257. Determine if the socket is using IPv6
  7258. Currently only works for server side addresses.
  7259. @param sp Socket object returned from #mprCreateSocket
  7260. @return True if the socket is using IPv6, otherwise zero.
  7261. @internal
  7262. @ingroup MprSocket
  7263. @stability Stable
  7264. */
  7265. PUBLIC bool mprIsSocketV6(MprSocket *sp);
  7266. /**
  7267. Test if the other end of the socket has been closed.
  7268. @description Determine if the other end of the socket has been closed and the socket is at end-of-file.
  7269. @param sp Socket object returned from #mprCreateSocket
  7270. @return True if the socket is at end-of-file.
  7271. @ingroup MprSocket
  7272. @stability Stable
  7273. */
  7274. PUBLIC bool mprIsSocketEof(MprSocket *sp);
  7275. /**
  7276. Listen on a server socket for incoming connections
  7277. @description Open a server socket and listen for client connections.
  7278. If ip is null, then this will listen on both IPv6 and IPv4.
  7279. @param sp Socket object returned via #mprCreateSocket
  7280. @param ip IP address to bind to. Set to 0.0.0.0 to bind to all possible addresses on a given port.
  7281. @param port TCP/IP port number to connect to.
  7282. @param flags Socket flags may use the following flags ored together:
  7283. @li MPR_SOCKET_BLOCK - to use blocking I/O. The default is non-blocking.
  7284. @li MPR_SOCKET_BROADCAST - Use IPv4 broadcast
  7285. @li MPR_SOCKET_DATAGRAM - Use IPv4 datagrams
  7286. @li MPR_SOCKET_NOREUSE - Set NOREUSE flag on the socket
  7287. @li MPR_SOCKET_NODELAY - Set NODELAY on the socket
  7288. @li MPR_SOCKET_THREAD - Process callbacks on a separate thread.
  7289. @return Zero if the connection is successful. Otherwise a negative MPR error code.
  7290. @ingroup MprSocket
  7291. @stability Stable
  7292. */
  7293. PUBLIC Socket mprListenOnSocket(MprSocket *sp, cchar *ip, int port, int flags);
  7294. /**
  7295. Parse an socket address IP address.
  7296. @description This parses a string containing an IP:PORT specification and returns the IP address and port
  7297. components. Handles ipv4 and ipv6 addresses.
  7298. @param address An IP:PORT specification. The :PORT is optional. When an IP address contains an ipv6 port it should be
  7299. written as
  7300. aaaa:bbbb:cccc:dddd:eeee:ffff:gggg:hhhh:iiii or
  7301. [aaaa:bbbb:cccc:dddd:eeee:ffff:gggg:hhhh:iiii]:port
  7302. @param ip Pointer to receive a dynamically allocated IP string.
  7303. @param port Pointer to an integer to receive the port value.
  7304. @param secure Pointer to an integer to receive true if the address requires SSL.
  7305. @param defaultPort The default port number to use if the address does not contain a port
  7306. @ingroup MprSocket
  7307. @stability Stable
  7308. */
  7309. PUBLIC int mprParseSocketAddress(cchar *address, cchar **ip, int *port, int *secure, int defaultPort);
  7310. /**
  7311. Read from a socket
  7312. @description Read data from a socket. The read will return with whatever bytes are available. If none and the socket
  7313. is in blocking mode, it will block untill there is some data available or the socket is disconnected.
  7314. @param sp Socket object returned from #mprCreateSocket
  7315. @param buf Pointer to a buffer to hold the read data.
  7316. @param size Size of the buffer.
  7317. @return A count of bytes actually read. Return a negative MPR error code on errors.
  7318. @return Return -1 for EOF and errors. On success, return the number of bytes read. Use mprIsSocketEof to
  7319. distinguision between EOF and errors.
  7320. @ingroup MprSocket
  7321. @stability Stable
  7322. */
  7323. PUBLIC ssize mprReadSocket(MprSocket *sp, void *buf, ssize size);
  7324. /**
  7325. Remove a socket wait handler.
  7326. @description Removes the socket wait handler created via mprAddSocketHandler.
  7327. @param sp Socket object created via mprCreateSocket
  7328. @ingroup MprSocket
  7329. @stability Stable
  7330. */
  7331. PUBLIC void mprRemoveSocketHandler(MprSocket *sp);
  7332. #if !ME_ROM
  7333. /**
  7334. Send a file to a socket
  7335. @description Write the contents of a file to a socket. If the socket is in non-blocking mode (the default), the write
  7336. may return having written less than the required bytes. This API permits the writing of data before and after
  7337. the file contents.
  7338. @param file File to write to the socket
  7339. @param sock Socket object returned from #mprCreateSocket
  7340. @param offset offset within the file from which to read data
  7341. @param bytes Length of file data to write
  7342. @param beforeVec Vector of data to write before the file contents
  7343. @param beforeCount Count of entries in beforeVect
  7344. @param afterVec Vector of data to write after the file contents
  7345. @param afterCount Count of entries in afterCount
  7346. @return A count of bytes actually written. Return a negative MPR error code on errors.
  7347. @ingroup MprSocket
  7348. @stability Stable
  7349. */
  7350. PUBLIC MprOff mprSendFileToSocket(MprSocket *sock, MprFile *file, MprOff offset, MprOff bytes, MprIOVec *beforeVec,
  7351. int beforeCount, MprIOVec *afterVec, int afterCount);
  7352. #endif
  7353. /**
  7354. Set the socket blocking mode.
  7355. @description Set the blocking mode for a socket. By default a socket is in non-blocking mode where read / write
  7356. calls will not block.
  7357. @param sp Socket object returned from #mprCreateSocket
  7358. @param on Set to zero to put the socket into non-blocking mode. Set to non-zero to enable blocking mode.
  7359. @return The old blocking mode if successful or a negative MPR error code.
  7360. @ingroup MprSocket
  7361. @stability Stable
  7362. */
  7363. PUBLIC int mprSetSocketBlockingMode(MprSocket *sp, bool on);
  7364. /**
  7365. Set the dispatcher to use for socket events
  7366. @param sp Socket object returned from #mprCreateSocket
  7367. @param dispatcher Dispatcher object reference
  7368. @ingroup MprSocket
  7369. @stability Stable
  7370. */
  7371. PUBLIC void mprSetSocketDispatcher(MprSocket *sp, MprDispatcher *dispatcher);
  7372. /**
  7373. Set an EOF condition on the socket
  7374. @param sp Socket object returned from #mprCreateSocket
  7375. @param eof Set to true to set an EOF condition. Set to false to clear it.
  7376. @ingroup MprSocket
  7377. @stability Stable
  7378. */
  7379. PUBLIC void mprSetSocketEof(MprSocket *sp, bool eof);
  7380. /**
  7381. Set the socket delay mode.
  7382. @description Set the socket delay behavior (nagle algorithm). By default a socket will partial packet writes
  7383. a little to try to accumulate data and coalesce TCP/IP packages. Setting the delay mode to false may
  7384. result in higher performance for interactive applications.
  7385. @param sp Socket object returned from #mprCreateSocket
  7386. @param on Set to non-zero to put the socket into no delay mode. Set to zero to enable the nagle algorithm.
  7387. @return The old delay mode if successful or a negative MPR error code.
  7388. @ingroup MprSocket
  7389. @stability Stable
  7390. */
  7391. PUBLIC int mprSetSocketNoDelay(MprSocket *sp, bool on);
  7392. /**
  7393. Test if the socket is doing an SSL handshake
  7394. @param sp Socket object returned from #mprCreateSocket
  7395. @return True if the SSL stack is handshaking
  7396. @ingroup MprSocket
  7397. @stability Stable
  7398. */
  7399. PUBLIC bool mprSocketHandshaking(MprSocket *sp);
  7400. /**
  7401. Test if the socket has buffered data.
  7402. @description Use this function to avoid waiting for incoming I/O if data is already buffered.
  7403. @param sp Socket object returned from #mprCreateSocket
  7404. @return True if the socket has pending data to read or write.
  7405. @ingroup MprSocket
  7406. @stability Stable
  7407. */
  7408. PUBLIC bool mprSocketHasBuffered(MprSocket *sp);
  7409. /**
  7410. Test if the socket has buffered read data.
  7411. @description Use this function to avoid waiting for incoming I/O if data is already buffered.
  7412. @param sp Socket object returned from #mprCreateSocket
  7413. @return True if the socket has pending read data.
  7414. @ingroup MprSocket
  7415. @stability Stable
  7416. */
  7417. PUBLIC bool mprSocketHasBufferedRead(MprSocket *sp);
  7418. /**
  7419. Test if the socket has buffered write data.
  7420. @description Use this function to detect that there is buffer data to write in a SSL stack.
  7421. @param sp Socket object returned from #mprCreateSocket
  7422. @return True if the socket has pending write data.
  7423. @ingroup MprSocket
  7424. @stability Stable
  7425. */
  7426. PUBLIC bool mprSocketHasBufferedWrite(MprSocket *sp);
  7427. /**
  7428. Steal the socket handle
  7429. @description Return the socket handle and set the MprSocket handle to the invalid socket.
  7430. This enables callers to use the O/S socket handle for their own purposes.
  7431. @param sp Socket object returned from #mprCreateSocket
  7432. @ingroup MprSocket
  7433. @stability Stable
  7434. */
  7435. PUBLIC Socket mprStealSocketHandle(MprSocket *sp);
  7436. /**
  7437. Upgrade a socket to use SSL/TLS
  7438. @param sp Socket to upgrade
  7439. @param ssl SSL configurations to use. Set to NULL to use the default.
  7440. @param peerName Required peer name in handshake with peer. Used by clients to verify the server hostname.
  7441. @returns Zero if successful, otherwise a negative MPR error code.
  7442. @ingroup MprSocket
  7443. @stability Stable
  7444. */
  7445. PUBLIC int mprUpgradeSocket(MprSocket *sp, struct MprSsl *ssl, cchar *peerName);
  7446. /**
  7447. Write to a socket
  7448. @description Write a block of data to a socket. If the socket is in non-blocking mode (the default), the write
  7449. may return having written less than the required bytes.
  7450. @param sp Socket object returned from #mprCreateSocket
  7451. @param buf Reference to a block to write to the socket
  7452. @param len Length of data to write. This may be less than the requested write length if the socket is in non-blocking
  7453. mode. Will return a negative MPR error code on errors.
  7454. @return A count of bytes actually written. Return a negative MPR error code on errors and if the socket cannot absorb any
  7455. more data. If the transport is saturated, will return a negative error and mprGetError() returns EAGAIN
  7456. or EWOULDBLOCK.
  7457. @ingroup MprSocket
  7458. @stability Stable
  7459. */
  7460. PUBLIC ssize mprWriteSocket(MprSocket *sp, cvoid *buf, ssize len);
  7461. /**
  7462. Write to a string to a socket
  7463. @description Write a string to a socket. If the socket is in non-blocking mode (the default), the write
  7464. may return having written less than the required bytes.
  7465. @param sp Socket object returned from #mprCreateSocket
  7466. @param str Null terminated string to write.
  7467. @return A count of bytes actually written. Return a negative MPR error code on errors.
  7468. @ingroup MprSocket
  7469. @stability Stable
  7470. */
  7471. PUBLIC ssize mprWriteSocketString(MprSocket *sp, cchar *str);
  7472. /**
  7473. Write a vector of buffers to a socket
  7474. @description Do scatter/gather I/O by writing a vector of buffers to a socket. May return with a short write having written
  7475. less than the total.
  7476. @param sp Socket object returned from #mprCreateSocket
  7477. @param iovec Vector of data to write before the file contents
  7478. @param count Count of entries in iovec
  7479. @return A count of bytes actually written. Return a negative MPR error code on errors and if the socket cannot absorb any
  7480. more data. If the transport is saturated, will return a negative error and mprGetError() returns EAGAIN or EWOULDBLOCK
  7481. @ingroup MprSocket
  7482. @stability Stable
  7483. */
  7484. PUBLIC ssize mprWriteSocketVector(MprSocket *sp, MprIOVec *iovec, int count);
  7485. /************************************ SSL *************************************/
  7486. /*
  7487. Root certificates for verifying peer certs.
  7488. */
  7489. #ifndef ME_SSL_ROOTS_CERT
  7490. #define ME_SSL_ROOTS_CERT "roots.crt"
  7491. #endif
  7492. #ifndef ME_MPR_SSL_CACHE
  7493. #define ME_MPR_SSL_CACHE 512
  7494. #endif
  7495. #ifndef ME_MPR_SSL_LOG_LEVEL
  7496. #define ME_MPR_SSL_LOG_LEVEL 7
  7497. #endif
  7498. #ifndef ME_MPR_SSL_RENEGOTIATE
  7499. #define ME_MPR_SSL_RENEGOTIATE 1
  7500. #endif
  7501. #ifndef ME_MPR_SSL_TICKET
  7502. #define ME_MPR_SSL_TICKET 1
  7503. #endif
  7504. #ifndef ME_MPR_SSL_TIMEOUT
  7505. #define ME_MPR_SSL_TIMEOUT 86400
  7506. #endif
  7507. #define ME_MPR_HAS_ALPN 1
  7508. #define MPR_HAS_CRPTO_ENGINE 1
  7509. /**
  7510. Callback function for SNI connections.
  7511. @ingroup MprSsl
  7512. @stability Evolving
  7513. */
  7514. typedef struct MprSsl *(*MprMatchSsl)(MprSocket *sp, cchar *hostname);
  7515. /**
  7516. SSL control structure
  7517. @defgroup MprSsl MprSsl
  7518. @stability Internal
  7519. */
  7520. typedef struct MprSsl {
  7521. cchar *keyFile; /**< Alternatively, locate the key in a file */
  7522. cchar *certFile; /**< Certificate filename */
  7523. cchar *revoke; /**< Certificate revocation list */
  7524. cchar *caFile; /**< Certificate verification cert file or bundle */
  7525. cchar *caPath; /**< Certificate verification cert directory (OpenSSL only) */
  7526. cchar *ciphers; /**< Candidate ciphers to use */
  7527. cchar *device; /**< Crypto hardware device to use */
  7528. cchar *hostname; /**< Hostname when using SNI */
  7529. MprList *alpn; /**< ALPN protocols */
  7530. void *config; /**< Extended provider SSL configuration */
  7531. bool changed; /**< Set if there is a change in the SSL config. Reset by providers */
  7532. bool configured; /**< Set if this SSL configuration has been processed */
  7533. bool ticket; /**< Enable session tickets */
  7534. bool renegotiate; /**< Renegotiate sessions */
  7535. bool verifyPeer; /**< Verify the peer verificate */
  7536. bool verifyIssuer; /**< Set if the certificate issuer should be also verified */
  7537. bool verified; /**< Peer has been verified */
  7538. int logLevel; /**< Level at which to start tracing SSL events */
  7539. int verifyDepth; /**< Cert chain depth that should be verified */
  7540. int protocols; /**< SSL protocols */
  7541. MprMatchSsl matchSsl; /**< Match the SSL configuration for SNI */
  7542. MprMutex *mutex; /**< Multithread sync */
  7543. } MprSsl;
  7544. /*
  7545. SSL protocols
  7546. */
  7547. #define MPR_PROTO_SSLV2 0x1 /**< SSL V2 protocol */
  7548. #define MPR_PROTO_SSLV3 0x2 /**< SSL V3 protocol */
  7549. #define MPR_PROTO_TLSV1_0 0x10 /**< TLS V1.0 protocol */
  7550. #define MPR_PROTO_TLSV1_1 0x20 /**< TLS V1.1 protocol */
  7551. #define MPR_PROTO_TLSV1_2 0x40 /**< TLS V1.2 protocol */
  7552. #define MPR_PROTO_TLSV1_3 0x80 /**< TLS V1.3 protocol */
  7553. #define MPR_PROTO_TLSV1 (MPR_PROTO_TLSV1_0 | MPR_PROTO_TLSV1_1 | MPR_PROTO_TLSV1_2 | MPR_PROTO_TLSV1_3)
  7554. #define MPR_PROTO_ALL 0xF3 /**< All protocols */
  7555. /**
  7556. Add the ciphers to use for SSL
  7557. @param ssl SSL instance returned from #mprCreateSsl
  7558. @param ciphers Cipher string to add to any existing ciphers
  7559. @ingroup MprSsl
  7560. @stability Stable
  7561. */
  7562. PUBLIC void mprAddSslCiphers(struct MprSsl *ssl, cchar *ciphers);
  7563. /**
  7564. Create the SSL control structure
  7565. @param server True if the SSL configuration will be used on the server side.
  7566. @ingroup MprSsl
  7567. @stability Stable
  7568. */
  7569. PUBLIC struct MprSsl *mprCreateSsl(int server);
  7570. /**
  7571. Create the a new SSL control structure based on an existing structure
  7572. @param src Structure to clone
  7573. @ingroup MprSsl
  7574. @stability Stable
  7575. */
  7576. PUBLIC struct MprSsl *mprCloneSsl(MprSsl *src);
  7577. /**
  7578. Load the SSL module.
  7579. @ingroup MprSsl
  7580. @stability Stable
  7581. */
  7582. PUBLIC int mprLoadSsl(void);
  7583. /**
  7584. Initialize the SSL provider
  7585. @ingroup MprSsl
  7586. @stability Stable
  7587. */
  7588. PUBLIC int mprSslInit(void *unused, MprModule *module);
  7589. /**
  7590. Preload SSL configuration
  7591. @ingroup MprSsl
  7592. @stability Evolving
  7593. */
  7594. PUBLIC int mprPreloadSsl(struct MprSsl *ssl, int flags);
  7595. /**
  7596. Set the ALPN protocols for SSL
  7597. @ingroup MprSsl
  7598. @stability Evolving
  7599. */
  7600. PUBLIC void mprSetSslAlpn(struct MprSsl *ssl, cchar *protocols);
  7601. /**
  7602. Set certificate to use for SSL
  7603. @param ssl SSL instance returned from #mprCreateSsl
  7604. @param certFile Path to the SSL certificate file
  7605. @ingroup MprSsl
  7606. @stability Stable
  7607. */
  7608. PUBLIC void mprSetSslCertFile(struct MprSsl *ssl, cchar *certFile);
  7609. /**
  7610. Set the client certificate file to use for SSL
  7611. @param ssl SSL instance returned from #mprCreateSsl
  7612. @param caFile Path to the SSL client certificate file
  7613. @ingroup MprSsl
  7614. @stability Stable
  7615. */
  7616. PUBLIC void mprSetSslCaFile(struct MprSsl *ssl, cchar *caFile);
  7617. /**
  7618. Set the path for the client certificate directory
  7619. @description This is supported for OpenSSL only.
  7620. @param ssl SSL instance returned from #mprCreateSsl
  7621. @param caPath Path to the SSL client certificate directory
  7622. @ingroup MprSsl
  7623. @stability Deprecated
  7624. @internal
  7625. */
  7626. PUBLIC void mprSetSslCaPath(struct MprSsl *ssl, cchar *caPath);
  7627. /**
  7628. Set the ciphers to use
  7629. @param ssl SSL instance returned from #mprCreateSsl
  7630. @param ciphers String of suitable ciphers
  7631. @ingroup MprSsl
  7632. @stability Stable
  7633. */
  7634. PUBLIC void mprSetSslCiphers(MprSsl *ssl, cchar *ciphers);
  7635. /**
  7636. Set the key file to use for SSL
  7637. @param ssl SSL instance returned from #mprCreateSsl
  7638. @param keyFile Path to the SSL key file
  7639. @ingroup MprSsl
  7640. @stability Stable
  7641. */
  7642. PUBLIC void mprSetSslKeyFile(struct MprSsl *ssl, cchar *keyFile);
  7643. /**
  7644. Set the desired hostname for this SSL configuration when using SNI
  7645. @param ssl SSL instance returned from #mprCreateSsl
  7646. @param hostname Name of the host when using SNI
  7647. @ingroup MprSsl
  7648. @stability Stable
  7649. */
  7650. PUBLIC void mprSetSslHostname(MprSsl *ssl, cchar *hostname);
  7651. /**
  7652. Set the SSL log level at which to start tracing SSL events
  7653. @param ssl SSL instance returned from #mprCreateSsl
  7654. @param level Log level (0-9)
  7655. @ingroup MprSsl
  7656. @stability Stable
  7657. */
  7658. PUBLIC void mprSetSslLogLevel(struct MprSsl *ssl, int level);
  7659. /**
  7660. Set a match callback to select the appropriate SSL configuration to use in response to a client SNI hello.
  7661. @param ssl SSL configuration instance
  7662. @param match MprMatchSsl callback.
  7663. @ingroup MprSsl
  7664. @stability Evolving
  7665. */
  7666. PUBLIC void mprSetSslMatch(struct MprSsl *ssl, MprMatchSsl match);
  7667. /**
  7668. Set the SSL protocol to use
  7669. @param ssl SSL instance returned from #mprCreateSsl
  7670. @param protocols SSL protocols mask
  7671. @ingroup MprSsl
  7672. @stability Stable
  7673. */
  7674. PUBLIC void mprSetSslProtocols(struct MprSsl *ssl, int protocols);
  7675. /**
  7676. Set the SSL provider to use
  7677. @param provider Socket provider object
  7678. @ingroup MprSsl
  7679. @stability Stable
  7680. */
  7681. PUBLIC void mprSetSslProvider(MprSocketProvider *provider);
  7682. /**
  7683. Control SSL session renegotiation
  7684. @param ssl SSL instance returned from #mprCreateSsl
  7685. @param enable Set to true to enable renegotiation (enabled by default)
  7686. @ingroup MprSsl
  7687. @stability Internal
  7688. */
  7689. PUBLIC void mprSetSslRenegotiate(MprSsl *ssl, bool enable);
  7690. /**
  7691. Define a list of certificates to revoke
  7692. @param ssl SSL instance returned from #mprCreateSsl
  7693. @param revoke Path to the SSL certificate revocation list
  7694. @ingroup MprSsl
  7695. @stability Stable
  7696. */
  7697. PUBLIC void mprSetSslRevoke(struct MprSsl *ssl, cchar *revoke);
  7698. /**
  7699. Enable SSL session tickets
  7700. @param ssl SSL instance returned from #mprCreateSsl
  7701. @param enable Set to true to enable
  7702. @ingroup MprSsl
  7703. @stability Stable
  7704. */
  7705. PUBLIC void mprSetSslTicket(MprSsl *ssl, bool enable);
  7706. /**
  7707. Control the depth of SSL SSL certificate verification
  7708. @param ssl SSL instance returned from #mprCreateSsl
  7709. @param depth Set to the number of intermediate certificates to verify. Defaults to 1.
  7710. @ingroup MprSsl
  7711. @stability Stable
  7712. */
  7713. PUBLIC void mprVerifySslDepth(struct MprSsl *ssl, int depth);
  7714. /**
  7715. Control the verification of SSL certificate issuers
  7716. @param ssl SSL instance returned from #mprCreateSsl
  7717. @param on Set to true to enable SSL certificate issuer verification.
  7718. @ingroup MprSsl
  7719. @stability Stable
  7720. */
  7721. PUBLIC void mprVerifySslIssuer(struct MprSsl *ssl, bool on);
  7722. /**
  7723. Require verification of peer certificates
  7724. @param ssl SSL instance returned from #mprCreateSsl
  7725. @param on Set to true to enable peer SSL certificate verification.
  7726. @ingroup MprSsl
  7727. @stability Stable
  7728. */
  7729. PUBLIC void mprVerifySslPeer(struct MprSsl *ssl, bool on);
  7730. #if ME_COM_EST
  7731. PUBLIC int mprCreateEstModule(void);
  7732. #endif
  7733. #if ME_COM_MATRIXSSL
  7734. PUBLIC int mprCreateMatrixSslModule(void);
  7735. #endif
  7736. #if ME_COM_NANOSSL
  7737. PUBLIC int mprCreateNanoSslModule(void);
  7738. #endif
  7739. #if ME_COM_OPENSSL
  7740. PUBLIC int mprCreateOpenSslModule(void);
  7741. #endif
  7742. /******************************* Worker Threads *******************************/
  7743. /**
  7744. Worker thread callback signature
  7745. @param data worker callback data. Set via mprStartWorker or mprActivateWorker
  7746. @param worker Reference to the worker thread object
  7747. @ingroup MprWorker
  7748. @stability Stable
  7749. */
  7750. typedef void (*MprWorkerProc)(void *data, struct MprWorker *worker);
  7751. /**
  7752. Statistics for Workers
  7753. @ingroup MprWorker
  7754. @stability Internal
  7755. */
  7756. typedef struct MprWorkerStats {
  7757. int max; /**< Configured max number of workers */
  7758. int min; /**< Configured minimum number of workers */
  7759. int maxUsed; /**< Max number of workers ever used used */
  7760. int idle; /**< Number of idle workers */
  7761. int busy; /**< Number of busy workers */
  7762. int yielded; /**< Number of busy workers yielded for GC */
  7763. } MprWorkerStats;
  7764. /**
  7765. Get the Worker service statistics
  7766. @param stats Reference to stats object to receive the stats
  7767. @ingroup MprWorker
  7768. @stability Internal
  7769. */
  7770. PUBLIC void mprGetWorkerStats(MprWorkerStats *stats);
  7771. /**
  7772. Worker Thread Service
  7773. @description The MPR provides a worker thread pool for rapid starting and assignment of threads to tasks.
  7774. @ingroup MprWorker
  7775. @stability Internal
  7776. */
  7777. typedef struct MprWorkerService {
  7778. MprList *busyThreads; /**< List of threads to service tasks */
  7779. MprList *idleThreads; /**< List of threads to service tasks */
  7780. int maxThreads; /**< Max # threads in worker pool */
  7781. int maxUsedThreads; /**< Max threads ever used */
  7782. int minThreads; /**< Max # threads in worker pool */
  7783. int nextThreadNum; /**< Unique next thread number */
  7784. int numThreads; /**< Current number of threads in worker pool */
  7785. ssize stackSize; /**< Stack size for worker threads */
  7786. MprMutex *mutex; /**< Per task synchronization */
  7787. struct MprEvent *pruneTimer; /**< Timer for excess threads pruner */
  7788. MprWorkerProc startWorker; /**< Worker thread startup hook */
  7789. } MprWorkerService;
  7790. /*
  7791. Internal
  7792. */
  7793. PUBLIC MprWorkerService *mprCreateWorkerService(void);
  7794. PUBLIC int mprStartWorkerService(void);
  7795. PUBLIC void mprStopWorkers(void);
  7796. PUBLIC void mprSetWorkerStartCallback(MprWorkerProc start);
  7797. /**
  7798. Get the count of available worker threads
  7799. Return the count of free threads in the worker thread pool.
  7800. @returns An integer count of worker threads.
  7801. @ingroup MprWorker
  7802. @stability Stable
  7803. */
  7804. PUBLIC int mprAvailableWorkers(void);
  7805. /**
  7806. Set the default worker stack size
  7807. @param size Stack size in bytes
  7808. @ingroup MprWorker
  7809. @stability Stable
  7810. */
  7811. PUBLIC void mprSetWorkerStackSize(int size);
  7812. /**
  7813. Set the minimum count of worker threads
  7814. Set the count of threads the worker pool will have. This will cause the worker pool to pre-create at least this
  7815. many threads.
  7816. @param count Minimum count of threads to use.
  7817. @ingroup MprWorker
  7818. @stability Stable
  7819. */
  7820. PUBLIC void mprSetMinWorkers(int count);
  7821. /**
  7822. Set the maximum count of worker threads
  7823. Set the maximum number of worker pool threads for the MPR. If this number if less than the current number of threads,
  7824. excess threads will be gracefully pruned as they exit.
  7825. @param count Maximum limit of threads to define.
  7826. @ingroup MprWorker
  7827. @stability Stable
  7828. */
  7829. PUBLIC void mprSetMaxWorkers(int count);
  7830. /**
  7831. Get the maximum count of worker pool threads
  7832. Get the maximum limit of worker pool threads.
  7833. @return The maximum count of worker pool threads.
  7834. @ingroup MprWorker
  7835. @stability Stable
  7836. */
  7837. PUBLIC int mprGetMaxWorkers(void);
  7838. /*
  7839. Worker Thread State
  7840. */
  7841. #define MPR_WORKER_BUSY 0x1 /**< Worker currently running to a callback */
  7842. #define MPR_WORKER_PRUNED 0x2 /**< Worker has been pruned and will be terminated */
  7843. #define MPR_WORKER_IDLE 0x4 /**< Worker is sleeping (idle) on idleCond */
  7844. /**
  7845. Worker thread structure. Worker threads are allocated and dedicated to tasks. When idle, they are stored in
  7846. an idle worker pool. An idle worker pruner runs regularly and terminates idle workers to save memory.
  7847. @defgroup MprWorker MprWorker
  7848. @see MPrWorkerProc MprWorkerService MprWorkerStats mprActivateWorker mprDedicateWorker mprGetCurrentWorker
  7849. mprGetMaxWorkers mprGetWorkerServiceStats mprReleaseWorker mprSetMaxWorkers mprSetMinWorkers
  7850. mprSetWorkerStackSize mprStartWorker
  7851. @stability Internal
  7852. */
  7853. typedef struct MprWorker {
  7854. MprWorkerProc proc; /**< Procedure to run */
  7855. MprWorkerProc cleanup; /**< Procedure to cleanup after run before sleeping */
  7856. void *data; /**< User per-worker data */
  7857. int state; /**< Worker state */
  7858. int running; /**< Worker running a job */
  7859. MprThread *thread; /**< Thread associated with this worker */
  7860. MprTicks lastActivity; /**< When the worker was last used */
  7861. MprWorkerService *workerService; /**< Worker service */
  7862. MprCond *idleCond; /**< Used to wait for work */
  7863. } MprWorker;
  7864. /*
  7865. Internal
  7866. */
  7867. PUBLIC void mprActivateWorker(MprWorker *worker, MprWorkerProc proc, void *data);
  7868. /**
  7869. Dedicate a worker thread to a current real thread. This implements thread affinity and is required on some platforms
  7870. where some APIs (waitpid on uClibc) cannot be called on a different thread.
  7871. @param worker Worker thread reference
  7872. @ingroup MprWorker
  7873. @stability Internal
  7874. */
  7875. PUBLIC void mprDedicateWorker(MprWorker *worker);
  7876. /**
  7877. Get the worker object if the current thread is actually a worker thread.
  7878. @returns A worker thread object if the thread is a worker thread. Otherwise, NULL.
  7879. @ingroup MprWorker
  7880. @stability Stable
  7881. */
  7882. PUBLIC MprWorker *mprGetCurrentWorker(void);
  7883. /**
  7884. Get the count of workers in the busy queue.
  7885. @description This is thread-safe with respect to MPR->state
  7886. @return Count of workers in the busy queue
  7887. @ingroup MprWorker
  7888. @stability Stable
  7889. */
  7890. PUBLIC ssize mprGetBusyWorkerCount(void);
  7891. /**
  7892. Release a worker thread. This releases a worker thread to be assignable to any real thread.
  7893. @param worker Worker thread reference
  7894. @stability Internal
  7895. */
  7896. PUBLIC void mprReleaseWorker(MprWorker *worker);
  7897. /**
  7898. Start a worker thread
  7899. @description Start a worker thread executing the given worker procedure callback.
  7900. @param proc Worker procedure callback
  7901. @param data Data parameter to the callback
  7902. @returns Zero if successful, otherwise a negative MPR error code.
  7903. @stability Internal
  7904. */
  7905. PUBLIC int mprStartWorker(MprWorkerProc proc, void *data);
  7906. /********************************** Crypto ************************************/
  7907. /**
  7908. Return a random number
  7909. @returns A random integer
  7910. @ingroup Mpr
  7911. @stability Stable
  7912. */
  7913. PUBLIC int mprRandom(void);
  7914. /**
  7915. Decode a null terminated string using base-46 encoding.
  7916. @description Decoding will terminate at the first null or '='.
  7917. @param str String to decode
  7918. @returns Buffer containing the encoded data
  7919. @ingroup Mpr
  7920. @stability Stable
  7921. */
  7922. PUBLIC char *mprDecode64(cchar *str);
  7923. /**
  7924. Decode base 64 blocks up to a NULL or equals
  7925. */
  7926. #define MPR_DECODE_TOKEQ 1
  7927. /**
  7928. Decode a null terminated string using base-46 encoding.
  7929. @param buf String to decode
  7930. @param len Return parameter with the Length of the decoded data
  7931. @param flags Set to MPR_DECODE_TOKEQ to stop at the first '='
  7932. @returns Buffer containing the encoded data and returns length in len.
  7933. @ingroup Mpr
  7934. @stability Stable
  7935. */
  7936. PUBLIC char *mprDecode64Block(cchar *buf, ssize *len, int flags);
  7937. /**
  7938. Encode a string using base-46 encoding.
  7939. @param str String to encode
  7940. @returns Buffer containing the encoded string.
  7941. @ingroup Mpr
  7942. @stability Stable
  7943. */
  7944. PUBLIC char *mprEncode64(cchar *str);
  7945. // Internal
  7946. PUBLIC void mprEncodeGenerate(void);
  7947. /**
  7948. Encode buffer using base-46 encoding.
  7949. @param buf Buffer to encode
  7950. @param len Length of the buffer to encode
  7951. @returns Buffer containing the encoded string.
  7952. @ingroup Mpr
  7953. @stability Stable
  7954. */
  7955. PUBLIC char *mprEncode64Block(cchar *buf, ssize len);
  7956. /**
  7957. Get an MD5 checksum
  7958. @param str String to examine
  7959. @returns An allocated MD5 checksum string.
  7960. @ingroup Mpr
  7961. @stability Stable
  7962. */
  7963. PUBLIC char *mprGetMD5(cchar *str);
  7964. /**
  7965. Get an MD5 checksum with optional prefix string and buffer length
  7966. @param buf Buffer to checksum
  7967. @param len Size of the buffer
  7968. @param prefix String prefix to insert at the start of the result
  7969. @returns An allocated MD5 checksum string.
  7970. @ingroup Mpr
  7971. @stability Stable
  7972. */
  7973. PUBLIC char *mprGetMD5WithPrefix(cchar *buf, ssize len, cchar *prefix);
  7974. /**
  7975. Get an SHA1 checksum
  7976. @param str String to examine
  7977. @returns An allocated SHA1 checksum string.
  7978. @ingroup Mpr
  7979. @stability Stable
  7980. */
  7981. PUBLIC char *mprGetSHA(cchar *str);
  7982. /**
  7983. Get an SHA1 checksum with optional prefix string and buffer length
  7984. @param buf Buffer to checksum
  7985. @param len Size of the buffer
  7986. @param prefix String prefix to insert at the start of the result
  7987. @returns An allocated string containing an SHA1 checksum.
  7988. @ingroup Mpr
  7989. @stability Stable
  7990. */
  7991. PUBLIC char *mprGetSHAWithPrefix(cchar *buf, ssize len, cchar *prefix);
  7992. /**
  7993. Get an SHA1 checksum of a null terminated string
  7994. @param str String to checksum
  7995. @returns An allocated string containing an SHA1 checksum.
  7996. @ingroup Mpr
  7997. @stability Stable
  7998. */
  7999. PUBLIC char *mprGetSHABase64(cchar *str);
  8000. /**
  8001. Encrypt a password using the Blowfish algorithm
  8002. @param password User's password to encrypt
  8003. @param salt Salt text to add to password. Helps to make each user's password unique.
  8004. @param rounds Number of times to encrypt. More times, makes the routine slower and passwords harder to crack.
  8005. @return The encrypted password.
  8006. @ingroup Mpr
  8007. @stability Stable
  8008. */
  8009. PUBLIC char *mprCryptPassword(cchar *password, cchar *salt, int rounds);
  8010. /**
  8011. Get a password from the terminal console
  8012. @param prompt Text prompt to display before reading the password
  8013. @return The entered password.
  8014. @ingroup Mpr
  8015. @stability Stable
  8016. */
  8017. PUBLIC char *mprGetPassword(cchar *prompt);
  8018. /**
  8019. Make salt for adding to a password.
  8020. @param size Size in bytes of the salt text.
  8021. @return The random salt text.
  8022. @ingroup Mpr
  8023. @stability Stable
  8024. */
  8025. PUBLIC char *mprMakeSalt(ssize size);
  8026. /**
  8027. Make a password hash for a plain-text password using the Blowfish algorithm.
  8028. @param password User's password to encrypt
  8029. @param saltLength Length of salt text to add to password. Helps to make each user's password unique.
  8030. @param rounds Number of times to encrypt. More times, makes the routine slower and passwords harder to crack.
  8031. @return The encrypted password.
  8032. @ingroup Mpr
  8033. @stability Stable
  8034. */
  8035. PUBLIC char *mprMakePassword(cchar *password, int saltLength, int rounds);
  8036. /**
  8037. Check a plain-text password against the defined hashed password.
  8038. @param plainTextPassword User's plain-text-password to check
  8039. @param passwordHash Required password in hashed format previously computed by mprMakePassword.
  8040. @return True if the password is correct.
  8041. @ingroup Mpr
  8042. @stability Stable
  8043. */
  8044. PUBLIC bool mprCheckPassword(cchar *plainTextPassword, cchar *passwordHash);
  8045. /********************************* Encoding ***********************************/
  8046. /*
  8047. Character encoding masks
  8048. */
  8049. #define MPR_ENCODE_HTML 0x1 /* Encode HTML specials */
  8050. #define MPR_ENCODE_SHELL 0x2 /* Encode shell specials */
  8051. #define MPR_ENCODE_URI 0x4 /* Encode for Uri.encode */
  8052. #define MPR_ENCODE_URI_COMPONENT 0x8 /* Encode for Uri.encodeComponent */
  8053. #define MPR_ENCODE_JS_URI 0x10 /* Encode according to ECMA encodeUri() */
  8054. #define MPR_ENCODE_JS_URI_COMPONENT 0x20 /* Encode according to ECMA encodeUriComponent */
  8055. #define MPR_ENCODE_SQL 0x40 /* Encode for a SQL command */
  8056. /**
  8057. Encode a string escaping typical command (shell) characters
  8058. @description Encode a string escaping all dangerous characters that have meaning for the unix or MS-DOS command shells.
  8059. @param cmd Command string to encode
  8060. @param escChar Escape character to use when encoding the command.
  8061. @return An allocated string containing the escaped command.
  8062. @ingroup Mpr
  8063. @stability Stable
  8064. */
  8065. PUBLIC char *mprEscapeCmd(cchar *cmd, int escChar);
  8066. /**
  8067. Encode a string by escaping typical HTML characters
  8068. @description Encode a string escaping all dangerous characters that have meaning in HTML documents
  8069. @param html HTML content to encode
  8070. @return An allocated string containing the escaped HTML.
  8071. @ingroup Mpr
  8072. @stability Stable
  8073. */
  8074. PUBLIC char *mprEscapeHtml(cchar *html);
  8075. /**
  8076. Encode a string by escaping SQL special characters
  8077. @description Encode a string escaping all dangerous characters that have meaning in SQL commands
  8078. @param cmd SQL command to encode
  8079. @return An allocated string containing the escaped SQL command.
  8080. @ingroup Mpr
  8081. @stability Stable
  8082. */
  8083. PUBLIC char *mprEscapeSQL(cchar *cmd);
  8084. /**
  8085. Encode a string by escaping URI characters
  8086. @description Encode a string escaping all characters that have meaning for URIs.
  8087. @param uri URI to encode
  8088. @param map Map to encode characters. Select from MPR_ENCODE_URI or MPR_ENCODE_URI_COMPONENT.
  8089. @return An allocated string containing the encoded URI.
  8090. @ingroup Mpr
  8091. @stability Stable
  8092. */
  8093. PUBLIC char *mprUriEncode(cchar *uri, int map);
  8094. /**
  8095. Decode a URI string by de-scaping URI characters
  8096. @description Decode a string with www-encoded characters that have meaning for URIs.
  8097. @param uri URI to decode
  8098. @return A reference to the buf argument.
  8099. @ingroup Mpr
  8100. @stability Stable
  8101. */
  8102. PUBLIC char *mprUriDecode(cchar *uri);
  8103. /**
  8104. Decode a URI string by de-scaping URI characters
  8105. @description Decode a string with www-encoded characters that have meaning for URIs.
  8106. This routines operates in-situ and modifies the buffer.
  8107. @param uri URI to decode
  8108. @return A reference to the buf argument.
  8109. @ingroup Mpr
  8110. @stability Stable
  8111. */
  8112. PUBLIC char *mprUriDecodeInSitu(char *uri);
  8113. /********************************* Signals ************************************/
  8114. #if MACOSX
  8115. #define MPR_MAX_SIGNALS 40 /**< Max signals that can be managed */
  8116. #elif LINUX
  8117. #define MPR_MAX_SIGNALS 48
  8118. #else
  8119. #define MPR_MAX_SIGNALS 40
  8120. #endif
  8121. /**
  8122. Signal callback procedure
  8123. @ingroup MprSignal
  8124. @stability Stable
  8125. */
  8126. typedef void (*MprSignalProc)(void *arg, struct MprSignal *sp);
  8127. /**
  8128. Per signal structure
  8129. @ingroup MprSignal
  8130. @stability Internal
  8131. */
  8132. typedef struct MprSignalInfo {
  8133. int triggered; /**< Set to true when triggered */
  8134. } MprSignalInfo;
  8135. /**
  8136. Signal control structure
  8137. @defgroup MprSignal MprSignal
  8138. @see MprSignalProc MprSignalService MprSingalInfo mprAddSignalHandler mprAddStandardSignals
  8139. @stability Internal
  8140. */
  8141. typedef struct MprSignal {
  8142. struct MprSignal *next; /**< Chain of handlers on the same signo */
  8143. MprSignalProc handler; /**< Signal handler (non-native) */
  8144. void (*sigaction)(int, siginfo_t*, void *); /**< Prior sigaction handler */
  8145. void *data; /**< Handler data */
  8146. MprDispatcher *dispatcher; /**< Dispatcher to service handler */
  8147. int flags; /**< Control flags */
  8148. int signo; /**< Signal number */
  8149. } MprSignal;
  8150. /**
  8151. Signal service control
  8152. @ingroup MprSignal
  8153. @stability Internal
  8154. */
  8155. typedef struct MprSignalService {
  8156. MprSignal **signals; /**< Signal handlers */
  8157. MprList *standard; /**< Standard signal handlers */
  8158. MprMutex *mutex; /**< Multithread sync */
  8159. MprSignalInfo info[MPR_MAX_SIGNALS]; /**< Actual signal info and arg */
  8160. int hasSignals; /**< Signal sent to process */
  8161. #if ME_UNIX_LIKE
  8162. struct sigaction prior[MPR_MAX_SIGNALS];/**< Prior sigaction handler before hooking */
  8163. #endif
  8164. } MprSignalService;
  8165. /*
  8166. Internal
  8167. */
  8168. PUBLIC MprSignalService *mprCreateSignalService(void);
  8169. PUBLIC void mprStopSignalService(void);
  8170. PUBLIC void mprRemoveSignalHandler(MprSignal *sp);
  8171. PUBLIC void mprServiceSignals(void);
  8172. /**
  8173. Add standard trapping of system signals. The trapped signals are SIGINT, SIGQUIT, SIGTERM, SIGPIPE and SIGXFSZ.
  8174. SIGPIPE and SIGXFSZ are ignored. A shutdown is initiated for SIGTERM whereas SIGINT and SIGQUIT will
  8175. do an abortive exit. SIGUSR1 will do an in-process restart.
  8176. @ingroup MprSignal
  8177. @stability Stable
  8178. */
  8179. PUBLIC void mprAddStandardSignals(void);
  8180. #define MPR_SIGNAL_BEFORE 0x1 /**< Flag to mprAddSignalHandler to run handler before existing handlers */
  8181. #define MPR_SIGNAL_AFTER 0x2 /**< Flag to mprAddSignalHandler to run handler after existing handlers */
  8182. /**
  8183. Add a signal handler. The signal handling mechanism will trap the specified signal if issued and create an
  8184. event on the given dispatcher. This will cause the handler function to be safely run by the dispatcher.
  8185. Normally, signal handlers are difficult to write as the code must be Async-safe. This API permits the use of
  8186. common, single-threaded code to be used for signal handlers without worrying about pre-emption by other signals
  8187. or threads.
  8188. @param signo Signal number to handle
  8189. @param handler Call back procedure to invoke. This has the signature #MprSignalProc.
  8190. @param arg Argument to provide to the handler.
  8191. @param dispatcher Event dispatcher on which to queue an event to run the handler.
  8192. @param flags Set to either MPR_SIGNAL_BEFORE or MPR_SIGNAL_AFTER to run the handler before/after existing handlers.
  8193. @ingroup MprSignal
  8194. @stability Stable
  8195. */
  8196. PUBLIC MprSignal *mprAddSignalHandler(int signo, void *handler, void *arg, MprDispatcher *dispatcher, int flags);
  8197. /******************************** Commands ************************************/
  8198. /**
  8199. Callback function before doing a fork()
  8200. @ingroup MprCmd
  8201. @stability Stable
  8202. */
  8203. typedef void (*MprForkCallback)(void *arg);
  8204. /**
  8205. Command execution service
  8206. @stability Internal
  8207. */
  8208. typedef struct MprCmdService {
  8209. MprList *cmds; /* List of all commands. This is a static list and elements are not retained for GC */
  8210. MprMutex *mutex; /* Multithread sync */
  8211. } MprCmdService;
  8212. /*
  8213. Internal
  8214. */
  8215. PUBLIC MprCmdService *mprCreateCmdService(void);
  8216. PUBLIC void mprStopCmdService(void);
  8217. #define MPR_CMD_EOF_COUNT 2
  8218. #define MPR_CMD_VXWORKS_EOF "_ _EOF_ _" /**< Special string for VxWorks CGI to emit to signal EOF */
  8219. #define MPR_CMD_VXWORKS_EOF_LEN 9 /**< Length of MPR_CMD_VXWORKS_EOF */
  8220. /*
  8221. Channels for clientFd and serverFd
  8222. */
  8223. #define MPR_CMD_STDIN 0 /**< Stdout for the client side */
  8224. #define MPR_CMD_STDOUT 1 /**< Stdin for the client side */
  8225. #define MPR_CMD_STDERR 2 /**< Stderr for the client side */
  8226. #define MPR_CMD_MAX_PIPE 3
  8227. /*
  8228. Handler for command output and completion
  8229. */
  8230. typedef void (*MprCmdProc)(struct MprCmd *cmd, int channel, void *data);
  8231. /*
  8232. Flags for mprRunCmd
  8233. */
  8234. #define MPR_CMD_NEW_SESSION 0x1 /**< mprRunCmd flag to create a new session on unix */
  8235. #define MPR_CMD_SHOW 0x2 /**< mprRunCmd flag to show the window of the created process on windows */
  8236. #define MPR_CMD_DETACH 0x4 /**< mprRunCmd flag to detach the child process and don't wait */
  8237. #define MPR_CMD_EXACT_ENV 0x8 /**< mprRunCmd flag to use the exact environment (no inherit from parent) */
  8238. #define MPR_CMD_IN 0x1000 /**< mprRunCmd flag to connect to stdin */
  8239. #define MPR_CMD_OUT 0x2000 /**< mprRunCmd flag to capture stdout */
  8240. #define MPR_CMD_ERR 0x4000 /**< mprRunCmd flag to capture stdout */
  8241. typedef struct MprCmdFile {
  8242. char *name;
  8243. int fd;
  8244. int clientFd;
  8245. #if ME_WIN_LIKE
  8246. HANDLE handle;
  8247. #endif
  8248. } MprCmdFile;
  8249. /**
  8250. Command execution Service
  8251. @description The MprCmd service enables execution of local commands. It uses three full-duplex pipes to communicate
  8252. read, write and error data with the command.
  8253. @stability Stable.
  8254. @see mprCloseCmdFd mprCreateCmd mprDestroyCmd mprDisableCmdEvents mprDisconnectCmd mprEnableCmdEvents
  8255. mprFinalizeCmd mprGetCmdBuf mprGetCmdExitStatus mprGetCmdFd mprIsCmdComplete mprIsCmdRunning
  8256. mprReadCmd mprReapCmd mprRunCmd mprRunCmdV mprSetCmdCallback mprSetCmdDir mprSetCmdEnv mprSetCmdSearchPath
  8257. mprStartCmd mprStopCmd mprWaitForCmd mprWriteCmd mprWriteCmdBlock
  8258. @defgroup MprCmd MprCmd
  8259. @stability Internal
  8260. */
  8261. typedef struct MprCmd {
  8262. cchar *program; /**< Program path name */
  8263. int pid; /**< Process ID of the created process */
  8264. int originalPid; /**< Persistent copy of the pid */
  8265. int status; /**< Command exit status */
  8266. int flags; /**< Control flags (userFlags not here) */
  8267. int eofCount; /**< Count of end-of-files */
  8268. int requiredEof; /**< Number of EOFs required for an exit */
  8269. int argc; /**< Count of args in argv */
  8270. int timedout; /**< Request has timedout */
  8271. bool complete; /**< All channels EOF and status gathered */
  8272. bool stopped; /**< Command stopped */
  8273. cchar **makeArgv; /**< Allocated argv */
  8274. cchar **argv; /**< List of args. Null terminated */
  8275. char *dir; /**< Current working dir for the process */
  8276. cchar **defaultEnv; /**< Environment to use if no env passed to mprStartCmd */
  8277. char *searchPath; /**< Search path to use to locate the command */
  8278. MprList *env; /**< List of environment variables. Null terminated. */
  8279. MprCmdFile files[MPR_CMD_MAX_PIPE]; /**< Stdin, stdout for the command */
  8280. MprWaitHandler *handlers[MPR_CMD_MAX_PIPE];
  8281. MprDispatcher *dispatcher; /**< Dispatcher to use for wait events */
  8282. MprCmdProc callback; /**< Handler for client output and completion */
  8283. void *callbackData; /**< Managed callback data reference */
  8284. MprForkCallback forkCallback; /**< Forked client callback */
  8285. MprSignal *signal; /**< Signal handler for SIGCHLD */
  8286. void *forkData; /**< Managed fork callback data reference */
  8287. MprBuf *stdoutBuf; /**< Standard output from the client */
  8288. MprBuf *stderrBuf; /**< Standard error output from the client */
  8289. void *userData; /**< User data storage */
  8290. int userFlags; /**< User flags storage */
  8291. #if ME_WIN_LIKE
  8292. char *command; /**< Windows command line */
  8293. HANDLE thread; /**< Handle of the primary thread for the created process */
  8294. HANDLE process; /**< Process handle for the created process */
  8295. #endif
  8296. #if VXWORKS
  8297. /*
  8298. Don't use MprCond so we can build single-threaded and still use MprCmd
  8299. */
  8300. SEM_ID startCond; /**< Synchronization semaphore for task start */
  8301. SEM_ID exitCond; /**< Synchronization semaphore for task exit */
  8302. #endif
  8303. MprMutex *mutex; /**< Multithread sync */
  8304. } MprCmd;
  8305. /**
  8306. Return true if command events are enabled.
  8307. @param cmd MprCmd object created via mprCreateCmd
  8308. @param channel Channel number to close. Should be either MPR_CMD_STDIN, MPR_CMD_STDOUT or MPR_CMD_STDERR.
  8309. @return true if I/O events are enabled for the given channel.
  8310. @ingroup MprCmd
  8311. @stability Internal
  8312. */
  8313. PUBLIC bool mprAreCmdEventsEnabled(MprCmd *cmd, int channel);
  8314. /**
  8315. Close the command channel
  8316. @param cmd MprCmd object created via mprCreateCmd
  8317. @param channel Channel number to close. Should be either MPR_CMD_STDIN, MPR_CMD_STDOUT or MPR_CMD_STDERR.
  8318. @ingroup MprCmd
  8319. @stability Stable
  8320. */
  8321. PUBLIC void mprCloseCmdFd(MprCmd *cmd, int channel);
  8322. /**
  8323. Create a new Command object
  8324. @returns A newly allocated MprCmd object.
  8325. @ingroup MprCmd
  8326. @stability Stable
  8327. */
  8328. PUBLIC MprCmd *mprCreateCmd(MprDispatcher *dispatcher);
  8329. /**
  8330. Destroy the command
  8331. @param cmd MprCmd object created via mprCreateCmd
  8332. @ingroup MprCmd
  8333. @stability Stable
  8334. */
  8335. PUBLIC void mprDestroyCmd(MprCmd *cmd);
  8336. /**
  8337. Disable command I/O events. This disables events on a given channel.
  8338. @param cmd MprCmd object created via mprCreateCmd
  8339. @param channel Channel number to close. Should be either MPR_CMD_STDIN, MPR_CMD_STDOUT or MPR_CMD_STDERR.
  8340. @ingroup MprCmd
  8341. @stability Stable
  8342. */
  8343. PUBLIC void mprDisableCmdEvents(MprCmd *cmd, int channel);
  8344. /**
  8345. Disconnect a command its underlying I/O channels. This is used to prevent further I/O wait events while
  8346. still preserving the MprCmd object.
  8347. @param cmd MprCmd object created via mprCreateCmd
  8348. @ingroup MprCmd
  8349. @stability Stable
  8350. */
  8351. PUBLIC void mprDisconnectCmd(MprCmd *cmd);
  8352. /**
  8353. Enable command I/O events. This enables events on a given channel.
  8354. @param cmd MprCmd object created via mprCreateCmd
  8355. @param channel Channel number to close. Should be either MPR_CMD_STDIN, MPR_CMD_STDOUT or MPR_CMD_STDERR.
  8356. @ingroup MprCmd
  8357. @stability Stable
  8358. */
  8359. PUBLIC void mprEnableCmdEvents(MprCmd *cmd, int channel);
  8360. /**
  8361. Enable command I/O events for the command's STDOUT and STDERR channels
  8362. @param cmd MprCmd object created via mprCreateCmd
  8363. @param on Set to true to enable events. Set to false to disable.
  8364. @return true if I/O events are enabled for the given channel.
  8365. @ingroup MprCmd
  8366. @stability Stable
  8367. */
  8368. PUBLIC void mprEnableCmdOutputEvents(MprCmd *cmd, bool on);
  8369. /**
  8370. Finalize the writing of data to the command process
  8371. @param cmd MprCmd object created via mprCreateCmd
  8372. @ingroup MprCmd
  8373. @stability Stable
  8374. */
  8375. PUBLIC void mprFinalizeCmd(MprCmd *cmd);
  8376. /**
  8377. Get the count of active commands.
  8378. @description This is thread-safe with respect to MPR->state
  8379. @return Count of running commands
  8380. @ingroup MprCmd
  8381. @stability Stable
  8382. */
  8383. PUBLIC ssize mprGetActiveCmdCount(void);
  8384. /**
  8385. Get the underlying buffer for a channel
  8386. @param cmd MprCmd object created via mprCreateCmd
  8387. @param channel Channel number to close. Should be either MPR_CMD_STDIN, MPR_CMD_STDOUT or MPR_CMD_STDERR.
  8388. @return A reference to the MprBuf buffer structure
  8389. @ingroup MprCmd
  8390. @stability Stable
  8391. */
  8392. PUBLIC MprBuf *mprGetCmdBuf(MprCmd *cmd, int channel);
  8393. /**
  8394. Get the command exit status
  8395. @param cmd MprCmd object created via mprCreateCmd
  8396. @return status If the command has exited, a status between 0 and 255 is returned. Otherwise, a negative error
  8397. code is returned.
  8398. @ingroup MprCmd
  8399. @stability Stable
  8400. */
  8401. PUBLIC int mprGetCmdExitStatus(MprCmd *cmd);
  8402. /**
  8403. Get the underlying file descriptor for an I/O channel
  8404. @param cmd MprCmd object created via mprCreateCmd
  8405. @param channel Channel number to close. Should be either MPR_CMD_STDIN, MPR_CMD_STDOUT or MPR_CMD_STDERR.
  8406. @return The file descriptor
  8407. @ingroup MprCmd
  8408. @stability Stable
  8409. */
  8410. PUBLIC int mprGetCmdFd(MprCmd *cmd, int channel);
  8411. /**
  8412. Test if a command is complete. A command is complete when the child has exited and all command output and error
  8413. output has been received.
  8414. @param cmd MprCmd object created via mprCreateCmd
  8415. */
  8416. PUBLIC int mprIsCmdComplete(MprCmd *cmd);
  8417. /**
  8418. Test if the command is still running.
  8419. @param cmd MprCmd object created via mprCreateCmd
  8420. @return True if the command is still running
  8421. @ingroup MprCmd
  8422. @stability Stable
  8423. */
  8424. PUBLIC bool mprIsCmdRunning(MprCmd *cmd);
  8425. #if ME_WIN_LIKE
  8426. /**
  8427. Poll for I/O on the command pipes. This is only used on windows which cannot adequately detect EOF on a named pipe.
  8428. @param cmd MprCmd object created via mprCreateCmd
  8429. @param timeout Time in milliseconds to wait for the command to complete and exit.
  8430. @ingroup MprCmd
  8431. @stability Stable
  8432. */
  8433. PUBLIC void mprPollWinCmd(MprCmd *cmd, MprTicks timeout);
  8434. /**
  8435. Start a timer calling mprPollWinCmd.
  8436. @description This is useful for detached commands.
  8437. @param cmd MprCmd object created via mprCreateCmd
  8438. @ingroup MprCmd
  8439. @stability Internal
  8440. */
  8441. PUBLIC void mprStartWinPollTimer(MprCmd *cmd);
  8442. #endif
  8443. /**
  8444. Make the I/O channels to send and receive data to and from the command.
  8445. @param cmd MprCmd object created via mprCreateCmd
  8446. @param channel Channel number to read from. Should be either MPR_CMD_STDIN, MPR_CMD_STDOUT or MPR_CMD_STDERR.
  8447. @param buf Buffer to read into
  8448. @param bufsize Size of buffer
  8449. @return Zero if successful. Otherwise a negative MPR error code.
  8450. @ingroup MprCmd
  8451. @stability Stable
  8452. */
  8453. PUBLIC ssize mprReadCmd(MprCmd *cmd, int channel, char *buf, ssize bufsize);
  8454. /**
  8455. Reap the command. This waits for and collect the command exit status.
  8456. @param cmd MprCmd object created via mprCreateCmd
  8457. @param timeout Time in milliseconds to wait for the command to complete and exit.
  8458. @return Zero if successful. Otherwise a negative MPR error code.
  8459. @ingroup MprCmd
  8460. @stability Stable
  8461. */
  8462. PUBLIC int mprReapCmd(MprCmd *cmd, MprTicks timeout);
  8463. /**
  8464. Run a simple blocking command using a string command line.
  8465. @param dispatcher MprDispatcher event queue to use for waiting. Set to NULL to use the default MPR dispatcher.
  8466. @param command Command line to run
  8467. @param input Command input. Data to write to the command which will be received on the comamnds stdin.
  8468. @param output Reference to a string to receive the stdout from the command.
  8469. @param error Reference to a string to receive the stderr from the command.
  8470. @param timeout Time in milliseconds to wait for the command to complete and exit. Set to -1 to wait forever.
  8471. @return Command exit status, or negative MPR error code.
  8472. @ingroup MprCmd
  8473. @stability Stable
  8474. */
  8475. PUBLIC int mprRun(MprDispatcher *dispatcher, cchar *command, cchar *input, char **output, char **error, MprTicks timeout);
  8476. /**
  8477. Run a command using a string command line. This starts the command via mprStartCmd() and waits for its completion.
  8478. @param cmd MprCmd object created via mprCreateCmd
  8479. @param command Command line to run
  8480. @param envp Array of environment strings. Each environment string should be of the form: "KEY=VALUE". The array
  8481. must be null terminated.
  8482. @param in Command input. Data to write to the command which will be received on the comamnds stdin.
  8483. @param out Reference to a string to receive the stdout from the command.
  8484. @param err Reference to a string to receive the stderr from the command.
  8485. @param timeout Time in milliseconds to wait for the command to complete and exit.
  8486. @param flags Flags to modify execution. Valid flags are:
  8487. MPR_CMD_NEW_SESSION Create a new session on Unix
  8488. MPR_CMD_SHOW Show the commands window on Windows
  8489. MPR_CMD_IN Connect to stdin
  8490. MPR_CMD_OUT Capture stdout
  8491. MPR_CMD_ERR Capture stderr
  8492. MPR_CMD_EXACT_ENV Use the exact environment supplied. Don't inherit and blend with existing environment.
  8493. @return Command exit status, or negative MPR error code.
  8494. @ingroup MprCmd
  8495. @stability Stable
  8496. */
  8497. PUBLIC int mprRunCmd(MprCmd *cmd, cchar *command, cchar **envp, cchar *in, char **out, char **err, MprTicks timeout, int flags);
  8498. /**
  8499. Run a command using an argv[] array of arguments. This invokes mprStartCmd() and waits for its completion.
  8500. @param cmd MprCmd object created via mprCreateCmd
  8501. @param argc Count of arguments in argv
  8502. @param argv Command arguments array
  8503. @param envp Array of environment strings. Each environment string should be of the form: "KEY=VALUE". The array
  8504. must be null terminated.
  8505. @param in Command input. Data to write to the command which will be received on the comamnds stdin.
  8506. @param out Reference to a string to receive the stdout from the command.
  8507. @param err Reference to a string to receive the stderr from the command.
  8508. @param timeout Time in milliseconds to wait for the command to complete and exit.
  8509. @param flags Flags to modify execution. Valid flags are:
  8510. MPR_CMD_NEW_SESSION Create a new session on Unix
  8511. MPR_CMD_SHOW Show the commands window on Windows
  8512. MPR_CMD_IN Connect to stdin
  8513. MPR_CMD_OUT Capture stdout
  8514. MPR_CMD_ERR Capture stderr
  8515. @return Zero if successful. Otherwise a negative MPR error code.
  8516. @ingroup MprCmd
  8517. @stability Stable
  8518. */
  8519. PUBLIC int mprRunCmdV(MprCmd *cmd, int argc, cchar **argv, cchar **envp, cchar *in, char **out, char **err,
  8520. MprTicks timeout, int flags);
  8521. /**
  8522. Define a callback to be invoked to receive response data from the command.
  8523. @param cmd MprCmd object created via mprCreateCmd
  8524. @param callback Function of the signature MprCmdProc which will be invoked for receive notification
  8525. for data from the commands stdout and stderr channels. MprCmdProc has the signature:
  8526. int callback(MprCmd *cmd, int channel, void *data) {}
  8527. @param data User defined data to be passed to the callback.
  8528. @ingroup MprCmd
  8529. @stability Stable
  8530. */
  8531. PUBLIC void mprSetCmdCallback(MprCmd *cmd, MprCmdProc callback, void *data);
  8532. /**
  8533. Set the default environment to use for commands.
  8534. @description This environment is used if one is not defined via #mprStartCmd
  8535. @param cmd MprCmd object created via mprCreateCmd
  8536. @param env Array of environment "KEY=VALUE" strings. Null terminated.
  8537. @ingroup MprCmd
  8538. @stability Stable
  8539. @internal
  8540. */
  8541. PUBLIC void mprSetCmdDefaultEnv(MprCmd *cmd, cchar **env);
  8542. /**
  8543. Set the home directory for the command
  8544. @param cmd MprCmd object created via mprCreateCmd
  8545. @param dir String directory path name.
  8546. @ingroup MprCmd
  8547. @stability Stable
  8548. */
  8549. PUBLIC void mprSetCmdDir(MprCmd *cmd, cchar *dir);
  8550. /**
  8551. Set the command environment
  8552. @param cmd MprCmd object created via mprCreateCmd
  8553. @param env Array of environment strings. Each environment string should be of the form: "KEY=VALUE". The array
  8554. must be null terminated.
  8555. @ingroup MprCmd
  8556. @stability Stable
  8557. */
  8558. PUBLIC void mprSetCmdEnv(MprCmd *cmd, cchar **env);
  8559. /**
  8560. Set the default command search path.
  8561. @description The search path is used to locate the program to run for the command.
  8562. @param cmd MprCmd object created via mprCreateCmd
  8563. @param search Search string. This is in a format similar to the PATH environment variable.
  8564. @ingroup MprCmd
  8565. @stability Stable
  8566. */
  8567. PUBLIC void mprSetCmdSearchPath(MprCmd *cmd, cchar *search);
  8568. /**
  8569. Start the command. This starts the command but does not wait for its completion. Once started, mprWriteCmd
  8570. can be used to write to the command and response data can be received via mprReadCmd.
  8571. @param cmd MprCmd object created via mprCreateCmd
  8572. @param argc Count of arguments in argv
  8573. @param argv Command arguments array
  8574. @param envp Array of environment strings. Each environment string should be of the form: "KEY=VALUE". The array
  8575. must be null terminated.
  8576. @param flags Flags to modify execution. Valid flags are:
  8577. MPR_CMD_NEW_SESSION Create a new session on Unix
  8578. MPR_CMD_SHOW Show the commands window on Windows
  8579. MPR_CMD_IN Connect to stdin
  8580. @return Zero if successful. Otherwise a negative MPR error code.
  8581. @ingroup MprCmd
  8582. @stability Stable
  8583. */
  8584. PUBLIC int mprStartCmd(MprCmd *cmd, int argc, cchar **argv, cchar **envp, int flags);
  8585. /**
  8586. Stop the command. The command is immediately killed.
  8587. @param cmd MprCmd object created via mprCreateCmd
  8588. @param signal Signal to send to the command to kill if required
  8589. @ingroup MprCmd
  8590. @stability Stable
  8591. */
  8592. PUBLIC int mprStopCmd(MprCmd *cmd, int signal);
  8593. /**
  8594. Wait for the command to complete.
  8595. @param cmd MprCmd object created via mprCreateCmd
  8596. @param timeout Time in milliseconds to wait for the command to complete and exit.
  8597. @return Zero if successful. Otherwise a negative MPR error code.
  8598. @ingroup MprCmd
  8599. @stability Stable
  8600. */
  8601. PUBLIC int mprWaitForCmd(MprCmd *cmd, MprTicks timeout);
  8602. /**
  8603. Write data to an I/O channel
  8604. @description This is a non-blocking write and may return having written less than requested.
  8605. @param cmd MprCmd object created via mprCreateCmd
  8606. @param channel Channel number to read from. Should be either MPR_CMD_STDIN, MPR_CMD_STDOUT or MPR_CMD_STDERR.
  8607. @param buf Buffer to read into
  8608. @param bufsize Size of buffer
  8609. @return Count of bytes written
  8610. @ingroup MprCmd
  8611. @stability Stable
  8612. */
  8613. PUBLIC ssize mprWriteCmd(MprCmd *cmd, int channel, cchar *buf, ssize bufsize);
  8614. /**
  8615. Write data to an I/O channel
  8616. @description This is a blocking write.
  8617. @param cmd MprCmd object created via mprCreateCmd
  8618. @param channel Channel number to read from. Should be either MPR_CMD_STDIN, MPR_CMD_STDOUT or MPR_CMD_STDERR.
  8619. @param buf Buffer to read into
  8620. @param bufsize Size of buffer
  8621. @return Count of bytes written
  8622. @ingroup MprCmd
  8623. @stability Stable
  8624. @internal
  8625. */
  8626. PUBLIC ssize mprWriteCmdBlock(MprCmd *cmd, int channel, cchar *buf, ssize bufsize);
  8627. /********************************** Cache *************************************/
  8628. /*
  8629. General cache options
  8630. */
  8631. #define MPR_CACHE_SHARED 0x1 /**< Use shared cache for mprCreateCache() */
  8632. #define MPR_CACHE_ADD 0x2 /**< mprWriteCache option to add key only if not already existing */
  8633. #define MPR_CACHE_SET 0x4 /**< mprWriteCache option to update key value, create if required */
  8634. #define MPR_CACHE_APPEND 0x8 /**< mprWriteCache option to set and append if already existing */
  8635. #define MPR_CACHE_PREPEND 0x10 /**< mprWriteCache option to set and prepend if already existing */
  8636. /*
  8637. Notification events
  8638. */
  8639. #define MPR_CACHE_NOTIFY_CREATE 1 /**< Item has been created */
  8640. #define MPR_CACHE_NOTIFY_REMOVE 2 /**< Item is about to be removed */
  8641. #define MPR_CACHE_NOTIFY_UPDATE 4 /**< Item has been updated */
  8642. /**
  8643. Cache item expiry callback
  8644. @param cache Cache object
  8645. @param key Cached item key
  8646. @param data Cached item data
  8647. @param event Event of interest.
  8648. @ingroup MprCache
  8649. @stability Evolving
  8650. */
  8651. typedef void (*MprCacheProc)(struct MprCache *cache, cchar *key, cchar *data, int event);
  8652. /**
  8653. In-memory caching. The MprCache provides a fast, in-memory caching of cache items. Cache items are string key / value
  8654. pairs. Cache items have a configurable lifespan and the Cache manager will automatically prune expired items.
  8655. Items also have an associated version number that can be used when writing to do transactional writes.
  8656. @defgroup MprCache MprCache
  8657. @see mprCreateCache mprDestroyCache mprExpireCache mprIncCache mprReadCache mprRemoveCache mprSetCacheLimits
  8658. mprWriteCache
  8659. @stability Internal
  8660. */
  8661. typedef struct MprCache {
  8662. MprHash *store; /**< Key/value store */
  8663. MprMutex *mutex; /**< Cache lock */
  8664. MprEvent *timer; /**< Pruning timer */
  8665. MprTicks lifespan; /**< Default lifespan (msec) */
  8666. MprCacheProc notify; /* Notification callback for item expiry */
  8667. int resolution; /**< Frequence for pruner */
  8668. ssize usedMem; /**< Memory in use for keys and data */
  8669. ssize maxKeys; /**< Max number of keys */
  8670. ssize maxMem; /**< Max memory for session data */
  8671. struct MprCache *shared; /**< Shared common cache */
  8672. } MprCache;
  8673. /**
  8674. Create a new cache object
  8675. @param options Set of option flags. Use #MPR_CACHE_SHARED to select a global shared cache object.
  8676. @return A cache instance object. On error, return null.
  8677. @ingroup MprCache
  8678. @stability Evolving
  8679. */
  8680. PUBLIC MprCache *mprCreateCache(int options);
  8681. /**
  8682. Initialize the cache service on startup. Should only be called by the MPR init on startup.
  8683. @return Zero if successful.
  8684. @stability Internal
  8685. */
  8686. PUBLIC int mprCreateCacheService(void);
  8687. /**
  8688. Destroy a new cache object
  8689. @param cache The cache instance object returned from #mprCreateCache.
  8690. @ingroup MprCache
  8691. @stability Evolving
  8692. */
  8693. PUBLIC void *mprDestroyCache(MprCache *cache);
  8694. /**
  8695. Set the expiry date for a cache item
  8696. @param cache The cache instance object returned from #mprCreateCache.
  8697. @param key Cache item key
  8698. @param expires Time when the cache item will expire. If expires is zero, the item is immediately removed from the cache.
  8699. @return Zero if the expiry is successfully updated. Return MPR_ERR_CANT_FIND if the cache item is not present in the
  8700. cache.
  8701. @ingroup MprCache
  8702. @stability Evolving
  8703. */
  8704. PUBLIC int mprExpireCacheItem(MprCache *cache, cchar *key, MprTicks expires);
  8705. /**
  8706. Get the Cache statistics
  8707. @param cache The cache instance object returned from #mprCreateCache.
  8708. @param numKeys Number of keys currently stored
  8709. @param mem Memory in use to store keys
  8710. @ingroup MprCache
  8711. @stability Evolving
  8712. @internal
  8713. */
  8714. PUBLIC void mprGetCacheStats(MprCache *cache, int *numKeys, ssize *mem);
  8715. /**
  8716. Increment a numeric cache item
  8717. @param cache The cache instance object returned from #mprCreateCache.
  8718. @param key Cache item key
  8719. @param amount Numeric amount to increment the cache item. This may be a negative number to decrement the item.
  8720. @return The new value for the cache item after incrementing.
  8721. @ingroup MprCache
  8722. @stability Evolving
  8723. */
  8724. PUBLIC int64 mprIncCache(MprCache *cache, cchar *key, int64 amount);
  8725. /**
  8726. Lookup an item in the cache.
  8727. @description Same as mprReadCache but will not update the last accessed time.
  8728. @param cache The cache instance object returned from #mprCreateCache.
  8729. @param key Cache item key
  8730. @param modified Optional MprTime value reference to receive the last modified time of the cache item. Set to null
  8731. if not required.
  8732. @param version Optional int64 value reference to receive the version number of the cache item. Set to null
  8733. if not required. Cache items have a version number that is incremented every time the item is updated.
  8734. @return The cache item value
  8735. @ingroup MprCache
  8736. @stability Evolving
  8737. */
  8738. PUBLIC char *mprLookupCache(MprCache *cache, cchar *key, MprTime *modified, int64 *version);
  8739. /**
  8740. Prune the cache
  8741. @description Prune the cache and discard all cached items
  8742. @param cache The cache instance object returned from #mprCreateCache.
  8743. @ingroup MprCache
  8744. @stability Evolving
  8745. */
  8746. PUBLIC void mprPruneCache(MprCache *cache);
  8747. /**
  8748. Read an item from the cache.
  8749. @param cache The cache instance object returned from #mprCreateCache.
  8750. @param key Cache item key
  8751. @param modified Optional MprTime value reference to receive the last modified time of the cache item. Set to null
  8752. if not required.
  8753. @param version Optional int64 value reference to receive the version number of the cache item. Set to null
  8754. if not required. Cache items have a version number that is incremented every time the item is updated.
  8755. @return The cache item value
  8756. @ingroup MprCache
  8757. @stability Evolving
  8758. */
  8759. PUBLIC char *mprReadCache(MprCache *cache, cchar *key, MprTime *modified, int64 *version);
  8760. /**
  8761. Remove items from the cache
  8762. @param cache The cache instance object returned from #mprCreateCache.
  8763. @param key Cache item key. If set to null, then remove all keys from the cache.
  8764. @return True if the cache item was removed.
  8765. @ingroup MprCache
  8766. @stability Evolving
  8767. */
  8768. PUBLIC bool mprRemoveCache(MprCache *cache, cchar *key);
  8769. /**
  8770. Set a notification callback to be invoked for events of interest on cached items.
  8771. WARNING: the callback may happen on any thread. Use careful locking to synchronize access to data. Take care
  8772. not to block the thread issuing the callback.
  8773. @param cache The cache instance object returned from #mprCreateCache.
  8774. @param notify MprCacheProc notification callback. Invoked for events of interest on cache items.
  8775. The event is set to MPR_CACHE_NOTIFY_REMOVE when items are removed from the cache. Invoked as:
  8776. (*MprCacheProc)(MprCache *cache, cchar *key, cchar *data, int event);
  8777. @ingroup MprCache
  8778. @stability Evolving
  8779. */
  8780. PUBLIC void mprSetCacheNotify(MprCache *cache, MprCacheProc notify);
  8781. /**
  8782. Set the cache resource limits
  8783. @param cache The cache instance object returned from #mprCreateCache.
  8784. @param keys Set the maximum number of keys the cache can store
  8785. @param lifespan Set the default lifespan for cache items in milliseconds
  8786. @param memory Memory limit in bytes for all cache keys and items.
  8787. @param resolution Set the cache item pruner resolution. This defines how frequently the cache manager will check
  8788. items for expiration.
  8789. @ingroup MprCache
  8790. @stability Evolving
  8791. */
  8792. PUBLIC void mprSetCacheLimits(MprCache *cache, int64 keys, MprTicks lifespan, int64 memory, int resolution);
  8793. /**
  8794. Set a linked managed memory reference for a cached item.
  8795. @param cache The cache instance object returned from #mprCreateCache.
  8796. @param key Cache item key to write
  8797. @param link Managed memory reference. May be NULL.
  8798. @ingroup MprCache
  8799. @stability Evolving
  8800. */
  8801. PUBLIC int mprSetCacheLink(MprCache *cache, cchar *key, void *link);
  8802. /**
  8803. Write a cache item
  8804. @param cache The cache instance object returned from #mprCreateCache.
  8805. @param key Cache item key to write
  8806. @param value Value to set for the cache item. This must be allocated memory.
  8807. @param modified Value to set for the cache last modified time. If set to zero, the current time is obtained via
  8808. #mprGetTime.
  8809. @param lifespan Lifespan of the item in milliseconds. The item will be removed from the cache by the Cache manager
  8810. when the lifetime expires unless it is rewritten to extend the lifespan.
  8811. @param version Expected version number of the item. This is used to do transactional writes to the cache item.
  8812. First the version number is retrieved via #mprReadCache and that version number is supplied to mprWriteCache when
  8813. the item is updated. If another caller updates the item in between the read/write, the version number will not
  8814. match when the item is subsequently written and this call will fail with the #MPR_ERR_BAD_STATE return code. Set to
  8815. zero if version checking is not required.
  8816. @param options Options to control how the item value is updated. Use #MPR_CACHE_SET to update the cache item and
  8817. create if it does not exist. Use #MPR_CACHE_ADD to add the item only if it does not already exits. Use
  8818. #MPR_CACHE_APPEND to append the parameter value to any existing cache item value. Use #MPR_CACHE_PREPEND to
  8819. prepend the value.
  8820. @return If writing the cache item was successful this call returns the number of bytes written. Otherwise a negative
  8821. MPR error code is returned. #MPR_ERR_BAD_STATE will be returned if an invalid version number is supplied.
  8822. #MPR_ERR_ALREADY_EXISTS will be returned if #MPR_CACHE_ADD is specified and the cache item already exists.
  8823. @ingroup MprCache
  8824. @stability Evolving
  8825. */
  8826. PUBLIC ssize mprWriteCache(MprCache *cache, cchar *key, cchar *value, MprTime modified, MprTicks lifespan,
  8827. int64 version, int options);
  8828. /******************************** Mime Types **********************************/
  8829. /**
  8830. Mime Type hash table entry (the URL extension is the key)
  8831. @stability Stable
  8832. @defgroup MprMime MprMime
  8833. @see MprMime mprAddMime mprCreateMimeTypes mprGetMimeProgram mprLookupMime mprSetMimeProgram
  8834. @stability Internal
  8835. */
  8836. typedef struct MprMime {
  8837. char *type; /**< Mime type string */
  8838. char *program; /**< Mime type string */
  8839. } MprMime;
  8840. /**
  8841. Add a mime type to the mime type table
  8842. @param table type hash table returned by #mprCreateMimeTypes
  8843. @param ext Filename extension to use as a key for the given mime type
  8844. @param mimeType Mime type string to associate with the ext key
  8845. @return Mime type entry object. This is owned by the mime type table.
  8846. @ingroup MprMime
  8847. @stability Stable
  8848. */
  8849. PUBLIC MprMime *mprAddMime(MprHash *table, cchar *ext, cchar *mimeType);
  8850. /**
  8851. Create the mime types
  8852. @param path Filename of a mime types definition file
  8853. @return Hash table of mime types keyed by file extension
  8854. @ingroup MprMime
  8855. @stability Stable
  8856. */
  8857. PUBLIC MprHash *mprCreateMimeTypes(cchar *path);
  8858. /**
  8859. Get the mime type program for a given mimeType
  8860. @param table type hash table returned by #mprCreateMimeTypes
  8861. @param mimeType Mime type to update
  8862. @return The program name associated with this mime type
  8863. @ingroup MprMime
  8864. @stability Stable
  8865. */
  8866. PUBLIC cchar *mprGetMimeProgram(MprHash *table, cchar *mimeType);
  8867. /**
  8868. Get the mime type for an extension.
  8869. This call will return the mime type from a limited internal set of mime types for the given path or extension.
  8870. @param table Hash table of mime types to examine
  8871. @param ext Path or extension to examine
  8872. @returns Mime type string. Returns null if mime type is not known.
  8873. @ingroup MprMime
  8874. @stability Stable
  8875. */
  8876. PUBLIC cchar *mprLookupMime(MprHash *table, cchar *ext);
  8877. /**
  8878. Set the mime type program
  8879. @param table type hash table returned by #mprCreateMimeTypes
  8880. @param mimeType Mime type to update
  8881. @param program Program name to associate with this mime type
  8882. @return Zero if the update is successful. Otherwise return MPR_ERR_CANT_FIND if the mime type is not present in
  8883. the mime type table.
  8884. @ingroup MprMime
  8885. @stability Stable
  8886. */
  8887. PUBLIC int mprSetMimeProgram(MprHash *table, cchar *mimeType, cchar *program);
  8888. /************************************ MPR *************************************/
  8889. /*
  8890. Mpr state
  8891. */
  8892. #define MPR_CREATED 1 /**< Applicationa and MPR services started */
  8893. #define MPR_STARTED 2 /**< Applicationa and MPR services started */
  8894. #define MPR_STOPPING 3 /**< App has been instructed to shutdown. Services should not accept new requests */
  8895. #define MPR_STOPPED 4 /**< App is idle and now stopped. All requests should abort. */
  8896. #define MPR_DESTROYING 5 /**< Destroying core MPR services and releasing memory */
  8897. #define MPR_DESTROYED 6 /**< Application and MPR object destroyed */
  8898. /*
  8899. MPR flags
  8900. */
  8901. #define MPR_LOG_ANEW 0x1 /**< Start anew on restart after backup */
  8902. #define MPR_LOG_CONFIG 0x2 /**< Show the configuration at the start of the log */
  8903. #define MPR_LOG_CMDLINE 0x4 /**< Command line log switch uses */
  8904. #define MPR_LOG_DETAILED 0x8 /**< Use detailed log formatting with timestamps and tags */
  8905. #define MPR_LOG_TAGGED 0x10 /**< Use tagged message formatting */
  8906. #define MPR_LOG_HEXDUMP 0x10 /**< Emit hexdump */
  8907. #define MPR_NOT_ALL 0x20 /**< Don't invoke all destructors when terminating */
  8908. typedef bool (*MprIdleCallback)(bool traceRequests);
  8909. /**
  8910. Service shutdown notifier
  8911. @description Services may create shutdown notifiers, called terminators that are informed when the application
  8912. commences a shutdown. The terminator may be invoked several times and the service should take appropriate
  8913. action based on given the MPR state.
  8914. \n\n
  8915. If the state parameter is set to MPR_STOPPING, the service should not accept any new requests, but otherwise not take
  8916. any destructive actions. Note this state is required to be reversible if the shutdown is cancelled.
  8917. \n\n
  8918. If the state is MPR_STOPPED, the service should cancel all running requests, close files and connections and release
  8919. all resources. This state is not reversible.
  8920. \n\n
  8921. This exitStrategy parameter is a flags word that defines the shutdown strategy. See #mprShutdown for details.
  8922. @param state Current MPR state. Set to #MPR_STARTED, #MPR_STOPPING, #MPR_STOPPED and #MPR_DESTROYED.
  8923. @param exitStrategy Flags word including the flags: MPR_EXIT_ABORT, MPR_EXIT_RESTART and MPR_EXIT_SAFE.
  8924. @param status The desired application exit status
  8925. @ingroup Mpr
  8926. @stability Stable
  8927. */
  8928. typedef void (*MprTerminator)(int state, int exitStrategy, int status);
  8929. /**
  8930. Primary MPR application control structure
  8931. @description The Mpr structure stores critical application state information.
  8932. @see mprAddTerminator mprBreakpoint mprCreate mprCreateOsService mprDecode64 mprDestroy mprEmptyString mprEncode64
  8933. mprEscapeCmd mprEscapseHtml mprGetApp mprGetAppDir mprGetAppName mprGetAppPath mprGetAppTitle mprGetAppVersion
  8934. mprGetCmdlineLogging mprGetDebugMode mprGetDomainName mprGetEndian mprGetError mprGetHostName
  8935. mprGetHwnd mprGetInst mprGetIpAddr mprGetKeyValue mprGetLogLevel mprGetMD5 mprGetMD5WithPrefix mprGetOsError
  8936. mprGetRandomBytes mprGetServerName mprIsDestroyed mprIsIdle mprIsStopping mprIsDestroying mprMakeArgv
  8937. mprRandom mprReadRegistry mprRemoveKeyValue mprRestart mprServicesAreIdle mprSetAppName
  8938. mprSetDebugMode mprSetDomainName mprSetHostName mprSetHwnd mprSetIdleCallback mprSetInst
  8939. mprSetIpAddr mprSetLogLevel mprSetServerName mprSetSocketMessage mprShouldAbortRequests mprShouldDenyNewRequests
  8940. mprSignalExit mprSleep mprStart mprStartEventsThread mprStartOsService mprStopOsService mprShutdown mprUriDecode
  8941. mprUriDecodeBuf mprUriEncode mprWriteRegistry
  8942. @defgroup Mpr Mpr
  8943. @stability Internal.
  8944. */
  8945. typedef struct Mpr {
  8946. MprHeap *heap; /**< Memory heap control */
  8947. MprLogHandler logHandler; /**< Current log handler callback */
  8948. MprFile *logFile; /**< Log file */
  8949. MprHash *mimeTypes; /**< Table of mime types */
  8950. MprHash *timeTokens; /**< Date/Time parsing tokens */
  8951. MprHash *keys; /**< Simple key/value store */
  8952. MprFile *stdError; /**< Standard error file */
  8953. MprFile *stdInput; /**< Standard input file */
  8954. MprFile *stdOutput; /**< Standard output file */
  8955. MprTime start; /**< When the MPR started */
  8956. MprTicks exitTimeout; /**< Request timeout when exiting */
  8957. ssize logSize; /**< Maximum log size */
  8958. cchar *appPath; /**< Path name of application executable */
  8959. cchar *appDir; /**< Path of directory containing app executable */
  8960. cchar **argv; /**< Application command line args (not alloced) */
  8961. char **argBuf; /**< Space for allocated argv */
  8962. cchar *logPath; /**< Log path name */
  8963. char *pathEnv; /**< Cached PATH env var. Used by MprCmd */
  8964. char *name; /**< Product name */
  8965. char *title; /**< Product title */
  8966. char *version; /**< Product version */
  8967. char *domainName; /**< Domain portion */
  8968. char *hostName; /**< Host name (fully qualified name) */
  8969. char *ip; /**< Public IP Address */
  8970. char *serverName; /**< Server name portion (no domain) */
  8971. int argc; /**< Count of command line args */
  8972. int eventing; /**< Servicing events thread is active */
  8973. int exitStrategy; /**< How to exit the app */
  8974. int flags; /**< Misc flags */
  8975. int hasError; /**< Mpr has an initialization error */
  8976. int logLevel; /**< Log trace level */
  8977. int logBackup; /**< Number of log files preserved when backing up */
  8978. int verifySsl; /**< Default verification of SSL certificates */
  8979. bool debugMode; /**< Run in debug mode (no timers) */
  8980. /*
  8981. Service pointers
  8982. */
  8983. struct MprCmdService *cmdService; /**< Command service object */
  8984. struct MprEventService *eventService; /**< Event service object */
  8985. struct MprModuleService *moduleService; /**< Module service object */
  8986. struct MprOsService *osService; /**< O/S service object */
  8987. struct MprSignalService *signalService; /**< Signal service object */
  8988. struct MprSocketService *socketService; /**< Socket service object */
  8989. struct MprThreadService *threadService; /**< Thread service object */
  8990. struct MprWorkerService *workerService; /**< Worker service object */
  8991. struct MprWaitService *waitService; /**< IO Waiting service object */
  8992. struct MprDispatcher *dispatcher; /**< Primary dispatcher */
  8993. struct MprDispatcher *nonBlock; /**< Nonblocking dispatcher */
  8994. /*
  8995. These are here to optimize access to these singleton service objects
  8996. */
  8997. void *appwebService; /**< Appweb service object */
  8998. void *ediService; /**< EDI object */
  8999. void *ejsService; /**< Ejscript service */
  9000. void *espService; /**< ESP service object */
  9001. void *httpService; /**< Http service object */
  9002. MprList *fileSystems; /**< File system objects */
  9003. MprTicks shutdownStarted; /**< When the shutdown started */
  9004. MprList *terminators; /**< Termination callbacks */
  9005. MprIdleCallback idleCallback; /**< Invoked to determine if the process is idle */
  9006. MprOsThread mainOsThread; /**< Main OS thread ID */
  9007. MprMutex *mutex; /**< Thread synchronization used for global lock */
  9008. MprSpin *spin; /**< Quick thread synchronization */
  9009. MprCond *cond; /**< Sync after starting events thread */
  9010. MprCond *stopCond; /**< Sync for stopping */
  9011. char *emptyString; /**< "" string */
  9012. char *oneString; /**< "1" string */
  9013. #if ME_WIN_LIKE
  9014. HINSTANCE appInstance; /**< Application instance (windows) */
  9015. #endif
  9016. MprFileSystem *romfs; /**< Rom file system object */
  9017. } Mpr;
  9018. PUBLIC void mprNop(void *ptr);
  9019. #if DOXYGEN || ME_WIN_LIKE
  9020. /**
  9021. Return the MPR control instance.
  9022. @description Return the MPR singleton control object.
  9023. @return Returns the MPR control object.
  9024. @ingroup Mpr
  9025. @stability Stable.
  9026. */
  9027. PUBLIC Mpr *mprGetMpr(void);
  9028. #define MPR mprGetMpr()
  9029. #else
  9030. #define mprGetMpr() MPR
  9031. PUBLIC_DATA Mpr *MPR;
  9032. #endif
  9033. #define MPR_DISABLE_GC 0x1 /**< Disable GC */
  9034. #define MPR_USER_EVENTS_THREAD 0x2 /**< User will explicitly manage own mprServiceEvents calls */
  9035. #define MPR_NO_WINDOW 0x4 /**< Don't create a windows Window */
  9036. #define MPR_DELAY_GC_THREAD 0x8 /**< Delay starting the GC thread */
  9037. #define MPR_DAEMON 0x10 /**< Make the process a daemon */
  9038. /**
  9039. Add a service terminator
  9040. @description Services may create shutdown notifiers called terminators that are informed when the application commences a shutdown.
  9041. The terminator may be invoked several times and the service should take appropriate action based on the MPR state.
  9042. \n\n
  9043. If the state parameter is set to MPR_STOPPING, the service should not accept any new requests, but otherwise not take
  9044. any destructive actions. Note this state is required to be reversible if the shutdown is cancelled.
  9045. \n\n
  9046. If the state is MPR_STOPPED, the service should cancel all running requests, close files and connections and release
  9047. all resources. This state is not reversible.
  9048. \n\n
  9049. This exitStrategy parameter is a flags word that defines the shutdown exit strategy. See #mprShutdown for details.
  9050. \n\n
  9051. Services may also call #mprShouldDenyNewRequests to test if the MPR state is MPR_STOPPING and #mprShouldAbortRequests
  9052. if the state is MPR_STOPPED.
  9053. @param terminator MprTerminator callback function
  9054. @ingroup Mpr
  9055. @stability Stable.
  9056. */
  9057. PUBLIC void mprAddTerminator(MprTerminator terminator);
  9058. /**
  9059. Initialize the application by creating an instance of the MPR.
  9060. @description Initializes the MPR and creates an Mpr control object. The Mpr Object manages all MPR facilities
  9061. and services. This must be called before using any MPR API. When processing is complete, you should call
  9062. #mprDestroy before exiting the application.
  9063. @param argc Count of command line args
  9064. @param argv Command line arguments for the application. Arguments may be passed into the Mpr for retrieval
  9065. by the unit test framework.
  9066. @param flags Set MPR_USER_EVENTS_THREAD if you will manage calling #mprServiceEvents manually if required.
  9067. There are three styles of MPR applications with respect to servicing events:
  9068. \n\n
  9069. 1) Applications that don't require servicing events for I/O, commands or timers
  9070. \n\n
  9071. 2) Applications that call #mprServiceEvents directly from their main program
  9072. \n\n
  9073. 3) Applications that have a dedicated service events thread
  9074. \n\n
  9075. Applications that do not perform I/O, run commands or create events may not need a service events thread.
  9076. While creating one will do no harm, performance may be enhanced for these applications by specifying MPR_USER_EVENTS_THREAD.
  9077. \n\n
  9078. Applications that have not forground processing requirements may invoke #mprServiceEvents from their main program instead
  9079. of creating a service events thread. This saves one thread.
  9080. \n\n
  9081. The default is to create a service events thread so the full scope of MPR services are supported.
  9082. @return Returns a pointer to the Mpr object.
  9083. @ingroup Mpr
  9084. @stability Stable.
  9085. */
  9086. PUBLIC Mpr *mprCreate(int argc, char **argv, int flags);
  9087. /**
  9088. Convert the process into a daemon on unix systems
  9089. @description This converts the current process into a detached child without a parent.
  9090. @returns Zero if successful. Otherwise a negative MPR error code.
  9091. @ingroup Mpr
  9092. @stability Stable
  9093. */
  9094. PUBLIC int mprDaemon(void);
  9095. /**
  9096. Destroy the MPR and all services using the MPR.
  9097. @description This call terminates the MPR and all services.
  9098. \n\n
  9099. An application initializes the MPR by calling #mprCreate. This creates the Mpr object, the memory allocator, garbage collector
  9100. and other services. An application exits by invoking #mprDestroy or by calling #mprShutdown then #mprDestroy.
  9101. \n\n
  9102. There are two styles of MPR applications with respect to shutdown:
  9103. \n\n
  9104. 1) Applications that have a dedicated service events thread.
  9105. \n\n
  9106. 2) Applications that call #mprServiceEvents directly from their main program.
  9107. \n\n
  9108. Applications that have a service events thread can call mprDestroy directly from their main program when ready to exit.
  9109. Applications that call mprServiceEvents from their main program will typically have some other MPR thread call
  9110. #mprShutdown to initiate a shutdown sequence. This will stop accepting new requests or connections and when the
  9111. application is idle, the #mprServiceEvents routine will return and then the main program can call then call mprDestroy.
  9112. \n\n
  9113. Once the shutdown conditions are satisfied, a thread executing #mprServiceEvents will return from that API and then
  9114. the application should call #mprDestroy and exit().
  9115. \n\n
  9116. If an application needs to tailor how it exits with respect to current requests, use #mprShutdown first to specify a
  9117. shutdown strategy.
  9118. @return True if the MPR can be destroyed. Returns false if the exit strategy MPR_EXIT_SAFE has been defined via
  9119. #mprShutdown and current requests have not completed within the exit timeout
  9120. period defined by #mprSetExitTimeout. In this case, the shutdown is cancelled and normal operations continue.
  9121. @ingroup Mpr
  9122. @stability Stable
  9123. */
  9124. PUBLIC bool mprDestroy(void);
  9125. /**
  9126. Reference to a permanent preallocated empty string.
  9127. @return An empty string
  9128. @ingroup Mpr
  9129. @stability Stable.
  9130. */
  9131. PUBLIC char *mprEmptyString(void);
  9132. /**
  9133. Get the application directory
  9134. @description Get the directory containing the application executable.
  9135. @returns A string containing the application directory.
  9136. @ingroup Mpr
  9137. @stability Stable.
  9138. */
  9139. PUBLIC cchar *mprGetAppDir(void);
  9140. /**
  9141. Get the application name defined via mprSetAppName
  9142. @returns the one-word lower case application name defined via mprSetAppName
  9143. @ingroup Mpr
  9144. @stability Stable.
  9145. */
  9146. PUBLIC cchar *mprGetAppName(void);
  9147. /**
  9148. Get the application executable path
  9149. @returns A string containing the application executable path.
  9150. @ingroup Mpr
  9151. @stability Stable.
  9152. */
  9153. PUBLIC cchar *mprGetAppPath(void);
  9154. /**
  9155. Get the application title string
  9156. @returns A string containing the application title string.
  9157. @ingroup Mpr
  9158. @stability Stable.
  9159. */
  9160. PUBLIC cchar *mprGetAppTitle(void);
  9161. /**
  9162. Get the application version string
  9163. @returns A string containing the application version string.
  9164. @ingroup Mpr
  9165. @stability Stable.
  9166. */
  9167. PUBLIC cchar *mprGetAppVersion(void);
  9168. /**
  9169. Get if command line logging is being used.
  9170. @description Logging may be initiated by invoking an MPR based program with a "--log" switch. This API assists
  9171. programs to tell the MPR that command line logging has been used.
  9172. @return True if command line logging is in use.
  9173. @ingroup Mpr
  9174. @stability Stable.
  9175. */
  9176. PUBLIC bool mprGetCmdlineLogging(void);
  9177. /**
  9178. Get the debug mode.
  9179. @description Returns whether the debug mode is enabled. Some modules
  9180. observe debug mode and disable timeouts and timers so that single-step
  9181. debugging can be used.
  9182. @return Returns true if debug mode is enabled, otherwise returns false.
  9183. @ingroup Mpr
  9184. @stability Stable.
  9185. */
  9186. PUBLIC bool mprGetDebugMode(void);
  9187. /**
  9188. Get the application domain name string
  9189. @returns A string containing the application domain name string.
  9190. @ingroup Mpr
  9191. @stability Stable.
  9192. */
  9193. PUBLIC cchar *mprGetDomainName(void);
  9194. /**
  9195. Return the endian byte ordering for the application
  9196. @return MPR_LITTLE_ENDIAN or MPR_BIG_ENDIAN.
  9197. @ingroup Mpr
  9198. @stability Stable.
  9199. */
  9200. PUBLIC int mprGetEndian(void);
  9201. /**
  9202. Return the error code for the most recent system or library operation.
  9203. @description Returns an error code from the most recent system call.
  9204. This will be mapped to be either a POSIX error code or an MPR error code.
  9205. @return The mapped error code.
  9206. @ingroup Mpr
  9207. @stability Stable.
  9208. */
  9209. PUBLIC int mprGetError(void);
  9210. /**
  9211. Get the exit status
  9212. @description Get the exit status set via #mprShutdown
  9213. May be called after #mprDestroy.
  9214. @return The proposed application exit status
  9215. @ingroup Mpr
  9216. @stability Stable.
  9217. */
  9218. PUBLIC int mprGetExitStatus(void);
  9219. /**
  9220. Get the application host name string
  9221. @returns A string containing the application host name string.
  9222. @ingroup Mpr
  9223. @stability Stable.
  9224. */
  9225. PUBLIC cchar *mprGetHostName(void);
  9226. /**
  9227. Get the application IP address string
  9228. @returns A string containing the application IP address string.
  9229. @ingroup Mpr
  9230. @stability Stable.
  9231. */
  9232. PUBLIC cchar *mprGetIpAddr(void);
  9233. /**
  9234. Get a key value
  9235. @param key String key value
  9236. @ingroup Mpr
  9237. @stability Stable
  9238. */
  9239. PUBLIC void *mprGetKey(cchar *key);
  9240. /**
  9241. Get the current logging level
  9242. @return The current log level.
  9243. @ingroup Mpr
  9244. @stability Stable.
  9245. */
  9246. PUBLIC int mprGetLogLevel(void);
  9247. /**
  9248. Get some random data
  9249. @param buf Reference to a buffer to hold the random data
  9250. @param size Size of the buffer
  9251. @param block Set to true if it is acceptable to block while accumulating entropy sufficient to provide good
  9252. random data. Setting to false will cause this API to not block and may return random data of a lower quality.
  9253. @ingroup Mpr
  9254. @stability Stable.
  9255. */
  9256. PUBLIC int mprGetRandomBytes(char *buf, ssize size, bool block);
  9257. /**
  9258. Get some random data in ascii
  9259. @param size Size of the random data string
  9260. @ingroup Mpr
  9261. @stability Stable.
  9262. */
  9263. PUBLIC char *mprGetRandomString(ssize size);
  9264. /**
  9265. Return the O/S error code.
  9266. @description Returns an O/S error code from the most recent system call.
  9267. This returns errno on Unix systems or GetLastError() on Windows..
  9268. @return The O/S error code.
  9269. @ingroup Mpr
  9270. @stability Stable.
  9271. */
  9272. PUBLIC int mprGetOsError(void);
  9273. /**
  9274. Get the application server name string
  9275. @returns A string containing the application server name string.
  9276. @ingroup Mpr
  9277. @stability Stable.
  9278. */
  9279. PUBLIC cchar *mprGetServerName(void);
  9280. /**
  9281. Get the MPR execution state
  9282. @returns MPR_CREATED, MPR_STARTED, MPR_STOPPING, MPR_STOPPED, MPR_DESTROYING, or MPR_DESTROYED.
  9283. @ingroup Mpr
  9284. @stability Stable
  9285. */
  9286. PUBLIC int mprGetState(void);
  9287. /**
  9288. Determine if the MPR has finished.
  9289. @description This is true if the MPR services have been shutdown completely. This is typically
  9290. used to determine if the App has been shutdown.
  9291. @returns True if the App has been instructed to exit and all the MPR services have been destroyed.
  9292. @ingroup Mpr
  9293. @stability Stable.
  9294. */
  9295. PUBLIC bool mprIsDestroyed(void);
  9296. /**
  9297. Determine if the App is idle.
  9298. @description This call returns true if the App is not currently servicing any requests. By default this returns true
  9299. if the MPR dispatcher, worker thread and command subsytems are idle. Callers can replace or augment the standard
  9300. idle testing by definining a new idle callback via mprSetIdleCallback.
  9301. \n\n
  9302. Note: this routine tests for worker threads but ignores other threads created via #mprCreateThread.
  9303. @param traceRequests If true, emit trace regarding running requests.
  9304. @return True if the App are idle.
  9305. @ingroup Mpr
  9306. @stability Stable.
  9307. */
  9308. PUBLIC bool mprIsIdle(bool traceRequests);
  9309. /**
  9310. Test if the application is stopping
  9311. If mprIsStopping is true, the application has commenced a shutdown. No new requests should be accepted and current request
  9312. should complete if possible. Use #mprIsDestroyed to test if the application has completed its shutdown.
  9313. @return True if the application is in the process of exiting
  9314. @ingroup Mpr
  9315. @stability Stable.
  9316. */
  9317. PUBLIC bool mprIsStopping(void);
  9318. /**
  9319. Test if the application is stopped
  9320. If this routine returns true, the application shutdown has passed the point of no return.
  9321. No new requests should be accepted and current requests should be aborted.
  9322. Use #mprIsStopping to test if shutdown has been initiated but current requests may continue.
  9323. Use #mprIsDestroyed to test if the application has completed its shutdown.
  9324. @return True if the application is in the process of exiting
  9325. @ingroup Mpr
  9326. @stability Stable
  9327. */
  9328. PUBLIC bool mprIsStopped(void);
  9329. /**
  9330. Test if the application is terminating and core services are being destroyed
  9331. All request should immediately terminate.
  9332. @return True if the application is in the process of exiting and core services should also exit.
  9333. @ingroup Mpr
  9334. @stability Stable
  9335. */
  9336. PUBLIC bool mprIsDestroying(void);
  9337. #define MPR_ARGV_ARGS_ONLY 0x1 /**< Command is missing program name */
  9338. /**
  9339. Make a argv style array of command arguments
  9340. @description The given command is parsed and broken into separate arguments and returned in a null-terminated, argv
  9341. array. Arguments in the command may be quoted with single or double quotes to group words into one argument.
  9342. Use back-quote "\\" to escape quotes.
  9343. This routine allocates memory and must not be called before #mprCreate. Consider #mprParseArgs if you need to convert
  9344. a command line before calling #mprCreate.
  9345. @param command Command string to parse.
  9346. @param argv Output parameter containing the parsed arguments.
  9347. @param flags Set to MPR_ARGV_ARGS_ONLY if the command string does not contain a program name. In this case, argv[0]
  9348. will be set to "".
  9349. @return The count of arguments in argv
  9350. @ingroup Mpr
  9351. @stability Stable.
  9352. */
  9353. PUBLIC int mprMakeArgv(cchar *command, cchar ***argv, int flags);
  9354. /**
  9355. Nap for a while
  9356. @description This routine blocks and does not yield for GC. Only use it for very short naps.
  9357. @param msec Number of milliseconds to sleep
  9358. @ingroup Mpr
  9359. @stability Stable.
  9360. */
  9361. PUBLIC void mprNap(MprTicks msec);
  9362. /**
  9363. Make a argv style array of command arguments
  9364. @description The given command is parsed and broken into separate arguments and returned in a null-terminated, argv
  9365. array. Arguments in the command may be quoted with single or double quotes to group words into one argument.
  9366. Use back-quote "\\" to escape quotes. This routine modifies supplied command parameter and does not allocate
  9367. any memory and may be used before mprCreate is invoked.
  9368. @param command Command string to parse.
  9369. @param argv Array for the arguments.
  9370. @param maxArgs Size of the argv array.
  9371. @return The count of arguments in argv
  9372. @ingroup Mpr
  9373. @stability Stable.
  9374. */
  9375. PUBLIC int mprParseArgs(char *command, char **argv, int maxArgs);
  9376. /**
  9377. Restart the application
  9378. @description This call immediately restarts the application. The standard input, output and error I/O channels are
  9379. preserved. All other open file descriptors are closed.
  9380. \n\n
  9381. If the application is started via a monitoring launch daemon such as launchd or appman, the application should not use
  9382. this API, but rather defer to the launch daemon to restart the application. In that case, the application should simply
  9383. do a shutdown via #mprShutdown and/or #mprDestroy.
  9384. @ingroup Mpr
  9385. @stability Stable.
  9386. */
  9387. PUBLIC void mprRestart(void);
  9388. /**
  9389. Determine if the MPR services.
  9390. @description This is the default routine invoked by mprIsIdle().
  9391. @param traceRequests If true, emit trace regarding running requests.
  9392. @return True if the MPR services are idle.
  9393. @ingroup Mpr
  9394. @stability Stable.
  9395. */
  9396. PUBLIC bool mprServicesAreIdle(bool traceRequests);
  9397. /**
  9398. Set the application name, title and version
  9399. @param name One word, lower case name for the app.
  9400. @param title Pascal case multi-word descriptive name.
  9401. @param version Version of the app. Major-Minor-Patch. E.g. 1.2.3.
  9402. @returns Zero if successful. Otherwise a negative MPR error code.
  9403. @ingroup Mpr
  9404. @stability Stable.
  9405. */
  9406. PUBLIC int mprSetAppName(cchar *name, cchar *title, cchar *version);
  9407. /**
  9408. Set the application executable path
  9409. @param path A string containing the application executable path.
  9410. @ingroup Mpr
  9411. @stability Stable.
  9412. */
  9413. PUBLIC void mprSetAppPath(cchar *path);
  9414. /**
  9415. Set if command line logging was requested.
  9416. @description Logging may be initiated by invoking an MPR based program with a "--log" switch. This API assists
  9417. programs to tell the MPR that command line logging has been used.
  9418. @param on Set to true to indicate command line logging is being used.
  9419. @return True if command line logging was enabled before this call.
  9420. @ingroup Mpr
  9421. @stability Stable.
  9422. */
  9423. PUBLIC bool mprSetCmdlineLogging(bool on);
  9424. /**
  9425. Turn on debug mode.
  9426. @description Debug mode disables timeouts and timers. This makes debugging
  9427. much easier.
  9428. @param on Set to true to enable debugging mode.
  9429. @ingroup Mpr
  9430. @stability Stable.
  9431. */
  9432. PUBLIC void mprSetDebugMode(bool on);
  9433. /**
  9434. Set the proposed exit status
  9435. @description Set the exit status that can be retrieved via #mprGetExitStatus.
  9436. @param status Proposed exit status value.
  9437. @ingroup Mpr
  9438. @stability Stable
  9439. */
  9440. PUBLIC void mprSetExitStatus(int status);
  9441. /**
  9442. Set the current logging verbosity level.
  9443. @description This call defines the maximum level of messages that will be
  9444. logged. Calls to mprLog specify a message level. If the message level
  9445. is greater than the defined logging level, the message is ignored.
  9446. @param level New logging level. Must be 0-5 inclusive.
  9447. @return Returns the previous logging level.
  9448. @ingroup MprLog
  9449. @stability Stable.
  9450. */
  9451. PUBLIC void mprSetLogLevel(int level);
  9452. /**
  9453. Set the application domain name string
  9454. @param s New value to use for the application domain name.
  9455. @ingroup Mpr
  9456. @stability Stable.
  9457. */
  9458. PUBLIC void mprSetDomainName(cchar *s);
  9459. /**
  9460. Set an environment variable value
  9461. @param key Variable name
  9462. @param value Variable value
  9463. @ingroup Mpr
  9464. @stability Stable.
  9465. */
  9466. PUBLIC void mprSetEnv(cchar *key, cchar *value);
  9467. /**
  9468. Set the error code.
  9469. @description Set errno or equivalent.
  9470. @ingroup Mpr
  9471. @stability Stable.
  9472. */
  9473. PUBLIC void mprSetError(int error);
  9474. /**
  9475. Set the exit timeout for a shutdown.
  9476. @description A shutdown waits for existing requests to complete before exiting. After this timeout has expired,
  9477. the application will either invoke exit() or cancel the shutdown depending on whether MPR_EXIT_SAFE is defined in
  9478. the exit strategy via #mprShutdown.
  9479. The default exit timeout is zero.
  9480. @param timeout Time in milliseconds to wait for current requests to complete and the application to become idle.
  9481. @ingroup Mpr
  9482. @stability Stable.
  9483. */
  9484. PUBLIC void mprSetExitTimeout(MprTicks timeout);
  9485. /**
  9486. Set the maximum number of open file/socket descriptors
  9487. @param limit Limit to enforce
  9488. @ingroup Mpr
  9489. @stability Stable
  9490. */
  9491. PUBLIC void mprSetFilesLimit(int limit);
  9492. /**
  9493. Set the application host name string. This is internal to the application and does not affect the O/S host name.
  9494. @param s New host name to use within the application
  9495. @ingroup Mpr
  9496. @stability Stable.
  9497. */
  9498. PUBLIC void mprSetHostName(cchar *s);
  9499. /**
  9500. Define a new idle callback to be invoked by mprIsIdle().
  9501. @param idleCallback Callback function to invoke to test if the application is idle.
  9502. @ingroup Mpr
  9503. @stability Stable.
  9504. */
  9505. PUBLIC MprIdleCallback mprSetIdleCallback(MprIdleCallback idleCallback);
  9506. /**
  9507. Sete the application IP address string
  9508. @param ip IP address string to store for the application
  9509. @ingroup Mpr
  9510. @stability Stable.
  9511. */
  9512. PUBLIC void mprSetIpAddr(cchar *ip);
  9513. /**
  9514. Store a key/value pair
  9515. @param key String key value
  9516. @param value Manage object reference
  9517. @ingroup Mpr
  9518. @stability Stable
  9519. */
  9520. PUBLIC void mprSetKey(cchar *key, void *value);
  9521. /**
  9522. Set the O/S error code.
  9523. @description Set errno or equivalent.
  9524. @ingroup Mpr
  9525. @stability Stable.
  9526. */
  9527. PUBLIC void mprSetOsError(int error);
  9528. /**
  9529. Set the application server name string
  9530. @param s New application server name to use within the application.
  9531. @ingroup Mpr
  9532. @stability Stable.
  9533. */
  9534. PUBLIC void mprSetServerName(cchar *s);
  9535. /**
  9536. Test if requests should be aborted.
  9537. @description This routine indicates that current requests should be terminated due to an application shutdown.
  9538. This will be true then the MPR->state >= MPR_EXIT_STOPPED.
  9539. See also #mprShouldDenyNewRequests.
  9540. @return True if new requests should be denied.
  9541. @ingroup Mpr
  9542. @stability Stable.
  9543. */
  9544. PUBLIC bool mprShouldAbortRequests(void);
  9545. /**
  9546. Test if new requests should be denied.
  9547. @description This routine indicates if an application shutdown has been initiated and services should not
  9548. accept new requests or connections.
  9549. This will be true then the MPR->state >= MPR_EXIT_STOPPING.
  9550. See also #mprShouldAbortRequests.
  9551. @return True if new requests should be denied.
  9552. @ingroup Mpr
  9553. @stability Stable.
  9554. */
  9555. PUBLIC bool mprShouldDenyNewRequests(void);
  9556. /**
  9557. Sleep for a while
  9558. @description This routine blocks for the given time and yields for GC during that time. Ensure all memory
  9559. is held before the sleep.
  9560. @param msec Number of milliseconds to sleep
  9561. @ingroup Mpr
  9562. @stability Stable.
  9563. */
  9564. PUBLIC void mprSleep(MprTicks msec);
  9565. /**
  9566. Start the Mpr services
  9567. @ingroup Mpr
  9568. @stability Stable.
  9569. */
  9570. PUBLIC int mprStart(void);
  9571. /**
  9572. Start an thread dedicated to servicing events. This will create a new thread and invoke mprServiceEvents.
  9573. @return Zero if successful.
  9574. @ingroup Mpr
  9575. @stability Stable.
  9576. */
  9577. PUBLIC int mprStartEventsThread(void);
  9578. /*
  9579. Shutdown flags
  9580. */
  9581. #define MPR_EXIT_NORMAL 0x0 /**< Normal (graceful) exit */
  9582. #define MPR_EXIT_ABORT 0x1 /**< Abort everything and call exit() */
  9583. #define MPR_EXIT_SAFE 0x2 /**< Graceful shutdown only if all requests complete */
  9584. #define MPR_EXIT_RESTART 0x4 /**< Restart after exiting */
  9585. #define MPR_EXIT_TIMEOUT -1 /**< Use timeout specified via #mprSetExitTimeout */
  9586. /**
  9587. Initiate shutdown of the MPR and application.
  9588. @description Commence shutdown of the application according to the shutdown policy defined by the "exitStrategy" parameter.
  9589. An application may call this routine from any thread to request the application exit. Depending on the exitStrategy, this
  9590. may be an abortive or graceful exit. A desired application exit status code can defined to indicate the cause of the shutdown.
  9591. \n\n
  9592. Once called, this routine will set the MPR execution state to MPR_EXIT_STOPPING. Services should detect this by calling
  9593. #mprShouldDenyNewRequests before accepting new connections or requests, but otherwise, services should not take any destructive
  9594. actions until the MPR state is advanced to MPR_EXIT_STOPPED by #mprDestroy. This state can be detected by calling
  9595. #mprShouldAbortRequests. Users can invoke #mprCancelShutdown to resume normal operations provided #mprDestroy has not
  9596. proceeded past the point of no return when destructive termination actions are commenced.
  9597. \n\n
  9598. Applications that have a user events thread and call #mprServiceEvents from their main program, will typically invoke
  9599. mprShutdown from some other MPR thread to initiate the shutdown. When running requests have completed, or when the
  9600. shutdown timeout expires (MPR->exitTimeout), the call to #mprServiceEvents in the main program will return and
  9601. the application can then call #mprDestroy to complete the shutdown.
  9602. \n\n
  9603. Note: This routine starts the shutdown process but does not perform any destructive actions.
  9604. @param exitStrategy Shutdown policy.
  9605. If the MPR_EXIT_ABORT flag is specified, the application will immediately call exit() and will terminate without
  9606. waiting for current requests to complete. This is not recommended for normal operation as data may be lost.
  9607. \n\n
  9608. If MPR_EXIT_SAFE is defined, the shutdown will be cancelled if all requests do not complete before the exit timeout
  9609. defined via #mprSetExitTimeout expires.
  9610. \n\n
  9611. Define the MPR_EXIT_RESTART flag for the application to automatically restart after exiting. Do not use this option if
  9612. the application is using a watchdog/angel process to automatically restart the application (such as appman by appweb).
  9613. @param status Proposed exit status to use when the application exits. See #mprGetExitStatus.
  9614. @param timeout Exit timeout in milliseconds to wait for current requests to complete. If set to -1, for the default exit timeout.
  9615. @ingroup Mpr
  9616. @stability Stable
  9617. */
  9618. PUBLIC void mprShutdown(int exitStrategy, int status, MprTicks timeout);
  9619. /**
  9620. Cancel a shutdown request
  9621. @description A graceful shutdown request initiated via #mprShutdown may be cancelled if the shutdown is still in progress
  9622. and has not passed the point of no return. If the MPR is still in the MPR_STOPPING state, the shutdown may be cancelled.
  9623. See #mprGetState.
  9624. @return True if the shutdown can be cancelled. Returns false if a shutdown has not been requested or if the shutdown has
  9625. advanced past the point of no return.
  9626. @ingroup Mpr
  9627. @stability Stable
  9628. */
  9629. PUBLIC bool mprCancelShutdown(void);
  9630. #if ME_WIN_LIKE
  9631. /**
  9632. Get the Windows window handle
  9633. @return the windows HWND reference
  9634. @ingroup Mpr
  9635. @stability Stable.
  9636. */
  9637. PUBLIC HWND mprGetHwnd(void);
  9638. /**
  9639. Get the windows application instance
  9640. @return The application instance identifier
  9641. @ingroup Mpr
  9642. @stability Stable.
  9643. */
  9644. PUBLIC HINSTANCE mprGetInst(void);
  9645. /**
  9646. Set the MPR windows handle
  9647. @param handle Set the MPR default windows handle
  9648. @ingroup Mpr
  9649. @stability Stable.
  9650. */
  9651. PUBLIC void mprSetHwnd(HWND handle);
  9652. /**
  9653. Set the windows application instance
  9654. @param inst The new windows application instance to set
  9655. @ingroup Mpr
  9656. @stability Stable.
  9657. */
  9658. PUBLIC void mprSetInst(HINSTANCE inst);
  9659. /**
  9660. Set the socket message number.
  9661. @description Set the socket message number to use when using WSAAsyncSelect for windows.
  9662. @param message Message number to use.
  9663. @ingroup Mpr
  9664. @stability Stable.
  9665. */
  9666. PUBLIC void mprSetSocketMessage(int message);
  9667. #endif
  9668. #if ME_WIN_LIKE || CYGWIN
  9669. /**
  9670. List the subkeys for a key in the Windows registry
  9671. @param key Windows registry key to enumerate subkeys
  9672. @return List of subkey string names
  9673. @ingroup Mpr
  9674. @stability Stable
  9675. */
  9676. PUBLIC MprList *mprListRegistry(cchar *key);
  9677. /**
  9678. Read a key from the Windows registry
  9679. @param key Windows registry key to read
  9680. @param name Windows registry name to read.
  9681. @return The key/name setting
  9682. @ingroup Mpr
  9683. @stability Stable.
  9684. */
  9685. PUBLIC char *mprReadRegistry(cchar *key, cchar *name);
  9686. /**
  9687. Write a key value the Windows registry
  9688. @param key Windows registry key to write
  9689. @param name Windows registry name to write.
  9690. @param value Value to set the key/name to.
  9691. @return Zero if successful. Otherwise return a negative MPR error code.
  9692. @ingroup Mpr
  9693. @stability Stable.
  9694. */
  9695. PUBLIC int mprWriteRegistry(cchar *key, cchar *name, cchar *value);
  9696. #endif /* ME_WIN_LIKE || CYGWIN */
  9697. #if VXWORKS
  9698. PUBLIC int mprFindVxSym(SYMTAB_ID sid, char *name, char **pvalue);
  9699. PUBLIC pid_t mprGetPid(void);
  9700. #ifndef getpid
  9701. #define getpid mprGetPid
  9702. #endif
  9703. #endif
  9704. /*
  9705. Internal
  9706. */
  9707. PUBLIC void mprWriteToOsLog(cchar *msg, int level);
  9708. #ifdef __cplusplus
  9709. }
  9710. #endif
  9711. #endif /* _h_MPR */
  9712. /*
  9713. Copyright (c) Embedthis Software. All Rights Reserved.
  9714. This software is distributed under a commercial license. Consult the LICENSE.md
  9715. distributed with this software for full details and copyrights.
  9716. */