goahead.h 139 KB

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