goahead.h 138 KB

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