goahead.h 138 KB

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