goahead.h 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188
  1. /*
  2. goahead.h -- GoAhead Web Server Header
  3. Copyright (c) All Rights Reserved. See details at the end of the file.
  4. */
  5. #ifndef _h_GOAHEAD
  6. #define _h_GOAHEAD 1
  7. /************************************ Overrides *******************************/
  8. /*
  9. Override osdep defaults
  10. */
  11. #define ME_MAX_IP 64 /**< Maximum IP address size */
  12. /************************************ Includes ********************************/
  13. #include "me.h"
  14. #include "osdep.h"
  15. /************************************ Defaults ********************************/
  16. #ifdef __cplusplus
  17. extern "C" {
  18. #endif
  19. /**************** jimbo modify ****************/
  20. #define IPv4_ADDR0 192
  21. #define IPv4_ADDR1 168
  22. #define IPv4_ADDR2 0
  23. #define IPv4_ADDR3 203
  24. #define ME_COMPILER_HAS_SINGLE_STACK 1
  25. /*************** jimbo end *******************/
  26. #if (ME_COM_MBEDTLS + ME_COM_MATRIXSSL + ME_COM_NANOSSL + ME_COM_OPENSSL) > 1
  27. #error "Cannot have more than one SSL provider configured"
  28. #endif
  29. #ifndef ME_GOAHEAD_LOGGING
  30. #define ME_GOAHEAD_LOGGING 1 /**< Default for logging is "on" */
  31. #endif
  32. #ifndef ME_GOAHEAD_TRACING
  33. #define ME_GOAHEAD_TRACING 1 /**< Default for tracing "on" */
  34. #endif
  35. #ifndef ME_GOAHEAD_DEBUG
  36. #if ME_DEBUG
  37. #define ME_GOAHEAD_DEBUG 1 /**< Debug logging on in debug builds by default */
  38. #else
  39. #define ME_GOAHEAD_DEBUG 0
  40. #endif
  41. #endif
  42. #if ECOS
  43. #if ME_GOAHEAD_CGI
  44. #error "Ecos does not support CGI. Disable ME_GOAHEAD_CGI"
  45. #endif
  46. #endif /* ECOS */
  47. #if QNX
  48. typedef long fd_mask;
  49. #define NFDBITS (sizeof (fd_mask) * NBBY) /* bits per mask */
  50. #endif
  51. #if MACOSX
  52. typedef int32_t fd_mask;
  53. #endif
  54. #if WINDOWS
  55. typedef fd_set fd_mask;
  56. #endif
  57. #if !LINUX
  58. PUBLIC char *basename(char *name);
  59. #endif
  60. #if VXWORKS
  61. PUBLIC int vxchdir(char *dirname);
  62. #endif
  63. #if DOXYGEN
  64. typedef int Socket;
  65. typedef int Socklen;
  66. typedef int64 Offset;
  67. #endif
  68. /**
  69. File status structure
  70. */
  71. typedef struct stat WebsStat;
  72. /*
  73. Copyright. The software license requires that this not be modified or removed.
  74. */
  75. #define EMBEDTHIS_GOAHEAD_COPYRIGHT \
  76. "Copyright (c) Embedthis Software Inc., 1993-2014. All Rights Reserved." \
  77. "Copyright (c) GoAhead Software Inc., 2003. All Rights Reserved."
  78. /************************************* Main ***********************************/
  79. #define ME_MAX_ARGC 32
  80. #if VXWORKS
  81. #define MAIN(name, _argc, _argv, _envp) \
  82. static int innerMain(int argc, char **argv, char **envp); \
  83. int name(char *arg0, ...) { \
  84. va_list args; \
  85. char *argp, *largv[ME_MAX_ARGC]; \
  86. int largc = 0; \
  87. va_start(args, arg0); \
  88. largv[largc++] = #name; \
  89. if (arg0) { \
  90. largv[largc++] = arg0; \
  91. } \
  92. for (argp = va_arg(args, char*); argp && largc < ME_MAX_ARGC; argp = va_arg(args, char*)) { \
  93. largv[largc++] = argp; \
  94. } \
  95. return innerMain(largc, largv, NULL); \
  96. } \
  97. static int innerMain(_argc, _argv, _envp)
  98. #elif ME_WIN_LIKE
  99. #define MAIN(name, _argc, _argv, _envp) \
  100. APIENTRY WinMain(HINSTANCE inst, HINSTANCE junk, char *command, int junk2) { \
  101. extern int main(); \
  102. char *largv[ME_MAX_ARGC]; \
  103. int largc; \
  104. largc = websParseArgs(command, &largv[1], ME_MAX_ARGC - 1); \
  105. largv[0] = #name; \
  106. main(largc, largv, NULL); \
  107. } \
  108. int main(_argc, _argv, _envp)
  109. #else
  110. #define MAIN(name, _argc, _argv, _envp) int main(_argc, _argv, _envp)
  111. #endif
  112. PUBLIC int websParseArgs(char *args, char **argv, int maxArgc);
  113. #if WINDOWS
  114. PUBLIC void websSetInst(HINSTANCE inst);
  115. PUBLIC HINSTANCE websGetInst();
  116. #endif
  117. /************************************ Tunables ********************************/
  118. #define WEBS_MAX_LISTEN 8 /**< Maximum number of listen endpoints */
  119. #define WEBS_SMALL_HASH 31 /**< General small hash size */
  120. #define WEBS_MAX_PASSWORD 32 /**< Default maximum password */
  121. /************************************* Error **********************************/
  122. #if ME_GOAHEAD_LOGGING
  123. #define WEBS_L __FILE__, __LINE__
  124. #define WEBS_ARGS_DEC char *file, int line
  125. #define WEBS_ARGS file, line
  126. PUBLIC_DATA int logLevel;
  127. /**
  128. Standard logging trace levels are 0 to 9 with 0 being the most verbose. These are ored with the error source
  129. and type flags. The WEBS_LOG_MASK is used to extract the trace level from a flags word. We expect most apps
  130. to run with level 2 trace enabled.
  131. */
  132. #define WEBS_ERROR 1 /**< Hard error trace level */
  133. #define WEBS_WARN 2 /**< Soft warning trace level */
  134. #define WEBS_CONFIG 2 /**< Configuration settings trace level. */
  135. #define WEBS_VERBOSE 9 /**< Highest level of trace */
  136. #define WEBS_LEVEL_MASK 0xF /**< Level mask */
  137. /*
  138. Log message flags
  139. */
  140. #define WEBS_ASSERT_MSG 0x10 /**< Originated from assert */
  141. #define WEBS_ERROR_MSG 0x20 /**< Originated from error */
  142. #define WEBS_LOG_MSG 0x100 /**< Originated from logmsg */
  143. #define WEBS_RAW_MSG 0x200 /**< Raw message output */
  144. #define WEBS_TRACE_MSG 0x400 /**< Originated from trace */
  145. #if ME_GOAHEAD_TRACING && ME_GOAHEAD_LOGGING
  146. #if ME_COMPILER_HAS_MACRO_VARARGS
  147. #define trace(l, ...) if (((l) & WEBS_LEVEL_MASK) <= websGetLogLevel()) { traceProc(l, __VA_ARGS__); } else {}
  148. #else
  149. inline void trace(int level, cchar *fmt, ...) {
  150. WebsLogHandler logHandler = logGetHandler();
  151. if ((level & WEBS_LEVEL_MASK) <= logLevel && logHandler) {
  152. va_list args; va_start(args, fmt);
  153. char *message = sfmtv((char*) fmt, args);
  154. logHandler(level | WEBS_TRACE_MSG, message);
  155. wfree(message);
  156. va_end(args);
  157. }
  158. }
  159. #endif
  160. #else
  161. #define trace(l, ...) if (1) ; else {}
  162. #endif
  163. #if ME_GOAHEAD_LOGGING
  164. #if ME_COMPILER_HAS_MACRO_VARARGS
  165. #define logmsg(l, ...) if ((l) <= logLevel) { logmsgProc(l, __VA_ARGS__); } else {}
  166. #else
  167. inline void logmsg(int level, cchar *fmt, ...) {
  168. WebsLogHandler logHandler = logGetHandler();
  169. if ((level & WEBS_LEVEL_MASK) <= logLevel && logHandler) {
  170. va_list args; va_start(args, fmt);
  171. char *message = sfmtv((char*) fmt, args);
  172. logHandler(level | WEBS_TRACE_MSG, message);
  173. wfree(message);
  174. va_end(args);
  175. }
  176. }
  177. #endif
  178. #else
  179. #define logmsg(l, ...) if (1) ; else {}
  180. #endif
  181. #if DOXYGEN
  182. #undef assert
  183. /**
  184. Assure that an assert condition is true
  185. @param cond Boolean result of a conditional test
  186. @stability Stable
  187. */
  188. extern void assert(bool cond);
  189. #elif ME_GOAHEAD_DEBUG
  190. #define assert(C) if (C) ; else assertError(WEBS_L, "%s", #C)
  191. PUBLIC void assertError(WEBS_ARGS_DEC, char *fmt, ...);
  192. #else
  193. #define assert(C) if (1) ; else {}
  194. #endif
  195. /**
  196. Callback for emitting trace log output
  197. @param level Integer between 0 and 9. Zero is the lowest trace level used for the most important messages.
  198. @param msg Message to log
  199. @return Zero if successful
  200. @internal
  201. */
  202. typedef void (*WebsLogHandler)(int level, cchar *msg);
  203. /**
  204. Emit an error message
  205. @return Zero if successful
  206. @stability Stable
  207. */
  208. PUBLIC void error(cchar *fmt, ...);
  209. /**
  210. Open the log logging module
  211. @return Zero if successful
  212. @internal
  213. */
  214. PUBLIC int logOpen(void);
  215. /**
  216. Close the log logging module
  217. @internal
  218. */
  219. PUBLIC void logClose(void);
  220. /**
  221. Get the log callback
  222. @return handler Callback handler function of type WebsLogHandler
  223. @stability Stable
  224. */
  225. PUBLIC WebsLogHandler logGetHandler(void);
  226. /**
  227. Set a log callback
  228. @param handler Callback handler function of type WebsLogHandler
  229. @return The previous callback function
  230. @stability Stable
  231. */
  232. PUBLIC WebsLogHandler logSetHandler(WebsLogHandler handler);
  233. /**
  234. Get the current trace log level
  235. @return Number between 0 and 9
  236. @ingroup Webs
  237. @stability Stable
  238. */
  239. PUBLIC int websGetLogLevel(void);
  240. /**
  241. Set the current trace log level
  242. @return Number between 0 and 9
  243. @ingroup Webs
  244. @stability Prototype
  245. */
  246. void websSetLogLevel(int level);
  247. /**
  248. Set the filename to save logging output
  249. @param path Filename path to use
  250. @stability Stable
  251. */
  252. PUBLIC void logSetPath(cchar *path);
  253. /**
  254. Emit a message to the log
  255. @description This emits a message at the specified level. GoAhead filters logging messages by defining a verbosity
  256. level at startup. Level 0 is the least verbose where only the most important messages will be output. Level 9 is the
  257. Logging support is enabled by the MakeMe setting: "logging: true" which creates the ME_GOAHEAD_LOGGING define in me.h
  258. most verbose. Level 2-4 are the most useful for debugging.
  259. @param level Integer verbosity level (0-9).
  260. @param fmt Printf style format string
  261. @param ... Arguments for the format string
  262. @stability Stable
  263. */
  264. PUBLIC void logmsgProc(int level, cchar *fmt, ...);
  265. /**
  266. Emit a debug trace message to the log
  267. @description This emits a message at the specified level. GoAhead filters logging messages by defining a verbosity
  268. level at startup. Level 0 is the least verbose where only the most important messages will be output. Level 9 is the
  269. most verbose. Level 2-4 are the most useful for debugging.
  270. Debug trace support is enabled by the MakeMe setting: "tracing: true" which creates the ME_GOAHEAD_TRACING define in
  271. me.h.
  272. @param level Integer verbosity level (0-9).
  273. @param fmt Printf style format string
  274. @param ... Arguments for the format string
  275. @stability Stable
  276. */
  277. PUBLIC void traceProc(int level, cchar *fmt, ...);
  278. #else /*! ME_GOAHEAD_LOGGING */
  279. #define assert(C) if (1) ; else {}
  280. #define error(l, ...) if (1) ; else {}
  281. #define trace(l, ...) if (1) ; else {}
  282. #define logOpen() if (1) ; else {}
  283. #define logClose() if (1) ; else {}
  284. #define websGetLogLevel() 0
  285. #define logmsg(l, ...) if (1) ; else {}
  286. #define logSetPath(p) if (1) ; else {}
  287. #endif
  288. /*********************************** HTTP Codes *******************************/
  289. /*
  290. Standard HTTP/1.1 status codes
  291. */
  292. #define HTTP_CODE_CONTINUE 100 /**< Continue with request, only partial content transmitted */
  293. #define HTTP_CODE_OK 200 /**< The request completed successfully */
  294. #define HTTP_CODE_CREATED 201 /**< The request has completed and a new resource was created */
  295. #define HTTP_CODE_ACCEPTED 202 /**< The request has been accepted and processing is continuing */
  296. #define HTTP_CODE_NOT_AUTHORITATIVE 203 /**< The request has completed but content may be from another source */
  297. #define HTTP_CODE_NO_CONTENT 204 /**< The request has completed and there is no response to send */
  298. #define HTTP_CODE_RESET 205 /**< The request has completed with no content. Client must reset view */
  299. #define HTTP_CODE_PARTIAL 206 /**< The request has completed and is returning partial content */
  300. #define HTTP_CODE_MOVED_PERMANENTLY 301 /**< The requested URI has moved permanently to a new location */
  301. #define HTTP_CODE_MOVED_TEMPORARILY 302 /**< The URI has moved temporarily to a new location */
  302. #define HTTP_CODE_SEE_OTHER 303 /**< The requested URI can be found at another URI location */
  303. #define HTTP_CODE_NOT_MODIFIED 304 /**< The requested resource has changed since the last request */
  304. #define HTTP_CODE_USE_PROXY 305 /**< The requested resource must be accessed via the location proxy */
  305. #define HTTP_CODE_TEMPORARY_REDIRECT 307 /**< The request should be repeated at another URI location */
  306. #define HTTP_CODE_BAD_REQUEST 400 /**< The request is malformed */
  307. #define HTTP_CODE_UNAUTHORIZED 401 /**< Authentication for the request has failed */
  308. #define HTTP_CODE_PAYMENT_REQUIRED 402 /**< Reserved for future use */
  309. #define HTTP_CODE_FORBIDDEN 403 /**< The request was legal, but the server refuses to process */
  310. #define HTTP_CODE_NOT_FOUND 404 /**< The requested resource was not found */
  311. #define HTTP_CODE_BAD_METHOD 405 /**< The request HTTP method was not supported by the resource */
  312. #define HTTP_CODE_NOT_ACCEPTABLE 406 /**< The requested resource cannot generate the required content */
  313. #define HTTP_CODE_REQUEST_TIMEOUT 408 /**< The server timed out waiting for the request to complete */
  314. #define HTTP_CODE_CONFLICT 409 /**< The request had a conflict in the request headers and URI */
  315. #define HTTP_CODE_GONE 410 /**< The requested resource is no longer available*/
  316. #define HTTP_CODE_LENGTH_REQUIRED 411 /**< The request did not specify a required content length*/
  317. #define HTTP_CODE_PRECOND_FAILED 412 /**< The server cannot satisfy one of the request preconditions */
  318. #define HTTP_CODE_REQUEST_TOO_LARGE 413 /**< The request is too large for the server to process */
  319. #define HTTP_CODE_REQUEST_URL_TOO_LARGE 414 /**< The request URI is too long for the server to process */
  320. #define HTTP_CODE_UNSUPPORTED_MEDIA_TYPE 415 /**< The request media type is not supported by the server or resource */
  321. #define HTTP_CODE_RANGE_NOT_SATISFIABLE 416 /**< The request content range does not exist for the resource */
  322. #define HTTP_CODE_EXPECTATION_FAILED 417 /**< The server cannot satisfy the Expect header requirements */
  323. #define HTTP_CODE_NO_RESPONSE 444 /**< The connection was closed with no response to the client */
  324. #define HTTP_CODE_INTERNAL_SERVER_ERROR 500 /**< Server processing or configuration error. No response generated */
  325. #define HTTP_CODE_NOT_IMPLEMENTED 501 /**< The server does not recognize the request or method */
  326. #define HTTP_CODE_BAD_GATEWAY 502 /**< The server cannot act as a gateway for the given request */
  327. #define HTTP_CODE_SERVICE_UNAVAILABLE 503 /**< The server is currently unavailable or overloaded */
  328. #define HTTP_CODE_GATEWAY_TIMEOUT 504 /**< The server gateway timed out waiting for the upstream server */
  329. #define HTTP_CODE_BAD_VERSION 505 /**< The server does not support the HTTP protocol version */
  330. #define HTTP_CODE_INSUFFICIENT_STORAGE 507 /**< The server has insufficient storage to complete the request */
  331. /*
  332. Proprietary HTTP status codes
  333. */
  334. #define HTTP_CODE_START_LOCAL_ERRORS 550
  335. #define HTTP_CODE_COMMS_ERROR 550 /**< The server had a communications error responding to the client */
  336. /************************************* WebsValue ******************************/
  337. #ifdef WITH_QT
  338. /*
  339. QT creates a global "hex" -- Ugh!
  340. */
  341. #define hex hexvalue
  342. #endif
  343. /**
  344. Value types.
  345. */
  346. typedef enum WebsType {
  347. undefined = 0,
  348. byteint = 1,
  349. shortint = 2,
  350. integer = 3,
  351. hex = 4,
  352. percent = 5,
  353. octal = 6,
  354. big = 7,
  355. flag = 8,
  356. floating = 9,
  357. string = 10,
  358. bytes = 11,
  359. symbol = 12,
  360. errmsg = 13
  361. } WebsType;
  362. /**
  363. System native time type. This is the time in seconds.
  364. This may be 32 or 64 bits and may be signed or unsigned on some systems.
  365. */
  366. typedef time_t WebsTime;
  367. /**
  368. Value union to store primitive value types
  369. */
  370. typedef struct WebsValue {
  371. union {
  372. char flag;
  373. char byteint;
  374. short shortint;
  375. char percent;
  376. long integer;
  377. long hex;
  378. long octal;
  379. long big[2];
  380. #if ME_FLOAT
  381. double floating;
  382. #endif
  383. char *string;
  384. char *bytes;
  385. char *errmsg;
  386. void *symbol;
  387. } value;
  388. WebsType type;
  389. uint valid : 8;
  390. uint allocated : 8; /* String was allocated */
  391. } WebsValue;
  392. /**
  393. The value is a numeric type
  394. */
  395. #define value_numeric(t) (t >= byteint && t <= big)
  396. /**
  397. The value is a string type
  398. */
  399. #define value_str(t) (t >= string && t <= bytes)
  400. /**
  401. The value is valid supported type
  402. */
  403. #define value_ok(t) (t > undefined && t <= symbol)
  404. /**
  405. Allocate strings using malloc
  406. */
  407. #define VALUE_ALLOCATE 0x1
  408. /**
  409. Create an integer value
  410. @param value Integer long value
  411. @return Value object containing the integer
  412. @stability Stable
  413. */
  414. PUBLIC WebsValue valueInteger(long value);
  415. /**
  416. Create an string value
  417. @param value String long value
  418. @param flags Set to VALUE_ALLOCATE to store a copy of the string reference
  419. @return Value object containing the string
  420. @stability Stable
  421. */
  422. PUBLIC WebsValue valueString(cchar *value, int flags);
  423. /**
  424. Create an symbol value containing an object reference
  425. @param value Value reference
  426. @return Value object containing the symbol reference
  427. @stability Stable
  428. */
  429. PUBLIC WebsValue valueSymbol(void *value);
  430. /**
  431. Free any allocated string in a value
  432. @param value Value object
  433. @stability Stable
  434. */
  435. PUBLIC void valueFree(WebsValue *value);
  436. /************************************* Ringq **********************************/
  437. /**
  438. A WebsBuf (ring queue) allows maximum utilization of memory for data storage and is
  439. ideal for input/output buffering. This module provides a highly efficient
  440. implementation and a vehicle for dynamic strings.
  441. \n\n
  442. WARNING: This is a public implementation and callers have full access to
  443. the queue structure and pointers. Change this module very carefully.
  444. \n\n
  445. This module follows the open/close model.
  446. \n\n
  447. Operation of a WebsBuf where bp is a pointer to a WebsBuf :
  448. bp->buflen contains the size of the buffer.
  449. bp->buf will point to the start of the buffer.
  450. bp->servp will point to the first (un-consumed) data byte.
  451. bp->endp will point to the next free location to which new data is added
  452. bp->endbuf will point to one past the end of the buffer.
  453. \n\n
  454. Eg. If the WebsBuf contains the data "abcdef", it might look like :
  455. \n\n
  456. +-------------------------------------------------------------------+
  457. | | | | | | | | a | b | c | d | e | f | | | | |
  458. +-------------------------------------------------------------------+
  459. ^ ^ ^ ^
  460. | | | |
  461. bp->buf bp->servp bp->endp bp->enduf
  462. \n\n
  463. The queue is empty when servp == endp. This means that the queue will hold
  464. at most bp->buflen -1 bytes. It is the fillers responsibility to ensure
  465. the WebsBuf is never filled such that servp == endp.
  466. \n\n
  467. It is the fillers responsibility to "wrap" the endp back to point to
  468. bp->buf when the pointer steps past the end. Correspondingly it is the
  469. consumers responsibility to "wrap" the servp when it steps to bp->endbuf.
  470. The bufPutc and bufGetc routines will do this automatically.
  471. @defgroup WebsBuf WebsBuf
  472. @stability Stable
  473. */
  474. typedef struct WebsBuf {
  475. char *buf; /**< Holding buffer for data */
  476. char *servp; /**< Pointer to start of data */
  477. char *endp; /**< Pointer to end of data */
  478. char *endbuf; /**< Pointer to end of buffer */
  479. ssize buflen; /**< Length of ring queue */
  480. ssize maxsize; /**< Maximum size */
  481. int increment; /**< Growth increment */
  482. } WebsBuf;
  483. /**
  484. Add a trailing null to the buffer. The end pointer is not changed.
  485. @param bp Buffer reference
  486. @ingroup WebsBuf
  487. @stability Stable
  488. */
  489. PUBLIC void bufAddNull(WebsBuf *bp);
  490. /**
  491. Adjust the endp pointer by the specified size.
  492. @description This is useful after manually copying data into the buffer and needing to adjust the end pointer.
  493. @param bp Buffer reference
  494. @param size Size of adjustment. May be positive or negative value.
  495. @ingroup WebsBuf
  496. @stability Stable
  497. */
  498. PUBLIC void bufAdjustEnd(WebsBuf *bp, ssize size);
  499. /**
  500. Adjust the start (servp) reference
  501. @param bp Buffer reference
  502. @param count Number of bytes to adjust
  503. @ingroup WebsBuf
  504. @stability Stable
  505. */
  506. PUBLIC void bufAdjustStart(WebsBuf *bp, ssize count);
  507. /**
  508. Compact the data in the buffer and move to the start of the buffer
  509. @param bp Buffer reference
  510. @ingroup WebsBuf
  511. @stability Stable
  512. */
  513. PUBLIC void bufCompact(WebsBuf *bp);
  514. /**
  515. Create a buffer
  516. @param bp Buffer reference
  517. @param increment Incremental size to grow the buffer. This will be increased by a power of two each time
  518. the buffer grows.
  519. @param maxsize Maximum size of the buffer
  520. @return Zero if successful
  521. @ingroup WebsBuf
  522. @stability Stable
  523. */
  524. PUBLIC int bufCreate(WebsBuf *bp, int increment, int maxsize);
  525. /**
  526. Flush all data in the buffer and reset the pointers.
  527. @param bp Buffer reference
  528. @ingroup WebsBuf
  529. @stability Stable
  530. */
  531. PUBLIC void bufFlush(WebsBuf *bp);
  532. /**
  533. Free allocated storage for the buffer
  534. @param bp Buffer reference
  535. @return Zero if successful
  536. @ingroup WebsBuf
  537. @stability Stable
  538. */
  539. PUBLIC void bufFree(WebsBuf *bp);
  540. /**
  541. Copy a block of from the buffer and adjust the servp.
  542. @param bp Buffer reference
  543. @param blk Block into which to place the data
  544. @param len Length of the block
  545. @return Number of bytes copied.
  546. @ingroup WebsBuf
  547. @stability Stable
  548. */
  549. PUBLIC ssize bufGetBlk(WebsBuf *bp, char *blk, ssize len);
  550. /**
  551. Return the maximum number of bytes the buffer can provide via a single block copy.
  552. @description Useful if the user is doing their own data retrieval.
  553. @param bp Buffer reference
  554. @return Number of bytes available for copying.
  555. @ingroup WebsBuf
  556. @stability Stable
  557. */
  558. PUBLIC ssize bufGetBlkMax(WebsBuf *bp);
  559. /**
  560. Get a character from the buffer and increment the servp
  561. @param bp Buffer reference
  562. @return The next character or -1 if the buffer is empty
  563. @ingroup WebsBuf
  564. @stability Stable
  565. */
  566. PUBLIC int bufGetc(WebsBuf *bp);
  567. /**
  568. Grow the buffer by at least the required amount of room
  569. @param bp Buffer reference
  570. @param room Available size required after growing the buffer
  571. @return True if the buffer can be grown to have the required amount of room.
  572. @ingroup WebsBuf
  573. @stability Stable
  574. */
  575. PUBLIC bool bufGrow(WebsBuf *bp, ssize room);
  576. /**
  577. Get the length of available data in the buffer
  578. @param bp Buffer reference
  579. @return Size of available data in bytes
  580. @ingroup WebsBuf
  581. @stability Stable
  582. */
  583. PUBLIC ssize bufLen(WebsBuf *bp);
  584. /**
  585. Insert a character to the buffer before the servp position and decrement the servp
  586. @param bp Buffer reference
  587. @param c Character to insert
  588. @return Zero if successful
  589. @ingroup WebsBuf
  590. @stability Stable
  591. */
  592. PUBLIC int bufInsertc(WebsBuf *bp, char c);
  593. /**
  594. Append a character to the buffer at the endp position and increment the endp
  595. @param bp Buffer reference
  596. @param c Character to append
  597. @return Zero if successful
  598. @ingroup WebsBuf
  599. @stability Stable
  600. */
  601. PUBLIC int bufPutc(WebsBuf *bp, char c);
  602. /**
  603. Put a block to the buffer.
  604. @param bp Buffer reference
  605. @param blk Block to append to the buffer
  606. @param len Size of the block
  607. @return Length of data appended. Should equal len.
  608. @ingroup WebsBuf
  609. @stability Stable
  610. */
  611. PUBLIC ssize bufPutBlk(WebsBuf *bp, cchar *blk, ssize len);
  612. /**
  613. Append a formatted string to the buffer at the endp position and increment the endp
  614. @param bp Buffer reference
  615. @param fmt Printf style format string
  616. @param ... Variable arguments for the format string
  617. @return Count of characters appended. Returns negative if there is an allocation error.
  618. @ingroup WebsBuf
  619. @stability Stable
  620. */
  621. PUBLIC ssize bufPut(WebsBuf *bp, cchar *fmt, ...) PRINTF_ATTRIBUTE(2,3);
  622. /**
  623. Append a string to the buffer at the endp position and increment the endp
  624. @param bp Buffer reference
  625. @param str String to append
  626. @return Count of characters appended. Returns negative if there is an allocation error.
  627. @ingroup WebsBuf
  628. @stability Stable
  629. */
  630. PUBLIC ssize bufPutStr(WebsBuf *bp, cchar *str);
  631. /**
  632. Reset the buffer pointers to the start of the buffer if empty
  633. @param bp Buffer reference
  634. @ingroup WebsBuf
  635. @stability Stable
  636. */
  637. PUBLIC void bufReset(WebsBuf *bp);
  638. /**
  639. Determine the room available in the buffer.
  640. @description This returns the maximum number of bytes the buffer can absorb in a single block copy.
  641. @param bp Buffer reference
  642. @return Number of bytes of available space.
  643. @ingroup WebsBuf
  644. @stability Stable
  645. */
  646. PUBLIC ssize bufRoom(WebsBuf *bp);
  647. /**
  648. Get a reference to the start of buffer data
  649. @param bp Buffer reference
  650. @return A string pointer.
  651. @ingroup WebsBuf
  652. @stability Stable
  653. */
  654. PUBLIC char *bufStart(WebsBuf *bp);
  655. /******************************* Malloc Replacement ***************************/
  656. #if ME_GOAHEAD_REPLACE_MALLOC
  657. /**
  658. GoAhead allocator memory block
  659. Memory block classes are: 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536.
  660. @defgroup WebsAlloc WebsAlloc
  661. @stability Stable
  662. */
  663. typedef struct WebsAlloc {
  664. union {
  665. void *next; /**< Pointer to next in q */
  666. int size; /**< Actual requested size */
  667. } u;
  668. int flags; /**< Per block allocation flags */
  669. } WebsAlloc;
  670. #define WEBS_DEFAULT_MEM (64 * 1024) /**< Default memory allocation */
  671. #define WEBS_MAX_CLASS 13 /**< Maximum class number + 1 */
  672. #define WEBS_SHIFT 4 /**< Convert size to class */
  673. #define WEBS_ROUND ((1 << (B_SHIFT)) - 1)
  674. #define WEBS_MALLOCED 0x80000000 /* Block was malloced */
  675. #define WEBS_FILL_CHAR (0x77) /* Fill byte for buffers */
  676. #define WEBS_FILL_WORD (0x77777777) /* Fill word for buffers */
  677. /*
  678. Flags. The integrity value is used as an arbitrary value to fill the flags.
  679. */
  680. #define WEBS_USE_MALLOC 0x1 /**< Okay to use malloc if required */
  681. #define WEBS_USER_BUF 0x2 /* User supplied buffer for mem */
  682. #define WEBS_INTEGRITY 0x8124000 /* Integrity value */
  683. #define WEBS_INTEGRITY_MASK 0xFFFF000 /* Integrity mask */
  684. #endif /* ME_GOAHEAD_REPLACE_MALLOC */
  685. /**
  686. Close the GoAhead memory allocator
  687. @ingroup WebsAlloc
  688. @stability Stable
  689. */
  690. PUBLIC void wcloseAlloc(void);
  691. /**
  692. Initialize the walloc module.
  693. @description The wopenAlloc function should be called the very first thing after the application starts and wclose
  694. should be called the last thing before exiting. If wopenAlloc is not called, it will be called on the first allocation
  695. with default values. "buf" points to memory to use of size "bufsize". If buf is NULL, memory is allocated using malloc.
  696. flags may be set to WEBS_USE_MALLOC if using malloc is okay. This routine will allocate * an initial buffer of size
  697. bufsize for use by the application.
  698. @param buf Optional user supplied block of memory to use for allocations
  699. @param bufsize Size of buf
  700. @param flags Allocation flags. Set to WEBS_USE_MALLOC to permit the use of malloc() to grow memory.
  701. @return Zero if successful, otherwise -1.
  702. @ingroup WebsAlloc
  703. @stability Stable
  704. */
  705. PUBLIC int wopenAlloc(void *buf, int bufsize, int flags);
  706. /**
  707. Allocate a block of the requested size
  708. @param size Memory size required
  709. @return A reference to the allocated block
  710. @ingroup WebsAlloc
  711. @stability Stable
  712. */
  713. PUBLIC void *walloc(ssize size);
  714. /**
  715. Free an allocated block of memory
  716. @param blk Reference to the memory block to free.
  717. @ingroup WebsAlloc
  718. @stability Stable
  719. */
  720. PUBLIC void wfree(void *blk);
  721. /**
  722. Reallocate a block of memory and grow its size
  723. @description If the new size is larger than the existing block, a new block will be allocated and the old data
  724. will be copied to the new block.
  725. @param blk Original block reference
  726. @param newsize Size of the new block.
  727. @return Reference to the new memory block
  728. @ingroup WebsAlloc
  729. @stability Stable
  730. */
  731. PUBLIC void *wrealloc(void *blk, ssize newsize);
  732. /**
  733. Duplicate memory
  734. @param ptr Original block reference
  735. @param usize Size to allocate
  736. @return Reference to the new memory block
  737. @ingroup WebsAlloc
  738. */
  739. PUBLIC void *wdup(cvoid *ptr, size_t usize);
  740. typedef void (*WebsMemNotifier)(ssize size);
  741. /**
  742. Define a global memory allocation notifier.
  743. @description The notifier is called if any memory allocation fails. It is called with the requested allocation size
  744. as its only parameter.
  745. @param cback Callback function to invoke for allocation failures.
  746. @ingroup WebsAlloc
  747. @stability Evolving
  748. */
  749. PUBLIC void websSetMemNotifier(WebsMemNotifier cback);
  750. #ifndef WEBS_SHIFT
  751. #define WEBS_SHIFT 4
  752. #endif
  753. #if DEPRECATE
  754. /*
  755. Deprecated in 4.0.0
  756. */
  757. PUBLIC ssize mtow(wchar *dest, ssize count, char *src, ssize len);
  758. PUBLIC ssize wtom(char *dest, ssize count, wchar *src, ssize len);
  759. PUBLIC wchar *amtow(char *src, ssize *len);
  760. PUBLIC char *awtom(wchar *src, ssize *len);
  761. #endif
  762. /******************************* Hash Table *********************************/
  763. /**
  764. Hash table entry structure.
  765. @description The hash structure supports growable hash tables with high performance, collision resistant hashes.
  766. Each hash entry has a descriptor entry. This is used to manage the hash table link chains.
  767. @see hashCreate hashFree hashLookup hashEnter hashDelete hashWalk hashFirst hashNext
  768. @defgroup WebsHash WebsHash
  769. @stability Stable
  770. */
  771. typedef struct WebsKey {
  772. struct WebsKey *forw; /* Pointer to next hash list */
  773. WebsValue name; /* Name of symbol */
  774. WebsValue content; /* Value of symbol */
  775. int arg; /* Parameter value */
  776. int bucket; /* Bucket index */
  777. } WebsKey;
  778. /**
  779. Hash table ID returned by hashCreate
  780. */
  781. typedef int WebsHash; /* Returned by symCreate */
  782. /**
  783. Create a hash table
  784. @param size Minimum size of the hash index
  785. @return Hash table ID. Negative if the hash cannot be created.
  786. @ingroup WebsHash
  787. @stability Stable
  788. */
  789. PUBLIC WebsHash hashCreate(int size);
  790. /**
  791. Free a hash table
  792. @param id Hash table id returned by hashCreate
  793. @ingroup WebsHash
  794. @stability Stable
  795. */
  796. PUBLIC void hashFree(WebsHash id);
  797. /**
  798. Lookup a name in the hash table
  799. @param id Hash table id returned by hashCreate
  800. @param name Key name to search for
  801. @return Reference to the WebKey object storing the key and value
  802. @ingroup WebsHash
  803. @stability Stable
  804. */
  805. PUBLIC WebsKey *hashLookup(WebsHash id, cchar *name);
  806. /**
  807. Lookup a name in the hash table and return a symbol reference
  808. @param sd Hash table id returned by hashCreate
  809. @param name Key name to search for
  810. @return Reference to the symbole
  811. @ingroup WebsHash
  812. @stability Evolving
  813. */
  814. PUBLIC void *hashLookupSymbol(WebsHash sd, cchar *name);
  815. /**
  816. Enter a new key and value into the hash table
  817. @param id Hash table id returned by hashCreate
  818. @param name Key name to create
  819. @param value Key value to enter
  820. @param arg Optional extra argument to store with the value
  821. @return Reference to the WebKey object storing the key and value
  822. @ingroup WebsHash
  823. @stability Stable
  824. */
  825. PUBLIC WebsKey *hashEnter(WebsHash id, cchar *name, WebsValue value, int arg);
  826. /**
  827. Delete a key by name
  828. @param id Hash table id returned by hashCreate
  829. @param name Key name to delete
  830. @return Zero if the delete was successful. Otherwise -1 if the key was not found.
  831. @ingroup WebsHash
  832. @stability Stable
  833. */
  834. PUBLIC int hashDelete(WebsHash id, cchar *name);
  835. /**
  836. Start walking the hash keys by returning the first key entry in the hash
  837. @param id Hash table id returned by hashCreate
  838. @return Reference to the first WebKey object. Return null if there are no keys in the hash.
  839. @ingroup WebsHash
  840. @stability Stable
  841. */
  842. PUBLIC WebsKey *hashFirst(WebsHash id);
  843. /**
  844. Continue walking the hash keys by returning the next key entry in the hash
  845. @param id Hash table id returned by hashCreate
  846. @param last Reference to a WebsKey to hold the current traversal key state.
  847. @return Reference to the next WebKey object. Returns null if no more keys exist to be traversed.
  848. @ingroup WebsHash
  849. @stability Stable
  850. */
  851. PUBLIC WebsKey *hashNext(WebsHash id, WebsKey *last);
  852. /************************************ Socket **********************************/
  853. /*
  854. Socket flags
  855. */
  856. #define SOCKET_EOF 0x1 /**< Seen end of file */
  857. #define SOCKET_CONNECTING 0x2 /**< Connect in progress */
  858. #define SOCKET_RESERVICE 0x4 /**< Socket needs re-servicing */
  859. #define SOCKET_ASYNC 0x8 /**< Use async connect */
  860. #define SOCKET_BLOCK 0x10 /**< Use blocking I/O */
  861. #define SOCKET_LISTENING 0x20 /**< Socket is server listener */
  862. #define SOCKET_CLOSING 0x40 /**< Socket is closing */
  863. #define SOCKET_CONNRESET 0x80 /**< Socket connection was reset */
  864. #define SOCKET_HANDSHAKING 0x100 /**< Doing SSL handshake */
  865. #define SOCKET_BUFFERED_READ 0x200 /**< Message pending on this socket */
  866. #define SOCKET_BUFFERED_WRITE 0x400 /**< Message pending on this socket */
  867. #define SOCKET_NODELAY 0x800 /**< Disable Nagle algorithm */
  868. #define SOCKET_PORT_MAX 0xffff /**< Max Port size */
  869. #ifndef ME_MAX_IP
  870. #define ME_MAX_IP 64 /**< Maximum IP address size */
  871. #endif
  872. /*
  873. Socket error values
  874. */
  875. #define SOCKET_WOULDBLOCK 1 /**< Socket would block on I/O */
  876. #define SOCKET_RESET 2 /**< Socket has been reset */
  877. #define SOCKET_NETDOWN 3 /**< Network is down */
  878. #define SOCKET_AGAIN 4 /**< Issue the request again */
  879. #define SOCKET_INTR 5 /**< Call was interrupted */
  880. #define SOCKET_INVAL 6 /**< Invalid */
  881. /*
  882. Handler event masks
  883. */
  884. #define SOCKET_READABLE 0x2 /**< Make socket readable */
  885. #define SOCKET_WRITABLE 0x4 /**< Make socket writable */
  886. #define SOCKET_EXCEPTION 0x8 /**< Interested in exceptions */
  887. /**
  888. Socket I/O callback
  889. @param sid Socket ID handle returned from socketConnect or when a new socket is passed to a SocketAccept
  890. callback..
  891. @param mask Mask of events of interest. Set to SOCKET_READABLE | SOCKET_WRITABLE | SOCKET_EXCEPTION.
  892. @param data Data argument to pass to the callback function.
  893. @ingroup WebsSocket
  894. @stability Stable
  895. */
  896. typedef void (*SocketHandler)(int sid, int mask, void *data);
  897. /**
  898. Socket accept callback
  899. @param sid Socket ID handle for the newly accepted socket
  900. @param ipaddr IP address of the connecting client.
  901. @param port Port of the connecting client.
  902. @param listenSid Socket ID for the listening socket
  903. @ingroup WebsSocket
  904. @stability Stable
  905. */
  906. typedef int (*SocketAccept)(int sid, cchar *ipaddr, int port, int listenSid);
  907. /**
  908. Socket control structure
  909. @see socketAddress socketAddressIsV6 socketClose socketCloseConnection socketCreateHandler
  910. socketDeletehandler socketReservice socketEof socketGetPort socketInfo socketIsV6
  911. socketOpen socketListen socketParseAddress socketProcess socketRead socketWrite socketWriteString
  912. socketSelect socketGetHandle socketSetBlock socketGetBlock socketAlloc socketFree socketGetError
  913. socketSetError socketPtr socketWaitForEvent socketRegisterInterest
  914. @defgroup WebsSocket WebsSocket
  915. @stability Stable
  916. */
  917. typedef struct WebsSocket {
  918. WebsBuf lineBuf; /**< Line ring queue */
  919. SocketAccept accept; /**< Accept handler */
  920. SocketHandler handler; /**< User I/O handler */
  921. char *ip; /**< Server listen address or remote client address */
  922. void *handler_data; /**< User handler data */
  923. int handlerMask; /**< Handler events of interest */
  924. int sid; /**< Index into socket[] */
  925. int port; /**< Port to listen on */
  926. int flags; /**< Current state flags */
  927. Socket sock; /**< Actual socket handle */
  928. int fileHandle; /**< ID of the file handler */
  929. int interestEvents; /**< Mask of events to watch for */
  930. int currentEvents; /**< Mask of ready events (FD_xx) */
  931. int selectEvents; /**< Events being selected */
  932. int saveMask; /**< saved Mask for socketFlush */
  933. int error; /**< Last error */
  934. int secure; /**< Socket is using SSL */
  935. int handshakes; /**< Number of renegotiations */
  936. } WebsSocket;
  937. /**
  938. Extract the numerical IP address and port for the given socket info
  939. @param addr Reference to the socket address.
  940. @param addrlen Length of the socket address
  941. @param ipbuf Buffer to contain the parsed IP address
  942. @param ipLen Size of ipbuf
  943. @param port Reference to an integer to hold the parsed port.
  944. @return Zero if successful. Otherwise -1 for parse errors.
  945. @ingroup WebsSocket
  946. @stability Stable
  947. */
  948. PUBLIC int socketAddress(struct sockaddr *addr, int addrlen, char *ipbuf, int ipLen, int *port);
  949. /**
  950. Determine if an IP address is an IPv6 address.
  951. @param ip String IP address.
  952. @return True if the address is an IPv6 address.
  953. @ingroup WebsSocket
  954. @stability Stable
  955. */
  956. PUBLIC bool socketAddressIsV6(cchar *ip);
  957. /**
  958. Allocate a socket object
  959. @param host String host IP address.
  960. @param port Socket port
  961. @param accept Optional SocketAccept accept callback function
  962. @param flags Control flags
  963. @return Socket ID handle to use with other APIs.
  964. @ingroup WebsSocket
  965. @stability Stable
  966. */
  967. PUBLIC int socketAlloc(cchar *host, int port, SocketAccept accept, int flags);
  968. /**
  969. Close the socket module
  970. @ingroup WebsSocket
  971. @stability Stable
  972. */
  973. PUBLIC void socketClose(void);
  974. /**
  975. Close a socket connection
  976. @param sid Socket ID handle returned from socketConnect or socketAccept.
  977. @ingroup WebsSocket
  978. @stability Stable
  979. */
  980. PUBLIC void socketCloseConnection(int sid);
  981. /**
  982. Connect to a server and create a new socket
  983. @param host Host IP address.
  984. @param port Port number to connect to
  985. @param flags Set to SOCKET_BLOCK for blocking I/O. Otherwise non-blocking I/O is used.
  986. @return True if the address is an IPv6 address.
  987. @ingroup WebsSocket
  988. @internal
  989. @stability Stable
  990. */
  991. PUBLIC int socketConnect(cchar *host, int port, int flags);
  992. /**
  993. Create a socket handler that will be invoked when I/O events occur.
  994. @param sid Socket ID handle returned from socketConnect or socketAccept.
  995. @param mask Mask of events of interest. Set to SOCKET_READABLE | SOCKET_WRITABLE | SOCKET_EXCEPTION.
  996. @param handler Socket handler function.
  997. @param arg Arbitrary object reference to pass to the SocketHandler callback function.
  998. @return True if the address is an IPv6 address.
  999. @ingroup WebsSocket
  1000. @stability Stable
  1001. */
  1002. PUBLIC void socketCreateHandler(int sid, int mask, SocketHandler handler, void *arg);
  1003. /**
  1004. Delete a socket handler created via socketCreateHandler
  1005. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1006. @ingroup WebsSocket
  1007. @stability Stable
  1008. */
  1009. PUBLIC void socketDeleteHandler(int sid);
  1010. /**
  1011. Determine if the socket is at end-of-file for input.
  1012. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1013. @return True if the address is at EOF
  1014. @ingroup WebsSocket
  1015. @stability Stable
  1016. */
  1017. PUBLIC bool socketEof(int sid);
  1018. /**
  1019. Free (and close) the socket
  1020. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1021. @ingroup WebsSocket
  1022. @stability Stable
  1023. */
  1024. PUBLIC void socketFree(int sid);
  1025. /**
  1026. Get the current blocking mode
  1027. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1028. @return True if the socket is in blocking mode.
  1029. @ingroup WebsSocket
  1030. @stability Stable
  1031. */
  1032. PUBLIC int socketGetBlock(int sid);
  1033. /**
  1034. Get the error code for the last socket operation on this thread.
  1035. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1036. @return Integer error code. See errno or GetLastError() on windows.
  1037. @ingroup WebsSocket
  1038. @stability Stable
  1039. */
  1040. PUBLIC int socketGetError(int sid);
  1041. /**
  1042. Get the underlying socket operating system socket/file handle
  1043. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1044. @return The socket handle
  1045. @ingroup WebsSocket
  1046. @stability Stable
  1047. */
  1048. PUBLIC Socket socketGetHandle(int sid);
  1049. /**
  1050. Get the list of sockets
  1051. @return The socket list pointer
  1052. @ingroup WebsSocket
  1053. @stability Stable
  1054. */
  1055. PUBLIC WebsSocket **socketGetList(void);
  1056. /**
  1057. Get the IP port associated with this socket.
  1058. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1059. @return The TCP/IP port for this socket
  1060. @ingroup WebsSocket
  1061. @stability Stable
  1062. */
  1063. PUBLIC int socketGetPort(int sid);
  1064. /**
  1065. Indicate if the system has a dual IPv4 and IPv6 stack
  1066. @return True if IPv4 and IPv6 are supported on a single stack
  1067. @ingroup WebsSocket
  1068. @stability Stable
  1069. */
  1070. PUBLIC bool socketHasDualNetworkStack(void);
  1071. /**
  1072. Indicate if the system has IPv6 support
  1073. @return True if IPv6 is supported on this system
  1074. @ingroup WebsSocket
  1075. @stability Stable
  1076. */
  1077. PUBLIC bool socketHasIPv6(void);
  1078. /**
  1079. Indicate that the application layer has buffered data for the socket.
  1080. @description This is used by SSL and other network stacks that buffer pending data
  1081. @param sp Socket object returned from #socketPtr
  1082. @param len Length of buffered data in bytes
  1083. @param dir Buffer direction. Set to MPR_READABLE for buffered read data and MPR_WRITABLE for buffered write data.
  1084. @ingroup WebsSocket
  1085. @stability Stable
  1086. */
  1087. PUBLIC void socketHiddenData(WebsSocket *sp, ssize len, int dir);
  1088. /**
  1089. Get a socket address structure for the specified IP:Port
  1090. @description This returns address details in *family, *protocol, *addr, and *addrlen.
  1091. @param ip IP address to parse
  1092. @param port TCP/IP port number
  1093. @param family Reference to an integer to hold the address family
  1094. @param protocol Reference to an integer to hold the address protocol
  1095. @param addr Reference to an integer to hold the address structure
  1096. @param addrlen Reference to an integer to hold the address structure length
  1097. @return Zero if successful, otherwise -1.
  1098. @ingroup WebsSocket
  1099. @stability Stable
  1100. */
  1101. PUBLIC int socketInfo(cchar *ip, int port, int *family, int *protocol, struct sockaddr_storage *addr, Socklen *addrlen);
  1102. /**
  1103. Determine if a socket is bound to an IPv6 address.
  1104. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1105. @return True if the socket is using IPv6.
  1106. @ingroup WebsSocket
  1107. @stability Stable
  1108. */
  1109. PUBLIC bool socketIsV6(int sid);
  1110. /**
  1111. Open a listening socket
  1112. @param host Host IP address on which to listen. Set to NULL to listen on all interfaces.
  1113. @param port TCP/IP port on which to listen
  1114. @param accept SocketAccept callback function to invoke to receive incoming connections.
  1115. @param flags Reserved
  1116. @return Zero if successful, otherwise -1.
  1117. @ingroup WebsSocket
  1118. @stability Stable
  1119. */
  1120. PUBLIC int socketListen(cchar *host, int port, SocketAccept accept, int flags);
  1121. /**
  1122. Open the socket module
  1123. @return Zero if successful, otherwise -1.
  1124. @ingroup WebsSocket
  1125. @stability Stable
  1126. */
  1127. PUBLIC int socketOpen(void);
  1128. /**
  1129. Parse an IP address into its constituent parts.
  1130. @description Parse the IP address and return the IP address and port components. Handles ipv4 and ipv6 addresses.
  1131. If the IP portion is absent, pip is set to null. If the port portion is absent, port is set to the defaultPort.
  1132. If a ":*" port specifier is used, pport is set to -1;
  1133. When an address contains an ipv6 port it should be written as
  1134. aaaa:bbbb:cccc:dddd:eeee:ffff:gggg:hhhh:iiii
  1135. or
  1136. [aaaa:bbbb:cccc:dddd:eeee:ffff:gggg:hhhh:iiii]:port
  1137. If supplied an IPv6 address, the backets are stripped in the returned IP address.
  1138. @param ipAddrPort IP address which may contain an optional ":port" component.
  1139. @param pip Returns a reference to an allocated string containing the IP address portion. Caller must free.
  1140. @param pport Reference to an integer to hold the port component.
  1141. @param secure Reference to an integer to be set to true if the address is using SSL/TLS.
  1142. @param defaultPort Default port number to use if no port specifier is included in ipAddrPort.
  1143. @return Zero if successful, otherwise -1.
  1144. @ingroup WebsSocket
  1145. @stability Stable
  1146. */
  1147. PUBLIC int socketParseAddress(cchar *ipAddrPort, char **pip, int *pport, int *secure, int defaultPort);
  1148. /**
  1149. Process pending socket I/O events.
  1150. @ingroup WebsSocket
  1151. @stability Stable
  1152. @internal
  1153. */
  1154. PUBLIC void socketProcess(void);
  1155. /**
  1156. Read data from a socket
  1157. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1158. @param buf Buffer to hold read data
  1159. @param len Size of the buffer
  1160. @return Count of bytes actually read. Returns -1 for errors and EOF. Distinguish between errors and EOF
  1161. via socketEof().
  1162. @ingroup WebsSocket
  1163. @stability Stable
  1164. */
  1165. PUBLIC ssize socketRead(int sid, void *buf, ssize len);
  1166. /**
  1167. Register interest in socket I/OEvents
  1168. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1169. @param mask Mask of events of interest. Set to SOCKET_READABLE | SOCKET_WRITABLE | SOCKET_EXCEPTION.
  1170. @ingroup WebsSocket
  1171. @stability Stable
  1172. */
  1173. PUBLIC void socketRegisterInterest(int sid, int mask);
  1174. /**
  1175. Request that the socket be reserviced.
  1176. @description This routine is useful when upper layers have unprocessed, buffered data for the socket.
  1177. This routine will cause the socket I/O callback handler to be invoked soon in the future.
  1178. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1179. @ingroup WebsSocket
  1180. @stability Stable
  1181. */
  1182. PUBLIC void socketReservice(int sid);
  1183. /**
  1184. Wait for I/O on a socket
  1185. @description This call uses the mask of events of interest defined by socketRegisterInterest. It blocks the caller
  1186. until a suitable I/O event or timeout occurs.
  1187. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1188. @param timeout Timeout in milliseconds.
  1189. @return Number of I/O events.
  1190. @ingroup WebsSocket
  1191. @stability Stable
  1192. */
  1193. PUBLIC int socketSelect(int sid, int timeout);
  1194. /**
  1195. Set the socket blocking mode
  1196. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1197. @param on Set to 1 to enable blocking
  1198. @return The previous blocking mode
  1199. @ingroup WebsSocket
  1200. @stability Stable
  1201. */
  1202. PUBLIC int socketSetBlock(int sid, int on);
  1203. /**
  1204. Set the error code for the last socket operation on this thread.
  1205. @param error Integer error code. See errno or GetLastError() on windows.
  1206. @ingroup WebsSocket
  1207. @stability Stable
  1208. */
  1209. PUBLIC void socketSetError(int error);
  1210. /**
  1211. Set the socket delay mode
  1212. @description This is used to enable or disable the TCP Nagle algorithm
  1213. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1214. @param on Set to 1 to disable the Nagle algorithm
  1215. @return The previous blocking mode
  1216. @ingroup WebsSocket
  1217. @stability Stable
  1218. */
  1219. PUBLIC int socketSetNoDelay(int sid, bool on);
  1220. /**
  1221. Wait for a socket I/O event
  1222. @param sp Socket object
  1223. @param mask Mask of events of interest. Set to SOCKET_READABLE | SOCKET_WRITABLE | SOCKET_EXCEPTION.
  1224. @return Zero if successful in waiting for the desired event, otherwise return -1.
  1225. @ingroup WebsSocket
  1226. @stability Stable
  1227. */
  1228. PUBLIC int socketWaitForEvent(WebsSocket *sp, int mask);
  1229. /**
  1230. Write data to the socket
  1231. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1232. @param buf Buffer containing data to write
  1233. @param len Size of buf
  1234. @return Count of bytes written. May be less than len if the socket is in non-blocking mode.
  1235. Returns -1 for errors and if the socket cannot absorb any more data. If the transport is saturated,
  1236. will return a negative error and errno will be set to EAGAIN or EWOULDBLOCK.
  1237. @ingroup WebsSocket
  1238. @stability Stable
  1239. */
  1240. PUBLIC ssize socketWrite(int sid, void *buf, ssize len);
  1241. /**
  1242. Return the socket object for the socket ID.
  1243. @param sid Socket ID handle returned from socketConnect or socketAccept.
  1244. @return Corresponding socket object.
  1245. @ingroup WebsSocket
  1246. @stability Stable
  1247. */
  1248. PUBLIC WebsSocket *socketPtr(int sid);
  1249. /*********************************** Runtime **********************************/
  1250. /**
  1251. GoAhead Web Server Runtime
  1252. @description GoAhead provides a secure runtime environment for safe string manipulation and to
  1253. help prevent buffer overflows and other potential security traps.
  1254. @defgroup WebsRuntime WebsRuntime
  1255. @see fmt wallocHandle wallocObject wfreeHandle hextoi itosbuf scaselesscmp scaselessmatch
  1256. sclone scmp scopy sfmt sfmtv slen slower smatch sstarts sncaselesscmp sncmp sncopy stok strim supper
  1257. @stability Stable
  1258. */
  1259. /**
  1260. Format a string into a static buffer.
  1261. @description This call format a string using printf style formatting arguments. A trailing null will
  1262. always be appended. The call returns the size of the allocated string excluding the null.
  1263. @param buf Pointer to the buffer.
  1264. @param maxSize Size of the buffer.
  1265. @param format Printf style format string
  1266. @param ... Variable arguments to format
  1267. @return Returns the buffer.
  1268. @ingroup WebsRuntime
  1269. @stability Stable
  1270. */
  1271. PUBLIC char *fmt(char *buf, ssize maxSize, cchar *format, ...);
  1272. /**
  1273. Allocate a handle from a map
  1274. @param map Reference to a location holding the map reference. On the first call, the map is allocated.
  1275. @return Integer handle index. Otherwise return -1 on allocation errors.
  1276. @ingroup WebsRuntime
  1277. @stability Stable
  1278. */
  1279. PUBLIC int wallocHandle(void *map);
  1280. /**
  1281. Allocate an object in a halloc map
  1282. @param map Reference to a location holding the map reference. On the first call, the map is allocated.
  1283. @param max Reference to an integer that holds the maximum handle in the map.
  1284. @param size Size of the object to allocate.
  1285. @return Integer handle index. Otherwise return -1 on allocation errors.
  1286. @ingroup WebsRuntime
  1287. @stability Stable
  1288. */
  1289. PUBLIC int wallocObject(void *map, int *max, int size);
  1290. /**
  1291. Free a handle in the map
  1292. @param map Reference to a location to hold the map reference.
  1293. @param handle Handle to free in the map.
  1294. @return Integer handle index. Otherwise return -1 on allocation errors.
  1295. @ingroup WebsRuntime
  1296. @stability Stable
  1297. */
  1298. PUBLIC int wfreeHandle(void *map, int handle);
  1299. /**
  1300. Convert a hex string to an integer
  1301. @description This call converts the supplied string to an integer using base 16.
  1302. @param str Pointer to the string to parse.
  1303. @return Returns the integer equivalent value of the string.
  1304. @ingroup WebsRuntime
  1305. @stability Stable
  1306. */
  1307. PUBLIC uint hextoi(cchar *str);
  1308. /**
  1309. Convert an integer to a string buffer.
  1310. @description This call converts the supplied 64 bit integer into a string formatted into the supplied buffer according
  1311. to the specified radix.
  1312. @param buf Pointer to the buffer that will hold the string.
  1313. @param size Size of the buffer.
  1314. @param value Integer value to convert
  1315. @param radix The base radix to use when encoding the number
  1316. @return Returns a reference to the string.
  1317. @ingroup WebsRuntime
  1318. @stability Stable
  1319. */
  1320. PUBLIC char *itosbuf(char *buf, ssize size, int64 value, int radix);
  1321. /**
  1322. Compare strings ignoring case. This is a safe replacement for strcasecmp. It can handle NULL args.
  1323. @description Compare two strings ignoring case differences. This call operates similarly to strcmp.
  1324. @param s1 First string to compare.
  1325. @param s2 Second string to compare.
  1326. @return Returns zero if the strings are equivalent, < 0 if s1 sorts lower than s2 in the collating sequence
  1327. or > 0 if it sorts higher.
  1328. @ingroup WebsRuntime
  1329. @stability Stable
  1330. */
  1331. PUBLIC int scaselesscmp(cchar *s1, cchar *s2);
  1332. /**
  1333. Compare strings ignoring case. This is similar to scaselesscmp but it returns a boolean.
  1334. @description Compare two strings ignoring case differences.
  1335. @param s1 First string to compare.
  1336. @param s2 Second string to compare.
  1337. @return Returns true if the strings are equivalent, otherwise false.
  1338. @ingroup WebsRuntime
  1339. @stability Stable
  1340. */
  1341. PUBLIC bool scaselessmatch(cchar *s1, cchar *s2);
  1342. /**
  1343. Clone a string
  1344. @description Copy a string into a newly allocated block.
  1345. @param str Pointer to the block to duplicate.
  1346. @return Returns a newly allocated string.
  1347. @ingroup WebsRuntime
  1348. @stability Stable
  1349. */
  1350. PUBLIC char *sclone(cchar *str);
  1351. /**
  1352. Clone a substring.
  1353. @description Copy a substring into a newly allocated block.
  1354. @param str Pointer to the block to duplicate.
  1355. @param len Number of bytes to copy. The actual length copied is the minimum of the given length and the length of
  1356. the supplied string. The result is null terminated.
  1357. @return Returns a newly allocated string.
  1358. @ingroup WebsRuntime
  1359. @stability Stable
  1360. */
  1361. PUBLIC char *snclone(cchar *str, ssize len);
  1362. /**
  1363. Compare strings.
  1364. @description Compare two strings. This is a safe replacement for strcmp. It can handle null args.
  1365. @param s1 First string to compare.
  1366. @param s2 Second string to compare.
  1367. @return Returns zero if the strings are identical. Return -1 if the first string is less than the second. Return 1
  1368. if the first string is greater than the second.
  1369. @ingroup WebsRuntime
  1370. @stability Stable
  1371. */
  1372. PUBLIC int scmp(cchar *s1, cchar *s2);
  1373. /**
  1374. Copy a string.
  1375. @description Safe replacement for strcpy. Copy a string and ensure the destination buffer is not overflowed.
  1376. The call returns the length of the resultant string or an error code if it will not fit into the target
  1377. string. This is similar to strcpy, but it will enforce a maximum size for the copied string and will
  1378. ensure it is always terminated with a null.
  1379. @param dest Pointer to a pointer that will hold the address of the allocated block.
  1380. @param destMax Maximum size of the target string in characters.
  1381. @param src String to copy
  1382. @return Returns the number of characters in the target string.
  1383. @ingroup WebsRuntime
  1384. @stability Stable
  1385. */
  1386. PUBLIC ssize scopy(char *dest, ssize destMax, cchar *src);
  1387. /*
  1388. String trim flags
  1389. */
  1390. #define WEBS_TRIM_START 0x1 /**< Flag for strim to trim from the start of the string */
  1391. #define WEBS_TRIM_END 0x2 /**< Flag for strim to trim from the end of the string */
  1392. #define WEBS_TRIM_BOTH 0x3 /**< Flag for strim to trim from both the start and the end of the string */
  1393. /**
  1394. Format a string. This is a secure version of printf that can handle null args.
  1395. @description Format the given arguments according to the printf style format. See fmt() for a full list of the
  1396. format specifies. This is a secure replacement for sprintf, it can handle null arguments without crashes.
  1397. @param format Printf style format string
  1398. @param ... Variable arguments for the format string
  1399. @return Returns a newly allocated string
  1400. @ingroup WebsRuntime
  1401. @stability Stable
  1402. */
  1403. PUBLIC char *sfmt(cchar *format, ...);
  1404. /**
  1405. Format a string with varargs. This is a secure version of printf that can handle null args.
  1406. @description Format the given arguments according to the printf style format. See fmt() for a full list of the
  1407. format specifies. This is a secure replacement for sprintf, it can handle null arguments without crashes.
  1408. @param format Printf style format string
  1409. @param args Varargs argument obtained from va_start.
  1410. @return Returns a newly allocated string
  1411. @ingroup WebsRuntime
  1412. @stability Stable
  1413. */
  1414. PUBLIC char *sfmtv(cchar *format, va_list args);
  1415. /**
  1416. Return the length of a string.
  1417. @description Safe replacement for strlen. This call returns the length of a string and tests if the length is
  1418. less than a given maximum. It will return zero for NULL args.
  1419. @param str String to measure.
  1420. @return Returns the length of the string
  1421. @ingroup WebsRuntime
  1422. @stability Stable
  1423. */
  1424. PUBLIC ssize slen(cchar *str);
  1425. /**
  1426. Convert a string to lower case.
  1427. @description Convert a string to its lower case equivalent.
  1428. @param str String to convert. This string is modified.
  1429. @return Reference to the supplied str. Caller must not free.
  1430. @ingroup WebsRuntime
  1431. @stability Stable
  1432. */
  1433. PUBLIC char *slower(char *str);
  1434. /**
  1435. Compare strings
  1436. @description Compare two strings. This is similar to #scmp but it returns a boolean.
  1437. @param s1 First string to compare.
  1438. @param s2 Second string to compare.
  1439. @return Returns true if the strings are equivalent, otherwise false.
  1440. @ingroup WebsRuntime
  1441. @stability Stable
  1442. */
  1443. PUBLIC bool smatch(cchar *s1, cchar *s2);
  1444. /**
  1445. Compare strings ignoring case.
  1446. @description Compare two strings ignoring case differences for a given string length. This call operates
  1447. similarly to strncasecmp.
  1448. @param s1 First string to compare.
  1449. @param s2 Second string to compare.
  1450. @param len Length of characters to compare.
  1451. @return Returns zero if the strings are equivalent, < 0 if s1 sorts lower than s2 in the collating sequence
  1452. or > 0 if it sorts higher.
  1453. @ingroup WebsRuntime
  1454. @stability Stable
  1455. */
  1456. PUBLIC int sncaselesscmp(cchar *s1, cchar *s2, ssize len);
  1457. /**
  1458. Compare strings.
  1459. @description Compare two strings for a given string length. This call operates similarly to strncmp.
  1460. @param s1 First string to compare.
  1461. @param s2 Second string to compare.
  1462. @param len Length of characters to compare.
  1463. @return Returns zero if the strings are equivalent, < 0 if s1 sorts lower than s2 in the collating sequence
  1464. or > 0 if it sorts higher.
  1465. @ingroup WebsRuntime
  1466. @stability Stable
  1467. */
  1468. PUBLIC int sncmp(cchar *s1, cchar *s2, ssize len);
  1469. /**
  1470. Copy characters from a string.
  1471. @description Safe replacement for strncpy. Copy bytes from a string and ensure the target string is not overflowed.
  1472. The call returns the length of the resultant string or an error code if it will not fit into the target
  1473. string. This is similar to strcpy, but it will enforce a maximum size for the copied string and will
  1474. ensure it is terminated with a null.
  1475. @param dest Pointer to a pointer that will hold the address of the allocated block.
  1476. @param destMax Maximum size of the target string in characters.
  1477. @param src String to copy
  1478. @param count Maximum count of characters to copy
  1479. @return Returns a reference to the destination if successful or NULL if the string won't fit.
  1480. @ingroup WebsRuntime
  1481. @stability Stable
  1482. */
  1483. PUBLIC ssize sncopy(char *dest, ssize destMax, cchar *src, ssize count);
  1484. /*
  1485. Test if a string is a radix 10 number.
  1486. @description The supported format is: [(+|-)][DIGITS]
  1487. @return true if all characters are digits or '+' or '-'
  1488. @ingroup WebsRuntime
  1489. @stability Stable
  1490. */
  1491. PUBLIC bool snumber(cchar *s);
  1492. /**
  1493. Split a string at a delimiter
  1494. @description Split a string and return parts. The string is modified.
  1495. This routiner never returns null. If there are leading delimiters, the empty string will be returned
  1496. and *last will be set to the portion after the delimiters.
  1497. If str is null, an empty string will be returned.
  1498. If there are no characters after the delimiter, then *last will be set to the empty string.
  1499. @param str String to tokenize.
  1500. @param delim Set of characters that are used as token separators.
  1501. @param last Reference to the portion after the delimiters. Will return an empty string if is not trailing portion.
  1502. @return Returns a pointer to the first part before the delimiters. If the string begins with delimiters, the empty
  1503. string will be returned.
  1504. @ingroup WebsRuntime
  1505. @stability Evolving
  1506. */
  1507. PUBLIC char *ssplit(char *str, cchar *delim, char **last);
  1508. /**
  1509. Test if the string starts with a given pattern.
  1510. @param str String to examine
  1511. @param prefix Pattern to search for
  1512. @return Returns TRUE if the pattern was found. Otherwise returns zero.
  1513. @ingroup MprString
  1514. @stability Stable
  1515. */
  1516. PUBLIC bool sstarts(cchar *str, cchar *prefix);
  1517. /**
  1518. Tokenize a string
  1519. @description Split a string into tokens.
  1520. @param str String to tokenize.
  1521. @param delim String of characters to use as token separators.
  1522. @param last Last token pointer.
  1523. @return Returns a pointer to the next token.
  1524. @ingroup WebsRuntime
  1525. @stability Stable
  1526. */
  1527. PUBLIC char *stok(char *str, cchar *delim, char **last);
  1528. /**
  1529. Trim a string.
  1530. @description Trim leading and trailing characters off a string.
  1531. @param str String to trim.
  1532. @param set String of characters to remove.
  1533. @param where Flags to indicate trim from the start, end or both. Use WEBS_TRIM_START, WEBS_TRIM_END, WEBS_TRIM_BOTH.
  1534. @return Returns a pointer to the trimmed string. May not equal \a str.
  1535. @ingroup WebsRuntime
  1536. @stability Stable
  1537. */
  1538. PUBLIC char *strim(char *str, cchar *set, int where);
  1539. /**
  1540. Convert a string to upper case.
  1541. @description Convert a string to its upper case equivalent.
  1542. @param str String to convert. This string is modified.
  1543. @return Returns a pointer to the converted string. Will always equal str. Caller must not free.
  1544. @ingroup WebsRuntime
  1545. @stability Stable
  1546. */
  1547. PUBLIC char *supper(char *str);
  1548. /**
  1549. Callback function for events
  1550. @param data Opaque data argument
  1551. @param id Event ID
  1552. @ingroup WebsRuntime
  1553. @stability Stable
  1554. */
  1555. typedef void (*WebsEventProc)(void *data, int id);
  1556. /**
  1557. Start a callback event
  1558. @description This schedules an event to run once. The event can be rescheduled in the callback by invoking
  1559. websRestartEvent.
  1560. @param delay Delay in milliseconds in which to run the callback
  1561. @param proc Callback procedure function. Signature is: void (*fn)(void *data, int id)
  1562. @param data Data reference to pass to the callback
  1563. @return A positive integer event ID
  1564. @ingroup WebsRuntime
  1565. @stability Stable
  1566. */
  1567. PUBLIC int websStartEvent(int delay, WebsEventProc proc, void *data);
  1568. /**
  1569. Stop an event
  1570. @param id Event id allocated by websStartEvent
  1571. @return Integer handle index. Otherwise return -1 on allocation errors.
  1572. @ingroup WebsRuntime
  1573. @stability Stable
  1574. */
  1575. PUBLIC void websStopEvent(int id);
  1576. /**
  1577. Restart an event
  1578. @param id Event id allocated by websStartEvent
  1579. @param delay Delay in milliseconds till the event next runs
  1580. @ingroup WebsRuntime
  1581. @stability Stable
  1582. */
  1583. PUBLIC void websRestartEvent(int id, int delay);
  1584. /**
  1585. Run due events
  1586. @ingroup WebsRuntime
  1587. @return Time delay till the next event
  1588. @internal
  1589. */
  1590. PUBLIC int websRunEvents(void);
  1591. /* Forward declare */
  1592. struct WebsRoute;
  1593. struct WebsUser;
  1594. struct WebsSession;
  1595. struct Webs;
  1596. /********************************** Upload ************************************/
  1597. #if ME_GOAHEAD_UPLOAD
  1598. /**
  1599. File upload structure
  1600. @see websUploadOpen websLookupUpload websGetUpload
  1601. @defgroup WebsUpload WebsUpload
  1602. */
  1603. typedef struct WebsUpload {
  1604. char *filename; /**< Local (temp) name of the file */
  1605. char *clientFilename; /**< Client side name of the file */
  1606. char *contentType; /**< Content type */
  1607. ssize size; /**< Uploaded file size */
  1608. } WebsUpload;
  1609. /**
  1610. Open the file upload filter
  1611. @ingroup WebsUpload
  1612. @stability Stable
  1613. */
  1614. PUBLIC void websUploadOpen(void);
  1615. /**
  1616. Get the hash of uploaded files for the request
  1617. @param wp Webs request object
  1618. @return Hash table of uploaded files
  1619. @ingroup WebsUpload
  1620. @stability Stable
  1621. */
  1622. PUBLIC WebsHash websGetUpload(struct Webs *wp);
  1623. /**
  1624. Open the file upload filter
  1625. @param wp Webs request object
  1626. @param key Form upload name
  1627. @return Upload object for the uploaded file
  1628. @ingroup WebsUpload
  1629. @stability Stable
  1630. */
  1631. PUBLIC WebsUpload *websLookupUpload(struct Webs *wp, cchar *key);
  1632. #endif
  1633. /********************************** Defines ***********************************/
  1634. #define WEBS_MAX_PORT_LEN 16 /* Max digits in port number */
  1635. #define WEBS_HASH_INIT 67 /* Hash size for form table */
  1636. #define WEBS_SESSION_HASH 31 /* Hash size for session stores */
  1637. #define WEBS_SESSION_PRUNE (60*1000) /* Prune sessions every minute */
  1638. /*
  1639. The license agreement stipulates that you must not change this definition.
  1640. */
  1641. #define WEBS_NAME "Server: GoAhead-http"
  1642. /*
  1643. Request flags
  1644. */
  1645. #define WEBS_ACCEPTED 0x1 /**< TLS connection accepted */
  1646. #define WEBS_CHUNKING 0x2 /**< Currently chunking output body data */
  1647. #define WEBS_CLOSED 0x4 /**< Connection closed, ready to free */
  1648. #define WEBS_COOKIE 0x8 /**< Cookie supplied in request */
  1649. #if DEPRECATED || 1
  1650. #define WEBS_FINALIZED 0x10 /**< Output is finalized */
  1651. #endif
  1652. #define WEBS_FORM 0x20 /**< Request is a form (url encoded data) */
  1653. #define WEBS_HEADERS_CREATED 0x40 /**< Headers have been created and buffered */
  1654. #define WEBS_HTTP11 0x80 /**< Request is using HTTP/1.1 */
  1655. #define WEBS_JSON 0x100 /**< Request has a JSON payload */
  1656. #define WEBS_KEEP_ALIVE 0x200 /**< HTTP/1.1 keep alive */
  1657. #define WEBS_REROUTE 0x400 /**< Restart route matching */
  1658. #define WEBS_RESPONSE_TRACED 0x800 /**< Started tracing the response */
  1659. #define WEBS_SECURE 0x1000 /**< Connection uses SSL */
  1660. #define WEBS_UPLOAD 0x2000 /**< Multipart-mime file upload */
  1661. #define WEBS_VARS_ADDED 0x4000 /**< Query and body form vars added */
  1662. #if ME_GOAHEAD_LEGACY
  1663. #define WEBS_LOCAL 0x8000 /**< Request from local system */
  1664. #endif
  1665. /*
  1666. Incoming chunk encoding states. Used for tx and rx chunking.
  1667. */
  1668. #define WEBS_CHUNK_UNCHUNKED 0 /**< Data is not transfer-chunk encoded */
  1669. #define WEBS_CHUNK_START 1 /**< Start of a new chunk */
  1670. #define WEBS_CHUNK_HEADER 2 /**< Preparing tx chunk header */
  1671. #define WEBS_CHUNK_DATA 3 /**< Start of chunk data */
  1672. /*
  1673. Webs state
  1674. */
  1675. #define WEBS_BEGIN 0 /**< Beginning state */
  1676. #define WEBS_CONTENT 1 /**< Ready for body data */
  1677. #define WEBS_READY 2 /**< Ready to route and start handler */
  1678. #define WEBS_RUNNING 3 /**< Processing request */
  1679. #define WEBS_COMPLETE 4 /**< Request complete */
  1680. /*
  1681. Session names
  1682. */
  1683. #define WEBS_SESSION "-goahead-session-"
  1684. #define WEBS_SESSION_USERNAME "_:USERNAME:_" /* Username variable */
  1685. /*
  1686. WebsDone flags
  1687. */
  1688. #define WEBS_CODE_MASK 0xFFFF /**< Mask valid status codes */
  1689. #define WEBS_CLOSE 0x20000 /**< Close connection */
  1690. #define WEBS_NOLOG 0x40000 /**< Don't write error to log */
  1691. /**
  1692. Callback for write I/O events
  1693. */
  1694. typedef void (*WebsWriteProc)(struct Webs *wp);
  1695. /**
  1696. GoAhead request structure. This is a per-socket connection structure.
  1697. @defgroup Webs Webs
  1698. */
  1699. typedef struct Webs {
  1700. WebsBuf rxbuf; /**< Raw receive buffer */
  1701. WebsBuf input; /**< Receive buffer after de-chunking */
  1702. WebsBuf output; /**< Transmit buffer after chunking */
  1703. WebsBuf chunkbuf; /**< Pre-chunking data buffer */
  1704. WebsBuf *txbuf;
  1705. WebsTime since; /**< Parsed if-modified-since time */
  1706. WebsTime timestamp; /**< Last transaction with browser */
  1707. WebsHash vars; /**< CGI standard variables */
  1708. int timeout; /**< Timeout handle */
  1709. char ipaddr[ME_MAX_IP]; /**< Connecting ipaddress */
  1710. char ifaddr[ME_MAX_IP]; /**< Local interface ipaddress */
  1711. int rxChunkState; /**< Rx chunk encoding state */
  1712. ssize rxChunkSize; /**< Rx chunk size */
  1713. char *rxEndp; /**< Pointer to end of raw data in input beyond endp */
  1714. ssize lastRead; /**< Number of bytes last read from the socket */
  1715. bool eof; /**< If at the end of the request content */
  1716. char txChunkPrefix[16]; /**< Transmit chunk prefix */
  1717. char *txChunkPrefixNext; /**< Current I/O pos in txChunkPrefix */
  1718. ssize txChunkPrefixLen; /**< Length of prefix */
  1719. ssize txChunkLen; /**< Length of the chunk */
  1720. int txChunkState; /**< Transmit chunk state */
  1721. char *authDetails; /**< Http header auth details */
  1722. char *authResponse; /**< Outgoing auth header */
  1723. char *authType; /**< Authorization type (Basic/DAA) */
  1724. char *contentType; /**< Body content type */
  1725. char *cookie; /**< Request cookie string */
  1726. char *decodedQuery; /**< Decoded request query */
  1727. char *digest; /**< Password digest */
  1728. char *ext; /**< Path extension */
  1729. char *filename; /**< Document path name */
  1730. char *host; /**< Requested host */
  1731. char *method; /**< HTTP request method */
  1732. char *password; /**< Authorization password */
  1733. char *path; /**< Path name without query. This is decoded. */
  1734. char *protoVersion; /**< Protocol version (HTTP/1.1)*/
  1735. char *protocol; /**< Protocol scheme (normally http|https) */
  1736. char *putname; /**< PUT temporary filename */
  1737. char *query; /**< Request query. This is decoded. */
  1738. char *realm; /**< Realm field supplied in auth header */
  1739. char *referrer; /**< The referring page */
  1740. char *url; /**< Full request url. This is not decoded. */
  1741. char *userAgent; /**< User agent (browser) */
  1742. char *username; /**< Authorization username */
  1743. int sid; /**< Socket id (handler) */
  1744. int listenSid; /**< Listen Socket id */
  1745. int port; /**< Request port number */
  1746. int state; /**< Current state */
  1747. int flags; /**< Current flags -- see above */
  1748. int code; /**< Response status code */
  1749. int routeCount; /**< Route count limiter */
  1750. ssize rxLen; /**< Rx content length */
  1751. ssize rxRemaining; /**< Remaining content to read from client */
  1752. ssize txLen; /**< Tx content length header value */
  1753. int wid; /**< Index into webs */
  1754. #if ME_GOAHEAD_CGI
  1755. char *cgiStdin; /**< Filename for CGI program input */
  1756. int cgifd; /**< File handle for CGI program input */
  1757. #endif
  1758. #if !ME_ROM
  1759. int putfd; /**< File handle to write PUT data */
  1760. #endif
  1761. int docfd; /**< File descriptor for document being served */
  1762. ssize written; /**< Bytes actually transferred */
  1763. ssize putLen; /**< Bytes read by a PUT request */
  1764. uint finalized: 1; /**< Request has been completed */
  1765. uint error: 1; /**< Request has an error */
  1766. uint connError: 1; /**< Request has a connection error */
  1767. WebsHash responseCookies; /**< Outgoing cookies */
  1768. struct WebsSession *session; /**< Session record */
  1769. struct WebsRoute *route; /**< Request route */
  1770. struct WebsUser *user; /**< User auth record */
  1771. WebsWriteProc writeData; /**< Handler write I/O event callback. Used by fileHandler */
  1772. int encoded; /**< True if the password is MD5(username:realm:password) */
  1773. #if ME_GOAHEAD_DIGEST
  1774. char *cnonce; /**< check nonce */
  1775. char *digestUri; /**< URI found in digest header */
  1776. char *nonce; /**< opaque-to-client string sent by server */
  1777. char *nc; /**< nonce count */
  1778. char *opaque; /**< opaque value passed from server */
  1779. char *qop; /**< quality operator */
  1780. #endif
  1781. #if ME_GOAHEAD_UPLOAD
  1782. int upfd; /**< Upload file handle */
  1783. WebsHash files; /**< Uploaded files */
  1784. char *boundary; /**< Mime boundary (static) */
  1785. ssize boundaryLen; /**< Boundary length */
  1786. int uploadState; /**< Current file upload state */
  1787. WebsUpload *currentFile; /**< Current file context */
  1788. char *clientFilename; /**< Current file filename */
  1789. char *uploadTmp; /**< Current temp filename for upload data */
  1790. char *uploadVar; /**< Current upload form variable name */
  1791. #endif
  1792. void *ssl; /**< SSL context */
  1793. } Webs;
  1794. #if ME_GOAHEAD_LEGACY
  1795. #define WEBS_LEGACY_HANDLER 0x1 /* Using legacy calling sequence */
  1796. #endif
  1797. /**
  1798. GoAhead handler service callback
  1799. @param wp Webs request object
  1800. @return True if the handler serviced the request
  1801. @ingroup Webs
  1802. @stability Stable
  1803. */
  1804. typedef bool (*WebsHandlerProc)(Webs *wp);
  1805. /**
  1806. GoAhead handler close to release memory prior to shutdown.
  1807. @description This callback is invoked when GoAhead is shutting down.
  1808. @ingroup Webs
  1809. @stability Stable
  1810. */
  1811. typedef void (*WebsHandlerClose)(void);
  1812. /**
  1813. GoAhead handler object
  1814. @ingroup Webs
  1815. @stability Stable
  1816. */
  1817. typedef struct WebsHandler {
  1818. char *name; /**< Handler name */
  1819. WebsHandlerProc match; /**< Handler match callback */
  1820. WebsHandlerProc service; /**< Handler service callback */
  1821. WebsHandlerClose close; /**< Handler close callback */
  1822. int flags; /**< Handler control flags */
  1823. } WebsHandler;
  1824. /**
  1825. Action callback
  1826. @param wp Webs request object
  1827. @ingroup Webs
  1828. @stability Stable
  1829. */
  1830. typedef void (*WebsAction)(Webs *wp);
  1831. #if ME_GOAHEAD_LEGACY
  1832. typedef void (*WebsProc)(Webs *wp, char *path, char *query);
  1833. #endif
  1834. /**
  1835. Error code list
  1836. @ingroup Webs
  1837. @stability Stable
  1838. */
  1839. typedef struct WebsError {
  1840. int code; /**< HTTP error code */
  1841. char *msg; /**< HTTP error message */
  1842. } WebsError;
  1843. /**
  1844. Mime type list
  1845. @ingroup Webs
  1846. @stability Stable
  1847. */
  1848. typedef struct WebsMime {
  1849. char *type; /**< Mime type */
  1850. char *ext; /**< File extension */
  1851. } WebsMime;
  1852. /**
  1853. File information structure.
  1854. @ingroup Webs
  1855. @stability Stable
  1856. */
  1857. typedef struct WebsFileInfo {
  1858. ulong size; /**< File length */
  1859. int isDir; /**< Set if directory */
  1860. WebsTime mtime; /**< Modified time */
  1861. } WebsFileInfo;
  1862. /**
  1863. Compiled Rom Page Index
  1864. @ingroup Webs
  1865. @stability Stable
  1866. */
  1867. typedef struct WebsRomIndex {
  1868. char *path; /**< Web page URL path */
  1869. uchar *page; /**< Web page data */
  1870. int size; /**< Size of web page in bytes */
  1871. Offset pos; /**< Current read position */
  1872. } WebsRomIndex;
  1873. #if ME_ROM
  1874. /**
  1875. List of documents to service when built with ROM support
  1876. @ingroup Webs
  1877. @stability Stable
  1878. */
  1879. PUBLIC_DATA WebsRomIndex websRomIndex[];
  1880. #endif
  1881. #define WEBS_DECODE_TOKEQ 1 /**< Decode base 64 blocks up to a NULL or equals */
  1882. /**
  1883. Accept a new connection
  1884. @param sid Socket ID handle for the newly accepted socket
  1885. @param ipaddr IP address originating the connection.
  1886. @param port Port number originating the connection.
  1887. @param listenSid Socket ID of the listening socket
  1888. @return Zero if successful, otherwise -1
  1889. @ingroup Webs
  1890. @stability Stable
  1891. */
  1892. PUBLIC int websAccept(int sid, cchar *ipaddr, int port, int listenSid);
  1893. /**
  1894. Open the action handler
  1895. @ingroup Webs
  1896. @stability Stable
  1897. */
  1898. PUBLIC void websActionOpen(void);
  1899. /**
  1900. Allocate a new Webs object
  1901. @param sid Socket ID handle for the newly accepted socket
  1902. @return The webs[] handle index for the allocated Webs object
  1903. @ingroup Webs
  1904. @stability Stable
  1905. */
  1906. PUBLIC int websAlloc(int sid);
  1907. /**
  1908. Cancel the request timeout.
  1909. @description Handlers may choose to manually manage the request timeout. This routine will disable the
  1910. centralized management of the timeout for this request.
  1911. @param wp Webs request object
  1912. @ingroup Webs
  1913. @stability Stable
  1914. */
  1915. PUBLIC void websCancelTimeout(Webs *wp);
  1916. #if ME_GOAHEAD_CGI
  1917. /**
  1918. Open the CGI handler
  1919. @return Zero if successful, otherwise -1
  1920. @ingroup Webs
  1921. @stability Stable
  1922. */
  1923. PUBLIC int websCgiOpen(void);
  1924. /**
  1925. CGI handler service callback
  1926. @param wp Webs object
  1927. @return Returns 1 if the request was handled.
  1928. @ingroup Webs
  1929. @stability Stable
  1930. */
  1931. PUBLIC int websCgiHandler(Webs *wp);
  1932. /**
  1933. Poll for output from CGI processes and output.
  1934. @return Time delay till next poll
  1935. @ingroup Webs
  1936. @stability Stable
  1937. */
  1938. PUBLIC int websCgiPoll(void);
  1939. /* Internal */
  1940. PUBLIC bool cgiHandler(Webs *wp);
  1941. #endif /* ME_GOAHEAD_CGI */
  1942. /**
  1943. Close the core GoAhead web server module
  1944. @description Invoked when GoAhead is shutting down.
  1945. @ingroup Webs
  1946. @stability Stable
  1947. */
  1948. PUBLIC void websClose(void);
  1949. /**
  1950. Close an open file
  1951. @param fd Open file handle returned by websOpenFile
  1952. @ingroup Webs
  1953. @stability Stable
  1954. */
  1955. PUBLIC void websCloseFile(int fd);
  1956. /**
  1957. Compare a request variable
  1958. @param wp Webs request object
  1959. @param var Variable name
  1960. @param value Value to compare with
  1961. @return True if the value matches. Otherwise return 0
  1962. @ingroup Webs
  1963. @stability Stable
  1964. */
  1965. PUBLIC int websCompareVar(Webs *wp, cchar *var, cchar *value);
  1966. /**
  1967. Consume input from the request input buffer.
  1968. @description This is called by handlers when consuming data from the request input buffer.
  1969. This call updates the input service pointers and compacts the input buffer if required.
  1970. @param wp Webs request object
  1971. @param nbytes Number of bytes the handler has consumed from the input buffer.
  1972. @ingroup Webs
  1973. @stability Stable
  1974. */
  1975. PUBLIC void websConsumeInput(Webs *wp, ssize nbytes);
  1976. /**
  1977. Decode the string using base-64 encoding
  1978. @description This modifies the original string
  1979. @param str String to decode
  1980. @return The original string. Caller must not free.
  1981. @ingroup Webs
  1982. @stability Stable
  1983. */
  1984. PUBLIC char *websDecode64(char *str);
  1985. /**
  1986. Decode a block using base-46 encoding
  1987. @param str String to decode. The string must be null terminated.
  1988. @param len Reference to an integer holding the length of the decoded string.
  1989. @param flags Reserved.
  1990. @return The original string.
  1991. @ingroup Webs
  1992. @stability Stable
  1993. */
  1994. PUBLIC char *websDecode64Block(char *str, ssize *len, int flags);
  1995. /**
  1996. Decode a URL expanding %NN encoding
  1997. @description Supports insitu decoding. i.e. Input and output buffers may be the same.
  1998. @param decoded Buffer to hold the decoded URL
  1999. @param input Input URL or buffer to decode
  2000. @param len Length of the decoded buffer.
  2001. @ingroup Webs
  2002. @stability Stable
  2003. */
  2004. PUBLIC void websDecodeUrl(char *decoded, char *input, ssize len);
  2005. /**
  2006. Define a request handler
  2007. @param name Name of the handler
  2008. @param match Handler callback match procedure. Invoked to match the request with the handler.
  2009. The handler should return true to accept the request.
  2010. @param service Handler callback service procedure. Invoked to service each request.
  2011. @param close Handler callback close procedure. Called when GoAhead is shutting down.
  2012. @param flags Set to WEBS_LEGACY_HANDLER to support the legacy handler API calling sequence.
  2013. @return Zero if successful, otherwise -1.
  2014. @ingroup Webs
  2015. @stability Stable
  2016. */
  2017. PUBLIC int websDefineHandler(cchar *name, WebsHandlerProc match, WebsHandlerProc service, WebsHandlerClose close, int flags);
  2018. /**
  2019. Complete a request.
  2020. @description A handler should call websDone() to complete the request.
  2021. @param wp Webs request object
  2022. @ingroup Webs
  2023. @stability Stable
  2024. */
  2025. PUBLIC void websDone(Webs *wp);
  2026. /**
  2027. Encode a string using base-64 encoding
  2028. @description The string is encoded insitu.
  2029. @param str String to encode
  2030. @return The original string.
  2031. @ingroup Webs
  2032. @stability Stable
  2033. */
  2034. PUBLIC char *websEncode64(char *str);
  2035. /**
  2036. Encode a block using base-64 encoding
  2037. @description The string is encoded insitu.
  2038. @param str String to encode.
  2039. @param len Length of string to encode
  2040. @return The original string.
  2041. @ingroup Webs
  2042. @stability Stable
  2043. */
  2044. PUBLIC char *websEncode64Block(char *str, ssize len);
  2045. /**
  2046. Escape unsafe characters in a string
  2047. @param str String to escape
  2048. @return An allocated block containing the escaped string. Caller must free.
  2049. @ingroup Webs
  2050. @stability Stable
  2051. */
  2052. PUBLIC char *websEscapeHtml(cchar *str);
  2053. /**
  2054. Complete a request with an error response
  2055. @param wp Webs request object
  2056. @param code HTTP status code
  2057. @param fmt Message printf style format
  2058. @param ... Format args
  2059. @ingroup Webs
  2060. @stability Stable
  2061. */
  2062. PUBLIC void websError(Webs *wp, int code, cchar *fmt, ...);
  2063. /**
  2064. Get a message for a HTTP status code
  2065. @param code HTTP status code
  2066. @return Http status message. Caller must not free.
  2067. @ingroup Webs
  2068. @stability Stable
  2069. */
  2070. PUBLIC cchar *websErrorMsg(int code);
  2071. /**
  2072. Open and initialize the file handler
  2073. @ingroup Webs
  2074. @stability Stable
  2075. */
  2076. PUBLIC void websFileOpen(void);
  2077. /**
  2078. Flush buffered transmit data and compact the transmit buffer to make room for more data
  2079. @description This call initiates sending buffered data. If blocking mode is selected via the block parameter,
  2080. this call will wait until all the data has been sent to the O/S for transmission to the client.
  2081. If block is false, the flush will be initiated and the call will return immediately without blocking.
  2082. @param wp Webs request object
  2083. @param block Set to true to wait for all data to be written to the socket. Set to false to
  2084. write whatever the socket can absorb without blocking.
  2085. @return -1 for I/O errors. Return zero if there is more data remaining in the buffer. Return 1 if the
  2086. contents of the transmit buffer are fully written and the buffer is now empty.
  2087. @ingroup Webs
  2088. @stability Stable
  2089. */
  2090. PUBLIC int websFlush(Webs *wp, bool block);
  2091. /**
  2092. Free the webs request object.
  2093. @description Callers should call websDone to complete requests prior to invoking websFree.
  2094. @param wp Webs request object
  2095. @ingroup Webs
  2096. @stability Stable
  2097. */
  2098. PUBLIC void websFree(Webs *wp);
  2099. /**
  2100. Get the background execution flag
  2101. @description If GoAhead is invoked with --background, it will run as a daemon in the background.
  2102. @return True if GoAhead is running in the background.
  2103. @ingroup Webs
  2104. @stability Stable
  2105. */
  2106. PUBLIC int websGetBackground(void);
  2107. #if ME_GOAHEAD_CGI
  2108. /**
  2109. Get a unique temporary filename for CGI communications
  2110. @return Allocated filename string. Caller must free.
  2111. @ingroup Webs
  2112. @stability Stable
  2113. */
  2114. PUBLIC char *websGetCgiCommName(void);
  2115. #endif /* ME_GOAHEAD_CGI */
  2116. /**
  2117. Get the request cookie if supplied
  2118. @param wp Webs request object
  2119. @return Cookie string if defined, otherwise null. Caller must not free.
  2120. @ingroup Webs
  2121. @stability Stable
  2122. */
  2123. PUBLIC cchar *websGetCookie(Webs *wp);
  2124. /**
  2125. Get a date as a string
  2126. @description If sbuf is supplied, it is used to calculate the date. Otherwise, the current time is used.
  2127. @param sbuf File info object
  2128. @return An allocated date string. Caller should free.
  2129. @ingroup Webs
  2130. @stability Stable
  2131. */
  2132. PUBLIC char *websGetDateString(WebsFileInfo *sbuf);
  2133. /**
  2134. Get the debug flag
  2135. @description If GoAhead is invoked with --debugger, the debug flag will be set to true
  2136. @return True if GoAhead is running in debug mode.
  2137. @ingroup Webs
  2138. @stability Stable
  2139. */
  2140. PUBLIC int websGetDebug(void);
  2141. /**
  2142. Get the base file directory for a request
  2143. @description Returns the request route directory if defined, otherwise returns the documents directory.
  2144. @param wp Webs request object
  2145. @return Path name string. Caller should not free.
  2146. @ingroup Webs
  2147. @stability Stable
  2148. */
  2149. PUBLIC cchar *websGetDir(Webs *wp);
  2150. /**
  2151. Get the GoAhead base documents directory
  2152. @description The documents directory is defined at build time and may be overridden by the GoAhead command line.
  2153. @return Path string for the documents directory.
  2154. @ingroup Webs
  2155. @stability Stable
  2156. */
  2157. PUBLIC char *websGetDocuments(void);
  2158. /**
  2159. Get the request EOF status
  2160. @description The request EOF status is set to true when all the request body (POST|PUT) data has been received.
  2161. @param wp Webs request object
  2162. @return True if all the request body data has been received.
  2163. @ingroup Webs
  2164. @stability Stable
  2165. */
  2166. PUBLIC int websGetEof(Webs *wp);
  2167. /**
  2168. Get the request URI extension
  2169. @param wp Webs request object
  2170. @return The URI filename extension component. Caller should not free.
  2171. @ingroup Webs
  2172. @stability Stable
  2173. */
  2174. PUBLIC cchar *websGetExt(Webs *wp);
  2175. /**
  2176. Get the request filename
  2177. @description The URI is mapped to a filename by decoding and prepending with the request directory.
  2178. @param wp Webs request object
  2179. @return Filename string. Caller should not free.
  2180. @ingroup Webs
  2181. @stability Stable
  2182. */
  2183. PUBLIC cchar *websGetFilename(Webs *wp);
  2184. /**
  2185. Get the request host
  2186. @description The request host is set to the Host HTTP header value if it is present. Otherwise it is set to
  2187. the request URI hostname.
  2188. @param wp Webs request object
  2189. @return Host string. Caller should not free.
  2190. @ingroup Webs
  2191. @stability Stable
  2192. */
  2193. PUBLIC cchar *websGetHost(Webs *wp);
  2194. /**
  2195. Get the request interface address
  2196. @param wp Webs request object
  2197. @return Network interface string. Caller should not free.
  2198. @ingroup Webs
  2199. @stability Stable
  2200. */
  2201. PUBLIC cchar *websGetIfaddr(Webs *wp);
  2202. /**
  2203. Get the default index document name
  2204. @description The default index is "index.html" and can be updated via websSetIndex.
  2205. @return Index name string. Caller should not free.
  2206. @ingroup Webs
  2207. @stability Stable
  2208. */
  2209. PUBLIC cchar *websGetIndex(void);
  2210. /**
  2211. Get the request method
  2212. @param wp Webs request object
  2213. @return HTTP method string. Caller should not free.
  2214. @ingroup Webs
  2215. @stability Stable
  2216. */
  2217. PUBLIC cchar *websGetMethod(Webs *wp);
  2218. /**
  2219. Get the request password
  2220. @description The request password may be encoded depending on the authentication scheme.
  2221. See wp->encoded to test if it is encoded.
  2222. @param wp Webs request object
  2223. @return Password string. Caller should not free.
  2224. @ingroup Webs
  2225. @stability Stable
  2226. */
  2227. PUBLIC cchar *websGetPassword(Webs *wp);
  2228. /**
  2229. Get the request path
  2230. @description The URI path component excludes the http protocol, hostname, port, reference and query components.
  2231. It always beings with "/".
  2232. @param wp Webs request object
  2233. @return Request path string. Caller should not free.
  2234. @ingroup Webs
  2235. @stability Stable
  2236. */
  2237. PUBLIC cchar *websGetPath(Webs *wp);
  2238. /**
  2239. Get the request TCP/IP port
  2240. @param wp Webs request object
  2241. @return TCP/IP Port integer
  2242. @ingroup Webs
  2243. @stability Stable
  2244. */
  2245. PUBLIC int websGetPort(Webs *wp);
  2246. /**
  2247. Get the request HTTP protocol
  2248. @description This will be set to either "http" or "https"
  2249. @param wp Webs request object
  2250. @return Protocol string. Caller should not free.
  2251. @ingroup Webs
  2252. @stability Stable
  2253. */
  2254. PUBLIC cchar *websGetProtocol(Webs *wp);
  2255. /**
  2256. Get the request query component
  2257. @param wp Webs request object
  2258. @return Request query string. Caller should not free.
  2259. @ingroup Webs
  2260. @stability Stable
  2261. */
  2262. PUBLIC cchar *websGetQuery(Webs *wp);
  2263. /**
  2264. Get the server host name
  2265. @return Host name string. Caller should not free.
  2266. @ingroup Webs
  2267. @stability Stable
  2268. */
  2269. PUBLIC cchar *websGetServer(void);
  2270. /**
  2271. Get the server host name with port number.
  2272. @return Host name string with port number. Caller should not free.
  2273. @ingroup Webs
  2274. @stability Stable
  2275. */
  2276. PUBLIC cchar *websGetServerUrl(void);
  2277. /**
  2278. Get the server IP address
  2279. @return Server IP address string. Caller should not free.
  2280. @ingroup Webs
  2281. @stability Stable
  2282. */
  2283. PUBLIC cchar *websGetServerAddress(void);
  2284. /**
  2285. Get the server IP address with port number
  2286. @return Server IP:PORT address string. Caller should not free.
  2287. @ingroup Webs
  2288. @stability Stable
  2289. */
  2290. PUBLIC cchar *websGetServerAddressUrl(void);
  2291. /**
  2292. Get the request URI
  2293. @description This returns the request URI. This may be modified if the request is rewritten via websRewrite
  2294. @param wp Webs request object
  2295. @return URI string. Caller should not free.
  2296. @ingroup Webs
  2297. @stability Stable
  2298. */
  2299. PUBLIC cchar *websGetUrl(Webs *wp);
  2300. /**
  2301. Get the client User-Agent HTTP header
  2302. @param wp Webs request object
  2303. @return User-Agent string. Caller should not free.
  2304. @ingroup Webs
  2305. @stability Stable
  2306. */
  2307. PUBLIC cchar *websGetUserAgent(Webs *wp);
  2308. /**
  2309. Get the request username
  2310. @description If the request is authenticated, this call returns the username supplied during authentication.
  2311. @param wp Webs request object
  2312. @return Username string if defined, otherwise null. Caller should not free.
  2313. @ingroup Webs
  2314. @stability Stable
  2315. */
  2316. PUBLIC cchar *websGetUsername(Webs *wp);
  2317. /**
  2318. Get a request variable
  2319. @description Request variables are defined for HTTP headers of the form HTTP_*.
  2320. Some request handlers also define their own variables. For example: CGI environment variables.
  2321. @param wp Webs request object
  2322. @param name Variable name
  2323. @param defaultValue Default value to return if the variable is not defined
  2324. @return Variable value string. Caller should not free.
  2325. @ingroup Webs
  2326. @stability Stable
  2327. */
  2328. PUBLIC cchar *websGetVar(Webs *wp, cchar *name, cchar *defaultValue);
  2329. /**
  2330. Listen on a TCP/IP address endpoint
  2331. @description The URI is mapped to a filename by decoding and prepending with the request directory.
  2332. For IPv6 addresses, use the format: [aaaa:bbbb:cccc:dddd:eeee:ffff:gggg:hhhh:iiii]:port.
  2333. @param endpoint IPv4 or IPv6 address on which to listen.
  2334. @return Positive integer holding a Socket ID handle if successful, otherwise -1.
  2335. @ingroup Webs
  2336. @stability Stable
  2337. */
  2338. PUBLIC int websListen(cchar *endpoint);
  2339. /**
  2340. Get an MD5 digest of a string
  2341. @param str String to analyze.
  2342. @return Allocated MD5 checksum. Caller should free.
  2343. @ingroup Webs
  2344. @stability Stable
  2345. */
  2346. PUBLIC char *websMD5(cchar *str);
  2347. /**
  2348. Get an MD5 digest of a block and optionally prepend a prefix.
  2349. @param buf Block to analyze
  2350. @param length Length of block
  2351. @param prefix Optional prefix to prepend to the MD5 sum.
  2352. @return Allocated MD5 checksum. Caller should free.
  2353. @ingroup Webs
  2354. @stability Stable
  2355. */
  2356. PUBLIC char *websMD5Block(cchar *buf, ssize length, cchar *prefix);
  2357. /**
  2358. Normalize a URI path
  2359. @description This removes "./", "../" and redundant separators.
  2360. @param path URI path to normalize
  2361. @return An allocated normalized URI path. Caller must free.
  2362. @ingroup Webs
  2363. @stability Stable
  2364. */
  2365. PUBLIC char *websNormalizeUriPath(cchar *path);
  2366. /**
  2367. Take not of the request activity and mark the time.
  2368. @description This is used to defer the request timeout whenever there is request I/O activity.
  2369. @param wp Webs request object
  2370. @ingroup Webs
  2371. @stability Stable
  2372. */
  2373. PUBLIC void websNoteRequestActivity(Webs *wp);
  2374. /**
  2375. Close the runtime code.
  2376. @description Called from websClose
  2377. @ingroup Webs
  2378. @internal
  2379. */
  2380. PUBLIC void websRuntimeClose(void);
  2381. /**
  2382. Open the runtime code.
  2383. @description Called from websOpen
  2384. @return Zero if successful
  2385. @ingroup Webs
  2386. @internal
  2387. */
  2388. PUBLIC int websRuntimeOpen(void);
  2389. /**
  2390. Open the web server
  2391. @description This initializes the web server and defines the documents directory.
  2392. @param documents Optional web documents directory. If set to null, the build time ME_GOAHEAD_DOCUMENTS value
  2393. is used for the documents directory.
  2394. @param routes Optional filename for a route configuration file to load. Additional route or
  2395. authentication configuration files can be loaded via websLoad.
  2396. @param routes Webs request object
  2397. @return Zero if successful, otherwise -1.
  2398. @ingroup Webs
  2399. @stability Stable
  2400. */
  2401. PUBLIC int websOpen(cchar *documents, cchar *routes);
  2402. /**
  2403. Close the O/S dependent code.
  2404. @description Called from websClose
  2405. @ingroup Webs
  2406. @internal
  2407. */
  2408. PUBLIC void websOsClose(void);
  2409. /**
  2410. Open the O/S dependent code.
  2411. @description Called from websOpen
  2412. @return Zero if successful, otherwise -1.
  2413. @ingroup Webs
  2414. @internal
  2415. */
  2416. PUBLIC int websOsOpen(void);
  2417. /**
  2418. Open the web page document for the current request
  2419. @param path Filename path to open
  2420. @param flags File open flags
  2421. @param mode Permissions mask
  2422. @return Positive file handle if successful, otherwise -1.
  2423. @ingroup Webs
  2424. @stability Stable
  2425. */
  2426. PUBLIC int websOpenFile(cchar *path, int flags, int mode);
  2427. /**
  2428. Open the options handler
  2429. @return Zero if successful, otherwise -1.
  2430. @ingroup Webs
  2431. @stability Stable
  2432. */
  2433. PUBLIC int websOptionsOpen(void);
  2434. /**
  2435. Close the document page
  2436. @param wp Webs request object
  2437. @ingroup Webs
  2438. @stability Stable
  2439. */
  2440. PUBLIC void websPageClose(Webs *wp);
  2441. /**
  2442. Test if the document page for the request corresponds to a directory
  2443. @param wp Webs request object
  2444. @return True if the filename is a directory
  2445. @ingroup Webs
  2446. @stability Stable
  2447. */
  2448. PUBLIC int websPageIsDirectory(Webs *wp);
  2449. /**
  2450. Open a web page document for a request
  2451. @param wp Webs request object
  2452. @param mode File open mode. Select from O_RDONLY and O_BINARY. Rom files systems ignore this argument.
  2453. @param perms Ignored
  2454. @return File handle if successful, otherwise -1.
  2455. @ingroup Webs
  2456. @stability Stable
  2457. */
  2458. PUBLIC int websPageOpen(Webs *wp, int mode, int perms);
  2459. /**
  2460. Read data from the request page document
  2461. @param wp Webs request object
  2462. @param buf Buffer for the read data
  2463. @param size Size of buf
  2464. @return Count of bytes read if successful, otherwise -1.
  2465. @ingroup Webs
  2466. @stability Stable
  2467. */
  2468. PUBLIC ssize websPageReadData(Webs *wp, char *buf, ssize size);
  2469. /**
  2470. Seek to a position in the request page document
  2471. @param wp Webs request object
  2472. @param offset Offset of location in the file to seek to. This is relative to the specified origin.
  2473. @param origin Set to SEEK_CUR, SEEK_SET or SEEK_END to position relative to the current position,
  2474. beginning or end of the document.
  2475. @ingroup Webs
  2476. @stability Stable
  2477. */
  2478. PUBLIC void websPageSeek(Webs *wp, Offset offset, int origin);
  2479. /**
  2480. Get file status for the current request document
  2481. @param wp Webs request object
  2482. @param sbuf File information structure to modify with file status
  2483. @return Zero if successful, otherwise -1.
  2484. @ingroup Webs
  2485. @stability Stable
  2486. */
  2487. PUBLIC int websPageStat(Webs *wp, WebsFileInfo *sbuf);
  2488. #if !ME_ROM
  2489. /**
  2490. Process request PUT body data
  2491. @description This routine is called by the core HTTP engine to process request PUT data.
  2492. @param wp Webs request object
  2493. @return True if processing the request can proceed.
  2494. @ingroup Webs
  2495. @stability Stable
  2496. */
  2497. PUBLIC bool websProcessPutData(Webs *wp);
  2498. #endif
  2499. /**
  2500. Pump the state machine
  2501. @description This routine will advance the connection state machine in response to events.
  2502. @param wp Webs request object
  2503. @ingroup Webs
  2504. @stability Stable
  2505. */
  2506. PUBLIC void websPump(Webs *wp);
  2507. /**
  2508. Define an action callback for use with the action handler.
  2509. @description The action handler binds a C function to a URI under "/action".
  2510. @param name URI path suffix. This suffix is added to "/action" to form the bound URI path.
  2511. @param fun Callback function. The signature is void (*WebsAction)(Webs *wp);
  2512. @return Zero if successful, otherwise -1.
  2513. @ingroup Webs
  2514. @stability Stable
  2515. */
  2516. PUBLIC int websDefineAction(cchar *name, void *fun);
  2517. /**
  2518. Read data from an open file
  2519. @param fd Open file handle returned by websOpenFile
  2520. @param buf Buffer for the read data
  2521. @param size Size of buf
  2522. @return Count of bytes read if successful, otherwise -1.
  2523. @ingroup Webs
  2524. @stability Stable
  2525. */
  2526. PUBLIC ssize websReadFile(int fd, char *buf, ssize size);
  2527. /**
  2528. Read all the data from a file
  2529. @param path File path to read from
  2530. @return An allocated buffer containing the file data with an appended null. Caller must free.
  2531. @ingroup Webs
  2532. @stability Stable
  2533. */
  2534. PUBLIC char *websReadWholeFile(cchar *path);
  2535. /**
  2536. Redirect the client to a new URL.
  2537. @description This creates a response to the client with a Location header directing the client to a new location.
  2538. The response uses a 302 HTTP status code.
  2539. @param wp Webs request object
  2540. @param url URL to direct the client to.
  2541. @ingroup Webs
  2542. @stability Stable
  2543. */
  2544. PUBLIC void websRedirect(Webs *wp, cchar *url);
  2545. /**
  2546. Redirect the client to a new URI
  2547. @description The routing configuration file can define redirection routes for various HTTP status codes.
  2548. This routine will utilize the appropriate route redirection based on the request route and specified status code.
  2549. @param wp Webs request object
  2550. @param status HTTP status code to use in selecting the route redirection.
  2551. @return Zero if successful, otherwise -1.
  2552. @ingroup Webs
  2553. @stability Stable
  2554. */
  2555. PUBLIC int websRedirectByStatus(Webs *wp, int status);
  2556. /**
  2557. Create and send a request response
  2558. @description This creates a response for the current request using the specified HTTP status code and
  2559. the supplied message.
  2560. @param wp Webs request object
  2561. @param status HTTP status code.
  2562. @param msg Response message body
  2563. @return Zero if successful, otherwise -1.
  2564. @ingroup Webs
  2565. @stability Stable
  2566. */
  2567. PUBLIC void websResponse(Webs *wp, int status, cchar *msg);
  2568. /**
  2569. Rewrite a request
  2570. @description Handlers may choose to not process a request but rather rewrite requests and then reroute.
  2571. @param wp Webs request object
  2572. @param url New request URL.
  2573. @return Zero if successful, otherwise -1.
  2574. @ingroup Webs
  2575. @stability Stable
  2576. */
  2577. PUBLIC int websRewriteRequest(Webs *wp, cchar *url);
  2578. /**
  2579. Open the file system module
  2580. @return Zero if successful, otherwise -1.
  2581. @ingroup Webs
  2582. @stability Stable
  2583. */
  2584. PUBLIC int websFsOpen(void);
  2585. /**
  2586. Close the file system module
  2587. @ingroup Webs
  2588. @stability Stable
  2589. */
  2590. PUBLIC void websFsClose(void);
  2591. /**
  2592. Seek to a position in the current request page document
  2593. @param fd Open file handle returned by websOpenFile
  2594. @param offset Location in the file to seek to.
  2595. @param origin Set to SEEK_CUR, SEEK_SET or SEEK_END to position relative to the current position,
  2596. beginning or end of the document.
  2597. @ingroup Webs
  2598. @stability Stable
  2599. */
  2600. PUBLIC Offset websSeekFile(int fd, Offset offset, int origin);
  2601. /**
  2602. Get file status for a file
  2603. @param path Filename path
  2604. @param sbuf File information structure to modify with file status
  2605. @return Zero if successful, otherwise -1.
  2606. @ingroup Webs
  2607. @stability Stable
  2608. */
  2609. PUBLIC int websStatFile(cchar *path, WebsFileInfo *sbuf);
  2610. /**
  2611. One line embedding API.
  2612. @description This call will also open auth.txt and route.txt for authentication and routing configuration.
  2613. @param endpoint IP:PORT address on which to listen
  2614. @param documents Directory containing web documents to serve
  2615. @ingroup Webs
  2616. @stability Stable
  2617. */
  2618. PUBLIC int websServer(cchar *endpoint, cchar *documents);
  2619. /**
  2620. Service I/O events until finished
  2621. @description This will wait for socket events and service those until *finished is set to true
  2622. @param finished Integer location to test. If set to true, then exit. Note: setting finished will not
  2623. automatically wake up the service routine.
  2624. @ingroup Webs
  2625. @stability Stable
  2626. */
  2627. PUBLIC void websServiceEvents(int *finished);
  2628. /**
  2629. Set the background processing flag
  2630. @param on Value to set the background flag to.
  2631. @ingroup Webs
  2632. @internal
  2633. */
  2634. PUBLIC void websSetBackground(int on);
  2635. /**
  2636. Define a background write I/O event callback
  2637. @param wp Webs request object
  2638. @param proc Write callback
  2639. */
  2640. PUBLIC void websSetBackgroundWriter(Webs *wp, WebsWriteProc proc);
  2641. /*
  2642. Flags for websSetCookie
  2643. */
  2644. #define WEBS_COOKIE_SECURE 0x1 /**< Flag for websSetCookie for secure cookies (https only) */
  2645. #define WEBS_COOKIE_HTTP 0x2 /**< Flag for websSetCookie for http cookies (http only) */
  2646. #define WEBS_COOKIE_SAME_LAX 0x4 /**< Flag for websSetCookie for SameSite=Lax */
  2647. #define WEBS_COOKIE_SAME_STRICT 0x8 /**< Flag for websSetCookie for SameSite=Strict */
  2648. /**
  2649. Define a cookie to include in the response
  2650. @param wp Webs request object
  2651. @param name Cookie name
  2652. @param value Cookie value
  2653. @param path URI path prefix applicable for this cookie
  2654. @param domain Domain applicable for this cookie
  2655. @param lifespan Cookie lifespan in seconds
  2656. @param flags Set to WEBS_COOKIE_SECURE for https only. Set to WEBS_COOKIE_HTTP for http only.
  2657. Otherwise the cookie applies to both http and https requests. Or in WEBS_COOKIE_SAME_LAX for SameSite=Lax
  2658. and WEBS_COOKIE_SAME_STRICT for SameSite=Strict.
  2659. @return Zero if successful, otherwise -1.
  2660. @ingroup Webs
  2661. @stability Stable
  2662. */
  2663. PUBLIC void websSetCookie(Webs *wp, cchar *name, cchar *value, cchar *path, cchar *domain, int lifespan, int flags);
  2664. /**
  2665. Set the debug processing flag
  2666. @param on Value to set the debug flag to.
  2667. @ingroup Webs
  2668. @internal
  2669. */
  2670. PUBLIC void websSetDebug(int on);
  2671. /**
  2672. Set the web documents directory
  2673. @description The web documents directory is used when resolving request URIs into filenames.
  2674. @param dir Directory path to use
  2675. @ingroup Webs
  2676. @stability Stable
  2677. */
  2678. PUBLIC void websSetDocuments(cchar *dir);
  2679. /**
  2680. Create the CGI environment variables for the current request.
  2681. @param wp Webs request object
  2682. @ingroup Webs
  2683. @stability Stable
  2684. */
  2685. PUBLIC void websSetEnv(Webs *wp);
  2686. /**
  2687. Create request variables for query and POST body data
  2688. @description This creates request variables if the request is a POST form (has a Content-Type of
  2689. application/x-www-form-urlencoded). The POST body data is consumed from the input buffer.
  2690. @param wp Webs request object
  2691. @ingroup Webs
  2692. @stability Stable
  2693. */
  2694. PUBLIC void websSetFormVars(Webs *wp);
  2695. /**
  2696. Define the host name for the server
  2697. @param host String host name
  2698. @ingroup Webs
  2699. @stability Stable
  2700. */
  2701. PUBLIC void websSetHost(cchar *host);
  2702. /**
  2703. Define the host IP address
  2704. @param ipaddr Host IP address
  2705. @ingroup Webs
  2706. @stability Stable
  2707. */
  2708. PUBLIC void websSetIpAddr(cchar *ipaddr);
  2709. /**
  2710. Create and send a request response
  2711. @description This creates a response for the current request using the specified HTTP status code and
  2712. the supplied message.
  2713. @param filename Web document name to use as the index. This should not contain any directory components.
  2714. @ingroup Webs
  2715. @stability Stable
  2716. */
  2717. PUBLIC void websSetIndex(cchar *filename);
  2718. /**
  2719. Create request variables for query string data
  2720. @param wp Webs request object
  2721. @ingroup Webs
  2722. @stability Stable
  2723. */
  2724. PUBLIC void websSetQueryVars(Webs *wp);
  2725. /**
  2726. Set the response HTTP status code
  2727. @param wp Webs request object
  2728. @param status HTTP status code
  2729. @ingroup Webs
  2730. @stability Stable
  2731. */
  2732. PUBLIC void websSetStatus(Webs *wp, int status);
  2733. /**
  2734. Set the response body content length
  2735. @param wp Webs request object
  2736. @param length Length value to use
  2737. @ingroup Webs
  2738. @stability Stable
  2739. */
  2740. PUBLIC void websSetTxLength(Webs *wp, ssize length);
  2741. /**
  2742. Set a request variable to a formatted string value
  2743. @description Request variables are defined for HTTP headers of the form HTTP_*.
  2744. Some request handlers also define their own variables. For example: CGI environment variables.
  2745. @param wp Webs request object
  2746. @param name Variable name to set
  2747. @param fmt Value format string
  2748. @param ... Args to format
  2749. @return the allocated WebsKey
  2750. @ingroup Webs
  2751. @stability Evolving
  2752. */
  2753. PUBLIC WebsKey *websSetVarFmt(Webs *wp, cchar *name, cchar *fmt, ...);
  2754. /**
  2755. Set a request variable to a string value
  2756. @description Request variables are defined for HTTP headers of the form HTTP_*.
  2757. Some request handlers also define their own variables. For example: CGI environment variables.
  2758. @param wp Webs request object
  2759. @param name Variable name to set
  2760. @param value Value to set
  2761. @return the allocated WebsKey
  2762. @ingroup Webs
  2763. @stability Evolving
  2764. */
  2765. PUBLIC WebsKey *websSetVar(Webs *wp, cchar *name, cchar *value);
  2766. /**
  2767. Test if a request variable is defined
  2768. @param wp Webs request object
  2769. @param name Variable name
  2770. @return True if the variable is defined
  2771. @ingroup Webs
  2772. @stability Stable
  2773. */
  2774. PUBLIC bool websTestVar(Webs *wp, cchar *name);
  2775. /**
  2776. Create a temporary filename
  2777. This does not guarantee the filename is unique or that it is not already in use by another application.
  2778. @param dir Directory to locate the temp file. Defaults to the O/S default temporary directory (usually /tmp)
  2779. @param prefix Filename prefix
  2780. @return An allocated filename string
  2781. @ingroup Webs
  2782. @stability Stable
  2783. */
  2784. PUBLIC char *websTempFile(cchar *dir, cchar *prefix);
  2785. /**
  2786. Open the date/time parsing module
  2787. @return Zero if successful, otherwise -1.
  2788. @ingroup Webs
  2789. @stability Evolving
  2790. */
  2791. PUBLIC int websTimeOpen(void);
  2792. /**
  2793. Close the date/time parsing module
  2794. @ingroup Webs
  2795. @stability Evolving
  2796. */
  2797. PUBLIC void websTimeClose(void);
  2798. /**
  2799. Parse a date/time string
  2800. @description Try to intelligently parse a date.
  2801. This is a tolerant parser. It is not validating and will do its best to parse any possible date string.
  2802. Supports the following date/time formats:
  2803. \n\n
  2804. ISO dates: 2009-05-21t16:06:05.000z
  2805. \n\n
  2806. Date: 07/28/2014, 07/28/08, Jan/28/2014, Jaunuary-28-2014, 28-jan-2014.
  2807. \n\n
  2808. Support date order: dd/mm/yy, mm/dd/yy and yyyy/mm/dd
  2809. \n\n
  2810. Support separators "/", ".", "-"
  2811. \n\n
  2812. Timezones: GMT|UTC[+-]NN[:]NN
  2813. \n\n
  2814. Time: 10:52[:23]
  2815. \n\n
  2816. @param time Reference to a
  2817. @param date Date/time string to parse
  2818. @param defaults Optionally supply missing components for the date/time. Set to NULL if not used.
  2819. @return Zero if successful, otherwise -1
  2820. @ingroup Webs
  2821. @stability Evolving
  2822. */
  2823. PUBLIC int websParseDateTime(WebsTime *time, cchar *date, struct tm *defaults);
  2824. /**
  2825. Parse a URL into its components
  2826. @param url URL to parse
  2827. @param buf Buffer to hold storage for various parsed components. Caller must free. NOTE: the parsed components may
  2828. point to locations in this buffer.
  2829. @param protocol Parsed URL protocol component
  2830. @param host Parsed hostname
  2831. @param port Parsed URL port
  2832. @param path Parsed URL path component
  2833. @param ext Parsed URL extension
  2834. @param reference Parsed URL reference portion (\#reference)
  2835. @param query Parsed URL query component
  2836. @return Zero if successful, otherwise -1.
  2837. @ingroup Webs
  2838. @stability Evolving
  2839. */
  2840. PUBLIC int websUrlParse(cchar *url, char **buf, char **protocol, char **host, char **port, char **path, char **ext,
  2841. char **reference, char **query);
  2842. /**
  2843. Test if a webs object is valid
  2844. @description After calling websDone, the websFree routine will have been called and the memory for the webs object
  2845. will be released. Call websValid to test a Webs object for validity.
  2846. @param wp Webs request object
  2847. @return True if the webs object is still valid and the request has not been completed.
  2848. @ingroup Webs
  2849. @stability Stable
  2850. */
  2851. PUBLIC bool websValid(Webs *wp);
  2852. /**
  2853. Validate a URI path as expected in a HTTP request line
  2854. @description This expects a URI beginning with "/" and containing only valid URI characters.
  2855. The URI is decoded, and normalized removing "../" and "." segments.
  2856. The URI must begin with a "/" both before and after decoding and normalization.
  2857. @param uri URI to validate.
  2858. @return A validated, normalized URI path. Caller must free.
  2859. @ingroup Webs
  2860. @stability Stable
  2861. */
  2862. PUBLIC char *websValidateUriPath(cchar *uri);
  2863. /**
  2864. Test if a URI is using only valid characters
  2865. Note this does not test if the URI is fully legal. Some components of the URI have restricted character sets
  2866. that this routine does not test. This tests if the URI has only characters valid to use in a URI before decoding.
  2867. i.e. It will permit %NN encodings. The set of valid characters is:
  2868. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%"
  2869. @param uri Uri to test
  2870. @return True if the URI string is comprised of legal URI characters.
  2871. @ingroup Webs
  2872. @stability Evolving
  2873. */
  2874. PUBLIC bool websValidUriChars(cchar *uri);
  2875. /**
  2876. Write a set of standard response headers
  2877. @param wp Webs request object
  2878. @param contentLength Value for the Content-Length header which describes the length of the response body
  2879. @param redirect Value for the Location header which redirects the client to a new URL.
  2880. @ingroup Webs
  2881. @see websSetStatus
  2882. @stability Stable
  2883. */
  2884. PUBLIC void websWriteHeaders(Webs *wp, ssize contentLength, cchar *redirect);
  2885. /**
  2886. Signify the end of the response headers
  2887. @description This call concludes the response headers and writes a blank line to the response.
  2888. @param wp Webs request object
  2889. @ingroup Webs
  2890. @stability Stable
  2891. */
  2892. PUBLIC void websWriteEndHeaders(Webs *wp);
  2893. /**
  2894. Write a response header
  2895. @description This routine writes a response header. It should be invoked after calling websWriteHeaders
  2896. to write the standard headers and before websWriteEndHeaders.
  2897. This routine differs from websWrite in that it traces header values to the log.
  2898. @param wp Webs request object
  2899. @param key Header key value
  2900. @param fmt Header value format string.
  2901. @param ... Arguments to the format string.
  2902. @return Zero if successful, otherwise -1.
  2903. @ingroup Webs
  2904. @stability Stable
  2905. */
  2906. PUBLIC int websWriteHeader(Webs *wp, cchar *key, cchar *fmt, ...);
  2907. /**
  2908. Write data to the response
  2909. @description The data is buffered and will be sent to the client when the buffer is full or websFlush is
  2910. called.
  2911. @param wp Webs request object
  2912. @param fmt Printf style format string.
  2913. @param ... Arguments to the format string.
  2914. @return Count of bytes written
  2915. @ingroup Webs
  2916. @stability Stable
  2917. */
  2918. PUBLIC ssize websWrite(Webs *wp, cchar *fmt, ...);
  2919. /**
  2920. Write data to the open file
  2921. @param fd Open file handle returned by websOpenFile
  2922. @param buf Buffer for the read data
  2923. @param size Size of buf
  2924. @return Count of bytes read if successful, otherwise -1.
  2925. @ingroup Webs
  2926. @stability Stable
  2927. */
  2928. PUBLIC ssize websWriteFile(int fd, cchar *buf, ssize size);
  2929. /**
  2930. Write a block of data to the response
  2931. @description The data is buffered and will be sent to the client when the buffer is full or websFlush is
  2932. called. This routine will never return "short", it will always write all the data unless there are errors.
  2933. @param wp Webs request object
  2934. @param buf Buffer of data to write
  2935. @param size Length of buf
  2936. @return Count of bytes written or -1. This will always equal size if there are no errors.
  2937. @ingroup Webs
  2938. @stability Stable
  2939. */
  2940. PUBLIC ssize websWriteBlock(Webs *wp, cchar *buf, ssize size);
  2941. /**
  2942. Write a block of data to the network
  2943. @description This bypassed output buffering and is the lowest level write.
  2944. @param wp Webs request object
  2945. @param buf Buffer of data to write
  2946. @param size Length of buf
  2947. @return Count of bytes written. May be less than len if the socket is in non-blocking mode.
  2948. Returns -1 for errors and if the socket cannot absorb any more data. If the transport is saturated,
  2949. will return a negative error and errno will be set to EAGAIN or EWOULDBLOCK.
  2950. @ingroup Webs
  2951. @stability Stable
  2952. */
  2953. PUBLIC ssize websWriteSocket(Webs *wp, cchar *buf, ssize size);
  2954. #if ME_GOAHEAD_UPLOAD
  2955. /**
  2956. Process upload data for form, multipart mime file upload.
  2957. @param wp Webs request object
  2958. @return True if processing the request can proceed.
  2959. @ingroup Webs
  2960. @stability Stable
  2961. */
  2962. PUBLIC bool websProcessUploadData(Webs *wp);
  2963. /**
  2964. Free file upload data structures.
  2965. @param wp Webs request object
  2966. @ingroup Webs
  2967. @stability Stable
  2968. */
  2969. PUBLIC void websFreeUpload(Webs *wp);
  2970. #endif
  2971. #if ME_GOAHEAD_CGI
  2972. /**
  2973. Process CGI request body data.
  2974. @param wp Webs request object
  2975. @return True if processing the request can proceed.
  2976. @ingroup Webs
  2977. @stability Stable
  2978. */
  2979. PUBLIC bool websProcessCgiData(Webs *wp);
  2980. #endif
  2981. /************************************** Crypto ********************************/
  2982. /**
  2983. Get some random data
  2984. @param buf Reference to a buffer to hold the random data
  2985. @param length Size of the buffer
  2986. @param block Set to true if it is acceptable to block while accumulating entropy sufficient to provide good
  2987. random data. Setting to false will cause this API to not block and may return random data of a lower quality.
  2988. @ingroup Crypto
  2989. @stability Prototype.
  2990. */
  2991. PUBLIC int websGetRandomBytes(char *buf, ssize length, bool block);
  2992. /**
  2993. Encrypt a password using the Blowfish algorithm
  2994. @param password User's password to encrypt
  2995. @param salt Salt text to add to password. Helps to make each user's password unique.
  2996. @param rounds Number of times to encrypt. More times, makes the routine slower and passwords harder to crack.
  2997. @return The encrypted password.
  2998. @ingroup Crypto
  2999. @stability Prototype
  3000. */
  3001. PUBLIC char *websCryptPassword(cchar *password, cchar *salt, int rounds);
  3002. /**
  3003. Make salt for adding to a password.
  3004. @param size Size in bytes of the salt text.
  3005. @return The random salt text. Caller must free.
  3006. @ingroup Crypto
  3007. @stability Prototype
  3008. */
  3009. PUBLIC char *websMakeSalt(ssize size);
  3010. /**
  3011. Make a password hash for a plain-text password using the Blowfish algorithm.
  3012. @param password User's password to encrypt
  3013. @param saltLength Length of salt text to add to password. Helps to make each user's password unique.
  3014. @param rounds Number of times to encrypt. More times, makes the routine slower and passwords harder to crack.
  3015. @return The encrypted password. Caller must free.
  3016. @ingroup Crypto
  3017. @stability Prototype
  3018. */
  3019. PUBLIC char *websMakePassword(cchar *password, int saltLength, int rounds);
  3020. /**
  3021. Check a plain-text password against the defined hashed password.
  3022. @param plainTextPassword User's plain-text-password to check
  3023. @param passwordHash Required password in hashed format previously computed by websMakePassword.
  3024. @return True if the password is correct.
  3025. @ingroup Crypto
  3026. @stability Prototype
  3027. */
  3028. PUBLIC bool websCheckPassword(cchar *plainTextPassword, cchar *passwordHash);
  3029. /**
  3030. Get a password from the terminal console
  3031. @param prompt Text prompt to display before reading the password
  3032. @return The entered password. Caller must free.
  3033. @ingroup Crypto
  3034. @stability Prototype
  3035. */
  3036. PUBLIC char *websReadPassword(cchar *prompt);
  3037. /*************************************** JST ***********************************/
  3038. #if ME_GOAHEAD_JAVASCRIPT
  3039. /**
  3040. Javascript native function
  3041. @param jid JavaScript engine ID
  3042. @param wp Webs request object
  3043. @param argc Count of function arguments
  3044. @param argv Array of function arguments
  3045. @param defaultValue Default value to return if the variable is not defined
  3046. @return Return zero if successful, otherwise -1.
  3047. @ingroup Webs
  3048. @stability Stable
  3049. */
  3050. typedef int (*WebsJstProc)(int jid, Webs *wp, int argc, char **argv);
  3051. /**
  3052. Define a Javscript native function.
  3053. @description This routine binds a C function to a Javascript function. When the Javascript function is called,
  3054. the C function is invoked.
  3055. @param name Javascript function name
  3056. @param fn C function to invoke
  3057. @return Zero if successful, otherwise -1.
  3058. @ingroup Webs
  3059. @stability Stable
  3060. */
  3061. PUBLIC int websDefineJst(cchar *name, WebsJstProc fn);
  3062. /**
  3063. Open the Javascript module.
  3064. @return Zero if successful, otherwise -1.
  3065. @ingroup Webs
  3066. @stability Stable
  3067. */
  3068. PUBLIC int websJstOpen(void);
  3069. /**
  3070. Write data to the response
  3071. @param jid Javascript ID handle
  3072. @param wp Webs request object
  3073. @param argc Count of arguments
  3074. @param argv Array arguments
  3075. @return Zero if successful, otherwise -1.
  3076. @ingroup Webs
  3077. @stability Stable
  3078. */
  3079. PUBLIC int websJstWrite(int jid, Webs *wp, int argc, char **argv);
  3080. #endif
  3081. /*************************************** SSL ***********************************/
  3082. #if ME_COM_SSL
  3083. /*
  3084. Default MakeMe settings
  3085. */
  3086. #ifndef ME_GOAHEAD_SSL_AUTHORITY
  3087. #define ME_GOAHEAD_SSL_AUTHORITY ""
  3088. #endif
  3089. #ifndef ME_GOAHEAD_SSL_CACHE
  3090. #define ME_GOAHEAD_SSL_CACHE 512
  3091. #endif
  3092. #ifndef ME_GOAHEAD_SSL_CERTIFICATE
  3093. #define ME_GOAHEAD_SSL_CERTIFICATE ""
  3094. #endif
  3095. #ifndef ME_GOAHEAD_SSL_CIPHERS
  3096. #define ME_GOAHEAD_SSL_CIPHERS ""
  3097. #endif
  3098. #ifndef ME_GOAHEAD_SSL_KEY
  3099. #define ME_GOAHEAD_SSL_KEY ""
  3100. #endif
  3101. #ifndef ME_GOAHEAD_SSL_LOG_LEVEL
  3102. #define ME_GOAHEAD_SSL_LOG_LEVEL 4
  3103. #endif
  3104. #ifndef ME_GOAHEAD_SSL_RENEGOTIATE
  3105. #define ME_GOAHEAD_SSL_RENEGOTIATE 1
  3106. #endif
  3107. #ifndef ME_GOAHEAD_SSL_REVOKE
  3108. #define ME_GOAHEAD_SSL_REVOKE ""
  3109. #endif
  3110. #ifndef ME_GOAHEAD_SSL_TICKET
  3111. #define ME_GOAHEAD_SSL_TICKET 1
  3112. #endif
  3113. #ifndef ME_GOAHEAD_SSL_TIMEOUT
  3114. #define ME_GOAHEAD_SSL_TIMEOUT 86400
  3115. #endif
  3116. #ifndef ME_GOAHEAD_SSL_VERIFY
  3117. #define ME_GOAHEAD_SSL_VERIFY 0
  3118. #endif
  3119. #ifndef ME_GOAHEAD_SSL_VERIFY_ISSUER
  3120. #define ME_GOAHEAD_SSL_VERIFY_ISSUER 0
  3121. #endif
  3122. /**
  3123. Open the ssl module
  3124. @return Zero if successful, otherwise -1.
  3125. @ingroup Webs
  3126. @stability Stable
  3127. */
  3128. PUBLIC int sslOpen(void);
  3129. /**
  3130. Close the ssl module
  3131. @ingroup Webs
  3132. @stability Stable
  3133. */
  3134. PUBLIC void sslClose(void);
  3135. /**
  3136. Free a ssl connection associated with a request
  3137. @param wp Webs request object
  3138. @ingroup Webs
  3139. @stability Stable
  3140. */
  3141. PUBLIC void sslFree(Webs *wp);
  3142. /**
  3143. Upgrade a request connection to utilize SSL
  3144. @description This routine is invoked on a connection received on a secure listening socket
  3145. @param wp Webs request object
  3146. @return Zero if successful, otherwise -1.
  3147. @ingroup Webs
  3148. @stability Stable
  3149. */
  3150. PUBLIC int sslUpgrade(Webs *wp);
  3151. /**
  3152. Read data from a secure socket
  3153. @param wp Webs request object
  3154. @param buf Buffer into which to read data
  3155. @param len Size of buf
  3156. @return Count of bytes read if successful, otherwise -1.
  3157. @ingroup Webs
  3158. @stability Stable
  3159. */
  3160. PUBLIC ssize sslRead(Webs *wp, void *buf, ssize len);
  3161. /**
  3162. WRite data to a secure socket
  3163. @param wp Webs request object
  3164. @param buf Buffer from which to write data
  3165. @param len Size of buf
  3166. @return Count of bytes written if successful, otherwise -1.
  3167. @ingroup Webs
  3168. @stability Stable
  3169. */
  3170. PUBLIC ssize sslWrite(Webs *wp, void *buf, ssize len);
  3171. #endif /* ME_COM_SSL */
  3172. /*************************************** Route *********************************/
  3173. /**
  3174. Callback to prompt the user for their password
  3175. @param wp Webs request object
  3176. @ingroup Webs
  3177. @stability Stable
  3178. */
  3179. typedef void (*WebsAskLogin)(Webs *wp);
  3180. /**
  3181. Callback to verify the username and password
  3182. @param wp Webs request object
  3183. @return True if the password is verified
  3184. @ingroup Webs
  3185. @stability Stable
  3186. */
  3187. typedef bool (*WebsVerify)(Webs *wp);
  3188. /**
  3189. Callback to parse authentication details submitted with the web request
  3190. @param wp Webs request object
  3191. @return True if the details can be parsed
  3192. @ingroup Webs
  3193. @stability Stable
  3194. */
  3195. typedef bool (*WebsParseAuth)(Webs *wp);
  3196. /**
  3197. Request route structure
  3198. @defgroup WebsRoute WebsRoute
  3199. */
  3200. typedef struct WebsRoute {
  3201. char *prefix; /**< Route path prefix */
  3202. ssize prefixLen; /**< Prefix length */
  3203. char *dir; /**< Filesystem base directory for route documents */
  3204. char *protocol; /**< HTTP protocol to use for this route */
  3205. char *authType; /**< Authentication type */
  3206. WebsHandler *handler; /**< Request handler to service requests */
  3207. WebsHash abilities; /**< Required user abilities */
  3208. WebsHash extensions; /**< Permissible URI extensions */
  3209. WebsHash redirects; /**< Response redirections */
  3210. WebsHash methods; /**< Supported HTTP methods */
  3211. WebsAskLogin askLogin; /**< Route path prefix */
  3212. WebsParseAuth parseAuth; /**< Parse authentication details callback*/
  3213. WebsVerify verify; /**< Verify password callback */
  3214. int flags; /**< Route control flags */
  3215. } WebsRoute;
  3216. /**
  3217. Add a route to the routing tables
  3218. @param uri Matching URI prefix
  3219. @param handler Request handler to service routed requests
  3220. @param pos Position in the list of routes. Zero inserts at the front of the list. A value of -1 will append to the
  3221. end of the list.
  3222. @return A route object
  3223. @ingroup WebsRoute
  3224. @stability Stable
  3225. */
  3226. PUBLIC WebsRoute *websAddRoute(cchar *uri, cchar *handler, int pos);
  3227. /**
  3228. Close the route module
  3229. @ingroup WebsRoute
  3230. @stability Stable
  3231. */
  3232. PUBLIC void websCloseRoute(void);
  3233. /**
  3234. Load routing tables from the specified filename
  3235. @param path Route configuration filename
  3236. @return Zero if successful, otherwise -1.
  3237. @ingroup WebsRoute
  3238. @stability Stable
  3239. */
  3240. PUBLIC int websLoad(cchar *path);
  3241. /**
  3242. Open the routing module
  3243. @ingroup WebsRoute
  3244. @stability Stable
  3245. */
  3246. PUBLIC int websOpenRoute(void);
  3247. /**
  3248. Remove a route from the routing tables
  3249. @param uri Matching URI prefix
  3250. @return Zero if successful, otherwise -1.
  3251. @ingroup WebsRoute
  3252. @stability Stable
  3253. */
  3254. PUBLIC int websRemoveRoute(cchar *uri);
  3255. /**
  3256. Route a request
  3257. @description This routine will select a matching route and will invoke the selected route handler to service
  3258. the request. In the process, authentication and request rewriting may take place.
  3259. This routine is called internally by the request pipeline.
  3260. @param wp Webs request object
  3261. @ingroup WebsRoute
  3262. @stability Stable
  3263. */
  3264. PUBLIC void websRouteRequest(Webs *wp);
  3265. /**
  3266. Run a request handler
  3267. @description This routine will run the handler and route selected by #websRouteRequest.
  3268. This routine is called internally by the request pipeline.
  3269. @param wp Webs request object
  3270. @return True if the handler serviced the request. Return false to test other routes to handle this request.
  3271. This is for legacy handlers that do not have a match callback.
  3272. @ingroup WebsRoute
  3273. @stability Stable
  3274. */
  3275. PUBLIC bool websRunRequest(Webs *wp);
  3276. /**
  3277. Configure a route by adding matching criteria
  3278. @param route Route to modify
  3279. @param dir Set the route documents directory filename
  3280. @param protocol Set the matching HTTP protocol (http or https)
  3281. @param methods Hash of permissible HTTP methods. (GET, HEAD, POST, PUT)
  3282. @param extensions Hash of permissible URI filename extensions.
  3283. @param abilities Required user abilities. The user must be authenticated.
  3284. @param abilities Required user abilities. If abilities are required, the user must be authenticated.
  3285. @param redirects Set of applicable response redirections when completing the request.
  3286. @return Zero if successful, otherwise -1.
  3287. @ingroup WebsRoute
  3288. @stability Evolving
  3289. */
  3290. PUBLIC int websSetRouteMatch(WebsRoute *route, cchar *dir, cchar *protocol, WebsHash methods, WebsHash extensions,
  3291. WebsHash abilities, WebsHash redirects);
  3292. /**
  3293. Set route authentication scheme
  3294. @param route Route to modify
  3295. @param authType Set to "basic", "digest" or "form".
  3296. @return Zero if successful, otherwise -1.
  3297. @ingroup WebsRoute
  3298. @stability Stable
  3299. */
  3300. PUBLIC int websSetRouteAuth(WebsRoute *route, cchar *authType);
  3301. /*************************************** Auth **********************************/
  3302. #if ME_GOAHEAD_AUTH
  3303. #define WEBS_USIZE 128 /* Size of realm:username */
  3304. /**
  3305. GoAhead Authentication
  3306. @defgroup WebsAuth WebsAuth
  3307. */
  3308. /**
  3309. User definition structure
  3310. @ingroup WebsAuth
  3311. @stability Stable
  3312. */
  3313. typedef struct WebsUser {
  3314. char *name; /**< User name */
  3315. char *password; /**< User password (encrypted) */
  3316. char *roles; /**< User roles */
  3317. WebsHash abilities; /**< Resolved user abilities */
  3318. } WebsUser;
  3319. /**
  3320. Role definition structure
  3321. @ingroup WebsAuth
  3322. @stability Stable
  3323. */
  3324. typedef struct WebsRole {
  3325. WebsHash abilities; /**< Resolved role abilities */
  3326. } WebsRole;
  3327. /**
  3328. Add a role
  3329. @description The role is added to the list of roles
  3330. @param role Role name
  3331. @param abilities Hash of abilities for the role
  3332. @return The allocated role.
  3333. @ingroup WebsAuth
  3334. @stability Stable
  3335. */
  3336. PUBLIC WebsRole *websAddRole(cchar *role, WebsHash abilities);
  3337. /**
  3338. Add a user
  3339. @description The user is added to the list of users
  3340. @param username User name
  3341. @param password User password (encrypted)
  3342. @param roles Space separated list of roles. This may also contain abilities.
  3343. @return User object.
  3344. @ingroup WebsAuth
  3345. @stability Stable
  3346. */
  3347. PUBLIC WebsUser *websAddUser(cchar *username, cchar *password, cchar *roles);
  3348. /**
  3349. Authenticate a user
  3350. @description The user is authenticated if required by the selected request route.
  3351. @param wp Webs request object
  3352. @return True if the route does not require authentication or the user is authenticated successfully.
  3353. @ingroup WebsAuth
  3354. @stability Stable
  3355. */
  3356. PUBLIC bool websAuthenticate(Webs *wp);
  3357. /**
  3358. Test if a user possesses the required ability
  3359. @param wp Webs request object
  3360. @param ability Set of required abilities.
  3361. @return True if the user has the required ability.
  3362. @ingroup WebsAuth
  3363. @stability Stable
  3364. */
  3365. PUBLIC bool websCan(Webs *wp, WebsHash ability);
  3366. /**
  3367. Close the authentication module
  3368. @ingroup WebsAuth
  3369. @stability Stable
  3370. */
  3371. PUBLIC void websCloseAuth(void);
  3372. /**
  3373. Compute the abilities for all users by resolving roles into abilities
  3374. @ingroup WebsAuth
  3375. @stability Stable
  3376. */
  3377. PUBLIC void websComputeAllUserAbilities(void);
  3378. /**
  3379. Set the password store verify callback
  3380. @return verify WebsVerify callback function
  3381. @ingroup WebsAuth
  3382. @stability Stable
  3383. */
  3384. PUBLIC WebsVerify websGetPasswordStoreVerify(void);
  3385. /**
  3386. Get the roles hash
  3387. @return The roles hash object
  3388. @ingroup WebsAuth
  3389. @stability Stable
  3390. */
  3391. PUBLIC WebsHash websGetRoles(void);
  3392. /**
  3393. Get the users hash
  3394. @return The users hash object
  3395. @ingroup WebsAuth
  3396. @stability Stable
  3397. */
  3398. PUBLIC WebsHash websGetUsers(void);
  3399. /**
  3400. Login a user by verifying the login credentials.
  3401. @description This may be called by handlers to manually authenticate a user.
  3402. @param wp Webs request object
  3403. @param username User name
  3404. @param password User password (encrypted)
  3405. @return True if the user can be authenticated.
  3406. @ingroup WebsAuth
  3407. @stability Stable
  3408. */
  3409. PUBLIC bool websLoginUser(Webs *wp, cchar *username, cchar *password);
  3410. /**
  3411. Logout a user and remove the user login session.
  3412. @param wp Webs request object
  3413. @return True if successful.
  3414. @ingroup WebsAuth
  3415. @stability Stable
  3416. */
  3417. PUBLIC bool websLogoutUser(Webs *wp);
  3418. /**
  3419. Lookup if a user exists
  3420. @param username User name to search for
  3421. @return User object or null if the user cannot be found
  3422. @ingroup WebsAuth
  3423. @stability Stable
  3424. */
  3425. PUBLIC WebsUser *websLookupUser(cchar *username);
  3426. /**
  3427. Remove a role from the system
  3428. @param role Role name
  3429. @return Zero if successful, otherwise -1
  3430. @ingroup WebsAuth
  3431. @stability Stable
  3432. */
  3433. PUBLIC int websRemoveRole(cchar *role);
  3434. /**
  3435. Remove a user from the system
  3436. @param name User name
  3437. @return Zero if successful, otherwise -1
  3438. @ingroup WebsAuth
  3439. @stability Stable
  3440. */
  3441. PUBLIC int websRemoveUser(cchar *name);
  3442. /**
  3443. Open the authentication module
  3444. @param minimal Reserved. Set to zero.
  3445. @return True if the user has the required ability.
  3446. @ingroup WebsAuth
  3447. @stability Stable
  3448. */
  3449. PUBLIC int websOpenAuth(int minimal);
  3450. /**
  3451. Set the password store verify callback
  3452. @param verify WebsVerify callback function
  3453. @ingroup WebsAuth
  3454. @stability Stable
  3455. */
  3456. PUBLIC void websSetPasswordStoreVerify(WebsVerify verify);
  3457. /**
  3458. Set a password for the user
  3459. @param username User name
  3460. @param password Null terminated password string
  3461. @return Zero if successful, otherwise -1.
  3462. @ingroup WebsAuth
  3463. @stability Stable
  3464. */
  3465. PUBLIC int websSetUserPassword(cchar *username, cchar *password);
  3466. /**
  3467. Define the set of roles for a user
  3468. @param username User name
  3469. @param roles Space separated list of roles or abilities
  3470. @return Zero if successful, otherwise -1.
  3471. @ingroup WebsAuth
  3472. @stability Stable
  3473. */
  3474. PUBLIC int websSetUserRoles(cchar *username, cchar *roles);
  3475. /**
  3476. User password verification routine from a custom password back-end store.
  3477. @param wp Webs request object
  3478. @return True if the user password verifies.
  3479. @ingroup WebsAuth
  3480. @stability Stable
  3481. */
  3482. PUBLIC bool websVerifyPasswordFromCustom(Webs *wp);
  3483. /**
  3484. User password verification routine from auth.txt
  3485. @param wp Webs request object
  3486. @return True if the user password verifies.
  3487. @ingroup WebsAuth
  3488. @stability Stable
  3489. */
  3490. PUBLIC bool websVerifyPasswordFromFile(Webs *wp);
  3491. #if ME_COMPILER_HAS_PAM
  3492. /**
  3493. Verify a password using the system PAM password database.
  3494. @param wp Webs request object
  3495. @return True if the user password verifies.
  3496. @ingroup WebsAuth
  3497. @stability Stable
  3498. */
  3499. PUBLIC bool websVerifyPasswordFromPam(Webs *wp);
  3500. #endif
  3501. #endif /* ME_GOAHEAD_AUTH */
  3502. /************************************** Sessions *******************************/
  3503. /**
  3504. Session state storage
  3505. @defgroup WebsSession WebsSession
  3506. */
  3507. typedef struct WebsSession {
  3508. char *id; /**< Session ID key */
  3509. int lifespan; /**< Session inactivity timeout (secs) */
  3510. WebsTime expires; /**< When the session expires */
  3511. WebsHash cache; /**< Cache of session variables */
  3512. } WebsSession;
  3513. /**
  3514. Test if a user possesses the required ability
  3515. @param wp Webs request object
  3516. @param id Session ID to use. Set to null to allocate a new session ID.
  3517. @param lifespan Lifespan of the session in seconds.
  3518. @return Allocated session object
  3519. @ingroup WebsSession
  3520. @stability Stable
  3521. */
  3522. PUBLIC WebsSession *websAllocSession(Webs *wp, cchar *id, int lifespan);
  3523. /**
  3524. Test if a user possesses the required ability
  3525. @param wp Webs request object
  3526. @return Allocated session object
  3527. @ingroup WebsSession
  3528. @stability Stable
  3529. */
  3530. PUBLIC WebsSession *websCreateSession(Webs *wp);
  3531. /**
  3532. Destroy the webs session object
  3533. @description Useful to be called as part of the user logout process
  3534. @param wp Webs request object
  3535. @ingroup WebsSession
  3536. @stability Prototype
  3537. */
  3538. PUBLIC void websDestroySession(Webs *wp);
  3539. /**
  3540. Get the session ID
  3541. @param wp Webs request object
  3542. @return The session ID if session state storage is defined for this request. Caller must free.
  3543. @ingroup WebsSession
  3544. @stability Stable
  3545. */
  3546. PUBLIC char *websGetSessionID(Webs *wp);
  3547. /**
  3548. Get the session state object for the current request
  3549. @param wp Webs request object
  3550. @param create Set to true to create a new session if one does not already exist.
  3551. @return Session object
  3552. @ingroup WebsSession
  3553. @stability Stable
  3554. */
  3555. PUBLIC WebsSession *websGetSession(Webs *wp, int create);
  3556. /**
  3557. Get a session variable
  3558. @param wp Webs request object
  3559. @param name Session variable name
  3560. @param defaultValue Default value to return if the variable does not exist
  3561. @return Session variable value or default value if it does not exist
  3562. @ingroup WebsSession
  3563. @stability Stable
  3564. */
  3565. PUBLIC cchar *websGetSessionVar(Webs *wp, cchar *name, cchar *defaultValue);
  3566. /**
  3567. Remove a session variable
  3568. @param wp Webs request object
  3569. @param name Session variable name
  3570. @ingroup WebsSession
  3571. @stability Stable
  3572. */
  3573. PUBLIC void websRemoveSessionVar(Webs *wp, cchar *name);
  3574. /**
  3575. Set a session variable name value
  3576. @param wp Webs request object
  3577. @param name Session variable name
  3578. @param value Value to set the variable to
  3579. @return Zero if successful, otherwise -1
  3580. @ingroup WebsSession
  3581. @stability Stable
  3582. */
  3583. PUBLIC int websSetSessionVar(Webs *wp, cchar *name, cchar *value);
  3584. /************************************ Legacy **********************************/
  3585. /*
  3586. Legacy mappings for pre GoAhead 3.X applications
  3587. This is a list of the name changes from GoAhead 2.X to GoAhead 3.x
  3588. To maximize forward compatibility, It is best to not use ME_GOAHEAD_LEGACY except as
  3589. a transitional compilation aid.
  3590. */
  3591. #if ME_GOAHEAD_LEGACY
  3592. #define B_L 0
  3593. #define a_assert assert
  3594. #define balloc walloc
  3595. #define bclose wcloseAlloc
  3596. #define bfree(loc, p) wfree(p)
  3597. #define bfreeSafe(loc, p) wfree(p)
  3598. #define bopen wopenAlloc
  3599. #define brealloc wrealloc
  3600. #define bstrdup sclone
  3601. #define emfReschedCallback websRestartEvent
  3602. #define emfSchedCallback websStartEvent
  3603. #define emfSchedProc WebsEventProc
  3604. #define emfSchedProcess websRunEvents
  3605. #define emfUnschedCallback websStopEvent
  3606. #define fmtStatic fmt
  3607. #define gassert assert
  3608. #define galloc walloc
  3609. #define gallocEntry wallocObject
  3610. #define gfree wfree
  3611. #define gFree wfreeHandle
  3612. #define grealloc wrealloc
  3613. #define gaccess access
  3614. #define gasctime asctime
  3615. #define gatoi atoi
  3616. #define gchmod chmod
  3617. #define wclose close
  3618. #define wclosedir closedir
  3619. #define gcreat creat
  3620. #define gctime ctime
  3621. #define gexecvp execvp
  3622. #define gfgets fgets
  3623. #define gfindclose _findclose
  3624. #define gfinddata_t _finddata_t
  3625. #define gfindfirst _findfirst
  3626. #define gfindnext _findnext
  3627. #define gfopen fopen
  3628. #define gfprintf fprintf
  3629. #define gfputs fputs
  3630. #define gfscanf fscanf
  3631. #define ggetcwd getcwd
  3632. #define ggetenv getenv
  3633. #define ggets gets
  3634. #define gisalnum isalnum
  3635. #define gisalpha isalpha
  3636. #define gisdigit isdigit
  3637. #define gislower islower
  3638. #define gisspace isspace
  3639. #define gisupper isupper
  3640. #define gisxdigit isxdigit
  3641. #define gloadModule loadModule
  3642. #define glseek lseek
  3643. #define gopendir opendir
  3644. #define gprintf printf
  3645. #define gread read
  3646. #define greaddir readdir
  3647. #define gremove remove
  3648. #define grename rename
  3649. #define gsprintf sprintf
  3650. #define gsscanf sscanf
  3651. #define gstat stat
  3652. #define gstrcat strcat
  3653. #define gstrchr strchr
  3654. #define gstrcmp strcmp
  3655. #define gstrcpy strcpy
  3656. #define gstrcspn strcspn
  3657. #define gstricmp strcmpci
  3658. #define gstritoa stritoa
  3659. #define gstrlen strlen
  3660. #define gstrlower strlower
  3661. #define gstrncat strncat
  3662. #define gstrncmp strncmp
  3663. #define gstrncpy strncpy
  3664. #define gstrnlen strnlen
  3665. #define gstrnset strnset
  3666. #define gstrrchr strrchr
  3667. #define gstrspn strspn
  3668. #define gstrstr strstr
  3669. #define gstrtok strtok
  3670. #define gstrtol strtol
  3671. #define gstrupper strupper
  3672. #define gtempnam websTempFile
  3673. #define gtolower tolower
  3674. #define gtoupper toupper
  3675. #define gunlink unlink
  3676. #define gvsprintf vsprintf
  3677. #define gwrite write
  3678. #define hAlloc wallocHandle
  3679. #define hAllocEntry wallocObject
  3680. #define hFree wfreeHandle
  3681. #define stritoa gstritoa
  3682. #define strlower gstrlower
  3683. #define strupper gstrupper
  3684. #define websAspDefine websDefineJst
  3685. #define websAspOpen websJstOpen
  3686. #define websAspRequest websJstRequest
  3687. #define websFormDefine websDefineAction
  3688. #define websGetDefaultDir websGetDocuments
  3689. #define websGetDefaultPage websGetIndex
  3690. #define websGetRequestDir(wp) wp->dir
  3691. #define websGetRequestIpAddr(wp) wp->ipaddr
  3692. #define websGetRequestFilename(wp) wp->filename
  3693. #define websGetRequestFlags(wp) wp->flags
  3694. #define websGetRequestLpath(wp) wp->filename
  3695. #define websGetRequestPath(wp) wp->path
  3696. #define websGetRequestPassword(wp) wp->password
  3697. #define websGetRequestUserName(wp) wp->username
  3698. #define websGetRequestWritten(wp) wp->written
  3699. #define websSetDefaultDir websSetDocuments
  3700. #define websSetDefaultPage websSetIndex
  3701. #define websSetRequestLpath websSetRequestFilename
  3702. #define websSetRequestWritten(wp, nbytes) if (1) { wp->written = nbytes; } else {}
  3703. #define websTimeoutCancel websCancelTimeout
  3704. #define websWriteDataNonBlock websWriteRaw
  3705. #define ringqOpen bufCreate
  3706. #define ringqClose bufFree
  3707. #define ringqLen bufLen
  3708. #define ringqPutc bufPutc
  3709. #define ringqInsertc bufInsertc
  3710. #define ringqPutStr bufPutStr
  3711. #define ringqGetc bufGetc
  3712. #define ringqGrow bufGrow
  3713. #define ringqPutBlk bufPutBlk
  3714. #define ringqPutBlkMax bufRoom
  3715. #define ringqPutBlkAdj bufAdjustEnd
  3716. #define ringqGetBlk bufGetBlk
  3717. #define ringqGetBlkMax bufGetBlkMax
  3718. #define ringqGetBlkAdj bufAdjustSTart
  3719. #define ringqFlush bufFlush
  3720. #define ringqCompact bufCompact
  3721. #define ringqReset bufReset
  3722. #define ringqAddNull bufAddNull
  3723. #define symCreate hashCreate
  3724. #define symClose hashFree
  3725. #define symLookup hashLookup
  3726. #define symEnter hashEnter
  3727. #define symDelete hashDelete
  3728. #define symWalk hashWalk
  3729. #define symFirst hashFirst
  3730. #define symNext hashNext
  3731. typedef Webs *webs_t;
  3732. typedef Webs WebsRec;
  3733. typedef Webs websType;
  3734. typedef WebsBuf ringq_t;
  3735. typedef WebsError websErrorType;
  3736. typedef WebsProc WebsFormProc;
  3737. typedef int (*WebsLegacyHandlerProc)(Webs *wp, char *prefix, char *dir, int flags);
  3738. typedef SocketHandler socketHandler_t;
  3739. typedef SocketAccept socketAccept_t;
  3740. typedef WebsType vtype_t;
  3741. typedef WebsHash sym_fd_t;
  3742. typedef WebsKey sym_t;
  3743. typedef WebsMime websMimeType;
  3744. typedef WebsSocket socket_t;
  3745. typedef WebsStat gstat_t;
  3746. typedef WebsValue value_t;
  3747. PUBLIC int fmtValloc(char **s, int n, cchar *fmt, va_list arg);
  3748. PUBLIC int fmtAlloc(char **s, int n, cchar *fmt, ...);
  3749. PUBLIC void websFooter(Webs *wp);
  3750. PUBLIC void websHeader(Webs *wp);
  3751. PUBLIC int websPublish(cchar *prefix, cchar *path);
  3752. PUBLIC void websSetRequestFilename(Webs *wp, cchar *filename);
  3753. PUBLIC int websUrlHandlerDefine(cchar *prefix, cchar *dir, int arg, WebsLegacyHandlerProc handler, int flags);
  3754. #if ME_ROM
  3755. typedef WebsRomIndex websRomIndexType;
  3756. #endif
  3757. #endif
  3758. #if ME_CUSTOMIZE
  3759. #include "customize.h"
  3760. #endif
  3761. #ifdef __cplusplus
  3762. }
  3763. #endif
  3764. #endif /* _h_GOAHEAD */
  3765. /*
  3766. Copyright (c) Embedthis Software. All Rights Reserved.
  3767. This software is distributed under commercial and open source licenses.
  3768. You may use the Embedthis GoAhead open source license or you may acquire
  3769. a commercial license from Embedthis Software. You agree to be fully bound
  3770. by the terms of either license. Consult the LICENSE.md distributed with
  3771. this software for full details and other copyrights.
  3772. */